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 static BlockAIOCB
*bdrv_co_aio_prw_vector(BdrvChild
*child
,
40 BdrvRequestFlags flags
,
41 BlockCompletionFunc
*cb
,
44 static void coroutine_fn
bdrv_co_do_rw(void *opaque
);
45 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
46 int64_t offset
, int count
, BdrvRequestFlags flags
);
48 void bdrv_parent_drained_begin(BlockDriverState
*bs
)
52 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
53 if (c
->role
->drained_begin
) {
54 c
->role
->drained_begin(c
);
59 void bdrv_parent_drained_end(BlockDriverState
*bs
)
63 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
64 if (c
->role
->drained_end
) {
65 c
->role
->drained_end(c
);
70 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
72 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
73 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
74 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
75 src
->opt_mem_alignment
);
76 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
77 src
->min_mem_alignment
);
78 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
81 void bdrv_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
83 BlockDriver
*drv
= bs
->drv
;
84 Error
*local_err
= NULL
;
86 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
92 /* Default alignment based on whether driver has byte interface */
93 bs
->bl
.request_alignment
= drv
->bdrv_co_preadv
? 1 : 512;
95 /* Take some limits from the children as a default */
97 bdrv_refresh_limits(bs
->file
->bs
, &local_err
);
99 error_propagate(errp
, local_err
);
102 bdrv_merge_limits(&bs
->bl
, &bs
->file
->bs
->bl
);
104 bs
->bl
.min_mem_alignment
= 512;
105 bs
->bl
.opt_mem_alignment
= getpagesize();
107 /* Safe default since most protocols use readv()/writev()/etc */
108 bs
->bl
.max_iov
= IOV_MAX
;
112 bdrv_refresh_limits(bs
->backing
->bs
, &local_err
);
114 error_propagate(errp
, local_err
);
117 bdrv_merge_limits(&bs
->bl
, &bs
->backing
->bs
->bl
);
120 /* Then let the driver override it */
121 if (drv
->bdrv_refresh_limits
) {
122 drv
->bdrv_refresh_limits(bs
, errp
);
127 * The copy-on-read flag is actually a reference count so multiple users may
128 * use the feature without worrying about clobbering its previous state.
129 * Copy-on-read stays enabled until all users have called to disable it.
131 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
133 atomic_inc(&bs
->copy_on_read
);
136 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
138 int old
= atomic_fetch_dec(&bs
->copy_on_read
);
142 /* Check if any requests are in-flight (including throttled requests) */
143 bool bdrv_requests_pending(BlockDriverState
*bs
)
147 if (atomic_read(&bs
->in_flight
)) {
151 QLIST_FOREACH(child
, &bs
->children
, next
) {
152 if (bdrv_requests_pending(child
->bs
)) {
160 static bool bdrv_drain_recurse(BlockDriverState
*bs
)
162 BdrvChild
*child
, *tmp
;
165 waited
= BDRV_POLL_WHILE(bs
, atomic_read(&bs
->in_flight
) > 0);
167 if (bs
->drv
&& bs
->drv
->bdrv_drain
) {
168 bs
->drv
->bdrv_drain(bs
);
171 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, tmp
) {
172 BlockDriverState
*bs
= child
->bs
;
174 qemu_get_current_aio_context() == qemu_get_aio_context();
175 assert(bs
->refcnt
> 0);
177 /* In case the recursive bdrv_drain_recurse processes a
178 * block_job_defer_to_main_loop BH and modifies the graph,
179 * let's hold a reference to bs until we are done.
181 * IOThread doesn't have such a BH, and it is not safe to call
182 * bdrv_unref without BQL, so skip doing it there.
186 waited
|= bdrv_drain_recurse(bs
);
197 BlockDriverState
*bs
;
201 static void bdrv_co_drain_bh_cb(void *opaque
)
203 BdrvCoDrainData
*data
= opaque
;
204 Coroutine
*co
= data
->co
;
205 BlockDriverState
*bs
= data
->bs
;
207 bdrv_dec_in_flight(bs
);
208 bdrv_drained_begin(bs
);
213 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
)
215 BdrvCoDrainData data
;
217 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
218 * other coroutines run if they were queued from
219 * qemu_co_queue_run_restart(). */
221 assert(qemu_in_coroutine());
222 data
= (BdrvCoDrainData
) {
223 .co
= qemu_coroutine_self(),
227 bdrv_inc_in_flight(bs
);
228 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs
),
229 bdrv_co_drain_bh_cb
, &data
);
231 qemu_coroutine_yield();
232 /* If we are resumed from some other event (such as an aio completion or a
233 * timer callback), it is a bug in the caller that should be fixed. */
237 void bdrv_drained_begin(BlockDriverState
*bs
)
239 if (qemu_in_coroutine()) {
240 bdrv_co_yield_to_drain(bs
);
244 if (atomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
245 aio_disable_external(bdrv_get_aio_context(bs
));
246 bdrv_parent_drained_begin(bs
);
249 bdrv_drain_recurse(bs
);
252 void bdrv_drained_end(BlockDriverState
*bs
)
254 assert(bs
->quiesce_counter
> 0);
255 if (atomic_fetch_dec(&bs
->quiesce_counter
) > 1) {
259 bdrv_parent_drained_end(bs
);
260 aio_enable_external(bdrv_get_aio_context(bs
));
264 * Wait for pending requests to complete on a single BlockDriverState subtree,
265 * and suspend block driver's internal I/O until next request arrives.
267 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
270 * Only this BlockDriverState's AioContext is run, so in-flight requests must
271 * not depend on events in other AioContexts. In that case, use
272 * bdrv_drain_all() instead.
274 void coroutine_fn
bdrv_co_drain(BlockDriverState
*bs
)
276 assert(qemu_in_coroutine());
277 bdrv_drained_begin(bs
);
278 bdrv_drained_end(bs
);
281 void bdrv_drain(BlockDriverState
*bs
)
283 bdrv_drained_begin(bs
);
284 bdrv_drained_end(bs
);
288 * Wait for pending requests to complete across all BlockDriverStates
290 * This function does not flush data to disk, use bdrv_flush_all() for that
291 * after calling this function.
293 * This pauses all block jobs and disables external clients. It must
294 * be paired with bdrv_drain_all_end().
296 * NOTE: no new block jobs or BlockDriverStates can be created between
297 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
299 void bdrv_drain_all_begin(void)
301 /* Always run first iteration so any pending completion BHs run */
303 BlockDriverState
*bs
;
305 GSList
*aio_ctxs
= NULL
, *ctx
;
307 block_job_pause_all();
309 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
310 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
312 aio_context_acquire(aio_context
);
313 bdrv_parent_drained_begin(bs
);
314 aio_disable_external(aio_context
);
315 aio_context_release(aio_context
);
317 if (!g_slist_find(aio_ctxs
, aio_context
)) {
318 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
322 /* Note that completion of an asynchronous I/O operation can trigger any
323 * number of other I/O operations on other devices---for example a
324 * coroutine can submit an I/O request to another device in response to
325 * request completion. Therefore we must keep looping until there was no
326 * more activity rather than simply draining each device independently.
331 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
332 AioContext
*aio_context
= ctx
->data
;
334 aio_context_acquire(aio_context
);
335 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
336 if (aio_context
== bdrv_get_aio_context(bs
)) {
337 waited
|= bdrv_drain_recurse(bs
);
340 aio_context_release(aio_context
);
344 g_slist_free(aio_ctxs
);
347 void bdrv_drain_all_end(void)
349 BlockDriverState
*bs
;
352 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
353 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
355 aio_context_acquire(aio_context
);
356 aio_enable_external(aio_context
);
357 bdrv_parent_drained_end(bs
);
358 aio_context_release(aio_context
);
361 block_job_resume_all();
364 void bdrv_drain_all(void)
366 bdrv_drain_all_begin();
367 bdrv_drain_all_end();
371 * Remove an active request from the tracked requests list
373 * This function should be called when a tracked request is completing.
375 static void tracked_request_end(BdrvTrackedRequest
*req
)
377 if (req
->serialising
) {
378 atomic_dec(&req
->bs
->serialising_in_flight
);
381 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
382 QLIST_REMOVE(req
, list
);
383 qemu_co_queue_restart_all(&req
->wait_queue
);
384 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
388 * Add an active request to the tracked requests list
390 static void tracked_request_begin(BdrvTrackedRequest
*req
,
391 BlockDriverState
*bs
,
394 enum BdrvTrackedRequestType type
)
396 *req
= (BdrvTrackedRequest
){
401 .co
= qemu_coroutine_self(),
402 .serialising
= false,
403 .overlap_offset
= offset
,
404 .overlap_bytes
= bytes
,
407 qemu_co_queue_init(&req
->wait_queue
);
409 qemu_co_mutex_lock(&bs
->reqs_lock
);
410 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
411 qemu_co_mutex_unlock(&bs
->reqs_lock
);
414 static void mark_request_serialising(BdrvTrackedRequest
*req
, uint64_t align
)
416 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
417 unsigned int overlap_bytes
= ROUND_UP(req
->offset
+ req
->bytes
, align
)
420 if (!req
->serialising
) {
421 atomic_inc(&req
->bs
->serialising_in_flight
);
422 req
->serialising
= true;
425 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
426 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
430 * Round a region to cluster boundaries (sector-based)
432 void bdrv_round_sectors_to_clusters(BlockDriverState
*bs
,
433 int64_t sector_num
, int nb_sectors
,
434 int64_t *cluster_sector_num
,
435 int *cluster_nb_sectors
)
439 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
440 *cluster_sector_num
= sector_num
;
441 *cluster_nb_sectors
= nb_sectors
;
443 int64_t c
= bdi
.cluster_size
/ BDRV_SECTOR_SIZE
;
444 *cluster_sector_num
= QEMU_ALIGN_DOWN(sector_num
, c
);
445 *cluster_nb_sectors
= QEMU_ALIGN_UP(sector_num
- *cluster_sector_num
+
451 * Round a region to cluster boundaries
453 void bdrv_round_to_clusters(BlockDriverState
*bs
,
454 int64_t offset
, unsigned int bytes
,
455 int64_t *cluster_offset
,
456 unsigned int *cluster_bytes
)
460 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
461 *cluster_offset
= offset
;
462 *cluster_bytes
= bytes
;
464 int64_t c
= bdi
.cluster_size
;
465 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
466 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
470 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
475 ret
= bdrv_get_info(bs
, &bdi
);
476 if (ret
< 0 || bdi
.cluster_size
== 0) {
477 return bs
->bl
.request_alignment
;
479 return bdi
.cluster_size
;
483 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
484 int64_t offset
, unsigned int bytes
)
487 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
491 if (req
->overlap_offset
>= offset
+ bytes
) {
497 void bdrv_inc_in_flight(BlockDriverState
*bs
)
499 atomic_inc(&bs
->in_flight
);
502 static void dummy_bh_cb(void *opaque
)
506 void bdrv_wakeup(BlockDriverState
*bs
)
508 /* The barrier (or an atomic op) is in the caller. */
509 if (atomic_read(&bs
->wakeup
)) {
510 aio_bh_schedule_oneshot(qemu_get_aio_context(), dummy_bh_cb
, NULL
);
514 void bdrv_dec_in_flight(BlockDriverState
*bs
)
516 atomic_dec(&bs
->in_flight
);
520 static bool coroutine_fn
wait_serialising_requests(BdrvTrackedRequest
*self
)
522 BlockDriverState
*bs
= self
->bs
;
523 BdrvTrackedRequest
*req
;
527 if (!atomic_read(&bs
->serialising_in_flight
)) {
533 qemu_co_mutex_lock(&bs
->reqs_lock
);
534 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
535 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
538 if (tracked_request_overlaps(req
, self
->overlap_offset
,
539 self
->overlap_bytes
))
541 /* Hitting this means there was a reentrant request, for
542 * example, a block driver issuing nested requests. This must
543 * never happen since it means deadlock.
545 assert(qemu_coroutine_self() != req
->co
);
547 /* If the request is already (indirectly) waiting for us, or
548 * will wait for us as soon as it wakes up, then just go on
549 * (instead of producing a deadlock in the former case). */
550 if (!req
->waiting_for
) {
551 self
->waiting_for
= req
;
552 qemu_co_queue_wait(&req
->wait_queue
, &bs
->reqs_lock
);
553 self
->waiting_for
= NULL
;
560 qemu_co_mutex_unlock(&bs
->reqs_lock
);
566 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
569 if (size
> BDRV_REQUEST_MAX_SECTORS
<< BDRV_SECTOR_BITS
) {
573 if (!bdrv_is_inserted(bs
)) {
584 typedef struct RwCo
{
590 BdrvRequestFlags flags
;
593 static void coroutine_fn
bdrv_rw_co_entry(void *opaque
)
597 if (!rwco
->is_write
) {
598 rwco
->ret
= bdrv_co_preadv(rwco
->child
, rwco
->offset
,
599 rwco
->qiov
->size
, rwco
->qiov
,
602 rwco
->ret
= bdrv_co_pwritev(rwco
->child
, rwco
->offset
,
603 rwco
->qiov
->size
, rwco
->qiov
,
609 * Process a vectored synchronous request using coroutines
611 static int bdrv_prwv_co(BdrvChild
*child
, int64_t offset
,
612 QEMUIOVector
*qiov
, bool is_write
,
613 BdrvRequestFlags flags
)
620 .is_write
= is_write
,
625 if (qemu_in_coroutine()) {
626 /* Fast-path if already in coroutine context */
627 bdrv_rw_co_entry(&rwco
);
629 co
= qemu_coroutine_create(bdrv_rw_co_entry
, &rwco
);
630 bdrv_coroutine_enter(child
->bs
, co
);
631 BDRV_POLL_WHILE(child
->bs
, rwco
.ret
== NOT_DONE
);
637 * Process a synchronous request using coroutines
639 static int bdrv_rw_co(BdrvChild
*child
, int64_t sector_num
, uint8_t *buf
,
640 int nb_sectors
, bool is_write
, BdrvRequestFlags flags
)
644 .iov_base
= (void *)buf
,
645 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
648 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
652 qemu_iovec_init_external(&qiov
, &iov
, 1);
653 return bdrv_prwv_co(child
, sector_num
<< BDRV_SECTOR_BITS
,
654 &qiov
, is_write
, flags
);
657 /* return < 0 if error. See bdrv_write() for the return codes */
658 int bdrv_read(BdrvChild
*child
, int64_t sector_num
,
659 uint8_t *buf
, int nb_sectors
)
661 return bdrv_rw_co(child
, sector_num
, buf
, nb_sectors
, false, 0);
664 /* Return < 0 if error. Important errors are:
665 -EIO generic I/O error (may happen for all errors)
666 -ENOMEDIUM No media inserted.
667 -EINVAL Invalid sector number or nb_sectors
668 -EACCES Trying to write a read-only device
670 int bdrv_write(BdrvChild
*child
, int64_t sector_num
,
671 const uint8_t *buf
, int nb_sectors
)
673 return bdrv_rw_co(child
, sector_num
, (uint8_t *)buf
, nb_sectors
, true, 0);
676 int bdrv_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
677 int count
, BdrvRequestFlags flags
)
685 qemu_iovec_init_external(&qiov
, &iov
, 1);
686 return bdrv_prwv_co(child
, offset
, &qiov
, true,
687 BDRV_REQ_ZERO_WRITE
| flags
);
691 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
692 * The operation is sped up by checking the block status and only writing
693 * zeroes to the device if they currently do not return zeroes. Optional
694 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
697 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
699 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
701 int64_t target_sectors
, ret
, nb_sectors
, sector_num
= 0;
702 BlockDriverState
*bs
= child
->bs
;
703 BlockDriverState
*file
;
706 target_sectors
= bdrv_nb_sectors(bs
);
707 if (target_sectors
< 0) {
708 return target_sectors
;
712 nb_sectors
= MIN(target_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
713 if (nb_sectors
<= 0) {
716 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &n
, &file
);
718 error_report("error getting block status at sector %" PRId64
": %s",
719 sector_num
, strerror(-ret
));
722 if (ret
& BDRV_BLOCK_ZERO
) {
726 ret
= bdrv_pwrite_zeroes(child
, sector_num
<< BDRV_SECTOR_BITS
,
727 n
<< BDRV_SECTOR_BITS
, flags
);
729 error_report("error writing zeroes at sector %" PRId64
": %s",
730 sector_num
, strerror(-ret
));
737 int bdrv_preadv(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
741 ret
= bdrv_prwv_co(child
, offset
, qiov
, false, 0);
749 int bdrv_pread(BdrvChild
*child
, int64_t offset
, void *buf
, int bytes
)
753 .iov_base
= (void *)buf
,
761 qemu_iovec_init_external(&qiov
, &iov
, 1);
762 return bdrv_preadv(child
, offset
, &qiov
);
765 int bdrv_pwritev(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
769 ret
= bdrv_prwv_co(child
, offset
, qiov
, true, 0);
777 int bdrv_pwrite(BdrvChild
*child
, int64_t offset
, const void *buf
, int bytes
)
781 .iov_base
= (void *) buf
,
789 qemu_iovec_init_external(&qiov
, &iov
, 1);
790 return bdrv_pwritev(child
, offset
, &qiov
);
794 * Writes to the file and ensures that no writes are reordered across this
795 * request (acts as a barrier)
797 * Returns 0 on success, -errno in error cases.
799 int bdrv_pwrite_sync(BdrvChild
*child
, int64_t offset
,
800 const void *buf
, int count
)
804 ret
= bdrv_pwrite(child
, offset
, buf
, count
);
809 ret
= bdrv_flush(child
->bs
);
817 typedef struct CoroutineIOCompletion
{
818 Coroutine
*coroutine
;
820 } CoroutineIOCompletion
;
822 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
824 CoroutineIOCompletion
*co
= opaque
;
827 aio_co_wake(co
->coroutine
);
830 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
831 uint64_t offset
, uint64_t bytes
,
832 QEMUIOVector
*qiov
, int flags
)
834 BlockDriver
*drv
= bs
->drv
;
836 unsigned int nb_sectors
;
838 assert(!(flags
& ~BDRV_REQ_MASK
));
840 if (drv
->bdrv_co_preadv
) {
841 return drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
844 sector_num
= offset
>> BDRV_SECTOR_BITS
;
845 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
847 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
848 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
849 assert((bytes
>> BDRV_SECTOR_BITS
) <= BDRV_REQUEST_MAX_SECTORS
);
851 if (drv
->bdrv_co_readv
) {
852 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
855 CoroutineIOCompletion co
= {
856 .coroutine
= qemu_coroutine_self(),
859 acb
= bs
->drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
860 bdrv_co_io_em_complete
, &co
);
864 qemu_coroutine_yield();
870 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
871 uint64_t offset
, uint64_t bytes
,
872 QEMUIOVector
*qiov
, int flags
)
874 BlockDriver
*drv
= bs
->drv
;
876 unsigned int nb_sectors
;
879 assert(!(flags
& ~BDRV_REQ_MASK
));
881 if (drv
->bdrv_co_pwritev
) {
882 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
,
883 flags
& bs
->supported_write_flags
);
884 flags
&= ~bs
->supported_write_flags
;
888 sector_num
= offset
>> BDRV_SECTOR_BITS
;
889 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
891 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
892 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
893 assert((bytes
>> BDRV_SECTOR_BITS
) <= BDRV_REQUEST_MAX_SECTORS
);
895 if (drv
->bdrv_co_writev_flags
) {
896 ret
= drv
->bdrv_co_writev_flags(bs
, sector_num
, nb_sectors
, qiov
,
897 flags
& bs
->supported_write_flags
);
898 flags
&= ~bs
->supported_write_flags
;
899 } else if (drv
->bdrv_co_writev
) {
900 assert(!bs
->supported_write_flags
);
901 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
);
904 CoroutineIOCompletion co
= {
905 .coroutine
= qemu_coroutine_self(),
908 acb
= bs
->drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
909 bdrv_co_io_em_complete
, &co
);
913 qemu_coroutine_yield();
919 if (ret
== 0 && (flags
& BDRV_REQ_FUA
)) {
920 ret
= bdrv_co_flush(bs
);
926 static int coroutine_fn
927 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
928 uint64_t bytes
, QEMUIOVector
*qiov
)
930 BlockDriver
*drv
= bs
->drv
;
932 if (!drv
->bdrv_co_pwritev_compressed
) {
936 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
939 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
940 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
)
942 BlockDriverState
*bs
= child
->bs
;
944 /* Perform I/O through a temporary buffer so that users who scribble over
945 * their read buffer while the operation is in progress do not end up
946 * modifying the image file. This is critical for zero-copy guest I/O
947 * where anything might happen inside guest memory.
951 BlockDriver
*drv
= bs
->drv
;
953 QEMUIOVector bounce_qiov
;
954 int64_t cluster_offset
;
955 unsigned int cluster_bytes
;
959 /* FIXME We cannot require callers to have write permissions when all they
960 * are doing is a read request. If we did things right, write permissions
961 * would be obtained anyway, but internally by the copy-on-read code. As
962 * long as it is implemented here rather than in a separat filter driver,
963 * the copy-on-read code doesn't have its own BdrvChild, however, for which
964 * it could request permissions. Therefore we have to bypass the permission
965 * system for the moment. */
966 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
968 /* Cover entire cluster so no additional backing file I/O is required when
969 * allocating cluster in the image file.
971 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
973 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
974 cluster_offset
, cluster_bytes
);
976 iov
.iov_len
= cluster_bytes
;
977 iov
.iov_base
= bounce_buffer
= qemu_try_blockalign(bs
, iov
.iov_len
);
978 if (bounce_buffer
== NULL
) {
983 qemu_iovec_init_external(&bounce_qiov
, &iov
, 1);
985 ret
= bdrv_driver_preadv(bs
, cluster_offset
, cluster_bytes
,
991 if (drv
->bdrv_co_pwrite_zeroes
&&
992 buffer_is_zero(bounce_buffer
, iov
.iov_len
)) {
993 /* FIXME: Should we (perhaps conditionally) be setting
994 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
995 * that still correctly reads as zero? */
996 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, cluster_bytes
, 0);
998 /* This does not change the data on the disk, it is not necessary
999 * to flush even in cache=writethrough mode.
1001 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, cluster_bytes
,
1006 /* It might be okay to ignore write errors for guest requests. If this
1007 * is a deliberate copy-on-read then we don't want to ignore the error.
1008 * Simply report it in all cases.
1013 skip_bytes
= offset
- cluster_offset
;
1014 qemu_iovec_from_buf(qiov
, 0, bounce_buffer
+ skip_bytes
, bytes
);
1017 qemu_vfree(bounce_buffer
);
1022 * Forwards an already correctly aligned request to the BlockDriver. This
1023 * handles copy on read, zeroing after EOF, and fragmentation of large
1024 * reads; any other features must be implemented by the caller.
1026 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1027 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1028 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1030 BlockDriverState
*bs
= child
->bs
;
1031 int64_t total_bytes
, max_bytes
;
1033 uint64_t bytes_remaining
= bytes
;
1036 assert(is_power_of_2(align
));
1037 assert((offset
& (align
- 1)) == 0);
1038 assert((bytes
& (align
- 1)) == 0);
1039 assert(!qiov
|| bytes
== qiov
->size
);
1040 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1041 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1044 /* TODO: We would need a per-BDS .supported_read_flags and
1045 * potential fallback support, if we ever implement any read flags
1046 * to pass through to drivers. For now, there aren't any
1047 * passthrough flags. */
1048 assert(!(flags
& ~(BDRV_REQ_NO_SERIALISING
| BDRV_REQ_COPY_ON_READ
)));
1050 /* Handle Copy on Read and associated serialisation */
1051 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1052 /* If we touch the same cluster it counts as an overlap. This
1053 * guarantees that allocating writes will be serialized and not race
1054 * with each other for the same cluster. For example, in copy-on-read
1055 * it ensures that the CoR read and write operations are atomic and
1056 * guest writes cannot interleave between them. */
1057 mark_request_serialising(req
, bdrv_get_cluster_size(bs
));
1060 if (!(flags
& BDRV_REQ_NO_SERIALISING
)) {
1061 wait_serialising_requests(req
);
1064 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1065 int64_t start_sector
= offset
>> BDRV_SECTOR_BITS
;
1066 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1067 unsigned int nb_sectors
= end_sector
- start_sector
;
1070 ret
= bdrv_is_allocated(bs
, start_sector
, nb_sectors
, &pnum
);
1075 if (!ret
|| pnum
!= nb_sectors
) {
1076 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
, qiov
);
1081 /* Forward the request to the BlockDriver, possibly fragmenting it */
1082 total_bytes
= bdrv_getlength(bs
);
1083 if (total_bytes
< 0) {
1088 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1089 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1090 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, 0);
1094 while (bytes_remaining
) {
1098 QEMUIOVector local_qiov
;
1100 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1102 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1103 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1105 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1106 num
, &local_qiov
, 0);
1108 qemu_iovec_destroy(&local_qiov
);
1110 num
= bytes_remaining
;
1111 ret
= qemu_iovec_memset(qiov
, bytes
- bytes_remaining
, 0,
1117 bytes_remaining
-= num
;
1121 return ret
< 0 ? ret
: 0;
1125 * Handle a read request in coroutine context
1127 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1128 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1129 BdrvRequestFlags flags
)
1131 BlockDriverState
*bs
= child
->bs
;
1132 BlockDriver
*drv
= bs
->drv
;
1133 BdrvTrackedRequest req
;
1135 uint64_t align
= bs
->bl
.request_alignment
;
1136 uint8_t *head_buf
= NULL
;
1137 uint8_t *tail_buf
= NULL
;
1138 QEMUIOVector local_qiov
;
1139 bool use_local_qiov
= false;
1146 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1151 bdrv_inc_in_flight(bs
);
1153 /* Don't do copy-on-read if we read data before write operation */
1154 if (atomic_read(&bs
->copy_on_read
) && !(flags
& BDRV_REQ_NO_SERIALISING
)) {
1155 flags
|= BDRV_REQ_COPY_ON_READ
;
1158 /* Align read if necessary by padding qiov */
1159 if (offset
& (align
- 1)) {
1160 head_buf
= qemu_blockalign(bs
, align
);
1161 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1162 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1163 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1164 use_local_qiov
= true;
1166 bytes
+= offset
& (align
- 1);
1167 offset
= offset
& ~(align
- 1);
1170 if ((offset
+ bytes
) & (align
- 1)) {
1171 if (!use_local_qiov
) {
1172 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1173 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1174 use_local_qiov
= true;
1176 tail_buf
= qemu_blockalign(bs
, align
);
1177 qemu_iovec_add(&local_qiov
, tail_buf
,
1178 align
- ((offset
+ bytes
) & (align
- 1)));
1180 bytes
= ROUND_UP(bytes
, align
);
1183 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1184 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
, align
,
1185 use_local_qiov
? &local_qiov
: qiov
,
1187 tracked_request_end(&req
);
1188 bdrv_dec_in_flight(bs
);
1190 if (use_local_qiov
) {
1191 qemu_iovec_destroy(&local_qiov
);
1192 qemu_vfree(head_buf
);
1193 qemu_vfree(tail_buf
);
1199 static int coroutine_fn
bdrv_co_do_readv(BdrvChild
*child
,
1200 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
,
1201 BdrvRequestFlags flags
)
1203 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
1207 return bdrv_co_preadv(child
, sector_num
<< BDRV_SECTOR_BITS
,
1208 nb_sectors
<< BDRV_SECTOR_BITS
, qiov
, flags
);
1211 int coroutine_fn
bdrv_co_readv(BdrvChild
*child
, int64_t sector_num
,
1212 int nb_sectors
, QEMUIOVector
*qiov
)
1214 trace_bdrv_co_readv(child
->bs
, sector_num
, nb_sectors
);
1216 return bdrv_co_do_readv(child
, sector_num
, nb_sectors
, qiov
, 0);
1219 /* Maximum buffer for write zeroes fallback, in bytes */
1220 #define MAX_WRITE_ZEROES_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
1222 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1223 int64_t offset
, int count
, BdrvRequestFlags flags
)
1225 BlockDriver
*drv
= bs
->drv
;
1227 struct iovec iov
= {0};
1229 bool need_flush
= false;
1233 int max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
, INT_MAX
);
1234 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1235 bs
->bl
.request_alignment
);
1236 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1237 MAX_WRITE_ZEROES_BOUNCE_BUFFER
);
1239 assert(alignment
% bs
->bl
.request_alignment
== 0);
1240 head
= offset
% alignment
;
1241 tail
= (offset
+ count
) % alignment
;
1242 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1243 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1245 while (count
> 0 && !ret
) {
1248 /* Align request. Block drivers can expect the "bulk" of the request
1249 * to be aligned, and that unaligned requests do not cross cluster
1253 /* Make a small request up to the first aligned sector. For
1254 * convenience, limit this request to max_transfer even if
1255 * we don't need to fall back to writes. */
1256 num
= MIN(MIN(count
, max_transfer
), alignment
- head
);
1257 head
= (head
+ num
) % alignment
;
1258 assert(num
< max_write_zeroes
);
1259 } else if (tail
&& num
> alignment
) {
1260 /* Shorten the request to the last aligned sector. */
1264 /* limit request size */
1265 if (num
> max_write_zeroes
) {
1266 num
= max_write_zeroes
;
1270 /* First try the efficient write zeroes operation */
1271 if (drv
->bdrv_co_pwrite_zeroes
) {
1272 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1273 flags
& bs
->supported_zero_flags
);
1274 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1275 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1279 assert(!bs
->supported_zero_flags
);
1282 if (ret
== -ENOTSUP
) {
1283 /* Fall back to bounce buffer if write zeroes is unsupported */
1284 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1286 if ((flags
& BDRV_REQ_FUA
) &&
1287 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1288 /* No need for bdrv_driver_pwrite() to do a fallback
1289 * flush on each chunk; use just one at the end */
1290 write_flags
&= ~BDRV_REQ_FUA
;
1293 num
= MIN(num
, max_transfer
);
1295 if (iov
.iov_base
== NULL
) {
1296 iov
.iov_base
= qemu_try_blockalign(bs
, num
);
1297 if (iov
.iov_base
== NULL
) {
1301 memset(iov
.iov_base
, 0, num
);
1303 qemu_iovec_init_external(&qiov
, &iov
, 1);
1305 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, write_flags
);
1307 /* Keep bounce buffer around if it is big enough for all
1308 * all future requests.
1310 if (num
< max_transfer
) {
1311 qemu_vfree(iov
.iov_base
);
1312 iov
.iov_base
= NULL
;
1321 if (ret
== 0 && need_flush
) {
1322 ret
= bdrv_co_flush(bs
);
1324 qemu_vfree(iov
.iov_base
);
1329 * Forwards an already correctly aligned write request to the BlockDriver,
1330 * after possibly fragmenting it.
1332 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
1333 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1334 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1336 BlockDriverState
*bs
= child
->bs
;
1337 BlockDriver
*drv
= bs
->drv
;
1341 int64_t start_sector
= offset
>> BDRV_SECTOR_BITS
;
1342 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1343 uint64_t bytes_remaining
= bytes
;
1346 assert(is_power_of_2(align
));
1347 assert((offset
& (align
- 1)) == 0);
1348 assert((bytes
& (align
- 1)) == 0);
1349 assert(!qiov
|| bytes
== qiov
->size
);
1350 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1351 assert(!(flags
& ~BDRV_REQ_MASK
));
1352 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1355 waited
= wait_serialising_requests(req
);
1356 assert(!waited
|| !req
->serialising
);
1357 assert(req
->overlap_offset
<= offset
);
1358 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1359 assert(child
->perm
& BLK_PERM_WRITE
);
1360 assert(end_sector
<= bs
->total_sectors
|| child
->perm
& BLK_PERM_RESIZE
);
1362 ret
= notifier_with_return_list_notify(&bs
->before_write_notifiers
, req
);
1364 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1365 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1366 qemu_iovec_is_zero(qiov
)) {
1367 flags
|= BDRV_REQ_ZERO_WRITE
;
1368 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1369 flags
|= BDRV_REQ_MAY_UNMAP
;
1374 /* Do nothing, write notifier decided to fail this request */
1375 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1376 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
1377 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
1378 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
1379 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1380 } else if (bytes
<= max_transfer
) {
1381 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1382 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1384 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1385 while (bytes_remaining
) {
1386 int num
= MIN(bytes_remaining
, max_transfer
);
1387 QEMUIOVector local_qiov
;
1388 int local_flags
= flags
;
1391 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
1392 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1393 /* If FUA is going to be emulated by flush, we only
1394 * need to flush on the last iteration */
1395 local_flags
&= ~BDRV_REQ_FUA
;
1397 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1398 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1400 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
1401 num
, &local_qiov
, local_flags
);
1402 qemu_iovec_destroy(&local_qiov
);
1406 bytes_remaining
-= num
;
1409 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
1411 atomic_inc(&bs
->write_gen
);
1412 bdrv_set_dirty(bs
, start_sector
, end_sector
- start_sector
);
1414 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1417 bs
->total_sectors
= MAX(bs
->total_sectors
, end_sector
);
1424 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
1427 BdrvRequestFlags flags
,
1428 BdrvTrackedRequest
*req
)
1430 BlockDriverState
*bs
= child
->bs
;
1431 uint8_t *buf
= NULL
;
1432 QEMUIOVector local_qiov
;
1434 uint64_t align
= bs
->bl
.request_alignment
;
1435 unsigned int head_padding_bytes
, tail_padding_bytes
;
1438 head_padding_bytes
= offset
& (align
- 1);
1439 tail_padding_bytes
= (align
- (offset
+ bytes
)) & (align
- 1);
1442 assert(flags
& BDRV_REQ_ZERO_WRITE
);
1443 if (head_padding_bytes
|| tail_padding_bytes
) {
1444 buf
= qemu_blockalign(bs
, align
);
1445 iov
= (struct iovec
) {
1449 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1451 if (head_padding_bytes
) {
1452 uint64_t zero_bytes
= MIN(bytes
, align
- head_padding_bytes
);
1454 /* RMW the unaligned part before head. */
1455 mark_request_serialising(req
, align
);
1456 wait_serialising_requests(req
);
1457 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1458 ret
= bdrv_aligned_preadv(child
, req
, offset
& ~(align
- 1), align
,
1459 align
, &local_qiov
, 0);
1463 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1465 memset(buf
+ head_padding_bytes
, 0, zero_bytes
);
1466 ret
= bdrv_aligned_pwritev(child
, req
, offset
& ~(align
- 1), align
,
1468 flags
& ~BDRV_REQ_ZERO_WRITE
);
1472 offset
+= zero_bytes
;
1473 bytes
-= zero_bytes
;
1476 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1477 if (bytes
>= align
) {
1478 /* Write the aligned part in the middle. */
1479 uint64_t aligned_bytes
= bytes
& ~(align
- 1);
1480 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
1485 bytes
-= aligned_bytes
;
1486 offset
+= aligned_bytes
;
1489 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1491 assert(align
== tail_padding_bytes
+ bytes
);
1492 /* RMW the unaligned part after tail. */
1493 mark_request_serialising(req
, align
);
1494 wait_serialising_requests(req
);
1495 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1496 ret
= bdrv_aligned_preadv(child
, req
, offset
, align
,
1497 align
, &local_qiov
, 0);
1501 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1503 memset(buf
, 0, bytes
);
1504 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
1505 &local_qiov
, flags
& ~BDRV_REQ_ZERO_WRITE
);
1514 * Handle a write request in coroutine context
1516 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
1517 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1518 BdrvRequestFlags flags
)
1520 BlockDriverState
*bs
= child
->bs
;
1521 BdrvTrackedRequest req
;
1522 uint64_t align
= bs
->bl
.request_alignment
;
1523 uint8_t *head_buf
= NULL
;
1524 uint8_t *tail_buf
= NULL
;
1525 QEMUIOVector local_qiov
;
1526 bool use_local_qiov
= false;
1532 if (bs
->read_only
) {
1535 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1537 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1542 bdrv_inc_in_flight(bs
);
1544 * Align write if necessary by performing a read-modify-write cycle.
1545 * Pad qiov with the read parts and be sure to have a tracked request not
1546 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1548 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
1551 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
1555 if (offset
& (align
- 1)) {
1556 QEMUIOVector head_qiov
;
1557 struct iovec head_iov
;
1559 mark_request_serialising(&req
, align
);
1560 wait_serialising_requests(&req
);
1562 head_buf
= qemu_blockalign(bs
, align
);
1563 head_iov
= (struct iovec
) {
1564 .iov_base
= head_buf
,
1567 qemu_iovec_init_external(&head_qiov
, &head_iov
, 1);
1569 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1570 ret
= bdrv_aligned_preadv(child
, &req
, offset
& ~(align
- 1), align
,
1571 align
, &head_qiov
, 0);
1575 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1577 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1578 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1579 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1580 use_local_qiov
= true;
1582 bytes
+= offset
& (align
- 1);
1583 offset
= offset
& ~(align
- 1);
1585 /* We have read the tail already if the request is smaller
1586 * than one aligned block.
1588 if (bytes
< align
) {
1589 qemu_iovec_add(&local_qiov
, head_buf
+ bytes
, align
- bytes
);
1594 if ((offset
+ bytes
) & (align
- 1)) {
1595 QEMUIOVector tail_qiov
;
1596 struct iovec tail_iov
;
1600 mark_request_serialising(&req
, align
);
1601 waited
= wait_serialising_requests(&req
);
1602 assert(!waited
|| !use_local_qiov
);
1604 tail_buf
= qemu_blockalign(bs
, align
);
1605 tail_iov
= (struct iovec
) {
1606 .iov_base
= tail_buf
,
1609 qemu_iovec_init_external(&tail_qiov
, &tail_iov
, 1);
1611 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1612 ret
= bdrv_aligned_preadv(child
, &req
, (offset
+ bytes
) & ~(align
- 1),
1613 align
, align
, &tail_qiov
, 0);
1617 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1619 if (!use_local_qiov
) {
1620 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1621 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1622 use_local_qiov
= true;
1625 tail_bytes
= (offset
+ bytes
) & (align
- 1);
1626 qemu_iovec_add(&local_qiov
, tail_buf
+ tail_bytes
, align
- tail_bytes
);
1628 bytes
= ROUND_UP(bytes
, align
);
1631 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
1632 use_local_qiov
? &local_qiov
: qiov
,
1637 if (use_local_qiov
) {
1638 qemu_iovec_destroy(&local_qiov
);
1640 qemu_vfree(head_buf
);
1641 qemu_vfree(tail_buf
);
1643 tracked_request_end(&req
);
1644 bdrv_dec_in_flight(bs
);
1648 static int coroutine_fn
bdrv_co_do_writev(BdrvChild
*child
,
1649 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
,
1650 BdrvRequestFlags flags
)
1652 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
1656 return bdrv_co_pwritev(child
, sector_num
<< BDRV_SECTOR_BITS
,
1657 nb_sectors
<< BDRV_SECTOR_BITS
, qiov
, flags
);
1660 int coroutine_fn
bdrv_co_writev(BdrvChild
*child
, int64_t sector_num
,
1661 int nb_sectors
, QEMUIOVector
*qiov
)
1663 trace_bdrv_co_writev(child
->bs
, sector_num
, nb_sectors
);
1665 return bdrv_co_do_writev(child
, sector_num
, nb_sectors
, qiov
, 0);
1668 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
1669 int count
, BdrvRequestFlags flags
)
1671 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, count
, flags
);
1673 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
1674 flags
&= ~BDRV_REQ_MAY_UNMAP
;
1677 return bdrv_co_pwritev(child
, offset
, count
, NULL
,
1678 BDRV_REQ_ZERO_WRITE
| flags
);
1682 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1684 int bdrv_flush_all(void)
1686 BdrvNextIterator it
;
1687 BlockDriverState
*bs
= NULL
;
1690 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
1691 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
1694 aio_context_acquire(aio_context
);
1695 ret
= bdrv_flush(bs
);
1696 if (ret
< 0 && !result
) {
1699 aio_context_release(aio_context
);
1706 typedef struct BdrvCoGetBlockStatusData
{
1707 BlockDriverState
*bs
;
1708 BlockDriverState
*base
;
1709 BlockDriverState
**file
;
1715 } BdrvCoGetBlockStatusData
;
1718 * Returns the allocation status of the specified sectors.
1719 * Drivers not implementing the functionality are assumed to not support
1720 * backing files, hence all their sectors are reported as allocated.
1722 * If 'sector_num' is beyond the end of the disk image the return value is 0
1723 * and 'pnum' is set to 0.
1725 * 'pnum' is set to the number of sectors (including and immediately following
1726 * the specified sector) that are known to be in the same
1727 * allocated/unallocated state.
1729 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1730 * beyond the end of the disk image it will be clamped.
1732 * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file'
1733 * points to the BDS which the sector range is allocated in.
1735 static int64_t coroutine_fn
bdrv_co_get_block_status(BlockDriverState
*bs
,
1737 int nb_sectors
, int *pnum
,
1738 BlockDriverState
**file
)
1740 int64_t total_sectors
;
1744 total_sectors
= bdrv_nb_sectors(bs
);
1745 if (total_sectors
< 0) {
1746 return total_sectors
;
1749 if (sector_num
>= total_sectors
) {
1754 n
= total_sectors
- sector_num
;
1755 if (n
< nb_sectors
) {
1759 if (!bs
->drv
->bdrv_co_get_block_status
) {
1761 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
1762 if (bs
->drv
->protocol_name
) {
1763 ret
|= BDRV_BLOCK_OFFSET_VALID
| (sector_num
* BDRV_SECTOR_SIZE
);
1769 bdrv_inc_in_flight(bs
);
1770 ret
= bs
->drv
->bdrv_co_get_block_status(bs
, sector_num
, nb_sectors
, pnum
,
1777 if (ret
& BDRV_BLOCK_RAW
) {
1778 assert(ret
& BDRV_BLOCK_OFFSET_VALID
);
1779 ret
= bdrv_co_get_block_status(*file
, ret
>> BDRV_SECTOR_BITS
,
1784 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
1785 ret
|= BDRV_BLOCK_ALLOCATED
;
1787 if (bdrv_unallocated_blocks_are_zero(bs
)) {
1788 ret
|= BDRV_BLOCK_ZERO
;
1789 } else if (bs
->backing
) {
1790 BlockDriverState
*bs2
= bs
->backing
->bs
;
1791 int64_t nb_sectors2
= bdrv_nb_sectors(bs2
);
1792 if (nb_sectors2
>= 0 && sector_num
>= nb_sectors2
) {
1793 ret
|= BDRV_BLOCK_ZERO
;
1798 if (*file
&& *file
!= bs
&&
1799 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
1800 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
1801 BlockDriverState
*file2
;
1804 ret2
= bdrv_co_get_block_status(*file
, ret
>> BDRV_SECTOR_BITS
,
1805 *pnum
, &file_pnum
, &file2
);
1807 /* Ignore errors. This is just providing extra information, it
1808 * is useful but not necessary.
1811 /* !file_pnum indicates an offset at or beyond the EOF; it is
1812 * perfectly valid for the format block driver to point to such
1813 * offsets, so catch it and mark everything as zero */
1814 ret
|= BDRV_BLOCK_ZERO
;
1816 /* Limit request to the range reported by the protocol driver */
1818 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
1824 bdrv_dec_in_flight(bs
);
1828 static int64_t coroutine_fn
bdrv_co_get_block_status_above(BlockDriverState
*bs
,
1829 BlockDriverState
*base
,
1833 BlockDriverState
**file
)
1835 BlockDriverState
*p
;
1839 for (p
= bs
; p
!= base
; p
= backing_bs(p
)) {
1840 ret
= bdrv_co_get_block_status(p
, sector_num
, nb_sectors
, pnum
, file
);
1841 if (ret
< 0 || ret
& BDRV_BLOCK_ALLOCATED
) {
1844 /* [sector_num, pnum] unallocated on this layer, which could be only
1845 * the first part of [sector_num, nb_sectors]. */
1846 nb_sectors
= MIN(nb_sectors
, *pnum
);
1851 /* Coroutine wrapper for bdrv_get_block_status_above() */
1852 static void coroutine_fn
bdrv_get_block_status_above_co_entry(void *opaque
)
1854 BdrvCoGetBlockStatusData
*data
= opaque
;
1856 data
->ret
= bdrv_co_get_block_status_above(data
->bs
, data
->base
,
1865 * Synchronous wrapper around bdrv_co_get_block_status_above().
1867 * See bdrv_co_get_block_status_above() for details.
1869 int64_t bdrv_get_block_status_above(BlockDriverState
*bs
,
1870 BlockDriverState
*base
,
1872 int nb_sectors
, int *pnum
,
1873 BlockDriverState
**file
)
1876 BdrvCoGetBlockStatusData data
= {
1880 .sector_num
= sector_num
,
1881 .nb_sectors
= nb_sectors
,
1886 if (qemu_in_coroutine()) {
1887 /* Fast-path if already in coroutine context */
1888 bdrv_get_block_status_above_co_entry(&data
);
1890 co
= qemu_coroutine_create(bdrv_get_block_status_above_co_entry
,
1892 bdrv_coroutine_enter(bs
, co
);
1893 BDRV_POLL_WHILE(bs
, !data
.done
);
1898 int64_t bdrv_get_block_status(BlockDriverState
*bs
,
1900 int nb_sectors
, int *pnum
,
1901 BlockDriverState
**file
)
1903 return bdrv_get_block_status_above(bs
, backing_bs(bs
),
1904 sector_num
, nb_sectors
, pnum
, file
);
1907 int coroutine_fn
bdrv_is_allocated(BlockDriverState
*bs
, int64_t sector_num
,
1908 int nb_sectors
, int *pnum
)
1910 BlockDriverState
*file
;
1911 int64_t ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, pnum
,
1916 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
1920 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
1922 * Return true if the given sector is allocated in any image between
1923 * BASE and TOP (inclusive). BASE can be NULL to check if the given
1924 * sector is allocated in any image of the chain. Return false otherwise.
1926 * 'pnum' is set to the number of sectors (including and immediately following
1927 * the specified sector) that are known to be in the same
1928 * allocated/unallocated state.
1931 int bdrv_is_allocated_above(BlockDriverState
*top
,
1932 BlockDriverState
*base
,
1934 int nb_sectors
, int *pnum
)
1936 BlockDriverState
*intermediate
;
1937 int ret
, n
= nb_sectors
;
1940 while (intermediate
&& intermediate
!= base
) {
1942 ret
= bdrv_is_allocated(intermediate
, sector_num
, nb_sectors
,
1952 * [sector_num, nb_sectors] is unallocated on top but intermediate
1955 * [sector_num+x, nr_sectors] allocated.
1957 if (n
> pnum_inter
&&
1958 (intermediate
== top
||
1959 sector_num
+ pnum_inter
< intermediate
->total_sectors
)) {
1963 intermediate
= backing_bs(intermediate
);
1970 typedef struct BdrvVmstateCo
{
1971 BlockDriverState
*bs
;
1978 static int coroutine_fn
1979 bdrv_co_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
1982 BlockDriver
*drv
= bs
->drv
;
1985 bdrv_inc_in_flight(bs
);
1989 } else if (drv
->bdrv_load_vmstate
) {
1991 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
1993 ret
= drv
->bdrv_save_vmstate(bs
, qiov
, pos
);
1995 } else if (bs
->file
) {
1996 ret
= bdrv_co_rw_vmstate(bs
->file
->bs
, qiov
, pos
, is_read
);
1999 bdrv_dec_in_flight(bs
);
2003 static void coroutine_fn
bdrv_co_rw_vmstate_entry(void *opaque
)
2005 BdrvVmstateCo
*co
= opaque
;
2006 co
->ret
= bdrv_co_rw_vmstate(co
->bs
, co
->qiov
, co
->pos
, co
->is_read
);
2010 bdrv_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
2013 if (qemu_in_coroutine()) {
2014 return bdrv_co_rw_vmstate(bs
, qiov
, pos
, is_read
);
2016 BdrvVmstateCo data
= {
2021 .ret
= -EINPROGRESS
,
2023 Coroutine
*co
= qemu_coroutine_create(bdrv_co_rw_vmstate_entry
, &data
);
2025 bdrv_coroutine_enter(bs
, co
);
2026 while (data
.ret
== -EINPROGRESS
) {
2027 aio_poll(bdrv_get_aio_context(bs
), true);
2033 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2034 int64_t pos
, int size
)
2037 struct iovec iov
= {
2038 .iov_base
= (void *) buf
,
2043 qemu_iovec_init_external(&qiov
, &iov
, 1);
2045 ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2053 int bdrv_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2055 return bdrv_rw_vmstate(bs
, qiov
, pos
, false);
2058 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2059 int64_t pos
, int size
)
2062 struct iovec iov
= {
2068 qemu_iovec_init_external(&qiov
, &iov
, 1);
2069 ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2077 int bdrv_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2079 return bdrv_rw_vmstate(bs
, qiov
, pos
, true);
2082 /**************************************************************/
2085 BlockAIOCB
*bdrv_aio_readv(BdrvChild
*child
, int64_t sector_num
,
2086 QEMUIOVector
*qiov
, int nb_sectors
,
2087 BlockCompletionFunc
*cb
, void *opaque
)
2089 trace_bdrv_aio_readv(child
->bs
, sector_num
, nb_sectors
, opaque
);
2091 assert(nb_sectors
<< BDRV_SECTOR_BITS
== qiov
->size
);
2092 return bdrv_co_aio_prw_vector(child
, sector_num
<< BDRV_SECTOR_BITS
, qiov
,
2093 0, cb
, opaque
, false);
2096 BlockAIOCB
*bdrv_aio_writev(BdrvChild
*child
, int64_t sector_num
,
2097 QEMUIOVector
*qiov
, int nb_sectors
,
2098 BlockCompletionFunc
*cb
, void *opaque
)
2100 trace_bdrv_aio_writev(child
->bs
, sector_num
, nb_sectors
, opaque
);
2102 assert(nb_sectors
<< BDRV_SECTOR_BITS
== qiov
->size
);
2103 return bdrv_co_aio_prw_vector(child
, sector_num
<< BDRV_SECTOR_BITS
, qiov
,
2104 0, cb
, opaque
, true);
2107 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2110 bdrv_aio_cancel_async(acb
);
2111 while (acb
->refcnt
> 1) {
2112 if (acb
->aiocb_info
->get_aio_context
) {
2113 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2114 } else if (acb
->bs
) {
2115 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2116 * assert that we're not using an I/O thread. Thread-safe
2117 * code should use bdrv_aio_cancel_async exclusively.
2119 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2120 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2125 qemu_aio_unref(acb
);
2128 /* Async version of aio cancel. The caller is not blocked if the acb implements
2129 * cancel_async, otherwise we do nothing and let the request normally complete.
2130 * In either case the completion callback must be called. */
2131 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2133 if (acb
->aiocb_info
->cancel_async
) {
2134 acb
->aiocb_info
->cancel_async(acb
);
2138 /**************************************************************/
2139 /* async block device emulation */
2141 typedef struct BlockRequest
{
2143 /* Used during read, write, trim */
2150 /* Used during ioctl */
2156 BlockCompletionFunc
*cb
;
2162 typedef struct BlockAIOCBCoroutine
{
2169 } BlockAIOCBCoroutine
;
2171 static const AIOCBInfo bdrv_em_co_aiocb_info
= {
2172 .aiocb_size
= sizeof(BlockAIOCBCoroutine
),
2175 static void bdrv_co_complete(BlockAIOCBCoroutine
*acb
)
2177 if (!acb
->need_bh
) {
2178 bdrv_dec_in_flight(acb
->common
.bs
);
2179 acb
->common
.cb(acb
->common
.opaque
, acb
->req
.error
);
2180 qemu_aio_unref(acb
);
2184 static void bdrv_co_em_bh(void *opaque
)
2186 BlockAIOCBCoroutine
*acb
= opaque
;
2188 assert(!acb
->need_bh
);
2189 bdrv_co_complete(acb
);
2192 static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine
*acb
)
2194 acb
->need_bh
= false;
2195 if (acb
->req
.error
!= -EINPROGRESS
) {
2196 BlockDriverState
*bs
= acb
->common
.bs
;
2198 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs
), bdrv_co_em_bh
, acb
);
2202 /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
2203 static void coroutine_fn
bdrv_co_do_rw(void *opaque
)
2205 BlockAIOCBCoroutine
*acb
= opaque
;
2207 if (!acb
->is_write
) {
2208 acb
->req
.error
= bdrv_co_preadv(acb
->child
, acb
->req
.offset
,
2209 acb
->req
.qiov
->size
, acb
->req
.qiov
, acb
->req
.flags
);
2211 acb
->req
.error
= bdrv_co_pwritev(acb
->child
, acb
->req
.offset
,
2212 acb
->req
.qiov
->size
, acb
->req
.qiov
, acb
->req
.flags
);
2215 bdrv_co_complete(acb
);
2218 static BlockAIOCB
*bdrv_co_aio_prw_vector(BdrvChild
*child
,
2221 BdrvRequestFlags flags
,
2222 BlockCompletionFunc
*cb
,
2227 BlockAIOCBCoroutine
*acb
;
2229 /* Matched by bdrv_co_complete's bdrv_dec_in_flight. */
2230 bdrv_inc_in_flight(child
->bs
);
2232 acb
= qemu_aio_get(&bdrv_em_co_aiocb_info
, child
->bs
, cb
, opaque
);
2234 acb
->need_bh
= true;
2235 acb
->req
.error
= -EINPROGRESS
;
2236 acb
->req
.offset
= offset
;
2237 acb
->req
.qiov
= qiov
;
2238 acb
->req
.flags
= flags
;
2239 acb
->is_write
= is_write
;
2241 co
= qemu_coroutine_create(bdrv_co_do_rw
, acb
);
2242 bdrv_coroutine_enter(child
->bs
, co
);
2244 bdrv_co_maybe_schedule_bh(acb
);
2245 return &acb
->common
;
2248 static void coroutine_fn
bdrv_aio_flush_co_entry(void *opaque
)
2250 BlockAIOCBCoroutine
*acb
= opaque
;
2251 BlockDriverState
*bs
= acb
->common
.bs
;
2253 acb
->req
.error
= bdrv_co_flush(bs
);
2254 bdrv_co_complete(acb
);
2257 BlockAIOCB
*bdrv_aio_flush(BlockDriverState
*bs
,
2258 BlockCompletionFunc
*cb
, void *opaque
)
2260 trace_bdrv_aio_flush(bs
, opaque
);
2263 BlockAIOCBCoroutine
*acb
;
2265 /* Matched by bdrv_co_complete's bdrv_dec_in_flight. */
2266 bdrv_inc_in_flight(bs
);
2268 acb
= qemu_aio_get(&bdrv_em_co_aiocb_info
, bs
, cb
, opaque
);
2269 acb
->need_bh
= true;
2270 acb
->req
.error
= -EINPROGRESS
;
2272 co
= qemu_coroutine_create(bdrv_aio_flush_co_entry
, acb
);
2273 bdrv_coroutine_enter(bs
, co
);
2275 bdrv_co_maybe_schedule_bh(acb
);
2276 return &acb
->common
;
2279 /**************************************************************/
2280 /* Coroutine block device emulation */
2282 typedef struct FlushCo
{
2283 BlockDriverState
*bs
;
2288 static void coroutine_fn
bdrv_flush_co_entry(void *opaque
)
2290 FlushCo
*rwco
= opaque
;
2292 rwco
->ret
= bdrv_co_flush(rwco
->bs
);
2295 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2300 bdrv_inc_in_flight(bs
);
2302 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2307 qemu_co_mutex_lock(&bs
->reqs_lock
);
2308 current_gen
= atomic_read(&bs
->write_gen
);
2310 /* Wait until any previous flushes are completed */
2311 while (bs
->active_flush_req
) {
2312 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2315 /* Flushes reach this point in nondecreasing current_gen order. */
2316 bs
->active_flush_req
= true;
2317 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2319 /* Write back all layers by calling one driver function */
2320 if (bs
->drv
->bdrv_co_flush
) {
2321 ret
= bs
->drv
->bdrv_co_flush(bs
);
2325 /* Write back cached data to the OS even with cache=unsafe */
2326 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_OS
);
2327 if (bs
->drv
->bdrv_co_flush_to_os
) {
2328 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2334 /* But don't actually force it to the disk with cache=unsafe */
2335 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2339 /* Check if we really need to flush anything */
2340 if (bs
->flushed_gen
== current_gen
) {
2344 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_DISK
);
2345 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2346 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2347 } else if (bs
->drv
->bdrv_aio_flush
) {
2349 CoroutineIOCompletion co
= {
2350 .coroutine
= qemu_coroutine_self(),
2353 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2357 qemu_coroutine_yield();
2362 * Some block drivers always operate in either writethrough or unsafe
2363 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2364 * know how the server works (because the behaviour is hardcoded or
2365 * depends on server-side configuration), so we can't ensure that
2366 * everything is safe on disk. Returning an error doesn't work because
2367 * that would break guests even if the server operates in writethrough
2370 * Let's hope the user knows what he's doing.
2379 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2380 * in the case of cache=unsafe, so there are no useless flushes.
2383 ret
= bs
->file
? bdrv_co_flush(bs
->file
->bs
) : 0;
2385 /* Notify any pending flushes that we have completed */
2387 bs
->flushed_gen
= current_gen
;
2390 qemu_co_mutex_lock(&bs
->reqs_lock
);
2391 bs
->active_flush_req
= false;
2392 /* Return value is ignored - it's ok if wait queue is empty */
2393 qemu_co_queue_next(&bs
->flush_queue
);
2394 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2397 bdrv_dec_in_flight(bs
);
2401 int bdrv_flush(BlockDriverState
*bs
)
2404 FlushCo flush_co
= {
2409 if (qemu_in_coroutine()) {
2410 /* Fast-path if already in coroutine context */
2411 bdrv_flush_co_entry(&flush_co
);
2413 co
= qemu_coroutine_create(bdrv_flush_co_entry
, &flush_co
);
2414 bdrv_coroutine_enter(bs
, co
);
2415 BDRV_POLL_WHILE(bs
, flush_co
.ret
== NOT_DONE
);
2418 return flush_co
.ret
;
2421 typedef struct DiscardCo
{
2422 BlockDriverState
*bs
;
2427 static void coroutine_fn
bdrv_pdiscard_co_entry(void *opaque
)
2429 DiscardCo
*rwco
= opaque
;
2431 rwco
->ret
= bdrv_co_pdiscard(rwco
->bs
, rwco
->offset
, rwco
->count
);
2434 int coroutine_fn
bdrv_co_pdiscard(BlockDriverState
*bs
, int64_t offset
,
2437 BdrvTrackedRequest req
;
2438 int max_pdiscard
, ret
;
2439 int head
, tail
, align
;
2445 ret
= bdrv_check_byte_request(bs
, offset
, count
);
2448 } else if (bs
->read_only
) {
2451 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
2453 /* Do nothing if disabled. */
2454 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2458 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2462 /* Discard is advisory, but some devices track and coalesce
2463 * unaligned requests, so we must pass everything down rather than
2464 * round here. Still, most devices will just silently ignore
2465 * unaligned requests (by returning -ENOTSUP), so we must fragment
2466 * the request accordingly. */
2467 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
2468 assert(align
% bs
->bl
.request_alignment
== 0);
2469 head
= offset
% align
;
2470 tail
= (offset
+ count
) % align
;
2472 bdrv_inc_in_flight(bs
);
2473 tracked_request_begin(&req
, bs
, offset
, count
, BDRV_TRACKED_DISCARD
);
2475 ret
= notifier_with_return_list_notify(&bs
->before_write_notifiers
, &req
);
2480 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT_MAX
),
2482 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
2489 /* Make small requests to get to alignment boundaries. */
2490 num
= MIN(count
, align
- head
);
2491 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
2492 num
%= bs
->bl
.request_alignment
;
2494 head
= (head
+ num
) % align
;
2495 assert(num
< max_pdiscard
);
2498 /* Shorten the request to the last aligned cluster. */
2500 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
2501 tail
> bs
->bl
.request_alignment
) {
2502 tail
%= bs
->bl
.request_alignment
;
2506 /* limit request size */
2507 if (num
> max_pdiscard
) {
2511 if (bs
->drv
->bdrv_co_pdiscard
) {
2512 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
2515 CoroutineIOCompletion co
= {
2516 .coroutine
= qemu_coroutine_self(),
2519 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
2520 bdrv_co_io_em_complete
, &co
);
2525 qemu_coroutine_yield();
2529 if (ret
&& ret
!= -ENOTSUP
) {
2538 atomic_inc(&bs
->write_gen
);
2539 bdrv_set_dirty(bs
, req
.offset
>> BDRV_SECTOR_BITS
,
2540 req
.bytes
>> BDRV_SECTOR_BITS
);
2541 tracked_request_end(&req
);
2542 bdrv_dec_in_flight(bs
);
2546 int bdrv_pdiscard(BlockDriverState
*bs
, int64_t offset
, int count
)
2556 if (qemu_in_coroutine()) {
2557 /* Fast-path if already in coroutine context */
2558 bdrv_pdiscard_co_entry(&rwco
);
2560 co
= qemu_coroutine_create(bdrv_pdiscard_co_entry
, &rwco
);
2561 bdrv_coroutine_enter(bs
, co
);
2562 BDRV_POLL_WHILE(bs
, rwco
.ret
== NOT_DONE
);
2568 int bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
2570 BlockDriver
*drv
= bs
->drv
;
2571 CoroutineIOCompletion co
= {
2572 .coroutine
= qemu_coroutine_self(),
2576 bdrv_inc_in_flight(bs
);
2577 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
2582 if (drv
->bdrv_co_ioctl
) {
2583 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
2585 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
2590 qemu_coroutine_yield();
2593 bdrv_dec_in_flight(bs
);
2597 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2599 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
2602 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
2604 return memset(qemu_blockalign(bs
, size
), 0, size
);
2607 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
2609 size_t align
= bdrv_opt_mem_align(bs
);
2611 /* Ensure that NULL is never returned on success */
2617 return qemu_try_memalign(align
, size
);
2620 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
2622 void *mem
= qemu_try_blockalign(bs
, size
);
2625 memset(mem
, 0, size
);
2632 * Check if all memory in this vector is sector aligned.
2634 bool bdrv_qiov_is_aligned(BlockDriverState
*bs
, QEMUIOVector
*qiov
)
2637 size_t alignment
= bdrv_min_mem_align(bs
);
2639 for (i
= 0; i
< qiov
->niov
; i
++) {
2640 if ((uintptr_t) qiov
->iov
[i
].iov_base
% alignment
) {
2643 if (qiov
->iov
[i
].iov_len
% alignment
) {
2651 void bdrv_add_before_write_notifier(BlockDriverState
*bs
,
2652 NotifierWithReturn
*notifier
)
2654 notifier_with_return_list_add(&bs
->before_write_notifiers
, notifier
);
2657 void bdrv_io_plug(BlockDriverState
*bs
)
2661 QLIST_FOREACH(child
, &bs
->children
, next
) {
2662 bdrv_io_plug(child
->bs
);
2665 if (atomic_fetch_inc(&bs
->io_plugged
) == 0) {
2666 BlockDriver
*drv
= bs
->drv
;
2667 if (drv
&& drv
->bdrv_io_plug
) {
2668 drv
->bdrv_io_plug(bs
);
2673 void bdrv_io_unplug(BlockDriverState
*bs
)
2677 assert(bs
->io_plugged
);
2678 if (atomic_fetch_dec(&bs
->io_plugged
) == 1) {
2679 BlockDriver
*drv
= bs
->drv
;
2680 if (drv
&& drv
->bdrv_io_unplug
) {
2681 drv
->bdrv_io_unplug(bs
);
2685 QLIST_FOREACH(child
, &bs
->children
, next
) {
2686 bdrv_io_unplug(child
->bs
);