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/blockjob.h"
29 #include "block/blockjob_int.h"
30 #include "block/block_int.h"
31 #include "qemu/cutils.h"
32 #include "qapi/error.h"
33 #include "qemu/error-report.h"
35 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
37 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
38 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
40 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
41 int64_t offset
, int bytes
, BdrvRequestFlags flags
);
43 void bdrv_parent_drained_begin(BlockDriverState
*bs
, BdrvChild
*ignore
)
47 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
51 if (c
->role
->drained_begin
) {
52 c
->role
->drained_begin(c
);
57 void bdrv_parent_drained_end(BlockDriverState
*bs
, BdrvChild
*ignore
)
61 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
65 if (c
->role
->drained_end
) {
66 c
->role
->drained_end(c
);
71 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
73 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
74 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
75 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
76 src
->opt_mem_alignment
);
77 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
78 src
->min_mem_alignment
);
79 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
82 void bdrv_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
84 BlockDriver
*drv
= bs
->drv
;
85 Error
*local_err
= NULL
;
87 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
93 /* Default alignment based on whether driver has byte interface */
94 bs
->bl
.request_alignment
= drv
->bdrv_co_preadv
? 1 : 512;
96 /* Take some limits from the children as a default */
98 bdrv_refresh_limits(bs
->file
->bs
, &local_err
);
100 error_propagate(errp
, local_err
);
103 bdrv_merge_limits(&bs
->bl
, &bs
->file
->bs
->bl
);
105 bs
->bl
.min_mem_alignment
= 512;
106 bs
->bl
.opt_mem_alignment
= getpagesize();
108 /* Safe default since most protocols use readv()/writev()/etc */
109 bs
->bl
.max_iov
= IOV_MAX
;
113 bdrv_refresh_limits(bs
->backing
->bs
, &local_err
);
115 error_propagate(errp
, local_err
);
118 bdrv_merge_limits(&bs
->bl
, &bs
->backing
->bs
->bl
);
121 /* Then let the driver override it */
122 if (drv
->bdrv_refresh_limits
) {
123 drv
->bdrv_refresh_limits(bs
, errp
);
128 * The copy-on-read flag is actually a reference count so multiple users may
129 * use the feature without worrying about clobbering its previous state.
130 * Copy-on-read stays enabled until all users have called to disable it.
132 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
134 atomic_inc(&bs
->copy_on_read
);
137 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
139 int old
= atomic_fetch_dec(&bs
->copy_on_read
);
145 BlockDriverState
*bs
;
152 static void coroutine_fn
bdrv_drain_invoke_entry(void *opaque
)
154 BdrvCoDrainData
*data
= opaque
;
155 BlockDriverState
*bs
= data
->bs
;
158 bs
->drv
->bdrv_co_drain_begin(bs
);
160 bs
->drv
->bdrv_co_drain_end(bs
);
163 /* Set data->done before reading bs->wakeup. */
164 atomic_mb_set(&data
->done
, true);
168 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
169 static void bdrv_drain_invoke(BlockDriverState
*bs
, bool begin
, bool recursive
)
171 BdrvChild
*child
, *tmp
;
172 BdrvCoDrainData data
= { .bs
= bs
, .done
= false, .begin
= begin
};
174 if (!bs
->drv
|| (begin
&& !bs
->drv
->bdrv_co_drain_begin
) ||
175 (!begin
&& !bs
->drv
->bdrv_co_drain_end
)) {
179 data
.co
= qemu_coroutine_create(bdrv_drain_invoke_entry
, &data
);
180 bdrv_coroutine_enter(bs
, data
.co
);
181 BDRV_POLL_WHILE(bs
, !data
.done
);
184 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, tmp
) {
185 bdrv_drain_invoke(child
->bs
, begin
, true);
190 static bool bdrv_drain_recurse(BlockDriverState
*bs
)
192 BdrvChild
*child
, *tmp
;
195 /* Wait for drained requests to finish */
196 waited
= BDRV_POLL_WHILE(bs
, atomic_read(&bs
->in_flight
) > 0);
198 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, tmp
) {
199 BlockDriverState
*bs
= child
->bs
;
201 qemu_get_current_aio_context() == qemu_get_aio_context();
202 assert(bs
->refcnt
> 0);
204 /* In case the recursive bdrv_drain_recurse processes a
205 * block_job_defer_to_main_loop BH and modifies the graph,
206 * let's hold a reference to bs until we are done.
208 * IOThread doesn't have such a BH, and it is not safe to call
209 * bdrv_unref without BQL, so skip doing it there.
213 waited
|= bdrv_drain_recurse(bs
);
222 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
224 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
227 static void bdrv_co_drain_bh_cb(void *opaque
)
229 BdrvCoDrainData
*data
= opaque
;
230 Coroutine
*co
= data
->co
;
231 BlockDriverState
*bs
= data
->bs
;
233 bdrv_dec_in_flight(bs
);
235 bdrv_do_drained_begin(bs
, data
->recursive
, data
->parent
);
237 bdrv_do_drained_end(bs
, data
->recursive
, data
->parent
);
244 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
,
245 bool begin
, bool recursive
,
248 BdrvCoDrainData data
;
250 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
251 * other coroutines run if they were queued from
252 * qemu_co_queue_run_restart(). */
254 assert(qemu_in_coroutine());
255 data
= (BdrvCoDrainData
) {
256 .co
= qemu_coroutine_self(),
260 .recursive
= recursive
,
263 bdrv_inc_in_flight(bs
);
264 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs
),
265 bdrv_co_drain_bh_cb
, &data
);
267 qemu_coroutine_yield();
268 /* If we are resumed from some other event (such as an aio completion or a
269 * timer callback), it is a bug in the caller that should be fixed. */
273 void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
276 BdrvChild
*child
, *next
;
278 if (qemu_in_coroutine()) {
279 bdrv_co_yield_to_drain(bs
, true, recursive
, parent
);
283 /* Stop things in parent-to-child order */
284 if (atomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
285 aio_disable_external(bdrv_get_aio_context(bs
));
288 bdrv_parent_drained_begin(bs
, parent
);
289 bdrv_drain_invoke(bs
, true, false);
290 bdrv_drain_recurse(bs
);
293 bs
->recursive_quiesce_counter
++;
294 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
295 bdrv_do_drained_begin(child
->bs
, true, child
);
300 void bdrv_drained_begin(BlockDriverState
*bs
)
302 bdrv_do_drained_begin(bs
, false, NULL
);
305 void bdrv_subtree_drained_begin(BlockDriverState
*bs
)
307 bdrv_do_drained_begin(bs
, true, NULL
);
310 void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
313 BdrvChild
*child
, *next
;
314 int old_quiesce_counter
;
316 if (qemu_in_coroutine()) {
317 bdrv_co_yield_to_drain(bs
, false, recursive
, parent
);
320 assert(bs
->quiesce_counter
> 0);
321 old_quiesce_counter
= atomic_fetch_dec(&bs
->quiesce_counter
);
323 /* Re-enable things in child-to-parent order */
324 bdrv_drain_invoke(bs
, false, false);
325 bdrv_parent_drained_end(bs
, parent
);
326 if (old_quiesce_counter
== 1) {
327 aio_enable_external(bdrv_get_aio_context(bs
));
331 bs
->recursive_quiesce_counter
--;
332 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
333 bdrv_do_drained_end(child
->bs
, true, child
);
338 void bdrv_drained_end(BlockDriverState
*bs
)
340 bdrv_do_drained_end(bs
, false, NULL
);
343 void bdrv_subtree_drained_end(BlockDriverState
*bs
)
345 bdrv_do_drained_end(bs
, true, NULL
);
348 void bdrv_apply_subtree_drain(BdrvChild
*child
, BlockDriverState
*new_parent
)
352 for (i
= 0; i
< new_parent
->recursive_quiesce_counter
; i
++) {
353 bdrv_do_drained_begin(child
->bs
, true, child
);
357 void bdrv_unapply_subtree_drain(BdrvChild
*child
, BlockDriverState
*old_parent
)
361 for (i
= 0; i
< old_parent
->recursive_quiesce_counter
; i
++) {
362 bdrv_do_drained_end(child
->bs
, true, child
);
367 * Wait for pending requests to complete on a single BlockDriverState subtree,
368 * and suspend block driver's internal I/O until next request arrives.
370 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
373 * Only this BlockDriverState's AioContext is run, so in-flight requests must
374 * not depend on events in other AioContexts. In that case, use
375 * bdrv_drain_all() instead.
377 void coroutine_fn
bdrv_co_drain(BlockDriverState
*bs
)
379 assert(qemu_in_coroutine());
380 bdrv_drained_begin(bs
);
381 bdrv_drained_end(bs
);
384 void bdrv_drain(BlockDriverState
*bs
)
386 bdrv_drained_begin(bs
);
387 bdrv_drained_end(bs
);
391 * Wait for pending requests to complete across all BlockDriverStates
393 * This function does not flush data to disk, use bdrv_flush_all() for that
394 * after calling this function.
396 * This pauses all block jobs and disables external clients. It must
397 * be paired with bdrv_drain_all_end().
399 * NOTE: no new block jobs or BlockDriverStates can be created between
400 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
402 void bdrv_drain_all_begin(void)
404 /* Always run first iteration so any pending completion BHs run */
406 BlockDriverState
*bs
;
408 GSList
*aio_ctxs
= NULL
, *ctx
;
410 /* BDRV_POLL_WHILE() for a node can only be called from its own I/O thread
411 * or the main loop AioContext. We potentially use BDRV_POLL_WHILE() on
412 * nodes in several different AioContexts, so make sure we're in the main
414 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
416 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
417 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
419 /* Stop things in parent-to-child order */
420 aio_context_acquire(aio_context
);
421 aio_disable_external(aio_context
);
422 bdrv_parent_drained_begin(bs
, NULL
);
423 bdrv_drain_invoke(bs
, true, true);
424 aio_context_release(aio_context
);
426 if (!g_slist_find(aio_ctxs
, aio_context
)) {
427 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
431 /* Note that completion of an asynchronous I/O operation can trigger any
432 * number of other I/O operations on other devices---for example a
433 * coroutine can submit an I/O request to another device in response to
434 * request completion. Therefore we must keep looping until there was no
435 * more activity rather than simply draining each device independently.
440 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
441 AioContext
*aio_context
= ctx
->data
;
443 aio_context_acquire(aio_context
);
444 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
445 if (aio_context
== bdrv_get_aio_context(bs
)) {
446 waited
|= bdrv_drain_recurse(bs
);
449 aio_context_release(aio_context
);
453 g_slist_free(aio_ctxs
);
456 void bdrv_drain_all_end(void)
458 BlockDriverState
*bs
;
461 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
462 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
464 /* Re-enable things in child-to-parent order */
465 aio_context_acquire(aio_context
);
466 bdrv_drain_invoke(bs
, false, true);
467 bdrv_parent_drained_end(bs
, NULL
);
468 aio_enable_external(aio_context
);
469 aio_context_release(aio_context
);
473 void bdrv_drain_all(void)
475 bdrv_drain_all_begin();
476 bdrv_drain_all_end();
480 * Remove an active request from the tracked requests list
482 * This function should be called when a tracked request is completing.
484 static void tracked_request_end(BdrvTrackedRequest
*req
)
486 if (req
->serialising
) {
487 atomic_dec(&req
->bs
->serialising_in_flight
);
490 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
491 QLIST_REMOVE(req
, list
);
492 qemu_co_queue_restart_all(&req
->wait_queue
);
493 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
497 * Add an active request to the tracked requests list
499 static void tracked_request_begin(BdrvTrackedRequest
*req
,
500 BlockDriverState
*bs
,
503 enum BdrvTrackedRequestType type
)
505 *req
= (BdrvTrackedRequest
){
510 .co
= qemu_coroutine_self(),
511 .serialising
= false,
512 .overlap_offset
= offset
,
513 .overlap_bytes
= bytes
,
516 qemu_co_queue_init(&req
->wait_queue
);
518 qemu_co_mutex_lock(&bs
->reqs_lock
);
519 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
520 qemu_co_mutex_unlock(&bs
->reqs_lock
);
523 static void mark_request_serialising(BdrvTrackedRequest
*req
, uint64_t align
)
525 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
526 unsigned int overlap_bytes
= ROUND_UP(req
->offset
+ req
->bytes
, align
)
529 if (!req
->serialising
) {
530 atomic_inc(&req
->bs
->serialising_in_flight
);
531 req
->serialising
= true;
534 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
535 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
539 * Round a region to cluster boundaries
541 void bdrv_round_to_clusters(BlockDriverState
*bs
,
542 int64_t offset
, int64_t bytes
,
543 int64_t *cluster_offset
,
544 int64_t *cluster_bytes
)
548 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
549 *cluster_offset
= offset
;
550 *cluster_bytes
= bytes
;
552 int64_t c
= bdi
.cluster_size
;
553 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
554 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
558 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
563 ret
= bdrv_get_info(bs
, &bdi
);
564 if (ret
< 0 || bdi
.cluster_size
== 0) {
565 return bs
->bl
.request_alignment
;
567 return bdi
.cluster_size
;
571 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
572 int64_t offset
, unsigned int bytes
)
575 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
579 if (req
->overlap_offset
>= offset
+ bytes
) {
585 void bdrv_inc_in_flight(BlockDriverState
*bs
)
587 atomic_inc(&bs
->in_flight
);
590 static void dummy_bh_cb(void *opaque
)
594 void bdrv_wakeup(BlockDriverState
*bs
)
596 /* The barrier (or an atomic op) is in the caller. */
597 if (atomic_read(&bs
->wakeup
)) {
598 aio_bh_schedule_oneshot(qemu_get_aio_context(), dummy_bh_cb
, NULL
);
602 void bdrv_dec_in_flight(BlockDriverState
*bs
)
604 atomic_dec(&bs
->in_flight
);
608 static bool coroutine_fn
wait_serialising_requests(BdrvTrackedRequest
*self
)
610 BlockDriverState
*bs
= self
->bs
;
611 BdrvTrackedRequest
*req
;
615 if (!atomic_read(&bs
->serialising_in_flight
)) {
621 qemu_co_mutex_lock(&bs
->reqs_lock
);
622 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
623 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
626 if (tracked_request_overlaps(req
, self
->overlap_offset
,
627 self
->overlap_bytes
))
629 /* Hitting this means there was a reentrant request, for
630 * example, a block driver issuing nested requests. This must
631 * never happen since it means deadlock.
633 assert(qemu_coroutine_self() != req
->co
);
635 /* If the request is already (indirectly) waiting for us, or
636 * will wait for us as soon as it wakes up, then just go on
637 * (instead of producing a deadlock in the former case). */
638 if (!req
->waiting_for
) {
639 self
->waiting_for
= req
;
640 qemu_co_queue_wait(&req
->wait_queue
, &bs
->reqs_lock
);
641 self
->waiting_for
= NULL
;
648 qemu_co_mutex_unlock(&bs
->reqs_lock
);
654 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
657 if (size
> BDRV_REQUEST_MAX_SECTORS
<< BDRV_SECTOR_BITS
) {
661 if (!bdrv_is_inserted(bs
)) {
672 typedef struct RwCo
{
678 BdrvRequestFlags flags
;
681 static void coroutine_fn
bdrv_rw_co_entry(void *opaque
)
685 if (!rwco
->is_write
) {
686 rwco
->ret
= bdrv_co_preadv(rwco
->child
, rwco
->offset
,
687 rwco
->qiov
->size
, rwco
->qiov
,
690 rwco
->ret
= bdrv_co_pwritev(rwco
->child
, rwco
->offset
,
691 rwco
->qiov
->size
, rwco
->qiov
,
697 * Process a vectored synchronous request using coroutines
699 static int bdrv_prwv_co(BdrvChild
*child
, int64_t offset
,
700 QEMUIOVector
*qiov
, bool is_write
,
701 BdrvRequestFlags flags
)
708 .is_write
= is_write
,
713 if (qemu_in_coroutine()) {
714 /* Fast-path if already in coroutine context */
715 bdrv_rw_co_entry(&rwco
);
717 co
= qemu_coroutine_create(bdrv_rw_co_entry
, &rwco
);
718 bdrv_coroutine_enter(child
->bs
, co
);
719 BDRV_POLL_WHILE(child
->bs
, rwco
.ret
== NOT_DONE
);
725 * Process a synchronous request using coroutines
727 static int bdrv_rw_co(BdrvChild
*child
, int64_t sector_num
, uint8_t *buf
,
728 int nb_sectors
, bool is_write
, BdrvRequestFlags flags
)
732 .iov_base
= (void *)buf
,
733 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
736 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
740 qemu_iovec_init_external(&qiov
, &iov
, 1);
741 return bdrv_prwv_co(child
, sector_num
<< BDRV_SECTOR_BITS
,
742 &qiov
, is_write
, flags
);
745 /* return < 0 if error. See bdrv_write() for the return codes */
746 int bdrv_read(BdrvChild
*child
, int64_t sector_num
,
747 uint8_t *buf
, int nb_sectors
)
749 return bdrv_rw_co(child
, sector_num
, buf
, nb_sectors
, false, 0);
752 /* Return < 0 if error. Important errors are:
753 -EIO generic I/O error (may happen for all errors)
754 -ENOMEDIUM No media inserted.
755 -EINVAL Invalid sector number or nb_sectors
756 -EACCES Trying to write a read-only device
758 int bdrv_write(BdrvChild
*child
, int64_t sector_num
,
759 const uint8_t *buf
, int nb_sectors
)
761 return bdrv_rw_co(child
, sector_num
, (uint8_t *)buf
, nb_sectors
, true, 0);
764 int bdrv_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
765 int bytes
, BdrvRequestFlags flags
)
773 qemu_iovec_init_external(&qiov
, &iov
, 1);
774 return bdrv_prwv_co(child
, offset
, &qiov
, true,
775 BDRV_REQ_ZERO_WRITE
| flags
);
779 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
780 * The operation is sped up by checking the block status and only writing
781 * zeroes to the device if they currently do not return zeroes. Optional
782 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
785 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
787 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
790 int64_t target_size
, bytes
, offset
= 0;
791 BlockDriverState
*bs
= child
->bs
;
793 target_size
= bdrv_getlength(bs
);
794 if (target_size
< 0) {
799 bytes
= MIN(target_size
- offset
, BDRV_REQUEST_MAX_BYTES
);
803 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, NULL
, NULL
);
805 error_report("error getting block status at offset %" PRId64
": %s",
806 offset
, strerror(-ret
));
809 if (ret
& BDRV_BLOCK_ZERO
) {
813 ret
= bdrv_pwrite_zeroes(child
, offset
, bytes
, flags
);
815 error_report("error writing zeroes at offset %" PRId64
": %s",
816 offset
, strerror(-ret
));
823 int bdrv_preadv(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
827 ret
= bdrv_prwv_co(child
, offset
, qiov
, false, 0);
835 int bdrv_pread(BdrvChild
*child
, int64_t offset
, void *buf
, int bytes
)
839 .iov_base
= (void *)buf
,
847 qemu_iovec_init_external(&qiov
, &iov
, 1);
848 return bdrv_preadv(child
, offset
, &qiov
);
851 int bdrv_pwritev(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
855 ret
= bdrv_prwv_co(child
, offset
, qiov
, true, 0);
863 int bdrv_pwrite(BdrvChild
*child
, int64_t offset
, const void *buf
, int bytes
)
867 .iov_base
= (void *) buf
,
875 qemu_iovec_init_external(&qiov
, &iov
, 1);
876 return bdrv_pwritev(child
, offset
, &qiov
);
880 * Writes to the file and ensures that no writes are reordered across this
881 * request (acts as a barrier)
883 * Returns 0 on success, -errno in error cases.
885 int bdrv_pwrite_sync(BdrvChild
*child
, int64_t offset
,
886 const void *buf
, int count
)
890 ret
= bdrv_pwrite(child
, offset
, buf
, count
);
895 ret
= bdrv_flush(child
->bs
);
903 typedef struct CoroutineIOCompletion
{
904 Coroutine
*coroutine
;
906 } CoroutineIOCompletion
;
908 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
910 CoroutineIOCompletion
*co
= opaque
;
913 aio_co_wake(co
->coroutine
);
916 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
917 uint64_t offset
, uint64_t bytes
,
918 QEMUIOVector
*qiov
, int flags
)
920 BlockDriver
*drv
= bs
->drv
;
922 unsigned int nb_sectors
;
924 assert(!(flags
& ~BDRV_REQ_MASK
));
930 if (drv
->bdrv_co_preadv
) {
931 return drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
934 sector_num
= offset
>> BDRV_SECTOR_BITS
;
935 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
937 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
938 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
939 assert((bytes
>> BDRV_SECTOR_BITS
) <= BDRV_REQUEST_MAX_SECTORS
);
941 if (drv
->bdrv_co_readv
) {
942 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
945 CoroutineIOCompletion co
= {
946 .coroutine
= qemu_coroutine_self(),
949 acb
= bs
->drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
950 bdrv_co_io_em_complete
, &co
);
954 qemu_coroutine_yield();
960 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
961 uint64_t offset
, uint64_t bytes
,
962 QEMUIOVector
*qiov
, int flags
)
964 BlockDriver
*drv
= bs
->drv
;
966 unsigned int nb_sectors
;
969 assert(!(flags
& ~BDRV_REQ_MASK
));
975 if (drv
->bdrv_co_pwritev
) {
976 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
,
977 flags
& bs
->supported_write_flags
);
978 flags
&= ~bs
->supported_write_flags
;
982 sector_num
= offset
>> BDRV_SECTOR_BITS
;
983 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
985 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
986 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
987 assert((bytes
>> BDRV_SECTOR_BITS
) <= BDRV_REQUEST_MAX_SECTORS
);
989 if (drv
->bdrv_co_writev_flags
) {
990 ret
= drv
->bdrv_co_writev_flags(bs
, sector_num
, nb_sectors
, qiov
,
991 flags
& bs
->supported_write_flags
);
992 flags
&= ~bs
->supported_write_flags
;
993 } else if (drv
->bdrv_co_writev
) {
994 assert(!bs
->supported_write_flags
);
995 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
);
998 CoroutineIOCompletion co
= {
999 .coroutine
= qemu_coroutine_self(),
1002 acb
= bs
->drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
1003 bdrv_co_io_em_complete
, &co
);
1007 qemu_coroutine_yield();
1013 if (ret
== 0 && (flags
& BDRV_REQ_FUA
)) {
1014 ret
= bdrv_co_flush(bs
);
1020 static int coroutine_fn
1021 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
1022 uint64_t bytes
, QEMUIOVector
*qiov
)
1024 BlockDriver
*drv
= bs
->drv
;
1030 if (!drv
->bdrv_co_pwritev_compressed
) {
1034 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1037 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
1038 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
)
1040 BlockDriverState
*bs
= child
->bs
;
1042 /* Perform I/O through a temporary buffer so that users who scribble over
1043 * their read buffer while the operation is in progress do not end up
1044 * modifying the image file. This is critical for zero-copy guest I/O
1045 * where anything might happen inside guest memory.
1047 void *bounce_buffer
;
1049 BlockDriver
*drv
= bs
->drv
;
1051 QEMUIOVector local_qiov
;
1052 int64_t cluster_offset
;
1053 int64_t cluster_bytes
;
1056 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1057 BDRV_REQUEST_MAX_BYTES
);
1058 unsigned int progress
= 0;
1064 /* FIXME We cannot require callers to have write permissions when all they
1065 * are doing is a read request. If we did things right, write permissions
1066 * would be obtained anyway, but internally by the copy-on-read code. As
1067 * long as it is implemented here rather than in a separate filter driver,
1068 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1069 * it could request permissions. Therefore we have to bypass the permission
1070 * system for the moment. */
1071 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1073 /* Cover entire cluster so no additional backing file I/O is required when
1074 * allocating cluster in the image file. Note that this value may exceed
1075 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1076 * is one reason we loop rather than doing it all at once.
1078 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
1079 skip_bytes
= offset
- cluster_offset
;
1081 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1082 cluster_offset
, cluster_bytes
);
1084 bounce_buffer
= qemu_try_blockalign(bs
,
1085 MIN(MIN(max_transfer
, cluster_bytes
),
1086 MAX_BOUNCE_BUFFER
));
1087 if (bounce_buffer
== NULL
) {
1092 while (cluster_bytes
) {
1095 ret
= bdrv_is_allocated(bs
, cluster_offset
,
1096 MIN(cluster_bytes
, max_transfer
), &pnum
);
1098 /* Safe to treat errors in querying allocation as if
1099 * unallocated; we'll probably fail again soon on the
1100 * read, but at least that will set a decent errno.
1102 pnum
= MIN(cluster_bytes
, max_transfer
);
1105 assert(skip_bytes
< pnum
);
1108 /* Must copy-on-read; use the bounce buffer */
1109 iov
.iov_base
= bounce_buffer
;
1110 iov
.iov_len
= pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1111 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1113 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1119 bdrv_debug_event(bs
, BLKDBG_COR_WRITE
);
1120 if (drv
->bdrv_co_pwrite_zeroes
&&
1121 buffer_is_zero(bounce_buffer
, pnum
)) {
1122 /* FIXME: Should we (perhaps conditionally) be setting
1123 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1124 * that still correctly reads as zero? */
1125 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
, 0);
1127 /* This does not change the data on the disk, it is not
1128 * necessary to flush even in cache=writethrough mode.
1130 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1135 /* It might be okay to ignore write errors for guest
1136 * requests. If this is a deliberate copy-on-read
1137 * then we don't want to ignore the error. Simply
1138 * report it in all cases.
1143 qemu_iovec_from_buf(qiov
, progress
, bounce_buffer
+ skip_bytes
,
1146 /* Read directly into the destination */
1147 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1148 qemu_iovec_concat(&local_qiov
, qiov
, progress
, pnum
- skip_bytes
);
1149 ret
= bdrv_driver_preadv(bs
, offset
+ progress
, local_qiov
.size
,
1151 qemu_iovec_destroy(&local_qiov
);
1157 cluster_offset
+= pnum
;
1158 cluster_bytes
-= pnum
;
1159 progress
+= pnum
- skip_bytes
;
1165 qemu_vfree(bounce_buffer
);
1170 * Forwards an already correctly aligned request to the BlockDriver. This
1171 * handles copy on read, zeroing after EOF, and fragmentation of large
1172 * reads; any other features must be implemented by the caller.
1174 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1175 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1176 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1178 BlockDriverState
*bs
= child
->bs
;
1179 int64_t total_bytes
, max_bytes
;
1181 uint64_t bytes_remaining
= bytes
;
1184 assert(is_power_of_2(align
));
1185 assert((offset
& (align
- 1)) == 0);
1186 assert((bytes
& (align
- 1)) == 0);
1187 assert(!qiov
|| bytes
== qiov
->size
);
1188 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1189 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1192 /* TODO: We would need a per-BDS .supported_read_flags and
1193 * potential fallback support, if we ever implement any read flags
1194 * to pass through to drivers. For now, there aren't any
1195 * passthrough flags. */
1196 assert(!(flags
& ~(BDRV_REQ_NO_SERIALISING
| BDRV_REQ_COPY_ON_READ
)));
1198 /* Handle Copy on Read and associated serialisation */
1199 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1200 /* If we touch the same cluster it counts as an overlap. This
1201 * guarantees that allocating writes will be serialized and not race
1202 * with each other for the same cluster. For example, in copy-on-read
1203 * it ensures that the CoR read and write operations are atomic and
1204 * guest writes cannot interleave between them. */
1205 mark_request_serialising(req
, bdrv_get_cluster_size(bs
));
1208 if (!(flags
& BDRV_REQ_NO_SERIALISING
)) {
1209 wait_serialising_requests(req
);
1212 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1215 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &pnum
);
1220 if (!ret
|| pnum
!= bytes
) {
1221 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
, qiov
);
1226 /* Forward the request to the BlockDriver, possibly fragmenting it */
1227 total_bytes
= bdrv_getlength(bs
);
1228 if (total_bytes
< 0) {
1233 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1234 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1235 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, 0);
1239 while (bytes_remaining
) {
1243 QEMUIOVector local_qiov
;
1245 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1247 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1248 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1250 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1251 num
, &local_qiov
, 0);
1253 qemu_iovec_destroy(&local_qiov
);
1255 num
= bytes_remaining
;
1256 ret
= qemu_iovec_memset(qiov
, bytes
- bytes_remaining
, 0,
1262 bytes_remaining
-= num
;
1266 return ret
< 0 ? ret
: 0;
1270 * Handle a read request in coroutine context
1272 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1273 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1274 BdrvRequestFlags flags
)
1276 BlockDriverState
*bs
= child
->bs
;
1277 BlockDriver
*drv
= bs
->drv
;
1278 BdrvTrackedRequest req
;
1280 uint64_t align
= bs
->bl
.request_alignment
;
1281 uint8_t *head_buf
= NULL
;
1282 uint8_t *tail_buf
= NULL
;
1283 QEMUIOVector local_qiov
;
1284 bool use_local_qiov
= false;
1287 trace_bdrv_co_preadv(child
->bs
, offset
, bytes
, flags
);
1293 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1298 bdrv_inc_in_flight(bs
);
1300 /* Don't do copy-on-read if we read data before write operation */
1301 if (atomic_read(&bs
->copy_on_read
) && !(flags
& BDRV_REQ_NO_SERIALISING
)) {
1302 flags
|= BDRV_REQ_COPY_ON_READ
;
1305 /* Align read if necessary by padding qiov */
1306 if (offset
& (align
- 1)) {
1307 head_buf
= qemu_blockalign(bs
, align
);
1308 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1309 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1310 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1311 use_local_qiov
= true;
1313 bytes
+= offset
& (align
- 1);
1314 offset
= offset
& ~(align
- 1);
1317 if ((offset
+ bytes
) & (align
- 1)) {
1318 if (!use_local_qiov
) {
1319 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1320 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1321 use_local_qiov
= true;
1323 tail_buf
= qemu_blockalign(bs
, align
);
1324 qemu_iovec_add(&local_qiov
, tail_buf
,
1325 align
- ((offset
+ bytes
) & (align
- 1)));
1327 bytes
= ROUND_UP(bytes
, align
);
1330 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1331 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
, align
,
1332 use_local_qiov
? &local_qiov
: qiov
,
1334 tracked_request_end(&req
);
1335 bdrv_dec_in_flight(bs
);
1337 if (use_local_qiov
) {
1338 qemu_iovec_destroy(&local_qiov
);
1339 qemu_vfree(head_buf
);
1340 qemu_vfree(tail_buf
);
1346 static int coroutine_fn
bdrv_co_do_readv(BdrvChild
*child
,
1347 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
,
1348 BdrvRequestFlags flags
)
1350 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
1354 return bdrv_co_preadv(child
, sector_num
<< BDRV_SECTOR_BITS
,
1355 nb_sectors
<< BDRV_SECTOR_BITS
, qiov
, flags
);
1358 int coroutine_fn
bdrv_co_readv(BdrvChild
*child
, int64_t sector_num
,
1359 int nb_sectors
, QEMUIOVector
*qiov
)
1361 return bdrv_co_do_readv(child
, sector_num
, nb_sectors
, qiov
, 0);
1364 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1365 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
1367 BlockDriver
*drv
= bs
->drv
;
1369 struct iovec iov
= {0};
1371 bool need_flush
= false;
1375 int max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
, INT_MAX
);
1376 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1377 bs
->bl
.request_alignment
);
1378 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1384 assert(alignment
% bs
->bl
.request_alignment
== 0);
1385 head
= offset
% alignment
;
1386 tail
= (offset
+ bytes
) % alignment
;
1387 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1388 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1390 while (bytes
> 0 && !ret
) {
1393 /* Align request. Block drivers can expect the "bulk" of the request
1394 * to be aligned, and that unaligned requests do not cross cluster
1398 /* Make a small request up to the first aligned sector. For
1399 * convenience, limit this request to max_transfer even if
1400 * we don't need to fall back to writes. */
1401 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1402 head
= (head
+ num
) % alignment
;
1403 assert(num
< max_write_zeroes
);
1404 } else if (tail
&& num
> alignment
) {
1405 /* Shorten the request to the last aligned sector. */
1409 /* limit request size */
1410 if (num
> max_write_zeroes
) {
1411 num
= max_write_zeroes
;
1415 /* First try the efficient write zeroes operation */
1416 if (drv
->bdrv_co_pwrite_zeroes
) {
1417 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1418 flags
& bs
->supported_zero_flags
);
1419 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1420 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1424 assert(!bs
->supported_zero_flags
);
1427 if (ret
== -ENOTSUP
) {
1428 /* Fall back to bounce buffer if write zeroes is unsupported */
1429 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1431 if ((flags
& BDRV_REQ_FUA
) &&
1432 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1433 /* No need for bdrv_driver_pwrite() to do a fallback
1434 * flush on each chunk; use just one at the end */
1435 write_flags
&= ~BDRV_REQ_FUA
;
1438 num
= MIN(num
, max_transfer
);
1440 if (iov
.iov_base
== NULL
) {
1441 iov
.iov_base
= qemu_try_blockalign(bs
, num
);
1442 if (iov
.iov_base
== NULL
) {
1446 memset(iov
.iov_base
, 0, num
);
1448 qemu_iovec_init_external(&qiov
, &iov
, 1);
1450 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, write_flags
);
1452 /* Keep bounce buffer around if it is big enough for all
1453 * all future requests.
1455 if (num
< max_transfer
) {
1456 qemu_vfree(iov
.iov_base
);
1457 iov
.iov_base
= NULL
;
1466 if (ret
== 0 && need_flush
) {
1467 ret
= bdrv_co_flush(bs
);
1469 qemu_vfree(iov
.iov_base
);
1474 * Forwards an already correctly aligned write request to the BlockDriver,
1475 * after possibly fragmenting it.
1477 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
1478 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1479 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1481 BlockDriverState
*bs
= child
->bs
;
1482 BlockDriver
*drv
= bs
->drv
;
1486 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1487 uint64_t bytes_remaining
= bytes
;
1494 if (bdrv_has_readonly_bitmaps(bs
)) {
1498 assert(is_power_of_2(align
));
1499 assert((offset
& (align
- 1)) == 0);
1500 assert((bytes
& (align
- 1)) == 0);
1501 assert(!qiov
|| bytes
== qiov
->size
);
1502 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1503 assert(!(flags
& ~BDRV_REQ_MASK
));
1504 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1507 waited
= wait_serialising_requests(req
);
1508 assert(!waited
|| !req
->serialising
);
1509 assert(req
->overlap_offset
<= offset
);
1510 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1511 assert(child
->perm
& BLK_PERM_WRITE
);
1512 assert(end_sector
<= bs
->total_sectors
|| child
->perm
& BLK_PERM_RESIZE
);
1514 ret
= notifier_with_return_list_notify(&bs
->before_write_notifiers
, req
);
1516 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1517 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1518 qemu_iovec_is_zero(qiov
)) {
1519 flags
|= BDRV_REQ_ZERO_WRITE
;
1520 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1521 flags
|= BDRV_REQ_MAY_UNMAP
;
1526 /* Do nothing, write notifier decided to fail this request */
1527 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1528 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
1529 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
1530 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
1531 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1532 } else if (bytes
<= max_transfer
) {
1533 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1534 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1536 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1537 while (bytes_remaining
) {
1538 int num
= MIN(bytes_remaining
, max_transfer
);
1539 QEMUIOVector local_qiov
;
1540 int local_flags
= flags
;
1543 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
1544 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1545 /* If FUA is going to be emulated by flush, we only
1546 * need to flush on the last iteration */
1547 local_flags
&= ~BDRV_REQ_FUA
;
1549 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1550 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1552 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
1553 num
, &local_qiov
, local_flags
);
1554 qemu_iovec_destroy(&local_qiov
);
1558 bytes_remaining
-= num
;
1561 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
1563 atomic_inc(&bs
->write_gen
);
1564 bdrv_set_dirty(bs
, offset
, bytes
);
1566 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1569 bs
->total_sectors
= MAX(bs
->total_sectors
, end_sector
);
1576 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
1579 BdrvRequestFlags flags
,
1580 BdrvTrackedRequest
*req
)
1582 BlockDriverState
*bs
= child
->bs
;
1583 uint8_t *buf
= NULL
;
1584 QEMUIOVector local_qiov
;
1586 uint64_t align
= bs
->bl
.request_alignment
;
1587 unsigned int head_padding_bytes
, tail_padding_bytes
;
1590 head_padding_bytes
= offset
& (align
- 1);
1591 tail_padding_bytes
= (align
- (offset
+ bytes
)) & (align
- 1);
1594 assert(flags
& BDRV_REQ_ZERO_WRITE
);
1595 if (head_padding_bytes
|| tail_padding_bytes
) {
1596 buf
= qemu_blockalign(bs
, align
);
1597 iov
= (struct iovec
) {
1601 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1603 if (head_padding_bytes
) {
1604 uint64_t zero_bytes
= MIN(bytes
, align
- head_padding_bytes
);
1606 /* RMW the unaligned part before head. */
1607 mark_request_serialising(req
, align
);
1608 wait_serialising_requests(req
);
1609 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1610 ret
= bdrv_aligned_preadv(child
, req
, offset
& ~(align
- 1), align
,
1611 align
, &local_qiov
, 0);
1615 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1617 memset(buf
+ head_padding_bytes
, 0, zero_bytes
);
1618 ret
= bdrv_aligned_pwritev(child
, req
, offset
& ~(align
- 1), align
,
1620 flags
& ~BDRV_REQ_ZERO_WRITE
);
1624 offset
+= zero_bytes
;
1625 bytes
-= zero_bytes
;
1628 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1629 if (bytes
>= align
) {
1630 /* Write the aligned part in the middle. */
1631 uint64_t aligned_bytes
= bytes
& ~(align
- 1);
1632 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
1637 bytes
-= aligned_bytes
;
1638 offset
+= aligned_bytes
;
1641 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1643 assert(align
== tail_padding_bytes
+ bytes
);
1644 /* RMW the unaligned part after tail. */
1645 mark_request_serialising(req
, align
);
1646 wait_serialising_requests(req
);
1647 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1648 ret
= bdrv_aligned_preadv(child
, req
, offset
, align
,
1649 align
, &local_qiov
, 0);
1653 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1655 memset(buf
, 0, bytes
);
1656 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
1657 &local_qiov
, flags
& ~BDRV_REQ_ZERO_WRITE
);
1666 * Handle a write request in coroutine context
1668 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
1669 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1670 BdrvRequestFlags flags
)
1672 BlockDriverState
*bs
= child
->bs
;
1673 BdrvTrackedRequest req
;
1674 uint64_t align
= bs
->bl
.request_alignment
;
1675 uint8_t *head_buf
= NULL
;
1676 uint8_t *tail_buf
= NULL
;
1677 QEMUIOVector local_qiov
;
1678 bool use_local_qiov
= false;
1681 trace_bdrv_co_pwritev(child
->bs
, offset
, bytes
, flags
);
1686 if (bs
->read_only
) {
1689 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1691 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1696 bdrv_inc_in_flight(bs
);
1698 * Align write if necessary by performing a read-modify-write cycle.
1699 * Pad qiov with the read parts and be sure to have a tracked request not
1700 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1702 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
1705 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
1709 if (offset
& (align
- 1)) {
1710 QEMUIOVector head_qiov
;
1711 struct iovec head_iov
;
1713 mark_request_serialising(&req
, align
);
1714 wait_serialising_requests(&req
);
1716 head_buf
= qemu_blockalign(bs
, align
);
1717 head_iov
= (struct iovec
) {
1718 .iov_base
= head_buf
,
1721 qemu_iovec_init_external(&head_qiov
, &head_iov
, 1);
1723 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1724 ret
= bdrv_aligned_preadv(child
, &req
, offset
& ~(align
- 1), align
,
1725 align
, &head_qiov
, 0);
1729 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1731 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1732 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1733 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1734 use_local_qiov
= true;
1736 bytes
+= offset
& (align
- 1);
1737 offset
= offset
& ~(align
- 1);
1739 /* We have read the tail already if the request is smaller
1740 * than one aligned block.
1742 if (bytes
< align
) {
1743 qemu_iovec_add(&local_qiov
, head_buf
+ bytes
, align
- bytes
);
1748 if ((offset
+ bytes
) & (align
- 1)) {
1749 QEMUIOVector tail_qiov
;
1750 struct iovec tail_iov
;
1754 mark_request_serialising(&req
, align
);
1755 waited
= wait_serialising_requests(&req
);
1756 assert(!waited
|| !use_local_qiov
);
1758 tail_buf
= qemu_blockalign(bs
, align
);
1759 tail_iov
= (struct iovec
) {
1760 .iov_base
= tail_buf
,
1763 qemu_iovec_init_external(&tail_qiov
, &tail_iov
, 1);
1765 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1766 ret
= bdrv_aligned_preadv(child
, &req
, (offset
+ bytes
) & ~(align
- 1),
1767 align
, align
, &tail_qiov
, 0);
1771 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1773 if (!use_local_qiov
) {
1774 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1775 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1776 use_local_qiov
= true;
1779 tail_bytes
= (offset
+ bytes
) & (align
- 1);
1780 qemu_iovec_add(&local_qiov
, tail_buf
+ tail_bytes
, align
- tail_bytes
);
1782 bytes
= ROUND_UP(bytes
, align
);
1785 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
1786 use_local_qiov
? &local_qiov
: qiov
,
1791 if (use_local_qiov
) {
1792 qemu_iovec_destroy(&local_qiov
);
1794 qemu_vfree(head_buf
);
1795 qemu_vfree(tail_buf
);
1797 tracked_request_end(&req
);
1798 bdrv_dec_in_flight(bs
);
1802 static int coroutine_fn
bdrv_co_do_writev(BdrvChild
*child
,
1803 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
,
1804 BdrvRequestFlags flags
)
1806 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
1810 return bdrv_co_pwritev(child
, sector_num
<< BDRV_SECTOR_BITS
,
1811 nb_sectors
<< BDRV_SECTOR_BITS
, qiov
, flags
);
1814 int coroutine_fn
bdrv_co_writev(BdrvChild
*child
, int64_t sector_num
,
1815 int nb_sectors
, QEMUIOVector
*qiov
)
1817 return bdrv_co_do_writev(child
, sector_num
, nb_sectors
, qiov
, 0);
1820 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
1821 int bytes
, BdrvRequestFlags flags
)
1823 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
1825 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
1826 flags
&= ~BDRV_REQ_MAY_UNMAP
;
1829 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
1830 BDRV_REQ_ZERO_WRITE
| flags
);
1834 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1836 int bdrv_flush_all(void)
1838 BdrvNextIterator it
;
1839 BlockDriverState
*bs
= NULL
;
1842 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
1843 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
1846 aio_context_acquire(aio_context
);
1847 ret
= bdrv_flush(bs
);
1848 if (ret
< 0 && !result
) {
1851 aio_context_release(aio_context
);
1858 typedef struct BdrvCoBlockStatusData
{
1859 BlockDriverState
*bs
;
1860 BlockDriverState
*base
;
1866 BlockDriverState
**file
;
1869 } BdrvCoBlockStatusData
;
1871 int64_t coroutine_fn
bdrv_co_get_block_status_from_file(BlockDriverState
*bs
,
1875 BlockDriverState
**file
)
1877 assert(bs
->file
&& bs
->file
->bs
);
1879 *file
= bs
->file
->bs
;
1880 return BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
|
1881 (sector_num
<< BDRV_SECTOR_BITS
);
1884 int64_t coroutine_fn
bdrv_co_get_block_status_from_backing(BlockDriverState
*bs
,
1888 BlockDriverState
**file
)
1890 assert(bs
->backing
&& bs
->backing
->bs
);
1892 *file
= bs
->backing
->bs
;
1893 return BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
|
1894 (sector_num
<< BDRV_SECTOR_BITS
);
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 purposes,
1903 * and the result should include BDRV_BLOCK_OFFSET_VALID and
1904 * BDRV_BLOCK_ZERO where possible; otherwise, the result may omit those
1905 * bits particularly if it allows for a larger value in 'pnum'.
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_get_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 /* TODO: until we have a byte-based driver callback, we also have to
1980 * round out to sectors, even if that is bigger than request_alignment */
1981 align
= MAX(bs
->bl
.request_alignment
, BDRV_SECTOR_SIZE
);
1982 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
1983 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
1986 int count
; /* sectors */
1989 assert(QEMU_IS_ALIGNED(aligned_offset
| aligned_bytes
,
1992 * The contract allows us to return pnum smaller than bytes, even
1993 * if the next query would see the same status; we truncate the
1994 * request to avoid overflowing the driver's 32-bit interface.
1996 longret
= bs
->drv
->bdrv_co_get_block_status(
1997 bs
, aligned_offset
>> BDRV_SECTOR_BITS
,
1998 MIN(INT_MAX
, aligned_bytes
) >> BDRV_SECTOR_BITS
, &count
,
2001 assert(INT_MIN
<= longret
);
2005 if (longret
& BDRV_BLOCK_OFFSET_VALID
) {
2006 local_map
= longret
& BDRV_BLOCK_OFFSET_MASK
;
2008 ret
= longret
& ~BDRV_BLOCK_OFFSET_MASK
;
2009 *pnum
= count
* BDRV_SECTOR_SIZE
;
2013 * The driver's result must be a multiple of request_alignment.
2014 * Clamp pnum and adjust map to original request.
2016 assert(QEMU_IS_ALIGNED(*pnum
, align
) && align
> offset
- aligned_offset
);
2017 *pnum
-= offset
- aligned_offset
;
2018 if (*pnum
> bytes
) {
2021 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2022 local_map
+= offset
- aligned_offset
;
2025 if (ret
& BDRV_BLOCK_RAW
) {
2026 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2027 ret
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2028 *pnum
, pnum
, &local_map
, &local_file
);
2032 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2033 ret
|= BDRV_BLOCK_ALLOCATED
;
2034 } else if (want_zero
) {
2035 if (bdrv_unallocated_blocks_are_zero(bs
)) {
2036 ret
|= BDRV_BLOCK_ZERO
;
2037 } else if (bs
->backing
) {
2038 BlockDriverState
*bs2
= bs
->backing
->bs
;
2039 int64_t size2
= bdrv_getlength(bs2
);
2041 if (size2
>= 0 && offset
>= size2
) {
2042 ret
|= BDRV_BLOCK_ZERO
;
2047 if (want_zero
&& local_file
&& local_file
!= bs
&&
2048 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2049 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2053 ret2
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2054 *pnum
, &file_pnum
, NULL
, NULL
);
2056 /* Ignore errors. This is just providing extra information, it
2057 * is useful but not necessary.
2059 if (ret2
& BDRV_BLOCK_EOF
&&
2060 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2062 * It is valid for the format block driver to read
2063 * beyond the end of the underlying file's current
2064 * size; such areas read as zero.
2066 ret
|= BDRV_BLOCK_ZERO
;
2068 /* Limit request to the range reported by the protocol driver */
2070 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2076 bdrv_dec_in_flight(bs
);
2077 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2078 ret
|= BDRV_BLOCK_EOF
;
2090 static int coroutine_fn
bdrv_co_block_status_above(BlockDriverState
*bs
,
2091 BlockDriverState
*base
,
2097 BlockDriverState
**file
)
2099 BlockDriverState
*p
;
2104 for (p
= bs
; p
!= base
; p
= backing_bs(p
)) {
2105 ret
= bdrv_co_block_status(p
, want_zero
, offset
, bytes
, pnum
, map
,
2110 if (ret
& BDRV_BLOCK_ZERO
&& ret
& BDRV_BLOCK_EOF
&& !first
) {
2112 * Reading beyond the end of the file continues to read
2113 * zeroes, but we can only widen the result to the
2114 * unallocated length we learned from an earlier
2119 if (ret
& (BDRV_BLOCK_ZERO
| BDRV_BLOCK_DATA
)) {
2122 /* [offset, pnum] unallocated on this layer, which could be only
2123 * the first part of [offset, bytes]. */
2124 bytes
= MIN(bytes
, *pnum
);
2130 /* Coroutine wrapper for bdrv_block_status_above() */
2131 static void coroutine_fn
bdrv_block_status_above_co_entry(void *opaque
)
2133 BdrvCoBlockStatusData
*data
= opaque
;
2135 data
->ret
= bdrv_co_block_status_above(data
->bs
, data
->base
,
2137 data
->offset
, data
->bytes
,
2138 data
->pnum
, data
->map
, data
->file
);
2143 * Synchronous wrapper around bdrv_co_block_status_above().
2145 * See bdrv_co_block_status_above() for details.
2147 static int bdrv_common_block_status_above(BlockDriverState
*bs
,
2148 BlockDriverState
*base
,
2149 bool want_zero
, int64_t offset
,
2150 int64_t bytes
, int64_t *pnum
,
2152 BlockDriverState
**file
)
2155 BdrvCoBlockStatusData data
= {
2158 .want_zero
= want_zero
,
2167 if (qemu_in_coroutine()) {
2168 /* Fast-path if already in coroutine context */
2169 bdrv_block_status_above_co_entry(&data
);
2171 co
= qemu_coroutine_create(bdrv_block_status_above_co_entry
, &data
);
2172 bdrv_coroutine_enter(bs
, co
);
2173 BDRV_POLL_WHILE(bs
, !data
.done
);
2178 int bdrv_block_status_above(BlockDriverState
*bs
, BlockDriverState
*base
,
2179 int64_t offset
, int64_t bytes
, int64_t *pnum
,
2180 int64_t *map
, BlockDriverState
**file
)
2182 return bdrv_common_block_status_above(bs
, base
, true, offset
, bytes
,
2186 int bdrv_block_status(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2187 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2189 return bdrv_block_status_above(bs
, backing_bs(bs
),
2190 offset
, bytes
, pnum
, map
, file
);
2193 int coroutine_fn
bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
,
2194 int64_t bytes
, int64_t *pnum
)
2199 ret
= bdrv_common_block_status_above(bs
, backing_bs(bs
), false, offset
,
2200 bytes
, pnum
? pnum
: &dummy
, NULL
,
2205 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2209 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2211 * Return true if (a prefix of) the given range is allocated in any image
2212 * between BASE and TOP (inclusive). BASE can be NULL to check if the given
2213 * offset is allocated in any image of the chain. Return false otherwise,
2214 * or negative errno on failure.
2216 * 'pnum' is set to the number of bytes (including and immediately
2217 * following the specified offset) that are known to be in the same
2218 * allocated/unallocated state. Note that a subsequent call starting
2219 * at 'offset + *pnum' may return the same allocation status (in other
2220 * words, the result is not necessarily the maximum possible range);
2221 * but 'pnum' will only be 0 when end of file is reached.
2224 int bdrv_is_allocated_above(BlockDriverState
*top
,
2225 BlockDriverState
*base
,
2226 int64_t offset
, int64_t bytes
, int64_t *pnum
)
2228 BlockDriverState
*intermediate
;
2233 while (intermediate
&& intermediate
!= base
) {
2237 ret
= bdrv_is_allocated(intermediate
, offset
, bytes
, &pnum_inter
);
2246 size_inter
= bdrv_getlength(intermediate
);
2247 if (size_inter
< 0) {
2250 if (n
> pnum_inter
&&
2251 (intermediate
== top
|| offset
+ pnum_inter
< size_inter
)) {
2255 intermediate
= backing_bs(intermediate
);
2262 typedef struct BdrvVmstateCo
{
2263 BlockDriverState
*bs
;
2270 static int coroutine_fn
2271 bdrv_co_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
2274 BlockDriver
*drv
= bs
->drv
;
2277 bdrv_inc_in_flight(bs
);
2281 } else if (drv
->bdrv_load_vmstate
) {
2283 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
2285 ret
= drv
->bdrv_save_vmstate(bs
, qiov
, pos
);
2287 } else if (bs
->file
) {
2288 ret
= bdrv_co_rw_vmstate(bs
->file
->bs
, qiov
, pos
, is_read
);
2291 bdrv_dec_in_flight(bs
);
2295 static void coroutine_fn
bdrv_co_rw_vmstate_entry(void *opaque
)
2297 BdrvVmstateCo
*co
= opaque
;
2298 co
->ret
= bdrv_co_rw_vmstate(co
->bs
, co
->qiov
, co
->pos
, co
->is_read
);
2302 bdrv_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
2305 if (qemu_in_coroutine()) {
2306 return bdrv_co_rw_vmstate(bs
, qiov
, pos
, is_read
);
2308 BdrvVmstateCo data
= {
2313 .ret
= -EINPROGRESS
,
2315 Coroutine
*co
= qemu_coroutine_create(bdrv_co_rw_vmstate_entry
, &data
);
2317 bdrv_coroutine_enter(bs
, co
);
2318 BDRV_POLL_WHILE(bs
, data
.ret
== -EINPROGRESS
);
2323 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2324 int64_t pos
, int size
)
2327 struct iovec iov
= {
2328 .iov_base
= (void *) buf
,
2333 qemu_iovec_init_external(&qiov
, &iov
, 1);
2335 ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2343 int bdrv_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2345 return bdrv_rw_vmstate(bs
, qiov
, pos
, false);
2348 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2349 int64_t pos
, int size
)
2352 struct iovec iov
= {
2358 qemu_iovec_init_external(&qiov
, &iov
, 1);
2359 ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2367 int bdrv_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2369 return bdrv_rw_vmstate(bs
, qiov
, pos
, true);
2372 /**************************************************************/
2375 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2378 bdrv_aio_cancel_async(acb
);
2379 while (acb
->refcnt
> 1) {
2380 if (acb
->aiocb_info
->get_aio_context
) {
2381 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2382 } else if (acb
->bs
) {
2383 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2384 * assert that we're not using an I/O thread. Thread-safe
2385 * code should use bdrv_aio_cancel_async exclusively.
2387 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2388 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2393 qemu_aio_unref(acb
);
2396 /* Async version of aio cancel. The caller is not blocked if the acb implements
2397 * cancel_async, otherwise we do nothing and let the request normally complete.
2398 * In either case the completion callback must be called. */
2399 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2401 if (acb
->aiocb_info
->cancel_async
) {
2402 acb
->aiocb_info
->cancel_async(acb
);
2406 /**************************************************************/
2407 /* Coroutine block device emulation */
2409 typedef struct FlushCo
{
2410 BlockDriverState
*bs
;
2415 static void coroutine_fn
bdrv_flush_co_entry(void *opaque
)
2417 FlushCo
*rwco
= opaque
;
2419 rwco
->ret
= bdrv_co_flush(rwco
->bs
);
2422 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2427 bdrv_inc_in_flight(bs
);
2429 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2434 qemu_co_mutex_lock(&bs
->reqs_lock
);
2435 current_gen
= atomic_read(&bs
->write_gen
);
2437 /* Wait until any previous flushes are completed */
2438 while (bs
->active_flush_req
) {
2439 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2442 /* Flushes reach this point in nondecreasing current_gen order. */
2443 bs
->active_flush_req
= true;
2444 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2446 /* Write back all layers by calling one driver function */
2447 if (bs
->drv
->bdrv_co_flush
) {
2448 ret
= bs
->drv
->bdrv_co_flush(bs
);
2452 /* Write back cached data to the OS even with cache=unsafe */
2453 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_OS
);
2454 if (bs
->drv
->bdrv_co_flush_to_os
) {
2455 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2461 /* But don't actually force it to the disk with cache=unsafe */
2462 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2466 /* Check if we really need to flush anything */
2467 if (bs
->flushed_gen
== current_gen
) {
2471 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_DISK
);
2473 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2474 * (even in case of apparent success) */
2478 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2479 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2480 } else if (bs
->drv
->bdrv_aio_flush
) {
2482 CoroutineIOCompletion co
= {
2483 .coroutine
= qemu_coroutine_self(),
2486 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2490 qemu_coroutine_yield();
2495 * Some block drivers always operate in either writethrough or unsafe
2496 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2497 * know how the server works (because the behaviour is hardcoded or
2498 * depends on server-side configuration), so we can't ensure that
2499 * everything is safe on disk. Returning an error doesn't work because
2500 * that would break guests even if the server operates in writethrough
2503 * Let's hope the user knows what he's doing.
2512 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2513 * in the case of cache=unsafe, so there are no useless flushes.
2516 ret
= bs
->file
? bdrv_co_flush(bs
->file
->bs
) : 0;
2518 /* Notify any pending flushes that we have completed */
2520 bs
->flushed_gen
= current_gen
;
2523 qemu_co_mutex_lock(&bs
->reqs_lock
);
2524 bs
->active_flush_req
= false;
2525 /* Return value is ignored - it's ok if wait queue is empty */
2526 qemu_co_queue_next(&bs
->flush_queue
);
2527 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2530 bdrv_dec_in_flight(bs
);
2534 int bdrv_flush(BlockDriverState
*bs
)
2537 FlushCo flush_co
= {
2542 if (qemu_in_coroutine()) {
2543 /* Fast-path if already in coroutine context */
2544 bdrv_flush_co_entry(&flush_co
);
2546 co
= qemu_coroutine_create(bdrv_flush_co_entry
, &flush_co
);
2547 bdrv_coroutine_enter(bs
, co
);
2548 BDRV_POLL_WHILE(bs
, flush_co
.ret
== NOT_DONE
);
2551 return flush_co
.ret
;
2554 typedef struct DiscardCo
{
2555 BlockDriverState
*bs
;
2560 static void coroutine_fn
bdrv_pdiscard_co_entry(void *opaque
)
2562 DiscardCo
*rwco
= opaque
;
2564 rwco
->ret
= bdrv_co_pdiscard(rwco
->bs
, rwco
->offset
, rwco
->bytes
);
2567 int coroutine_fn
bdrv_co_pdiscard(BlockDriverState
*bs
, int64_t offset
,
2570 BdrvTrackedRequest req
;
2571 int max_pdiscard
, ret
;
2572 int head
, tail
, align
;
2578 if (bdrv_has_readonly_bitmaps(bs
)) {
2582 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
2585 } else if (bs
->read_only
) {
2588 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
2590 /* Do nothing if disabled. */
2591 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2595 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2599 /* Discard is advisory, but some devices track and coalesce
2600 * unaligned requests, so we must pass everything down rather than
2601 * round here. Still, most devices will just silently ignore
2602 * unaligned requests (by returning -ENOTSUP), so we must fragment
2603 * the request accordingly. */
2604 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
2605 assert(align
% bs
->bl
.request_alignment
== 0);
2606 head
= offset
% align
;
2607 tail
= (offset
+ bytes
) % align
;
2609 bdrv_inc_in_flight(bs
);
2610 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
2612 ret
= notifier_with_return_list_notify(&bs
->before_write_notifiers
, &req
);
2617 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT_MAX
),
2619 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
2625 /* Make small requests to get to alignment boundaries. */
2626 num
= MIN(bytes
, align
- head
);
2627 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
2628 num
%= bs
->bl
.request_alignment
;
2630 head
= (head
+ num
) % align
;
2631 assert(num
< max_pdiscard
);
2634 /* Shorten the request to the last aligned cluster. */
2636 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
2637 tail
> bs
->bl
.request_alignment
) {
2638 tail
%= bs
->bl
.request_alignment
;
2642 /* limit request size */
2643 if (num
> max_pdiscard
) {
2651 if (bs
->drv
->bdrv_co_pdiscard
) {
2652 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
2655 CoroutineIOCompletion co
= {
2656 .coroutine
= qemu_coroutine_self(),
2659 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
2660 bdrv_co_io_em_complete
, &co
);
2665 qemu_coroutine_yield();
2669 if (ret
&& ret
!= -ENOTSUP
) {
2678 atomic_inc(&bs
->write_gen
);
2679 bdrv_set_dirty(bs
, req
.offset
, req
.bytes
);
2680 tracked_request_end(&req
);
2681 bdrv_dec_in_flight(bs
);
2685 int bdrv_pdiscard(BlockDriverState
*bs
, int64_t offset
, int bytes
)
2695 if (qemu_in_coroutine()) {
2696 /* Fast-path if already in coroutine context */
2697 bdrv_pdiscard_co_entry(&rwco
);
2699 co
= qemu_coroutine_create(bdrv_pdiscard_co_entry
, &rwco
);
2700 bdrv_coroutine_enter(bs
, co
);
2701 BDRV_POLL_WHILE(bs
, rwco
.ret
== NOT_DONE
);
2707 int bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
2709 BlockDriver
*drv
= bs
->drv
;
2710 CoroutineIOCompletion co
= {
2711 .coroutine
= qemu_coroutine_self(),
2715 bdrv_inc_in_flight(bs
);
2716 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
2721 if (drv
->bdrv_co_ioctl
) {
2722 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
2724 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
2729 qemu_coroutine_yield();
2732 bdrv_dec_in_flight(bs
);
2736 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2738 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
2741 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
2743 return memset(qemu_blockalign(bs
, size
), 0, size
);
2746 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
2748 size_t align
= bdrv_opt_mem_align(bs
);
2750 /* Ensure that NULL is never returned on success */
2756 return qemu_try_memalign(align
, size
);
2759 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
2761 void *mem
= qemu_try_blockalign(bs
, size
);
2764 memset(mem
, 0, size
);
2771 * Check if all memory in this vector is sector aligned.
2773 bool bdrv_qiov_is_aligned(BlockDriverState
*bs
, QEMUIOVector
*qiov
)
2776 size_t alignment
= bdrv_min_mem_align(bs
);
2778 for (i
= 0; i
< qiov
->niov
; i
++) {
2779 if ((uintptr_t) qiov
->iov
[i
].iov_base
% alignment
) {
2782 if (qiov
->iov
[i
].iov_len
% alignment
) {
2790 void bdrv_add_before_write_notifier(BlockDriverState
*bs
,
2791 NotifierWithReturn
*notifier
)
2793 notifier_with_return_list_add(&bs
->before_write_notifiers
, notifier
);
2796 void bdrv_io_plug(BlockDriverState
*bs
)
2800 QLIST_FOREACH(child
, &bs
->children
, next
) {
2801 bdrv_io_plug(child
->bs
);
2804 if (atomic_fetch_inc(&bs
->io_plugged
) == 0) {
2805 BlockDriver
*drv
= bs
->drv
;
2806 if (drv
&& drv
->bdrv_io_plug
) {
2807 drv
->bdrv_io_plug(bs
);
2812 void bdrv_io_unplug(BlockDriverState
*bs
)
2816 assert(bs
->io_plugged
);
2817 if (atomic_fetch_dec(&bs
->io_plugged
) == 1) {
2818 BlockDriver
*drv
= bs
->drv
;
2819 if (drv
&& drv
->bdrv_io_unplug
) {
2820 drv
->bdrv_io_unplug(bs
);
2824 QLIST_FOREACH(child
, &bs
->children
, next
) {
2825 bdrv_io_unplug(child
->bs
);
2829 void bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
)
2833 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
2834 bs
->drv
->bdrv_register_buf(bs
, host
, size
);
2836 QLIST_FOREACH(child
, &bs
->children
, next
) {
2837 bdrv_register_buf(child
->bs
, host
, size
);
2841 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
)
2845 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
2846 bs
->drv
->bdrv_unregister_buf(bs
, host
);
2848 QLIST_FOREACH(child
, &bs
->children
, next
) {
2849 bdrv_unregister_buf(child
->bs
, host
);