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 int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
42 int64_t offset
, int bytes
, BdrvRequestFlags flags
);
44 void bdrv_parent_drained_begin(BlockDriverState
*bs
, BdrvChild
*ignore
)
48 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
52 if (c
->role
->drained_begin
) {
53 c
->role
->drained_begin(c
);
58 void bdrv_parent_drained_end(BlockDriverState
*bs
, BdrvChild
*ignore
)
62 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
66 if (c
->role
->drained_end
) {
67 c
->role
->drained_end(c
);
72 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
74 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
75 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
76 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
77 src
->opt_mem_alignment
);
78 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
79 src
->min_mem_alignment
);
80 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
83 void bdrv_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
85 BlockDriver
*drv
= bs
->drv
;
86 Error
*local_err
= NULL
;
88 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
94 /* Default alignment based on whether driver has byte interface */
95 bs
->bl
.request_alignment
= (drv
->bdrv_co_preadv
||
96 drv
->bdrv_aio_preadv
) ? 1 : 512;
98 /* Take some limits from the children as a default */
100 bdrv_refresh_limits(bs
->file
->bs
, &local_err
);
102 error_propagate(errp
, local_err
);
105 bdrv_merge_limits(&bs
->bl
, &bs
->file
->bs
->bl
);
107 bs
->bl
.min_mem_alignment
= 512;
108 bs
->bl
.opt_mem_alignment
= getpagesize();
110 /* Safe default since most protocols use readv()/writev()/etc */
111 bs
->bl
.max_iov
= IOV_MAX
;
115 bdrv_refresh_limits(bs
->backing
->bs
, &local_err
);
117 error_propagate(errp
, local_err
);
120 bdrv_merge_limits(&bs
->bl
, &bs
->backing
->bs
->bl
);
123 /* Then let the driver override it */
124 if (drv
->bdrv_refresh_limits
) {
125 drv
->bdrv_refresh_limits(bs
, errp
);
130 * The copy-on-read flag is actually a reference count so multiple users may
131 * use the feature without worrying about clobbering its previous state.
132 * Copy-on-read stays enabled until all users have called to disable it.
134 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
136 atomic_inc(&bs
->copy_on_read
);
139 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
141 int old
= atomic_fetch_dec(&bs
->copy_on_read
);
147 BlockDriverState
*bs
;
154 static void coroutine_fn
bdrv_drain_invoke_entry(void *opaque
)
156 BdrvCoDrainData
*data
= opaque
;
157 BlockDriverState
*bs
= data
->bs
;
160 bs
->drv
->bdrv_co_drain_begin(bs
);
162 bs
->drv
->bdrv_co_drain_end(bs
);
165 /* Set data->done before reading bs->wakeup. */
166 atomic_mb_set(&data
->done
, true);
170 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
171 static void bdrv_drain_invoke(BlockDriverState
*bs
, bool begin
, bool recursive
)
173 BdrvChild
*child
, *tmp
;
174 BdrvCoDrainData data
= { .bs
= bs
, .done
= false, .begin
= begin
};
176 if (!bs
->drv
|| (begin
&& !bs
->drv
->bdrv_co_drain_begin
) ||
177 (!begin
&& !bs
->drv
->bdrv_co_drain_end
)) {
181 data
.co
= qemu_coroutine_create(bdrv_drain_invoke_entry
, &data
);
182 bdrv_coroutine_enter(bs
, data
.co
);
183 BDRV_POLL_WHILE(bs
, !data
.done
);
186 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, tmp
) {
187 bdrv_drain_invoke(child
->bs
, begin
, true);
192 static bool bdrv_drain_recurse(BlockDriverState
*bs
)
194 BdrvChild
*child
, *tmp
;
197 /* Wait for drained requests to finish */
198 waited
= BDRV_POLL_WHILE(bs
, atomic_read(&bs
->in_flight
) > 0);
200 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, tmp
) {
201 BlockDriverState
*bs
= child
->bs
;
203 qemu_get_current_aio_context() == qemu_get_aio_context();
204 assert(bs
->refcnt
> 0);
206 /* In case the recursive bdrv_drain_recurse processes a
207 * block_job_defer_to_main_loop BH and modifies the graph,
208 * let's hold a reference to bs until we are done.
210 * IOThread doesn't have such a BH, and it is not safe to call
211 * bdrv_unref without BQL, so skip doing it there.
215 waited
|= bdrv_drain_recurse(bs
);
224 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
226 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
229 static void bdrv_co_drain_bh_cb(void *opaque
)
231 BdrvCoDrainData
*data
= opaque
;
232 Coroutine
*co
= data
->co
;
233 BlockDriverState
*bs
= data
->bs
;
235 bdrv_dec_in_flight(bs
);
237 bdrv_do_drained_begin(bs
, data
->recursive
, data
->parent
);
239 bdrv_do_drained_end(bs
, data
->recursive
, data
->parent
);
246 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
,
247 bool begin
, bool recursive
,
250 BdrvCoDrainData data
;
252 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
253 * other coroutines run if they were queued by aio_co_enter(). */
255 assert(qemu_in_coroutine());
256 data
= (BdrvCoDrainData
) {
257 .co
= qemu_coroutine_self(),
261 .recursive
= recursive
,
264 bdrv_inc_in_flight(bs
);
265 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs
),
266 bdrv_co_drain_bh_cb
, &data
);
268 qemu_coroutine_yield();
269 /* If we are resumed from some other event (such as an aio completion or a
270 * timer callback), it is a bug in the caller that should be fixed. */
274 void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
277 BdrvChild
*child
, *next
;
279 if (qemu_in_coroutine()) {
280 bdrv_co_yield_to_drain(bs
, true, recursive
, parent
);
284 /* Stop things in parent-to-child order */
285 if (atomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
286 aio_disable_external(bdrv_get_aio_context(bs
));
289 bdrv_parent_drained_begin(bs
, parent
);
290 bdrv_drain_invoke(bs
, true, false);
291 bdrv_drain_recurse(bs
);
294 bs
->recursive_quiesce_counter
++;
295 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
296 bdrv_do_drained_begin(child
->bs
, true, child
);
301 void bdrv_drained_begin(BlockDriverState
*bs
)
303 bdrv_do_drained_begin(bs
, false, NULL
);
306 void bdrv_subtree_drained_begin(BlockDriverState
*bs
)
308 bdrv_do_drained_begin(bs
, true, NULL
);
311 void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
314 BdrvChild
*child
, *next
;
315 int old_quiesce_counter
;
317 if (qemu_in_coroutine()) {
318 bdrv_co_yield_to_drain(bs
, false, recursive
, parent
);
321 assert(bs
->quiesce_counter
> 0);
322 old_quiesce_counter
= atomic_fetch_dec(&bs
->quiesce_counter
);
324 /* Re-enable things in child-to-parent order */
325 bdrv_drain_invoke(bs
, false, false);
326 bdrv_parent_drained_end(bs
, parent
);
327 if (old_quiesce_counter
== 1) {
328 aio_enable_external(bdrv_get_aio_context(bs
));
332 bs
->recursive_quiesce_counter
--;
333 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
334 bdrv_do_drained_end(child
->bs
, true, child
);
339 void bdrv_drained_end(BlockDriverState
*bs
)
341 bdrv_do_drained_end(bs
, false, NULL
);
344 void bdrv_subtree_drained_end(BlockDriverState
*bs
)
346 bdrv_do_drained_end(bs
, true, NULL
);
349 void bdrv_apply_subtree_drain(BdrvChild
*child
, BlockDriverState
*new_parent
)
353 for (i
= 0; i
< new_parent
->recursive_quiesce_counter
; i
++) {
354 bdrv_do_drained_begin(child
->bs
, true, child
);
358 void bdrv_unapply_subtree_drain(BdrvChild
*child
, BlockDriverState
*old_parent
)
362 for (i
= 0; i
< old_parent
->recursive_quiesce_counter
; i
++) {
363 bdrv_do_drained_end(child
->bs
, true, child
);
368 * Wait for pending requests to complete on a single BlockDriverState subtree,
369 * and suspend block driver's internal I/O until next request arrives.
371 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
374 * Only this BlockDriverState's AioContext is run, so in-flight requests must
375 * not depend on events in other AioContexts. In that case, use
376 * bdrv_drain_all() instead.
378 void coroutine_fn
bdrv_co_drain(BlockDriverState
*bs
)
380 assert(qemu_in_coroutine());
381 bdrv_drained_begin(bs
);
382 bdrv_drained_end(bs
);
385 void bdrv_drain(BlockDriverState
*bs
)
387 bdrv_drained_begin(bs
);
388 bdrv_drained_end(bs
);
392 * Wait for pending requests to complete across all BlockDriverStates
394 * This function does not flush data to disk, use bdrv_flush_all() for that
395 * after calling this function.
397 * This pauses all block jobs and disables external clients. It must
398 * be paired with bdrv_drain_all_end().
400 * NOTE: no new block jobs or BlockDriverStates can be created between
401 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
403 void bdrv_drain_all_begin(void)
405 /* Always run first iteration so any pending completion BHs run */
407 BlockDriverState
*bs
;
409 GSList
*aio_ctxs
= NULL
, *ctx
;
411 /* BDRV_POLL_WHILE() for a node can only be called from its own I/O thread
412 * or the main loop AioContext. We potentially use BDRV_POLL_WHILE() on
413 * nodes in several different AioContexts, so make sure we're in the main
415 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
417 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
418 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
420 /* Stop things in parent-to-child order */
421 aio_context_acquire(aio_context
);
422 aio_disable_external(aio_context
);
423 bdrv_parent_drained_begin(bs
, NULL
);
424 bdrv_drain_invoke(bs
, true, true);
425 aio_context_release(aio_context
);
427 if (!g_slist_find(aio_ctxs
, aio_context
)) {
428 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
432 /* Note that completion of an asynchronous I/O operation can trigger any
433 * number of other I/O operations on other devices---for example a
434 * coroutine can submit an I/O request to another device in response to
435 * request completion. Therefore we must keep looping until there was no
436 * more activity rather than simply draining each device independently.
441 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
442 AioContext
*aio_context
= ctx
->data
;
444 aio_context_acquire(aio_context
);
445 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
446 if (aio_context
== bdrv_get_aio_context(bs
)) {
447 waited
|= bdrv_drain_recurse(bs
);
450 aio_context_release(aio_context
);
454 g_slist_free(aio_ctxs
);
457 void bdrv_drain_all_end(void)
459 BlockDriverState
*bs
;
462 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
463 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
465 /* Re-enable things in child-to-parent order */
466 aio_context_acquire(aio_context
);
467 bdrv_drain_invoke(bs
, false, true);
468 bdrv_parent_drained_end(bs
, NULL
);
469 aio_enable_external(aio_context
);
470 aio_context_release(aio_context
);
474 void bdrv_drain_all(void)
476 bdrv_drain_all_begin();
477 bdrv_drain_all_end();
481 * Remove an active request from the tracked requests list
483 * This function should be called when a tracked request is completing.
485 static void tracked_request_end(BdrvTrackedRequest
*req
)
487 if (req
->serialising
) {
488 atomic_dec(&req
->bs
->serialising_in_flight
);
491 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
492 QLIST_REMOVE(req
, list
);
493 qemu_co_queue_restart_all(&req
->wait_queue
);
494 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
498 * Add an active request to the tracked requests list
500 static void tracked_request_begin(BdrvTrackedRequest
*req
,
501 BlockDriverState
*bs
,
504 enum BdrvTrackedRequestType type
)
506 *req
= (BdrvTrackedRequest
){
511 .co
= qemu_coroutine_self(),
512 .serialising
= false,
513 .overlap_offset
= offset
,
514 .overlap_bytes
= bytes
,
517 qemu_co_queue_init(&req
->wait_queue
);
519 qemu_co_mutex_lock(&bs
->reqs_lock
);
520 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
521 qemu_co_mutex_unlock(&bs
->reqs_lock
);
524 static void mark_request_serialising(BdrvTrackedRequest
*req
, uint64_t align
)
526 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
527 unsigned int overlap_bytes
= ROUND_UP(req
->offset
+ req
->bytes
, align
)
530 if (!req
->serialising
) {
531 atomic_inc(&req
->bs
->serialising_in_flight
);
532 req
->serialising
= true;
535 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
536 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
540 * Round a region to cluster boundaries
542 void bdrv_round_to_clusters(BlockDriverState
*bs
,
543 int64_t offset
, int64_t bytes
,
544 int64_t *cluster_offset
,
545 int64_t *cluster_bytes
)
549 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
550 *cluster_offset
= offset
;
551 *cluster_bytes
= bytes
;
553 int64_t c
= bdi
.cluster_size
;
554 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
555 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
559 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
564 ret
= bdrv_get_info(bs
, &bdi
);
565 if (ret
< 0 || bdi
.cluster_size
== 0) {
566 return bs
->bl
.request_alignment
;
568 return bdi
.cluster_size
;
572 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
573 int64_t offset
, unsigned int bytes
)
576 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
580 if (req
->overlap_offset
>= offset
+ bytes
) {
586 void bdrv_inc_in_flight(BlockDriverState
*bs
)
588 atomic_inc(&bs
->in_flight
);
591 void bdrv_wakeup(BlockDriverState
*bs
)
593 aio_wait_kick(bdrv_get_aio_wait(bs
));
596 void bdrv_dec_in_flight(BlockDriverState
*bs
)
598 atomic_dec(&bs
->in_flight
);
602 static bool coroutine_fn
wait_serialising_requests(BdrvTrackedRequest
*self
)
604 BlockDriverState
*bs
= self
->bs
;
605 BdrvTrackedRequest
*req
;
609 if (!atomic_read(&bs
->serialising_in_flight
)) {
615 qemu_co_mutex_lock(&bs
->reqs_lock
);
616 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
617 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
620 if (tracked_request_overlaps(req
, self
->overlap_offset
,
621 self
->overlap_bytes
))
623 /* Hitting this means there was a reentrant request, for
624 * example, a block driver issuing nested requests. This must
625 * never happen since it means deadlock.
627 assert(qemu_coroutine_self() != req
->co
);
629 /* If the request is already (indirectly) waiting for us, or
630 * will wait for us as soon as it wakes up, then just go on
631 * (instead of producing a deadlock in the former case). */
632 if (!req
->waiting_for
) {
633 self
->waiting_for
= req
;
634 qemu_co_queue_wait(&req
->wait_queue
, &bs
->reqs_lock
);
635 self
->waiting_for
= NULL
;
642 qemu_co_mutex_unlock(&bs
->reqs_lock
);
648 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
651 if (size
> BDRV_REQUEST_MAX_SECTORS
<< BDRV_SECTOR_BITS
) {
655 if (!bdrv_is_inserted(bs
)) {
666 typedef struct RwCo
{
672 BdrvRequestFlags flags
;
675 static void coroutine_fn
bdrv_rw_co_entry(void *opaque
)
679 if (!rwco
->is_write
) {
680 rwco
->ret
= bdrv_co_preadv(rwco
->child
, rwco
->offset
,
681 rwco
->qiov
->size
, rwco
->qiov
,
684 rwco
->ret
= bdrv_co_pwritev(rwco
->child
, rwco
->offset
,
685 rwco
->qiov
->size
, rwco
->qiov
,
691 * Process a vectored synchronous request using coroutines
693 static int bdrv_prwv_co(BdrvChild
*child
, int64_t offset
,
694 QEMUIOVector
*qiov
, bool is_write
,
695 BdrvRequestFlags flags
)
702 .is_write
= is_write
,
707 if (qemu_in_coroutine()) {
708 /* Fast-path if already in coroutine context */
709 bdrv_rw_co_entry(&rwco
);
711 co
= qemu_coroutine_create(bdrv_rw_co_entry
, &rwco
);
712 bdrv_coroutine_enter(child
->bs
, co
);
713 BDRV_POLL_WHILE(child
->bs
, rwco
.ret
== NOT_DONE
);
719 * Process a synchronous request using coroutines
721 static int bdrv_rw_co(BdrvChild
*child
, int64_t sector_num
, uint8_t *buf
,
722 int nb_sectors
, bool is_write
, BdrvRequestFlags flags
)
726 .iov_base
= (void *)buf
,
727 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
730 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
734 qemu_iovec_init_external(&qiov
, &iov
, 1);
735 return bdrv_prwv_co(child
, sector_num
<< BDRV_SECTOR_BITS
,
736 &qiov
, is_write
, flags
);
739 /* return < 0 if error. See bdrv_write() for the return codes */
740 int bdrv_read(BdrvChild
*child
, int64_t sector_num
,
741 uint8_t *buf
, int nb_sectors
)
743 return bdrv_rw_co(child
, sector_num
, buf
, nb_sectors
, false, 0);
746 /* Return < 0 if error. Important errors are:
747 -EIO generic I/O error (may happen for all errors)
748 -ENOMEDIUM No media inserted.
749 -EINVAL Invalid sector number or nb_sectors
750 -EACCES Trying to write a read-only device
752 int bdrv_write(BdrvChild
*child
, int64_t sector_num
,
753 const uint8_t *buf
, int nb_sectors
)
755 return bdrv_rw_co(child
, sector_num
, (uint8_t *)buf
, nb_sectors
, true, 0);
758 int bdrv_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
759 int bytes
, BdrvRequestFlags flags
)
767 qemu_iovec_init_external(&qiov
, &iov
, 1);
768 return bdrv_prwv_co(child
, offset
, &qiov
, true,
769 BDRV_REQ_ZERO_WRITE
| flags
);
773 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
774 * The operation is sped up by checking the block status and only writing
775 * zeroes to the device if they currently do not return zeroes. Optional
776 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
779 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
781 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
784 int64_t target_size
, bytes
, offset
= 0;
785 BlockDriverState
*bs
= child
->bs
;
787 target_size
= bdrv_getlength(bs
);
788 if (target_size
< 0) {
793 bytes
= MIN(target_size
- offset
, BDRV_REQUEST_MAX_BYTES
);
797 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, NULL
, NULL
);
799 error_report("error getting block status at offset %" PRId64
": %s",
800 offset
, strerror(-ret
));
803 if (ret
& BDRV_BLOCK_ZERO
) {
807 ret
= bdrv_pwrite_zeroes(child
, offset
, bytes
, flags
);
809 error_report("error writing zeroes at offset %" PRId64
": %s",
810 offset
, strerror(-ret
));
817 int bdrv_preadv(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
821 ret
= bdrv_prwv_co(child
, offset
, qiov
, false, 0);
829 int bdrv_pread(BdrvChild
*child
, int64_t offset
, void *buf
, int bytes
)
833 .iov_base
= (void *)buf
,
841 qemu_iovec_init_external(&qiov
, &iov
, 1);
842 return bdrv_preadv(child
, offset
, &qiov
);
845 int bdrv_pwritev(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
849 ret
= bdrv_prwv_co(child
, offset
, qiov
, true, 0);
857 int bdrv_pwrite(BdrvChild
*child
, int64_t offset
, const void *buf
, int bytes
)
861 .iov_base
= (void *) buf
,
869 qemu_iovec_init_external(&qiov
, &iov
, 1);
870 return bdrv_pwritev(child
, offset
, &qiov
);
874 * Writes to the file and ensures that no writes are reordered across this
875 * request (acts as a barrier)
877 * Returns 0 on success, -errno in error cases.
879 int bdrv_pwrite_sync(BdrvChild
*child
, int64_t offset
,
880 const void *buf
, int count
)
884 ret
= bdrv_pwrite(child
, offset
, buf
, count
);
889 ret
= bdrv_flush(child
->bs
);
897 typedef struct CoroutineIOCompletion
{
898 Coroutine
*coroutine
;
900 } CoroutineIOCompletion
;
902 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
904 CoroutineIOCompletion
*co
= opaque
;
907 aio_co_wake(co
->coroutine
);
910 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
911 uint64_t offset
, uint64_t bytes
,
912 QEMUIOVector
*qiov
, int flags
)
914 BlockDriver
*drv
= bs
->drv
;
916 unsigned int nb_sectors
;
918 assert(!(flags
& ~BDRV_REQ_MASK
));
924 if (drv
->bdrv_co_preadv
) {
925 return drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
928 if (drv
->bdrv_aio_preadv
) {
930 CoroutineIOCompletion co
= {
931 .coroutine
= qemu_coroutine_self(),
934 acb
= drv
->bdrv_aio_preadv(bs
, offset
, bytes
, qiov
, flags
,
935 bdrv_co_io_em_complete
, &co
);
939 qemu_coroutine_yield();
944 sector_num
= offset
>> BDRV_SECTOR_BITS
;
945 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
947 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
948 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
949 assert((bytes
>> BDRV_SECTOR_BITS
) <= BDRV_REQUEST_MAX_SECTORS
);
950 assert(drv
->bdrv_co_readv
);
952 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
955 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
956 uint64_t offset
, uint64_t bytes
,
957 QEMUIOVector
*qiov
, int flags
)
959 BlockDriver
*drv
= bs
->drv
;
961 unsigned int nb_sectors
;
964 assert(!(flags
& ~BDRV_REQ_MASK
));
970 if (drv
->bdrv_co_pwritev
) {
971 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
,
972 flags
& bs
->supported_write_flags
);
973 flags
&= ~bs
->supported_write_flags
;
977 if (drv
->bdrv_aio_pwritev
) {
979 CoroutineIOCompletion co
= {
980 .coroutine
= qemu_coroutine_self(),
983 acb
= drv
->bdrv_aio_pwritev(bs
, offset
, bytes
, qiov
,
984 flags
& bs
->supported_write_flags
,
985 bdrv_co_io_em_complete
, &co
);
986 flags
&= ~bs
->supported_write_flags
;
990 qemu_coroutine_yield();
996 sector_num
= offset
>> BDRV_SECTOR_BITS
;
997 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
999 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1000 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1001 assert((bytes
>> BDRV_SECTOR_BITS
) <= BDRV_REQUEST_MAX_SECTORS
);
1003 assert(drv
->bdrv_co_writev
);
1004 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
,
1005 flags
& bs
->supported_write_flags
);
1006 flags
&= ~bs
->supported_write_flags
;
1009 if (ret
== 0 && (flags
& BDRV_REQ_FUA
)) {
1010 ret
= bdrv_co_flush(bs
);
1016 static int coroutine_fn
1017 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
1018 uint64_t bytes
, QEMUIOVector
*qiov
)
1020 BlockDriver
*drv
= bs
->drv
;
1026 if (!drv
->bdrv_co_pwritev_compressed
) {
1030 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1033 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
1034 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
)
1036 BlockDriverState
*bs
= child
->bs
;
1038 /* Perform I/O through a temporary buffer so that users who scribble over
1039 * their read buffer while the operation is in progress do not end up
1040 * modifying the image file. This is critical for zero-copy guest I/O
1041 * where anything might happen inside guest memory.
1043 void *bounce_buffer
;
1045 BlockDriver
*drv
= bs
->drv
;
1047 QEMUIOVector local_qiov
;
1048 int64_t cluster_offset
;
1049 int64_t cluster_bytes
;
1052 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1053 BDRV_REQUEST_MAX_BYTES
);
1054 unsigned int progress
= 0;
1060 /* FIXME We cannot require callers to have write permissions when all they
1061 * are doing is a read request. If we did things right, write permissions
1062 * would be obtained anyway, but internally by the copy-on-read code. As
1063 * long as it is implemented here rather than in a separate filter driver,
1064 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1065 * it could request permissions. Therefore we have to bypass the permission
1066 * system for the moment. */
1067 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1069 /* Cover entire cluster so no additional backing file I/O is required when
1070 * allocating cluster in the image file. Note that this value may exceed
1071 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1072 * is one reason we loop rather than doing it all at once.
1074 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
1075 skip_bytes
= offset
- cluster_offset
;
1077 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1078 cluster_offset
, cluster_bytes
);
1080 bounce_buffer
= qemu_try_blockalign(bs
,
1081 MIN(MIN(max_transfer
, cluster_bytes
),
1082 MAX_BOUNCE_BUFFER
));
1083 if (bounce_buffer
== NULL
) {
1088 while (cluster_bytes
) {
1091 ret
= bdrv_is_allocated(bs
, cluster_offset
,
1092 MIN(cluster_bytes
, max_transfer
), &pnum
);
1094 /* Safe to treat errors in querying allocation as if
1095 * unallocated; we'll probably fail again soon on the
1096 * read, but at least that will set a decent errno.
1098 pnum
= MIN(cluster_bytes
, max_transfer
);
1101 assert(skip_bytes
< pnum
);
1104 /* Must copy-on-read; use the bounce buffer */
1105 iov
.iov_base
= bounce_buffer
;
1106 iov
.iov_len
= pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1107 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1109 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1115 bdrv_debug_event(bs
, BLKDBG_COR_WRITE
);
1116 if (drv
->bdrv_co_pwrite_zeroes
&&
1117 buffer_is_zero(bounce_buffer
, pnum
)) {
1118 /* FIXME: Should we (perhaps conditionally) be setting
1119 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1120 * that still correctly reads as zero? */
1121 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
, 0);
1123 /* This does not change the data on the disk, it is not
1124 * necessary to flush even in cache=writethrough mode.
1126 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1131 /* It might be okay to ignore write errors for guest
1132 * requests. If this is a deliberate copy-on-read
1133 * then we don't want to ignore the error. Simply
1134 * report it in all cases.
1139 qemu_iovec_from_buf(qiov
, progress
, bounce_buffer
+ skip_bytes
,
1142 /* Read directly into the destination */
1143 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1144 qemu_iovec_concat(&local_qiov
, qiov
, progress
, pnum
- skip_bytes
);
1145 ret
= bdrv_driver_preadv(bs
, offset
+ progress
, local_qiov
.size
,
1147 qemu_iovec_destroy(&local_qiov
);
1153 cluster_offset
+= pnum
;
1154 cluster_bytes
-= pnum
;
1155 progress
+= pnum
- skip_bytes
;
1161 qemu_vfree(bounce_buffer
);
1166 * Forwards an already correctly aligned request to the BlockDriver. This
1167 * handles copy on read, zeroing after EOF, and fragmentation of large
1168 * reads; any other features must be implemented by the caller.
1170 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1171 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1172 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1174 BlockDriverState
*bs
= child
->bs
;
1175 int64_t total_bytes
, max_bytes
;
1177 uint64_t bytes_remaining
= bytes
;
1180 assert(is_power_of_2(align
));
1181 assert((offset
& (align
- 1)) == 0);
1182 assert((bytes
& (align
- 1)) == 0);
1183 assert(!qiov
|| bytes
== qiov
->size
);
1184 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1185 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1188 /* TODO: We would need a per-BDS .supported_read_flags and
1189 * potential fallback support, if we ever implement any read flags
1190 * to pass through to drivers. For now, there aren't any
1191 * passthrough flags. */
1192 assert(!(flags
& ~(BDRV_REQ_NO_SERIALISING
| BDRV_REQ_COPY_ON_READ
)));
1194 /* Handle Copy on Read and associated serialisation */
1195 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1196 /* If we touch the same cluster it counts as an overlap. This
1197 * guarantees that allocating writes will be serialized and not race
1198 * with each other for the same cluster. For example, in copy-on-read
1199 * it ensures that the CoR read and write operations are atomic and
1200 * guest writes cannot interleave between them. */
1201 mark_request_serialising(req
, bdrv_get_cluster_size(bs
));
1204 if (!(flags
& BDRV_REQ_NO_SERIALISING
)) {
1205 wait_serialising_requests(req
);
1208 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1211 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &pnum
);
1216 if (!ret
|| pnum
!= bytes
) {
1217 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
, qiov
);
1222 /* Forward the request to the BlockDriver, possibly fragmenting it */
1223 total_bytes
= bdrv_getlength(bs
);
1224 if (total_bytes
< 0) {
1229 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1230 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1231 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, 0);
1235 while (bytes_remaining
) {
1239 QEMUIOVector local_qiov
;
1241 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1243 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1244 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1246 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1247 num
, &local_qiov
, 0);
1249 qemu_iovec_destroy(&local_qiov
);
1251 num
= bytes_remaining
;
1252 ret
= qemu_iovec_memset(qiov
, bytes
- bytes_remaining
, 0,
1258 bytes_remaining
-= num
;
1262 return ret
< 0 ? ret
: 0;
1266 * Handle a read request in coroutine context
1268 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1269 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1270 BdrvRequestFlags flags
)
1272 BlockDriverState
*bs
= child
->bs
;
1273 BlockDriver
*drv
= bs
->drv
;
1274 BdrvTrackedRequest req
;
1276 uint64_t align
= bs
->bl
.request_alignment
;
1277 uint8_t *head_buf
= NULL
;
1278 uint8_t *tail_buf
= NULL
;
1279 QEMUIOVector local_qiov
;
1280 bool use_local_qiov
= false;
1283 trace_bdrv_co_preadv(child
->bs
, offset
, bytes
, flags
);
1289 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1294 bdrv_inc_in_flight(bs
);
1296 /* Don't do copy-on-read if we read data before write operation */
1297 if (atomic_read(&bs
->copy_on_read
) && !(flags
& BDRV_REQ_NO_SERIALISING
)) {
1298 flags
|= BDRV_REQ_COPY_ON_READ
;
1301 /* Align read if necessary by padding qiov */
1302 if (offset
& (align
- 1)) {
1303 head_buf
= qemu_blockalign(bs
, align
);
1304 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1305 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1306 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1307 use_local_qiov
= true;
1309 bytes
+= offset
& (align
- 1);
1310 offset
= offset
& ~(align
- 1);
1313 if ((offset
+ bytes
) & (align
- 1)) {
1314 if (!use_local_qiov
) {
1315 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1316 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1317 use_local_qiov
= true;
1319 tail_buf
= qemu_blockalign(bs
, align
);
1320 qemu_iovec_add(&local_qiov
, tail_buf
,
1321 align
- ((offset
+ bytes
) & (align
- 1)));
1323 bytes
= ROUND_UP(bytes
, align
);
1326 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1327 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
, align
,
1328 use_local_qiov
? &local_qiov
: qiov
,
1330 tracked_request_end(&req
);
1331 bdrv_dec_in_flight(bs
);
1333 if (use_local_qiov
) {
1334 qemu_iovec_destroy(&local_qiov
);
1335 qemu_vfree(head_buf
);
1336 qemu_vfree(tail_buf
);
1342 static int coroutine_fn
bdrv_co_do_readv(BdrvChild
*child
,
1343 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
,
1344 BdrvRequestFlags flags
)
1346 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
1350 return bdrv_co_preadv(child
, sector_num
<< BDRV_SECTOR_BITS
,
1351 nb_sectors
<< BDRV_SECTOR_BITS
, qiov
, flags
);
1354 int coroutine_fn
bdrv_co_readv(BdrvChild
*child
, int64_t sector_num
,
1355 int nb_sectors
, QEMUIOVector
*qiov
)
1357 return bdrv_co_do_readv(child
, sector_num
, nb_sectors
, qiov
, 0);
1360 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1361 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
1363 BlockDriver
*drv
= bs
->drv
;
1365 struct iovec iov
= {0};
1367 bool need_flush
= false;
1371 int max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
, INT_MAX
);
1372 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1373 bs
->bl
.request_alignment
);
1374 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1380 assert(alignment
% bs
->bl
.request_alignment
== 0);
1381 head
= offset
% alignment
;
1382 tail
= (offset
+ bytes
) % alignment
;
1383 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1384 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1386 while (bytes
> 0 && !ret
) {
1389 /* Align request. Block drivers can expect the "bulk" of the request
1390 * to be aligned, and that unaligned requests do not cross cluster
1394 /* Make a small request up to the first aligned sector. For
1395 * convenience, limit this request to max_transfer even if
1396 * we don't need to fall back to writes. */
1397 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1398 head
= (head
+ num
) % alignment
;
1399 assert(num
< max_write_zeroes
);
1400 } else if (tail
&& num
> alignment
) {
1401 /* Shorten the request to the last aligned sector. */
1405 /* limit request size */
1406 if (num
> max_write_zeroes
) {
1407 num
= max_write_zeroes
;
1411 /* First try the efficient write zeroes operation */
1412 if (drv
->bdrv_co_pwrite_zeroes
) {
1413 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1414 flags
& bs
->supported_zero_flags
);
1415 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1416 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1420 assert(!bs
->supported_zero_flags
);
1423 if (ret
== -ENOTSUP
) {
1424 /* Fall back to bounce buffer if write zeroes is unsupported */
1425 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1427 if ((flags
& BDRV_REQ_FUA
) &&
1428 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1429 /* No need for bdrv_driver_pwrite() to do a fallback
1430 * flush on each chunk; use just one at the end */
1431 write_flags
&= ~BDRV_REQ_FUA
;
1434 num
= MIN(num
, max_transfer
);
1436 if (iov
.iov_base
== NULL
) {
1437 iov
.iov_base
= qemu_try_blockalign(bs
, num
);
1438 if (iov
.iov_base
== NULL
) {
1442 memset(iov
.iov_base
, 0, num
);
1444 qemu_iovec_init_external(&qiov
, &iov
, 1);
1446 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, write_flags
);
1448 /* Keep bounce buffer around if it is big enough for all
1449 * all future requests.
1451 if (num
< max_transfer
) {
1452 qemu_vfree(iov
.iov_base
);
1453 iov
.iov_base
= NULL
;
1462 if (ret
== 0 && need_flush
) {
1463 ret
= bdrv_co_flush(bs
);
1465 qemu_vfree(iov
.iov_base
);
1470 * Forwards an already correctly aligned write request to the BlockDriver,
1471 * after possibly fragmenting it.
1473 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
1474 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1475 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1477 BlockDriverState
*bs
= child
->bs
;
1478 BlockDriver
*drv
= bs
->drv
;
1482 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1483 uint64_t bytes_remaining
= bytes
;
1490 if (bdrv_has_readonly_bitmaps(bs
)) {
1494 assert(is_power_of_2(align
));
1495 assert((offset
& (align
- 1)) == 0);
1496 assert((bytes
& (align
- 1)) == 0);
1497 assert(!qiov
|| bytes
== qiov
->size
);
1498 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1499 assert(!(flags
& ~BDRV_REQ_MASK
));
1500 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1503 waited
= wait_serialising_requests(req
);
1504 assert(!waited
|| !req
->serialising
);
1505 assert(req
->overlap_offset
<= offset
);
1506 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1507 assert(child
->perm
& BLK_PERM_WRITE
);
1508 assert(end_sector
<= bs
->total_sectors
|| child
->perm
& BLK_PERM_RESIZE
);
1510 ret
= notifier_with_return_list_notify(&bs
->before_write_notifiers
, req
);
1512 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1513 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1514 qemu_iovec_is_zero(qiov
)) {
1515 flags
|= BDRV_REQ_ZERO_WRITE
;
1516 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1517 flags
|= BDRV_REQ_MAY_UNMAP
;
1522 /* Do nothing, write notifier decided to fail this request */
1523 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1524 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
1525 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
1526 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
1527 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1528 } else if (bytes
<= max_transfer
) {
1529 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1530 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1532 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1533 while (bytes_remaining
) {
1534 int num
= MIN(bytes_remaining
, max_transfer
);
1535 QEMUIOVector local_qiov
;
1536 int local_flags
= flags
;
1539 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
1540 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1541 /* If FUA is going to be emulated by flush, we only
1542 * need to flush on the last iteration */
1543 local_flags
&= ~BDRV_REQ_FUA
;
1545 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1546 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1548 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
1549 num
, &local_qiov
, local_flags
);
1550 qemu_iovec_destroy(&local_qiov
);
1554 bytes_remaining
-= num
;
1557 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
1559 atomic_inc(&bs
->write_gen
);
1560 bdrv_set_dirty(bs
, offset
, bytes
);
1562 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1565 bs
->total_sectors
= MAX(bs
->total_sectors
, end_sector
);
1572 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
1575 BdrvRequestFlags flags
,
1576 BdrvTrackedRequest
*req
)
1578 BlockDriverState
*bs
= child
->bs
;
1579 uint8_t *buf
= NULL
;
1580 QEMUIOVector local_qiov
;
1582 uint64_t align
= bs
->bl
.request_alignment
;
1583 unsigned int head_padding_bytes
, tail_padding_bytes
;
1586 head_padding_bytes
= offset
& (align
- 1);
1587 tail_padding_bytes
= (align
- (offset
+ bytes
)) & (align
- 1);
1590 assert(flags
& BDRV_REQ_ZERO_WRITE
);
1591 if (head_padding_bytes
|| tail_padding_bytes
) {
1592 buf
= qemu_blockalign(bs
, align
);
1593 iov
= (struct iovec
) {
1597 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1599 if (head_padding_bytes
) {
1600 uint64_t zero_bytes
= MIN(bytes
, align
- head_padding_bytes
);
1602 /* RMW the unaligned part before head. */
1603 mark_request_serialising(req
, align
);
1604 wait_serialising_requests(req
);
1605 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1606 ret
= bdrv_aligned_preadv(child
, req
, offset
& ~(align
- 1), align
,
1607 align
, &local_qiov
, 0);
1611 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1613 memset(buf
+ head_padding_bytes
, 0, zero_bytes
);
1614 ret
= bdrv_aligned_pwritev(child
, req
, offset
& ~(align
- 1), align
,
1616 flags
& ~BDRV_REQ_ZERO_WRITE
);
1620 offset
+= zero_bytes
;
1621 bytes
-= zero_bytes
;
1624 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1625 if (bytes
>= align
) {
1626 /* Write the aligned part in the middle. */
1627 uint64_t aligned_bytes
= bytes
& ~(align
- 1);
1628 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
1633 bytes
-= aligned_bytes
;
1634 offset
+= aligned_bytes
;
1637 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1639 assert(align
== tail_padding_bytes
+ bytes
);
1640 /* RMW the unaligned part after tail. */
1641 mark_request_serialising(req
, align
);
1642 wait_serialising_requests(req
);
1643 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1644 ret
= bdrv_aligned_preadv(child
, req
, offset
, align
,
1645 align
, &local_qiov
, 0);
1649 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1651 memset(buf
, 0, bytes
);
1652 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
1653 &local_qiov
, flags
& ~BDRV_REQ_ZERO_WRITE
);
1662 * Handle a write request in coroutine context
1664 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
1665 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1666 BdrvRequestFlags flags
)
1668 BlockDriverState
*bs
= child
->bs
;
1669 BdrvTrackedRequest req
;
1670 uint64_t align
= bs
->bl
.request_alignment
;
1671 uint8_t *head_buf
= NULL
;
1672 uint8_t *tail_buf
= NULL
;
1673 QEMUIOVector local_qiov
;
1674 bool use_local_qiov
= false;
1677 trace_bdrv_co_pwritev(child
->bs
, offset
, bytes
, flags
);
1682 if (bs
->read_only
) {
1685 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1687 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1692 bdrv_inc_in_flight(bs
);
1694 * Align write if necessary by performing a read-modify-write cycle.
1695 * Pad qiov with the read parts and be sure to have a tracked request not
1696 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1698 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
1700 if (flags
& BDRV_REQ_ZERO_WRITE
) {
1701 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
1705 if (offset
& (align
- 1)) {
1706 QEMUIOVector head_qiov
;
1707 struct iovec head_iov
;
1709 mark_request_serialising(&req
, align
);
1710 wait_serialising_requests(&req
);
1712 head_buf
= qemu_blockalign(bs
, align
);
1713 head_iov
= (struct iovec
) {
1714 .iov_base
= head_buf
,
1717 qemu_iovec_init_external(&head_qiov
, &head_iov
, 1);
1719 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1720 ret
= bdrv_aligned_preadv(child
, &req
, offset
& ~(align
- 1), align
,
1721 align
, &head_qiov
, 0);
1725 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1727 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1728 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1729 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1730 use_local_qiov
= true;
1732 bytes
+= offset
& (align
- 1);
1733 offset
= offset
& ~(align
- 1);
1735 /* We have read the tail already if the request is smaller
1736 * than one aligned block.
1738 if (bytes
< align
) {
1739 qemu_iovec_add(&local_qiov
, head_buf
+ bytes
, align
- bytes
);
1744 if ((offset
+ bytes
) & (align
- 1)) {
1745 QEMUIOVector tail_qiov
;
1746 struct iovec tail_iov
;
1750 mark_request_serialising(&req
, align
);
1751 waited
= wait_serialising_requests(&req
);
1752 assert(!waited
|| !use_local_qiov
);
1754 tail_buf
= qemu_blockalign(bs
, align
);
1755 tail_iov
= (struct iovec
) {
1756 .iov_base
= tail_buf
,
1759 qemu_iovec_init_external(&tail_qiov
, &tail_iov
, 1);
1761 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1762 ret
= bdrv_aligned_preadv(child
, &req
, (offset
+ bytes
) & ~(align
- 1),
1763 align
, align
, &tail_qiov
, 0);
1767 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1769 if (!use_local_qiov
) {
1770 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1771 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1772 use_local_qiov
= true;
1775 tail_bytes
= (offset
+ bytes
) & (align
- 1);
1776 qemu_iovec_add(&local_qiov
, tail_buf
+ tail_bytes
, align
- tail_bytes
);
1778 bytes
= ROUND_UP(bytes
, align
);
1781 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
1782 use_local_qiov
? &local_qiov
: qiov
,
1787 if (use_local_qiov
) {
1788 qemu_iovec_destroy(&local_qiov
);
1790 qemu_vfree(head_buf
);
1791 qemu_vfree(tail_buf
);
1793 tracked_request_end(&req
);
1794 bdrv_dec_in_flight(bs
);
1798 static int coroutine_fn
bdrv_co_do_writev(BdrvChild
*child
,
1799 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
,
1800 BdrvRequestFlags flags
)
1802 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
1806 return bdrv_co_pwritev(child
, sector_num
<< BDRV_SECTOR_BITS
,
1807 nb_sectors
<< BDRV_SECTOR_BITS
, qiov
, flags
);
1810 int coroutine_fn
bdrv_co_writev(BdrvChild
*child
, int64_t sector_num
,
1811 int nb_sectors
, QEMUIOVector
*qiov
)
1813 return bdrv_co_do_writev(child
, sector_num
, nb_sectors
, qiov
, 0);
1816 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
1817 int bytes
, BdrvRequestFlags flags
)
1819 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
1821 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
1822 flags
&= ~BDRV_REQ_MAY_UNMAP
;
1825 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
1826 BDRV_REQ_ZERO_WRITE
| flags
);
1830 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1832 int bdrv_flush_all(void)
1834 BdrvNextIterator it
;
1835 BlockDriverState
*bs
= NULL
;
1838 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
1839 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
1842 aio_context_acquire(aio_context
);
1843 ret
= bdrv_flush(bs
);
1844 if (ret
< 0 && !result
) {
1847 aio_context_release(aio_context
);
1854 typedef struct BdrvCoBlockStatusData
{
1855 BlockDriverState
*bs
;
1856 BlockDriverState
*base
;
1862 BlockDriverState
**file
;
1865 } BdrvCoBlockStatusData
;
1867 int coroutine_fn
bdrv_co_block_status_from_file(BlockDriverState
*bs
,
1873 BlockDriverState
**file
)
1875 assert(bs
->file
&& bs
->file
->bs
);
1878 *file
= bs
->file
->bs
;
1879 return BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
1882 int coroutine_fn
bdrv_co_block_status_from_backing(BlockDriverState
*bs
,
1888 BlockDriverState
**file
)
1890 assert(bs
->backing
&& bs
->backing
->bs
);
1893 *file
= bs
->backing
->bs
;
1894 return BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
1898 * Returns the allocation status of the specified sectors.
1899 * Drivers not implementing the functionality are assumed to not support
1900 * backing files, hence all their sectors are reported as allocated.
1902 * If 'want_zero' is true, the caller is querying for mapping
1903 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
1904 * _ZERO where possible; otherwise, the result favors larger 'pnum',
1905 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
1907 * If 'offset' is beyond the end of the disk image the return value is
1908 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
1910 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
1911 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
1912 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
1914 * 'pnum' is set to the number of bytes (including and immediately
1915 * following the specified offset) that are easily known to be in the
1916 * same allocated/unallocated state. Note that a second call starting
1917 * at the original offset plus returned pnum may have the same status.
1918 * The returned value is non-zero on success except at end-of-file.
1920 * Returns negative errno on failure. Otherwise, if the
1921 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
1922 * set to the host mapping and BDS corresponding to the guest offset.
1924 static int coroutine_fn
bdrv_co_block_status(BlockDriverState
*bs
,
1926 int64_t offset
, int64_t bytes
,
1927 int64_t *pnum
, int64_t *map
,
1928 BlockDriverState
**file
)
1931 int64_t n
; /* bytes */
1933 int64_t local_map
= 0;
1934 BlockDriverState
*local_file
= NULL
;
1935 int64_t aligned_offset
, aligned_bytes
;
1940 total_size
= bdrv_getlength(bs
);
1941 if (total_size
< 0) {
1946 if (offset
>= total_size
) {
1947 ret
= BDRV_BLOCK_EOF
;
1955 n
= total_size
- offset
;
1960 /* Must be non-NULL or bdrv_getlength() would have failed */
1962 if (!bs
->drv
->bdrv_co_block_status
) {
1964 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
1965 if (offset
+ bytes
== total_size
) {
1966 ret
|= BDRV_BLOCK_EOF
;
1968 if (bs
->drv
->protocol_name
) {
1969 ret
|= BDRV_BLOCK_OFFSET_VALID
;
1976 bdrv_inc_in_flight(bs
);
1978 /* Round out to request_alignment boundaries */
1979 align
= bs
->bl
.request_alignment
;
1980 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
1981 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
1983 ret
= bs
->drv
->bdrv_co_block_status(bs
, want_zero
, aligned_offset
,
1984 aligned_bytes
, pnum
, &local_map
,
1992 * The driver's result must be a non-zero multiple of request_alignment.
1993 * Clamp pnum and adjust map to original request.
1995 assert(*pnum
&& QEMU_IS_ALIGNED(*pnum
, align
) &&
1996 align
> offset
- aligned_offset
);
1997 *pnum
-= offset
- aligned_offset
;
1998 if (*pnum
> bytes
) {
2001 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2002 local_map
+= offset
- aligned_offset
;
2005 if (ret
& BDRV_BLOCK_RAW
) {
2006 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2007 ret
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2008 *pnum
, pnum
, &local_map
, &local_file
);
2012 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2013 ret
|= BDRV_BLOCK_ALLOCATED
;
2014 } else if (want_zero
) {
2015 if (bdrv_unallocated_blocks_are_zero(bs
)) {
2016 ret
|= BDRV_BLOCK_ZERO
;
2017 } else if (bs
->backing
) {
2018 BlockDriverState
*bs2
= bs
->backing
->bs
;
2019 int64_t size2
= bdrv_getlength(bs2
);
2021 if (size2
>= 0 && offset
>= size2
) {
2022 ret
|= BDRV_BLOCK_ZERO
;
2027 if (want_zero
&& local_file
&& local_file
!= bs
&&
2028 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2029 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2033 ret2
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2034 *pnum
, &file_pnum
, NULL
, NULL
);
2036 /* Ignore errors. This is just providing extra information, it
2037 * is useful but not necessary.
2039 if (ret2
& BDRV_BLOCK_EOF
&&
2040 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2042 * It is valid for the format block driver to read
2043 * beyond the end of the underlying file's current
2044 * size; such areas read as zero.
2046 ret
|= BDRV_BLOCK_ZERO
;
2048 /* Limit request to the range reported by the protocol driver */
2050 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2056 bdrv_dec_in_flight(bs
);
2057 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2058 ret
|= BDRV_BLOCK_EOF
;
2070 static int coroutine_fn
bdrv_co_block_status_above(BlockDriverState
*bs
,
2071 BlockDriverState
*base
,
2077 BlockDriverState
**file
)
2079 BlockDriverState
*p
;
2084 for (p
= bs
; p
!= base
; p
= backing_bs(p
)) {
2085 ret
= bdrv_co_block_status(p
, want_zero
, offset
, bytes
, pnum
, map
,
2090 if (ret
& BDRV_BLOCK_ZERO
&& ret
& BDRV_BLOCK_EOF
&& !first
) {
2092 * Reading beyond the end of the file continues to read
2093 * zeroes, but we can only widen the result to the
2094 * unallocated length we learned from an earlier
2099 if (ret
& (BDRV_BLOCK_ZERO
| BDRV_BLOCK_DATA
)) {
2102 /* [offset, pnum] unallocated on this layer, which could be only
2103 * the first part of [offset, bytes]. */
2104 bytes
= MIN(bytes
, *pnum
);
2110 /* Coroutine wrapper for bdrv_block_status_above() */
2111 static void coroutine_fn
bdrv_block_status_above_co_entry(void *opaque
)
2113 BdrvCoBlockStatusData
*data
= opaque
;
2115 data
->ret
= bdrv_co_block_status_above(data
->bs
, data
->base
,
2117 data
->offset
, data
->bytes
,
2118 data
->pnum
, data
->map
, data
->file
);
2123 * Synchronous wrapper around bdrv_co_block_status_above().
2125 * See bdrv_co_block_status_above() for details.
2127 static int bdrv_common_block_status_above(BlockDriverState
*bs
,
2128 BlockDriverState
*base
,
2129 bool want_zero
, int64_t offset
,
2130 int64_t bytes
, int64_t *pnum
,
2132 BlockDriverState
**file
)
2135 BdrvCoBlockStatusData data
= {
2138 .want_zero
= want_zero
,
2147 if (qemu_in_coroutine()) {
2148 /* Fast-path if already in coroutine context */
2149 bdrv_block_status_above_co_entry(&data
);
2151 co
= qemu_coroutine_create(bdrv_block_status_above_co_entry
, &data
);
2152 bdrv_coroutine_enter(bs
, co
);
2153 BDRV_POLL_WHILE(bs
, !data
.done
);
2158 int bdrv_block_status_above(BlockDriverState
*bs
, BlockDriverState
*base
,
2159 int64_t offset
, int64_t bytes
, int64_t *pnum
,
2160 int64_t *map
, BlockDriverState
**file
)
2162 return bdrv_common_block_status_above(bs
, base
, true, offset
, bytes
,
2166 int bdrv_block_status(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2167 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2169 return bdrv_block_status_above(bs
, backing_bs(bs
),
2170 offset
, bytes
, pnum
, map
, file
);
2173 int coroutine_fn
bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
,
2174 int64_t bytes
, int64_t *pnum
)
2179 ret
= bdrv_common_block_status_above(bs
, backing_bs(bs
), false, offset
,
2180 bytes
, pnum
? pnum
: &dummy
, NULL
,
2185 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2189 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2191 * Return true if (a prefix of) the given range is allocated in any image
2192 * between BASE and TOP (inclusive). BASE can be NULL to check if the given
2193 * offset is allocated in any image of the chain. Return false otherwise,
2194 * or negative errno on failure.
2196 * 'pnum' is set to the number of bytes (including and immediately
2197 * following the specified offset) that are known to be in the same
2198 * allocated/unallocated state. Note that a subsequent call starting
2199 * at 'offset + *pnum' may return the same allocation status (in other
2200 * words, the result is not necessarily the maximum possible range);
2201 * but 'pnum' will only be 0 when end of file is reached.
2204 int bdrv_is_allocated_above(BlockDriverState
*top
,
2205 BlockDriverState
*base
,
2206 int64_t offset
, int64_t bytes
, int64_t *pnum
)
2208 BlockDriverState
*intermediate
;
2213 while (intermediate
&& intermediate
!= base
) {
2217 ret
= bdrv_is_allocated(intermediate
, offset
, bytes
, &pnum_inter
);
2226 size_inter
= bdrv_getlength(intermediate
);
2227 if (size_inter
< 0) {
2230 if (n
> pnum_inter
&&
2231 (intermediate
== top
|| offset
+ pnum_inter
< size_inter
)) {
2235 intermediate
= backing_bs(intermediate
);
2242 typedef struct BdrvVmstateCo
{
2243 BlockDriverState
*bs
;
2250 static int coroutine_fn
2251 bdrv_co_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
2254 BlockDriver
*drv
= bs
->drv
;
2257 bdrv_inc_in_flight(bs
);
2261 } else if (drv
->bdrv_load_vmstate
) {
2263 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
2265 ret
= drv
->bdrv_save_vmstate(bs
, qiov
, pos
);
2267 } else if (bs
->file
) {
2268 ret
= bdrv_co_rw_vmstate(bs
->file
->bs
, qiov
, pos
, is_read
);
2271 bdrv_dec_in_flight(bs
);
2275 static void coroutine_fn
bdrv_co_rw_vmstate_entry(void *opaque
)
2277 BdrvVmstateCo
*co
= opaque
;
2278 co
->ret
= bdrv_co_rw_vmstate(co
->bs
, co
->qiov
, co
->pos
, co
->is_read
);
2282 bdrv_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
2285 if (qemu_in_coroutine()) {
2286 return bdrv_co_rw_vmstate(bs
, qiov
, pos
, is_read
);
2288 BdrvVmstateCo data
= {
2293 .ret
= -EINPROGRESS
,
2295 Coroutine
*co
= qemu_coroutine_create(bdrv_co_rw_vmstate_entry
, &data
);
2297 bdrv_coroutine_enter(bs
, co
);
2298 BDRV_POLL_WHILE(bs
, data
.ret
== -EINPROGRESS
);
2303 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2304 int64_t pos
, int size
)
2307 struct iovec iov
= {
2308 .iov_base
= (void *) buf
,
2313 qemu_iovec_init_external(&qiov
, &iov
, 1);
2315 ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2323 int bdrv_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2325 return bdrv_rw_vmstate(bs
, qiov
, pos
, false);
2328 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2329 int64_t pos
, int size
)
2332 struct iovec iov
= {
2338 qemu_iovec_init_external(&qiov
, &iov
, 1);
2339 ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2347 int bdrv_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2349 return bdrv_rw_vmstate(bs
, qiov
, pos
, true);
2352 /**************************************************************/
2355 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2358 bdrv_aio_cancel_async(acb
);
2359 while (acb
->refcnt
> 1) {
2360 if (acb
->aiocb_info
->get_aio_context
) {
2361 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2362 } else if (acb
->bs
) {
2363 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2364 * assert that we're not using an I/O thread. Thread-safe
2365 * code should use bdrv_aio_cancel_async exclusively.
2367 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2368 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2373 qemu_aio_unref(acb
);
2376 /* Async version of aio cancel. The caller is not blocked if the acb implements
2377 * cancel_async, otherwise we do nothing and let the request normally complete.
2378 * In either case the completion callback must be called. */
2379 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2381 if (acb
->aiocb_info
->cancel_async
) {
2382 acb
->aiocb_info
->cancel_async(acb
);
2386 /**************************************************************/
2387 /* Coroutine block device emulation */
2389 typedef struct FlushCo
{
2390 BlockDriverState
*bs
;
2395 static void coroutine_fn
bdrv_flush_co_entry(void *opaque
)
2397 FlushCo
*rwco
= opaque
;
2399 rwco
->ret
= bdrv_co_flush(rwco
->bs
);
2402 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2407 bdrv_inc_in_flight(bs
);
2409 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2414 qemu_co_mutex_lock(&bs
->reqs_lock
);
2415 current_gen
= atomic_read(&bs
->write_gen
);
2417 /* Wait until any previous flushes are completed */
2418 while (bs
->active_flush_req
) {
2419 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2422 /* Flushes reach this point in nondecreasing current_gen order. */
2423 bs
->active_flush_req
= true;
2424 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2426 /* Write back all layers by calling one driver function */
2427 if (bs
->drv
->bdrv_co_flush
) {
2428 ret
= bs
->drv
->bdrv_co_flush(bs
);
2432 /* Write back cached data to the OS even with cache=unsafe */
2433 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_OS
);
2434 if (bs
->drv
->bdrv_co_flush_to_os
) {
2435 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2441 /* But don't actually force it to the disk with cache=unsafe */
2442 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2446 /* Check if we really need to flush anything */
2447 if (bs
->flushed_gen
== current_gen
) {
2451 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_DISK
);
2453 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2454 * (even in case of apparent success) */
2458 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2459 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2460 } else if (bs
->drv
->bdrv_aio_flush
) {
2462 CoroutineIOCompletion co
= {
2463 .coroutine
= qemu_coroutine_self(),
2466 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2470 qemu_coroutine_yield();
2475 * Some block drivers always operate in either writethrough or unsafe
2476 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2477 * know how the server works (because the behaviour is hardcoded or
2478 * depends on server-side configuration), so we can't ensure that
2479 * everything is safe on disk. Returning an error doesn't work because
2480 * that would break guests even if the server operates in writethrough
2483 * Let's hope the user knows what he's doing.
2492 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2493 * in the case of cache=unsafe, so there are no useless flushes.
2496 ret
= bs
->file
? bdrv_co_flush(bs
->file
->bs
) : 0;
2498 /* Notify any pending flushes that we have completed */
2500 bs
->flushed_gen
= current_gen
;
2503 qemu_co_mutex_lock(&bs
->reqs_lock
);
2504 bs
->active_flush_req
= false;
2505 /* Return value is ignored - it's ok if wait queue is empty */
2506 qemu_co_queue_next(&bs
->flush_queue
);
2507 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2510 bdrv_dec_in_flight(bs
);
2514 int bdrv_flush(BlockDriverState
*bs
)
2517 FlushCo flush_co
= {
2522 if (qemu_in_coroutine()) {
2523 /* Fast-path if already in coroutine context */
2524 bdrv_flush_co_entry(&flush_co
);
2526 co
= qemu_coroutine_create(bdrv_flush_co_entry
, &flush_co
);
2527 bdrv_coroutine_enter(bs
, co
);
2528 BDRV_POLL_WHILE(bs
, flush_co
.ret
== NOT_DONE
);
2531 return flush_co
.ret
;
2534 typedef struct DiscardCo
{
2535 BlockDriverState
*bs
;
2540 static void coroutine_fn
bdrv_pdiscard_co_entry(void *opaque
)
2542 DiscardCo
*rwco
= opaque
;
2544 rwco
->ret
= bdrv_co_pdiscard(rwco
->bs
, rwco
->offset
, rwco
->bytes
);
2547 int coroutine_fn
bdrv_co_pdiscard(BlockDriverState
*bs
, int64_t offset
,
2550 BdrvTrackedRequest req
;
2551 int max_pdiscard
, ret
;
2552 int head
, tail
, align
;
2558 if (bdrv_has_readonly_bitmaps(bs
)) {
2562 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
2565 } else if (bs
->read_only
) {
2568 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
2570 /* Do nothing if disabled. */
2571 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2575 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2579 /* Discard is advisory, but some devices track and coalesce
2580 * unaligned requests, so we must pass everything down rather than
2581 * round here. Still, most devices will just silently ignore
2582 * unaligned requests (by returning -ENOTSUP), so we must fragment
2583 * the request accordingly. */
2584 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
2585 assert(align
% bs
->bl
.request_alignment
== 0);
2586 head
= offset
% align
;
2587 tail
= (offset
+ bytes
) % align
;
2589 bdrv_inc_in_flight(bs
);
2590 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
2592 ret
= notifier_with_return_list_notify(&bs
->before_write_notifiers
, &req
);
2597 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT_MAX
),
2599 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
2605 /* Make small requests to get to alignment boundaries. */
2606 num
= MIN(bytes
, align
- head
);
2607 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
2608 num
%= bs
->bl
.request_alignment
;
2610 head
= (head
+ num
) % align
;
2611 assert(num
< max_pdiscard
);
2614 /* Shorten the request to the last aligned cluster. */
2616 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
2617 tail
> bs
->bl
.request_alignment
) {
2618 tail
%= bs
->bl
.request_alignment
;
2622 /* limit request size */
2623 if (num
> max_pdiscard
) {
2631 if (bs
->drv
->bdrv_co_pdiscard
) {
2632 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
2635 CoroutineIOCompletion co
= {
2636 .coroutine
= qemu_coroutine_self(),
2639 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
2640 bdrv_co_io_em_complete
, &co
);
2645 qemu_coroutine_yield();
2649 if (ret
&& ret
!= -ENOTSUP
) {
2658 atomic_inc(&bs
->write_gen
);
2659 bdrv_set_dirty(bs
, req
.offset
, req
.bytes
);
2660 tracked_request_end(&req
);
2661 bdrv_dec_in_flight(bs
);
2665 int bdrv_pdiscard(BlockDriverState
*bs
, int64_t offset
, int bytes
)
2675 if (qemu_in_coroutine()) {
2676 /* Fast-path if already in coroutine context */
2677 bdrv_pdiscard_co_entry(&rwco
);
2679 co
= qemu_coroutine_create(bdrv_pdiscard_co_entry
, &rwco
);
2680 bdrv_coroutine_enter(bs
, co
);
2681 BDRV_POLL_WHILE(bs
, rwco
.ret
== NOT_DONE
);
2687 int bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
2689 BlockDriver
*drv
= bs
->drv
;
2690 CoroutineIOCompletion co
= {
2691 .coroutine
= qemu_coroutine_self(),
2695 bdrv_inc_in_flight(bs
);
2696 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
2701 if (drv
->bdrv_co_ioctl
) {
2702 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
2704 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
2709 qemu_coroutine_yield();
2712 bdrv_dec_in_flight(bs
);
2716 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2718 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
2721 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
2723 return memset(qemu_blockalign(bs
, size
), 0, size
);
2726 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
2728 size_t align
= bdrv_opt_mem_align(bs
);
2730 /* Ensure that NULL is never returned on success */
2736 return qemu_try_memalign(align
, size
);
2739 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
2741 void *mem
= qemu_try_blockalign(bs
, size
);
2744 memset(mem
, 0, size
);
2751 * Check if all memory in this vector is sector aligned.
2753 bool bdrv_qiov_is_aligned(BlockDriverState
*bs
, QEMUIOVector
*qiov
)
2756 size_t alignment
= bdrv_min_mem_align(bs
);
2758 for (i
= 0; i
< qiov
->niov
; i
++) {
2759 if ((uintptr_t) qiov
->iov
[i
].iov_base
% alignment
) {
2762 if (qiov
->iov
[i
].iov_len
% alignment
) {
2770 void bdrv_add_before_write_notifier(BlockDriverState
*bs
,
2771 NotifierWithReturn
*notifier
)
2773 notifier_with_return_list_add(&bs
->before_write_notifiers
, notifier
);
2776 void bdrv_io_plug(BlockDriverState
*bs
)
2780 QLIST_FOREACH(child
, &bs
->children
, next
) {
2781 bdrv_io_plug(child
->bs
);
2784 if (atomic_fetch_inc(&bs
->io_plugged
) == 0) {
2785 BlockDriver
*drv
= bs
->drv
;
2786 if (drv
&& drv
->bdrv_io_plug
) {
2787 drv
->bdrv_io_plug(bs
);
2792 void bdrv_io_unplug(BlockDriverState
*bs
)
2796 assert(bs
->io_plugged
);
2797 if (atomic_fetch_dec(&bs
->io_plugged
) == 1) {
2798 BlockDriver
*drv
= bs
->drv
;
2799 if (drv
&& drv
->bdrv_io_unplug
) {
2800 drv
->bdrv_io_unplug(bs
);
2804 QLIST_FOREACH(child
, &bs
->children
, next
) {
2805 bdrv_io_unplug(child
->bs
);
2809 void bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
)
2813 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
2814 bs
->drv
->bdrv_register_buf(bs
, host
, size
);
2816 QLIST_FOREACH(child
, &bs
->children
, next
) {
2817 bdrv_register_buf(child
->bs
, host
, size
);
2821 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
)
2825 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
2826 bs
->drv
->bdrv_unregister_buf(bs
, host
);
2828 QLIST_FOREACH(child
, &bs
->children
, next
) {
2829 bdrv_unregister_buf(child
->bs
, host
);