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
)
47 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
48 if (c
->role
->drained_begin
) {
49 c
->role
->drained_begin(c
);
54 void bdrv_parent_drained_end(BlockDriverState
*bs
)
58 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
59 if (c
->role
->drained_end
) {
60 c
->role
->drained_end(c
);
65 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
67 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
68 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
69 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
70 src
->opt_mem_alignment
);
71 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
72 src
->min_mem_alignment
);
73 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
76 void bdrv_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
78 BlockDriver
*drv
= bs
->drv
;
79 Error
*local_err
= NULL
;
81 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
87 /* Default alignment based on whether driver has byte interface */
88 bs
->bl
.request_alignment
= drv
->bdrv_co_preadv
? 1 : 512;
90 /* Take some limits from the children as a default */
92 bdrv_refresh_limits(bs
->file
->bs
, &local_err
);
94 error_propagate(errp
, local_err
);
97 bdrv_merge_limits(&bs
->bl
, &bs
->file
->bs
->bl
);
99 bs
->bl
.min_mem_alignment
= 512;
100 bs
->bl
.opt_mem_alignment
= getpagesize();
102 /* Safe default since most protocols use readv()/writev()/etc */
103 bs
->bl
.max_iov
= IOV_MAX
;
107 bdrv_refresh_limits(bs
->backing
->bs
, &local_err
);
109 error_propagate(errp
, local_err
);
112 bdrv_merge_limits(&bs
->bl
, &bs
->backing
->bs
->bl
);
115 /* Then let the driver override it */
116 if (drv
->bdrv_refresh_limits
) {
117 drv
->bdrv_refresh_limits(bs
, errp
);
122 * The copy-on-read flag is actually a reference count so multiple users may
123 * use the feature without worrying about clobbering its previous state.
124 * Copy-on-read stays enabled until all users have called to disable it.
126 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
128 atomic_inc(&bs
->copy_on_read
);
131 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
133 int old
= atomic_fetch_dec(&bs
->copy_on_read
);
137 /* Check if any requests are in-flight (including throttled requests) */
138 bool bdrv_requests_pending(BlockDriverState
*bs
)
142 if (atomic_read(&bs
->in_flight
)) {
146 QLIST_FOREACH(child
, &bs
->children
, next
) {
147 if (bdrv_requests_pending(child
->bs
)) {
157 BlockDriverState
*bs
;
161 static void coroutine_fn
bdrv_drain_invoke_entry(void *opaque
)
163 BdrvCoDrainData
*data
= opaque
;
164 BlockDriverState
*bs
= data
->bs
;
166 bs
->drv
->bdrv_co_drain(bs
);
168 /* Set data->done before reading bs->wakeup. */
169 atomic_mb_set(&data
->done
, true);
173 static void bdrv_drain_invoke(BlockDriverState
*bs
)
175 BdrvCoDrainData data
= { .bs
= bs
, .done
= false };
177 if (!bs
->drv
|| !bs
->drv
->bdrv_co_drain
) {
181 data
.co
= qemu_coroutine_create(bdrv_drain_invoke_entry
, &data
);
182 bdrv_coroutine_enter(bs
, data
.co
);
183 BDRV_POLL_WHILE(bs
, !data
.done
);
186 static bool bdrv_drain_recurse(BlockDriverState
*bs
)
188 BdrvChild
*child
, *tmp
;
191 waited
= BDRV_POLL_WHILE(bs
, atomic_read(&bs
->in_flight
) > 0);
193 /* Ensure any pending metadata writes are submitted to bs->file. */
194 bdrv_drain_invoke(bs
);
196 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, tmp
) {
197 BlockDriverState
*bs
= child
->bs
;
199 qemu_get_current_aio_context() == qemu_get_aio_context();
200 assert(bs
->refcnt
> 0);
202 /* In case the recursive bdrv_drain_recurse processes a
203 * block_job_defer_to_main_loop BH and modifies the graph,
204 * let's hold a reference to bs until we are done.
206 * IOThread doesn't have such a BH, and it is not safe to call
207 * bdrv_unref without BQL, so skip doing it there.
211 waited
|= bdrv_drain_recurse(bs
);
220 static void bdrv_co_drain_bh_cb(void *opaque
)
222 BdrvCoDrainData
*data
= opaque
;
223 Coroutine
*co
= data
->co
;
224 BlockDriverState
*bs
= data
->bs
;
226 bdrv_dec_in_flight(bs
);
227 bdrv_drained_begin(bs
);
232 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
)
234 BdrvCoDrainData data
;
236 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
237 * other coroutines run if they were queued from
238 * qemu_co_queue_run_restart(). */
240 assert(qemu_in_coroutine());
241 data
= (BdrvCoDrainData
) {
242 .co
= qemu_coroutine_self(),
246 bdrv_inc_in_flight(bs
);
247 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs
),
248 bdrv_co_drain_bh_cb
, &data
);
250 qemu_coroutine_yield();
251 /* If we are resumed from some other event (such as an aio completion or a
252 * timer callback), it is a bug in the caller that should be fixed. */
256 void bdrv_drained_begin(BlockDriverState
*bs
)
258 if (qemu_in_coroutine()) {
259 bdrv_co_yield_to_drain(bs
);
263 if (atomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
264 aio_disable_external(bdrv_get_aio_context(bs
));
265 bdrv_parent_drained_begin(bs
);
268 bdrv_drain_recurse(bs
);
271 void bdrv_drained_end(BlockDriverState
*bs
)
273 assert(bs
->quiesce_counter
> 0);
274 if (atomic_fetch_dec(&bs
->quiesce_counter
) > 1) {
278 bdrv_parent_drained_end(bs
);
279 aio_enable_external(bdrv_get_aio_context(bs
));
283 * Wait for pending requests to complete on a single BlockDriverState subtree,
284 * and suspend block driver's internal I/O until next request arrives.
286 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
289 * Only this BlockDriverState's AioContext is run, so in-flight requests must
290 * not depend on events in other AioContexts. In that case, use
291 * bdrv_drain_all() instead.
293 void coroutine_fn
bdrv_co_drain(BlockDriverState
*bs
)
295 assert(qemu_in_coroutine());
296 bdrv_drained_begin(bs
);
297 bdrv_drained_end(bs
);
300 void bdrv_drain(BlockDriverState
*bs
)
302 bdrv_drained_begin(bs
);
303 bdrv_drained_end(bs
);
307 * Wait for pending requests to complete across all BlockDriverStates
309 * This function does not flush data to disk, use bdrv_flush_all() for that
310 * after calling this function.
312 * This pauses all block jobs and disables external clients. It must
313 * be paired with bdrv_drain_all_end().
315 * NOTE: no new block jobs or BlockDriverStates can be created between
316 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
318 void bdrv_drain_all_begin(void)
320 /* Always run first iteration so any pending completion BHs run */
322 BlockDriverState
*bs
;
324 GSList
*aio_ctxs
= NULL
, *ctx
;
326 block_job_pause_all();
328 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
329 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
331 aio_context_acquire(aio_context
);
332 bdrv_parent_drained_begin(bs
);
333 aio_disable_external(aio_context
);
334 aio_context_release(aio_context
);
336 if (!g_slist_find(aio_ctxs
, aio_context
)) {
337 aio_ctxs
= g_slist_prepend(aio_ctxs
, aio_context
);
341 /* Note that completion of an asynchronous I/O operation can trigger any
342 * number of other I/O operations on other devices---for example a
343 * coroutine can submit an I/O request to another device in response to
344 * request completion. Therefore we must keep looping until there was no
345 * more activity rather than simply draining each device independently.
350 for (ctx
= aio_ctxs
; ctx
!= NULL
; ctx
= ctx
->next
) {
351 AioContext
*aio_context
= ctx
->data
;
353 aio_context_acquire(aio_context
);
354 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
355 if (aio_context
== bdrv_get_aio_context(bs
)) {
356 waited
|= bdrv_drain_recurse(bs
);
359 aio_context_release(aio_context
);
363 g_slist_free(aio_ctxs
);
366 void bdrv_drain_all_end(void)
368 BlockDriverState
*bs
;
371 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
372 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
374 aio_context_acquire(aio_context
);
375 aio_enable_external(aio_context
);
376 bdrv_parent_drained_end(bs
);
377 aio_context_release(aio_context
);
380 block_job_resume_all();
383 void bdrv_drain_all(void)
385 bdrv_drain_all_begin();
386 bdrv_drain_all_end();
390 * Remove an active request from the tracked requests list
392 * This function should be called when a tracked request is completing.
394 static void tracked_request_end(BdrvTrackedRequest
*req
)
396 if (req
->serialising
) {
397 atomic_dec(&req
->bs
->serialising_in_flight
);
400 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
401 QLIST_REMOVE(req
, list
);
402 qemu_co_queue_restart_all(&req
->wait_queue
);
403 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
407 * Add an active request to the tracked requests list
409 static void tracked_request_begin(BdrvTrackedRequest
*req
,
410 BlockDriverState
*bs
,
413 enum BdrvTrackedRequestType type
)
415 *req
= (BdrvTrackedRequest
){
420 .co
= qemu_coroutine_self(),
421 .serialising
= false,
422 .overlap_offset
= offset
,
423 .overlap_bytes
= bytes
,
426 qemu_co_queue_init(&req
->wait_queue
);
428 qemu_co_mutex_lock(&bs
->reqs_lock
);
429 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
430 qemu_co_mutex_unlock(&bs
->reqs_lock
);
433 static void mark_request_serialising(BdrvTrackedRequest
*req
, uint64_t align
)
435 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
436 unsigned int overlap_bytes
= ROUND_UP(req
->offset
+ req
->bytes
, align
)
439 if (!req
->serialising
) {
440 atomic_inc(&req
->bs
->serialising_in_flight
);
441 req
->serialising
= true;
444 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
445 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
449 * Round a region to cluster boundaries
451 void bdrv_round_to_clusters(BlockDriverState
*bs
,
452 int64_t offset
, unsigned int bytes
,
453 int64_t *cluster_offset
,
454 unsigned int *cluster_bytes
)
458 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
459 *cluster_offset
= offset
;
460 *cluster_bytes
= bytes
;
462 int64_t c
= bdi
.cluster_size
;
463 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
464 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
468 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
473 ret
= bdrv_get_info(bs
, &bdi
);
474 if (ret
< 0 || bdi
.cluster_size
== 0) {
475 return bs
->bl
.request_alignment
;
477 return bdi
.cluster_size
;
481 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
482 int64_t offset
, unsigned int bytes
)
485 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
489 if (req
->overlap_offset
>= offset
+ bytes
) {
495 void bdrv_inc_in_flight(BlockDriverState
*bs
)
497 atomic_inc(&bs
->in_flight
);
500 static void dummy_bh_cb(void *opaque
)
504 void bdrv_wakeup(BlockDriverState
*bs
)
506 /* The barrier (or an atomic op) is in the caller. */
507 if (atomic_read(&bs
->wakeup
)) {
508 aio_bh_schedule_oneshot(qemu_get_aio_context(), dummy_bh_cb
, NULL
);
512 void bdrv_dec_in_flight(BlockDriverState
*bs
)
514 atomic_dec(&bs
->in_flight
);
518 static bool coroutine_fn
wait_serialising_requests(BdrvTrackedRequest
*self
)
520 BlockDriverState
*bs
= self
->bs
;
521 BdrvTrackedRequest
*req
;
525 if (!atomic_read(&bs
->serialising_in_flight
)) {
531 qemu_co_mutex_lock(&bs
->reqs_lock
);
532 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
533 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
536 if (tracked_request_overlaps(req
, self
->overlap_offset
,
537 self
->overlap_bytes
))
539 /* Hitting this means there was a reentrant request, for
540 * example, a block driver issuing nested requests. This must
541 * never happen since it means deadlock.
543 assert(qemu_coroutine_self() != req
->co
);
545 /* If the request is already (indirectly) waiting for us, or
546 * will wait for us as soon as it wakes up, then just go on
547 * (instead of producing a deadlock in the former case). */
548 if (!req
->waiting_for
) {
549 self
->waiting_for
= req
;
550 qemu_co_queue_wait(&req
->wait_queue
, &bs
->reqs_lock
);
551 self
->waiting_for
= NULL
;
558 qemu_co_mutex_unlock(&bs
->reqs_lock
);
564 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
567 if (size
> BDRV_REQUEST_MAX_SECTORS
<< BDRV_SECTOR_BITS
) {
571 if (!bdrv_is_inserted(bs
)) {
582 typedef struct RwCo
{
588 BdrvRequestFlags flags
;
591 static void coroutine_fn
bdrv_rw_co_entry(void *opaque
)
595 if (!rwco
->is_write
) {
596 rwco
->ret
= bdrv_co_preadv(rwco
->child
, rwco
->offset
,
597 rwco
->qiov
->size
, rwco
->qiov
,
600 rwco
->ret
= bdrv_co_pwritev(rwco
->child
, rwco
->offset
,
601 rwco
->qiov
->size
, rwco
->qiov
,
607 * Process a vectored synchronous request using coroutines
609 static int bdrv_prwv_co(BdrvChild
*child
, int64_t offset
,
610 QEMUIOVector
*qiov
, bool is_write
,
611 BdrvRequestFlags flags
)
618 .is_write
= is_write
,
623 if (qemu_in_coroutine()) {
624 /* Fast-path if already in coroutine context */
625 bdrv_rw_co_entry(&rwco
);
627 co
= qemu_coroutine_create(bdrv_rw_co_entry
, &rwco
);
628 bdrv_coroutine_enter(child
->bs
, co
);
629 BDRV_POLL_WHILE(child
->bs
, rwco
.ret
== NOT_DONE
);
635 * Process a synchronous request using coroutines
637 static int bdrv_rw_co(BdrvChild
*child
, int64_t sector_num
, uint8_t *buf
,
638 int nb_sectors
, bool is_write
, BdrvRequestFlags flags
)
642 .iov_base
= (void *)buf
,
643 .iov_len
= nb_sectors
* BDRV_SECTOR_SIZE
,
646 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
650 qemu_iovec_init_external(&qiov
, &iov
, 1);
651 return bdrv_prwv_co(child
, sector_num
<< BDRV_SECTOR_BITS
,
652 &qiov
, is_write
, flags
);
655 /* return < 0 if error. See bdrv_write() for the return codes */
656 int bdrv_read(BdrvChild
*child
, int64_t sector_num
,
657 uint8_t *buf
, int nb_sectors
)
659 return bdrv_rw_co(child
, sector_num
, buf
, nb_sectors
, false, 0);
662 /* Return < 0 if error. Important errors are:
663 -EIO generic I/O error (may happen for all errors)
664 -ENOMEDIUM No media inserted.
665 -EINVAL Invalid sector number or nb_sectors
666 -EACCES Trying to write a read-only device
668 int bdrv_write(BdrvChild
*child
, int64_t sector_num
,
669 const uint8_t *buf
, int nb_sectors
)
671 return bdrv_rw_co(child
, sector_num
, (uint8_t *)buf
, nb_sectors
, true, 0);
674 int bdrv_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
675 int bytes
, BdrvRequestFlags flags
)
683 qemu_iovec_init_external(&qiov
, &iov
, 1);
684 return bdrv_prwv_co(child
, offset
, &qiov
, true,
685 BDRV_REQ_ZERO_WRITE
| flags
);
689 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
690 * The operation is sped up by checking the block status and only writing
691 * zeroes to the device if they currently do not return zeroes. Optional
692 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
695 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
697 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
699 int64_t target_sectors
, ret
, nb_sectors
, sector_num
= 0;
700 BlockDriverState
*bs
= child
->bs
;
701 BlockDriverState
*file
;
704 target_sectors
= bdrv_nb_sectors(bs
);
705 if (target_sectors
< 0) {
706 return target_sectors
;
710 nb_sectors
= MIN(target_sectors
- sector_num
, BDRV_REQUEST_MAX_SECTORS
);
711 if (nb_sectors
<= 0) {
714 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &n
, &file
);
716 error_report("error getting block status at sector %" PRId64
": %s",
717 sector_num
, strerror(-ret
));
720 if (ret
& BDRV_BLOCK_ZERO
) {
724 ret
= bdrv_pwrite_zeroes(child
, sector_num
<< BDRV_SECTOR_BITS
,
725 n
<< BDRV_SECTOR_BITS
, flags
);
727 error_report("error writing zeroes at sector %" PRId64
": %s",
728 sector_num
, strerror(-ret
));
735 int bdrv_preadv(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
739 ret
= bdrv_prwv_co(child
, offset
, qiov
, false, 0);
747 int bdrv_pread(BdrvChild
*child
, int64_t offset
, void *buf
, int bytes
)
751 .iov_base
= (void *)buf
,
759 qemu_iovec_init_external(&qiov
, &iov
, 1);
760 return bdrv_preadv(child
, offset
, &qiov
);
763 int bdrv_pwritev(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
767 ret
= bdrv_prwv_co(child
, offset
, qiov
, true, 0);
775 int bdrv_pwrite(BdrvChild
*child
, int64_t offset
, const void *buf
, int bytes
)
779 .iov_base
= (void *) buf
,
787 qemu_iovec_init_external(&qiov
, &iov
, 1);
788 return bdrv_pwritev(child
, offset
, &qiov
);
792 * Writes to the file and ensures that no writes are reordered across this
793 * request (acts as a barrier)
795 * Returns 0 on success, -errno in error cases.
797 int bdrv_pwrite_sync(BdrvChild
*child
, int64_t offset
,
798 const void *buf
, int count
)
802 ret
= bdrv_pwrite(child
, offset
, buf
, count
);
807 ret
= bdrv_flush(child
->bs
);
815 typedef struct CoroutineIOCompletion
{
816 Coroutine
*coroutine
;
818 } CoroutineIOCompletion
;
820 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
822 CoroutineIOCompletion
*co
= opaque
;
825 aio_co_wake(co
->coroutine
);
828 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
829 uint64_t offset
, uint64_t bytes
,
830 QEMUIOVector
*qiov
, int flags
)
832 BlockDriver
*drv
= bs
->drv
;
834 unsigned int nb_sectors
;
836 assert(!(flags
& ~BDRV_REQ_MASK
));
838 if (drv
->bdrv_co_preadv
) {
839 return drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
842 sector_num
= offset
>> BDRV_SECTOR_BITS
;
843 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
845 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
846 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
847 assert((bytes
>> BDRV_SECTOR_BITS
) <= BDRV_REQUEST_MAX_SECTORS
);
849 if (drv
->bdrv_co_readv
) {
850 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
853 CoroutineIOCompletion co
= {
854 .coroutine
= qemu_coroutine_self(),
857 acb
= bs
->drv
->bdrv_aio_readv(bs
, sector_num
, qiov
, nb_sectors
,
858 bdrv_co_io_em_complete
, &co
);
862 qemu_coroutine_yield();
868 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
869 uint64_t offset
, uint64_t bytes
,
870 QEMUIOVector
*qiov
, int flags
)
872 BlockDriver
*drv
= bs
->drv
;
874 unsigned int nb_sectors
;
877 assert(!(flags
& ~BDRV_REQ_MASK
));
879 if (drv
->bdrv_co_pwritev
) {
880 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
,
881 flags
& bs
->supported_write_flags
);
882 flags
&= ~bs
->supported_write_flags
;
886 sector_num
= offset
>> BDRV_SECTOR_BITS
;
887 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
889 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
890 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
891 assert((bytes
>> BDRV_SECTOR_BITS
) <= BDRV_REQUEST_MAX_SECTORS
);
893 if (drv
->bdrv_co_writev_flags
) {
894 ret
= drv
->bdrv_co_writev_flags(bs
, sector_num
, nb_sectors
, qiov
,
895 flags
& bs
->supported_write_flags
);
896 flags
&= ~bs
->supported_write_flags
;
897 } else if (drv
->bdrv_co_writev
) {
898 assert(!bs
->supported_write_flags
);
899 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
);
902 CoroutineIOCompletion co
= {
903 .coroutine
= qemu_coroutine_self(),
906 acb
= bs
->drv
->bdrv_aio_writev(bs
, sector_num
, qiov
, nb_sectors
,
907 bdrv_co_io_em_complete
, &co
);
911 qemu_coroutine_yield();
917 if (ret
== 0 && (flags
& BDRV_REQ_FUA
)) {
918 ret
= bdrv_co_flush(bs
);
924 static int coroutine_fn
925 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
926 uint64_t bytes
, QEMUIOVector
*qiov
)
928 BlockDriver
*drv
= bs
->drv
;
930 if (!drv
->bdrv_co_pwritev_compressed
) {
934 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
937 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
938 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
)
940 BlockDriverState
*bs
= child
->bs
;
942 /* Perform I/O through a temporary buffer so that users who scribble over
943 * their read buffer while the operation is in progress do not end up
944 * modifying the image file. This is critical for zero-copy guest I/O
945 * where anything might happen inside guest memory.
949 BlockDriver
*drv
= bs
->drv
;
951 QEMUIOVector local_qiov
;
952 int64_t cluster_offset
;
953 unsigned int cluster_bytes
;
956 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
957 BDRV_REQUEST_MAX_BYTES
);
958 unsigned int progress
= 0;
960 /* FIXME We cannot require callers to have write permissions when all they
961 * are doing is a read request. If we did things right, write permissions
962 * would be obtained anyway, but internally by the copy-on-read code. As
963 * long as it is implemented here rather than in a separate filter driver,
964 * the copy-on-read code doesn't have its own BdrvChild, however, for which
965 * it could request permissions. Therefore we have to bypass the permission
966 * system for the moment. */
967 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
969 /* Cover entire cluster so no additional backing file I/O is required when
970 * allocating cluster in the image file. Note that this value may exceed
971 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
972 * is one reason we loop rather than doing it all at once.
974 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
975 skip_bytes
= offset
- cluster_offset
;
977 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
978 cluster_offset
, cluster_bytes
);
980 bounce_buffer
= qemu_try_blockalign(bs
,
981 MIN(MIN(max_transfer
, cluster_bytes
),
983 if (bounce_buffer
== NULL
) {
988 while (cluster_bytes
) {
991 ret
= bdrv_is_allocated(bs
, cluster_offset
,
992 MIN(cluster_bytes
, max_transfer
), &pnum
);
994 /* Safe to treat errors in querying allocation as if
995 * unallocated; we'll probably fail again soon on the
996 * read, but at least that will set a decent errno.
998 pnum
= MIN(cluster_bytes
, max_transfer
);
1001 assert(skip_bytes
< pnum
);
1004 /* Must copy-on-read; use the bounce buffer */
1005 iov
.iov_base
= bounce_buffer
;
1006 iov
.iov_len
= pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1007 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1009 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1015 bdrv_debug_event(bs
, BLKDBG_COR_WRITE
);
1016 if (drv
->bdrv_co_pwrite_zeroes
&&
1017 buffer_is_zero(bounce_buffer
, pnum
)) {
1018 /* FIXME: Should we (perhaps conditionally) be setting
1019 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1020 * that still correctly reads as zero? */
1021 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
, 0);
1023 /* This does not change the data on the disk, it is not
1024 * necessary to flush even in cache=writethrough mode.
1026 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1031 /* It might be okay to ignore write errors for guest
1032 * requests. If this is a deliberate copy-on-read
1033 * then we don't want to ignore the error. Simply
1034 * report it in all cases.
1039 qemu_iovec_from_buf(qiov
, progress
, bounce_buffer
+ skip_bytes
,
1042 /* Read directly into the destination */
1043 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1044 qemu_iovec_concat(&local_qiov
, qiov
, progress
, pnum
- skip_bytes
);
1045 ret
= bdrv_driver_preadv(bs
, offset
+ progress
, local_qiov
.size
,
1047 qemu_iovec_destroy(&local_qiov
);
1053 cluster_offset
+= pnum
;
1054 cluster_bytes
-= pnum
;
1055 progress
+= pnum
- skip_bytes
;
1061 qemu_vfree(bounce_buffer
);
1066 * Forwards an already correctly aligned request to the BlockDriver. This
1067 * handles copy on read, zeroing after EOF, and fragmentation of large
1068 * reads; any other features must be implemented by the caller.
1070 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1071 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1072 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1074 BlockDriverState
*bs
= child
->bs
;
1075 int64_t total_bytes
, max_bytes
;
1077 uint64_t bytes_remaining
= bytes
;
1080 assert(is_power_of_2(align
));
1081 assert((offset
& (align
- 1)) == 0);
1082 assert((bytes
& (align
- 1)) == 0);
1083 assert(!qiov
|| bytes
== qiov
->size
);
1084 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1085 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1088 /* TODO: We would need a per-BDS .supported_read_flags and
1089 * potential fallback support, if we ever implement any read flags
1090 * to pass through to drivers. For now, there aren't any
1091 * passthrough flags. */
1092 assert(!(flags
& ~(BDRV_REQ_NO_SERIALISING
| BDRV_REQ_COPY_ON_READ
)));
1094 /* Handle Copy on Read and associated serialisation */
1095 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1096 /* If we touch the same cluster it counts as an overlap. This
1097 * guarantees that allocating writes will be serialized and not race
1098 * with each other for the same cluster. For example, in copy-on-read
1099 * it ensures that the CoR read and write operations are atomic and
1100 * guest writes cannot interleave between them. */
1101 mark_request_serialising(req
, bdrv_get_cluster_size(bs
));
1104 if (!(flags
& BDRV_REQ_NO_SERIALISING
)) {
1105 wait_serialising_requests(req
);
1108 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1109 /* TODO: Simplify further once bdrv_is_allocated no longer
1110 * requires sector alignment */
1111 int64_t start
= QEMU_ALIGN_DOWN(offset
, BDRV_SECTOR_SIZE
);
1112 int64_t end
= QEMU_ALIGN_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1115 ret
= bdrv_is_allocated(bs
, start
, end
- start
, &pnum
);
1120 if (!ret
|| pnum
!= end
- start
) {
1121 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
, qiov
);
1126 /* Forward the request to the BlockDriver, possibly fragmenting it */
1127 total_bytes
= bdrv_getlength(bs
);
1128 if (total_bytes
< 0) {
1133 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1134 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1135 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, 0);
1139 while (bytes_remaining
) {
1143 QEMUIOVector local_qiov
;
1145 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1147 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1148 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1150 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1151 num
, &local_qiov
, 0);
1153 qemu_iovec_destroy(&local_qiov
);
1155 num
= bytes_remaining
;
1156 ret
= qemu_iovec_memset(qiov
, bytes
- bytes_remaining
, 0,
1162 bytes_remaining
-= num
;
1166 return ret
< 0 ? ret
: 0;
1170 * Handle a read request in coroutine context
1172 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1173 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1174 BdrvRequestFlags flags
)
1176 BlockDriverState
*bs
= child
->bs
;
1177 BlockDriver
*drv
= bs
->drv
;
1178 BdrvTrackedRequest req
;
1180 uint64_t align
= bs
->bl
.request_alignment
;
1181 uint8_t *head_buf
= NULL
;
1182 uint8_t *tail_buf
= NULL
;
1183 QEMUIOVector local_qiov
;
1184 bool use_local_qiov
= false;
1187 trace_bdrv_co_preadv(child
->bs
, offset
, bytes
, flags
);
1193 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1198 bdrv_inc_in_flight(bs
);
1200 /* Don't do copy-on-read if we read data before write operation */
1201 if (atomic_read(&bs
->copy_on_read
) && !(flags
& BDRV_REQ_NO_SERIALISING
)) {
1202 flags
|= BDRV_REQ_COPY_ON_READ
;
1205 /* Align read if necessary by padding qiov */
1206 if (offset
& (align
- 1)) {
1207 head_buf
= qemu_blockalign(bs
, align
);
1208 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1209 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1210 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1211 use_local_qiov
= true;
1213 bytes
+= offset
& (align
- 1);
1214 offset
= offset
& ~(align
- 1);
1217 if ((offset
+ bytes
) & (align
- 1)) {
1218 if (!use_local_qiov
) {
1219 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1220 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1221 use_local_qiov
= true;
1223 tail_buf
= qemu_blockalign(bs
, align
);
1224 qemu_iovec_add(&local_qiov
, tail_buf
,
1225 align
- ((offset
+ bytes
) & (align
- 1)));
1227 bytes
= ROUND_UP(bytes
, align
);
1230 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1231 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
, align
,
1232 use_local_qiov
? &local_qiov
: qiov
,
1234 tracked_request_end(&req
);
1235 bdrv_dec_in_flight(bs
);
1237 if (use_local_qiov
) {
1238 qemu_iovec_destroy(&local_qiov
);
1239 qemu_vfree(head_buf
);
1240 qemu_vfree(tail_buf
);
1246 static int coroutine_fn
bdrv_co_do_readv(BdrvChild
*child
,
1247 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
,
1248 BdrvRequestFlags flags
)
1250 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
1254 return bdrv_co_preadv(child
, sector_num
<< BDRV_SECTOR_BITS
,
1255 nb_sectors
<< BDRV_SECTOR_BITS
, qiov
, flags
);
1258 int coroutine_fn
bdrv_co_readv(BdrvChild
*child
, int64_t sector_num
,
1259 int nb_sectors
, QEMUIOVector
*qiov
)
1261 return bdrv_co_do_readv(child
, sector_num
, nb_sectors
, qiov
, 0);
1264 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1265 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
1267 BlockDriver
*drv
= bs
->drv
;
1269 struct iovec iov
= {0};
1271 bool need_flush
= false;
1275 int max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
, INT_MAX
);
1276 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1277 bs
->bl
.request_alignment
);
1278 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1280 assert(alignment
% bs
->bl
.request_alignment
== 0);
1281 head
= offset
% alignment
;
1282 tail
= (offset
+ bytes
) % alignment
;
1283 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1284 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1286 while (bytes
> 0 && !ret
) {
1289 /* Align request. Block drivers can expect the "bulk" of the request
1290 * to be aligned, and that unaligned requests do not cross cluster
1294 /* Make a small request up to the first aligned sector. For
1295 * convenience, limit this request to max_transfer even if
1296 * we don't need to fall back to writes. */
1297 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1298 head
= (head
+ num
) % alignment
;
1299 assert(num
< max_write_zeroes
);
1300 } else if (tail
&& num
> alignment
) {
1301 /* Shorten the request to the last aligned sector. */
1305 /* limit request size */
1306 if (num
> max_write_zeroes
) {
1307 num
= max_write_zeroes
;
1311 /* First try the efficient write zeroes operation */
1312 if (drv
->bdrv_co_pwrite_zeroes
) {
1313 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1314 flags
& bs
->supported_zero_flags
);
1315 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1316 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1320 assert(!bs
->supported_zero_flags
);
1323 if (ret
== -ENOTSUP
) {
1324 /* Fall back to bounce buffer if write zeroes is unsupported */
1325 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1327 if ((flags
& BDRV_REQ_FUA
) &&
1328 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1329 /* No need for bdrv_driver_pwrite() to do a fallback
1330 * flush on each chunk; use just one at the end */
1331 write_flags
&= ~BDRV_REQ_FUA
;
1334 num
= MIN(num
, max_transfer
);
1336 if (iov
.iov_base
== NULL
) {
1337 iov
.iov_base
= qemu_try_blockalign(bs
, num
);
1338 if (iov
.iov_base
== NULL
) {
1342 memset(iov
.iov_base
, 0, num
);
1344 qemu_iovec_init_external(&qiov
, &iov
, 1);
1346 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, write_flags
);
1348 /* Keep bounce buffer around if it is big enough for all
1349 * all future requests.
1351 if (num
< max_transfer
) {
1352 qemu_vfree(iov
.iov_base
);
1353 iov
.iov_base
= NULL
;
1362 if (ret
== 0 && need_flush
) {
1363 ret
= bdrv_co_flush(bs
);
1365 qemu_vfree(iov
.iov_base
);
1370 * Forwards an already correctly aligned write request to the BlockDriver,
1371 * after possibly fragmenting it.
1373 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
1374 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1375 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1377 BlockDriverState
*bs
= child
->bs
;
1378 BlockDriver
*drv
= bs
->drv
;
1382 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1383 uint64_t bytes_remaining
= bytes
;
1386 if (bdrv_has_readonly_bitmaps(bs
)) {
1390 assert(is_power_of_2(align
));
1391 assert((offset
& (align
- 1)) == 0);
1392 assert((bytes
& (align
- 1)) == 0);
1393 assert(!qiov
|| bytes
== qiov
->size
);
1394 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1395 assert(!(flags
& ~BDRV_REQ_MASK
));
1396 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1399 waited
= wait_serialising_requests(req
);
1400 assert(!waited
|| !req
->serialising
);
1401 assert(req
->overlap_offset
<= offset
);
1402 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1403 assert(child
->perm
& BLK_PERM_WRITE
);
1404 assert(end_sector
<= bs
->total_sectors
|| child
->perm
& BLK_PERM_RESIZE
);
1406 ret
= notifier_with_return_list_notify(&bs
->before_write_notifiers
, req
);
1408 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1409 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1410 qemu_iovec_is_zero(qiov
)) {
1411 flags
|= BDRV_REQ_ZERO_WRITE
;
1412 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1413 flags
|= BDRV_REQ_MAY_UNMAP
;
1418 /* Do nothing, write notifier decided to fail this request */
1419 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1420 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
1421 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
1422 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
1423 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1424 } else if (bytes
<= max_transfer
) {
1425 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1426 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1428 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1429 while (bytes_remaining
) {
1430 int num
= MIN(bytes_remaining
, max_transfer
);
1431 QEMUIOVector local_qiov
;
1432 int local_flags
= flags
;
1435 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
1436 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1437 /* If FUA is going to be emulated by flush, we only
1438 * need to flush on the last iteration */
1439 local_flags
&= ~BDRV_REQ_FUA
;
1441 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1442 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1444 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
1445 num
, &local_qiov
, local_flags
);
1446 qemu_iovec_destroy(&local_qiov
);
1450 bytes_remaining
-= num
;
1453 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
1455 atomic_inc(&bs
->write_gen
);
1456 bdrv_set_dirty(bs
, offset
, bytes
);
1458 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1461 bs
->total_sectors
= MAX(bs
->total_sectors
, end_sector
);
1468 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
1471 BdrvRequestFlags flags
,
1472 BdrvTrackedRequest
*req
)
1474 BlockDriverState
*bs
= child
->bs
;
1475 uint8_t *buf
= NULL
;
1476 QEMUIOVector local_qiov
;
1478 uint64_t align
= bs
->bl
.request_alignment
;
1479 unsigned int head_padding_bytes
, tail_padding_bytes
;
1482 head_padding_bytes
= offset
& (align
- 1);
1483 tail_padding_bytes
= (align
- (offset
+ bytes
)) & (align
- 1);
1486 assert(flags
& BDRV_REQ_ZERO_WRITE
);
1487 if (head_padding_bytes
|| tail_padding_bytes
) {
1488 buf
= qemu_blockalign(bs
, align
);
1489 iov
= (struct iovec
) {
1493 qemu_iovec_init_external(&local_qiov
, &iov
, 1);
1495 if (head_padding_bytes
) {
1496 uint64_t zero_bytes
= MIN(bytes
, align
- head_padding_bytes
);
1498 /* RMW the unaligned part before head. */
1499 mark_request_serialising(req
, align
);
1500 wait_serialising_requests(req
);
1501 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1502 ret
= bdrv_aligned_preadv(child
, req
, offset
& ~(align
- 1), align
,
1503 align
, &local_qiov
, 0);
1507 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1509 memset(buf
+ head_padding_bytes
, 0, zero_bytes
);
1510 ret
= bdrv_aligned_pwritev(child
, req
, offset
& ~(align
- 1), align
,
1512 flags
& ~BDRV_REQ_ZERO_WRITE
);
1516 offset
+= zero_bytes
;
1517 bytes
-= zero_bytes
;
1520 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1521 if (bytes
>= align
) {
1522 /* Write the aligned part in the middle. */
1523 uint64_t aligned_bytes
= bytes
& ~(align
- 1);
1524 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
1529 bytes
-= aligned_bytes
;
1530 offset
+= aligned_bytes
;
1533 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1535 assert(align
== tail_padding_bytes
+ bytes
);
1536 /* RMW the unaligned part after tail. */
1537 mark_request_serialising(req
, align
);
1538 wait_serialising_requests(req
);
1539 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1540 ret
= bdrv_aligned_preadv(child
, req
, offset
, align
,
1541 align
, &local_qiov
, 0);
1545 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1547 memset(buf
, 0, bytes
);
1548 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
1549 &local_qiov
, flags
& ~BDRV_REQ_ZERO_WRITE
);
1558 * Handle a write request in coroutine context
1560 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
1561 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1562 BdrvRequestFlags flags
)
1564 BlockDriverState
*bs
= child
->bs
;
1565 BdrvTrackedRequest req
;
1566 uint64_t align
= bs
->bl
.request_alignment
;
1567 uint8_t *head_buf
= NULL
;
1568 uint8_t *tail_buf
= NULL
;
1569 QEMUIOVector local_qiov
;
1570 bool use_local_qiov
= false;
1573 trace_bdrv_co_pwritev(child
->bs
, offset
, bytes
, flags
);
1578 if (bs
->read_only
) {
1581 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1583 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1588 bdrv_inc_in_flight(bs
);
1590 * Align write if necessary by performing a read-modify-write cycle.
1591 * Pad qiov with the read parts and be sure to have a tracked request not
1592 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1594 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
1597 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
1601 if (offset
& (align
- 1)) {
1602 QEMUIOVector head_qiov
;
1603 struct iovec head_iov
;
1605 mark_request_serialising(&req
, align
);
1606 wait_serialising_requests(&req
);
1608 head_buf
= qemu_blockalign(bs
, align
);
1609 head_iov
= (struct iovec
) {
1610 .iov_base
= head_buf
,
1613 qemu_iovec_init_external(&head_qiov
, &head_iov
, 1);
1615 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1616 ret
= bdrv_aligned_preadv(child
, &req
, offset
& ~(align
- 1), align
,
1617 align
, &head_qiov
, 0);
1621 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1623 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1624 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1625 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1626 use_local_qiov
= true;
1628 bytes
+= offset
& (align
- 1);
1629 offset
= offset
& ~(align
- 1);
1631 /* We have read the tail already if the request is smaller
1632 * than one aligned block.
1634 if (bytes
< align
) {
1635 qemu_iovec_add(&local_qiov
, head_buf
+ bytes
, align
- bytes
);
1640 if ((offset
+ bytes
) & (align
- 1)) {
1641 QEMUIOVector tail_qiov
;
1642 struct iovec tail_iov
;
1646 mark_request_serialising(&req
, align
);
1647 waited
= wait_serialising_requests(&req
);
1648 assert(!waited
|| !use_local_qiov
);
1650 tail_buf
= qemu_blockalign(bs
, align
);
1651 tail_iov
= (struct iovec
) {
1652 .iov_base
= tail_buf
,
1655 qemu_iovec_init_external(&tail_qiov
, &tail_iov
, 1);
1657 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1658 ret
= bdrv_aligned_preadv(child
, &req
, (offset
+ bytes
) & ~(align
- 1),
1659 align
, align
, &tail_qiov
, 0);
1663 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1665 if (!use_local_qiov
) {
1666 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1667 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1668 use_local_qiov
= true;
1671 tail_bytes
= (offset
+ bytes
) & (align
- 1);
1672 qemu_iovec_add(&local_qiov
, tail_buf
+ tail_bytes
, align
- tail_bytes
);
1674 bytes
= ROUND_UP(bytes
, align
);
1677 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
1678 use_local_qiov
? &local_qiov
: qiov
,
1683 if (use_local_qiov
) {
1684 qemu_iovec_destroy(&local_qiov
);
1686 qemu_vfree(head_buf
);
1687 qemu_vfree(tail_buf
);
1689 tracked_request_end(&req
);
1690 bdrv_dec_in_flight(bs
);
1694 static int coroutine_fn
bdrv_co_do_writev(BdrvChild
*child
,
1695 int64_t sector_num
, int nb_sectors
, QEMUIOVector
*qiov
,
1696 BdrvRequestFlags flags
)
1698 if (nb_sectors
< 0 || nb_sectors
> BDRV_REQUEST_MAX_SECTORS
) {
1702 return bdrv_co_pwritev(child
, sector_num
<< BDRV_SECTOR_BITS
,
1703 nb_sectors
<< BDRV_SECTOR_BITS
, qiov
, flags
);
1706 int coroutine_fn
bdrv_co_writev(BdrvChild
*child
, int64_t sector_num
,
1707 int nb_sectors
, QEMUIOVector
*qiov
)
1709 return bdrv_co_do_writev(child
, sector_num
, nb_sectors
, qiov
, 0);
1712 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
1713 int bytes
, BdrvRequestFlags flags
)
1715 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
1717 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
1718 flags
&= ~BDRV_REQ_MAY_UNMAP
;
1721 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
1722 BDRV_REQ_ZERO_WRITE
| flags
);
1726 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1728 int bdrv_flush_all(void)
1730 BdrvNextIterator it
;
1731 BlockDriverState
*bs
= NULL
;
1734 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
1735 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
1738 aio_context_acquire(aio_context
);
1739 ret
= bdrv_flush(bs
);
1740 if (ret
< 0 && !result
) {
1743 aio_context_release(aio_context
);
1750 typedef struct BdrvCoGetBlockStatusData
{
1751 BlockDriverState
*bs
;
1752 BlockDriverState
*base
;
1753 BlockDriverState
**file
;
1759 } BdrvCoGetBlockStatusData
;
1761 int64_t coroutine_fn
bdrv_co_get_block_status_from_file(BlockDriverState
*bs
,
1765 BlockDriverState
**file
)
1767 assert(bs
->file
&& bs
->file
->bs
);
1769 *file
= bs
->file
->bs
;
1770 return BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
|
1771 (sector_num
<< BDRV_SECTOR_BITS
);
1774 int64_t coroutine_fn
bdrv_co_get_block_status_from_backing(BlockDriverState
*bs
,
1778 BlockDriverState
**file
)
1780 assert(bs
->backing
&& bs
->backing
->bs
);
1782 *file
= bs
->backing
->bs
;
1783 return BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
|
1784 (sector_num
<< BDRV_SECTOR_BITS
);
1788 * Returns the allocation status of the specified sectors.
1789 * Drivers not implementing the functionality are assumed to not support
1790 * backing files, hence all their sectors are reported as allocated.
1792 * If 'sector_num' is beyond the end of the disk image the return value is
1793 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
1795 * 'pnum' is set to the number of sectors (including and immediately following
1796 * the specified sector) that are known to be in the same
1797 * allocated/unallocated state.
1799 * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
1800 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
1801 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
1803 * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file'
1804 * points to the BDS which the sector range is allocated in.
1806 static int64_t coroutine_fn
bdrv_co_get_block_status(BlockDriverState
*bs
,
1808 int nb_sectors
, int *pnum
,
1809 BlockDriverState
**file
)
1811 int64_t total_sectors
;
1816 total_sectors
= bdrv_nb_sectors(bs
);
1817 if (total_sectors
< 0) {
1818 return total_sectors
;
1821 if (sector_num
>= total_sectors
) {
1823 return BDRV_BLOCK_EOF
;
1830 n
= total_sectors
- sector_num
;
1831 if (n
< nb_sectors
) {
1835 if (!bs
->drv
->bdrv_co_get_block_status
) {
1837 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
1838 if (sector_num
+ nb_sectors
== total_sectors
) {
1839 ret
|= BDRV_BLOCK_EOF
;
1841 if (bs
->drv
->protocol_name
) {
1842 ret
|= BDRV_BLOCK_OFFSET_VALID
| (sector_num
* BDRV_SECTOR_SIZE
);
1848 bdrv_inc_in_flight(bs
);
1849 ret
= bs
->drv
->bdrv_co_get_block_status(bs
, sector_num
, nb_sectors
, pnum
,
1856 if (ret
& BDRV_BLOCK_RAW
) {
1857 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& *file
);
1858 ret
= bdrv_co_get_block_status(*file
, ret
>> BDRV_SECTOR_BITS
,
1863 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
1864 ret
|= BDRV_BLOCK_ALLOCATED
;
1866 if (bdrv_unallocated_blocks_are_zero(bs
)) {
1867 ret
|= BDRV_BLOCK_ZERO
;
1868 } else if (bs
->backing
) {
1869 BlockDriverState
*bs2
= bs
->backing
->bs
;
1870 int64_t nb_sectors2
= bdrv_nb_sectors(bs2
);
1871 if (nb_sectors2
>= 0 && sector_num
>= nb_sectors2
) {
1872 ret
|= BDRV_BLOCK_ZERO
;
1877 if (*file
&& *file
!= bs
&&
1878 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
1879 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
1880 BlockDriverState
*file2
;
1883 ret2
= bdrv_co_get_block_status(*file
, ret
>> BDRV_SECTOR_BITS
,
1884 *pnum
, &file_pnum
, &file2
);
1886 /* Ignore errors. This is just providing extra information, it
1887 * is useful but not necessary.
1889 if (ret2
& BDRV_BLOCK_EOF
&&
1890 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
1892 * It is valid for the format block driver to read
1893 * beyond the end of the underlying file's current
1894 * size; such areas read as zero.
1896 ret
|= BDRV_BLOCK_ZERO
;
1898 /* Limit request to the range reported by the protocol driver */
1900 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
1906 bdrv_dec_in_flight(bs
);
1907 if (ret
>= 0 && sector_num
+ *pnum
== total_sectors
) {
1908 ret
|= BDRV_BLOCK_EOF
;
1913 static int64_t coroutine_fn
bdrv_co_get_block_status_above(BlockDriverState
*bs
,
1914 BlockDriverState
*base
,
1918 BlockDriverState
**file
)
1920 BlockDriverState
*p
;
1925 for (p
= bs
; p
!= base
; p
= backing_bs(p
)) {
1926 ret
= bdrv_co_get_block_status(p
, sector_num
, nb_sectors
, pnum
, file
);
1930 if (ret
& BDRV_BLOCK_ZERO
&& ret
& BDRV_BLOCK_EOF
&& !first
) {
1932 * Reading beyond the end of the file continues to read
1933 * zeroes, but we can only widen the result to the
1934 * unallocated length we learned from an earlier
1939 if (ret
& (BDRV_BLOCK_ZERO
| BDRV_BLOCK_DATA
)) {
1942 /* [sector_num, pnum] unallocated on this layer, which could be only
1943 * the first part of [sector_num, nb_sectors]. */
1944 nb_sectors
= MIN(nb_sectors
, *pnum
);
1950 /* Coroutine wrapper for bdrv_get_block_status_above() */
1951 static void coroutine_fn
bdrv_get_block_status_above_co_entry(void *opaque
)
1953 BdrvCoGetBlockStatusData
*data
= opaque
;
1955 data
->ret
= bdrv_co_get_block_status_above(data
->bs
, data
->base
,
1964 * Synchronous wrapper around bdrv_co_get_block_status_above().
1966 * See bdrv_co_get_block_status_above() for details.
1968 int64_t bdrv_get_block_status_above(BlockDriverState
*bs
,
1969 BlockDriverState
*base
,
1971 int nb_sectors
, int *pnum
,
1972 BlockDriverState
**file
)
1975 BdrvCoGetBlockStatusData data
= {
1979 .sector_num
= sector_num
,
1980 .nb_sectors
= nb_sectors
,
1985 if (qemu_in_coroutine()) {
1986 /* Fast-path if already in coroutine context */
1987 bdrv_get_block_status_above_co_entry(&data
);
1989 co
= qemu_coroutine_create(bdrv_get_block_status_above_co_entry
,
1991 bdrv_coroutine_enter(bs
, co
);
1992 BDRV_POLL_WHILE(bs
, !data
.done
);
1997 int64_t bdrv_get_block_status(BlockDriverState
*bs
,
1999 int nb_sectors
, int *pnum
,
2000 BlockDriverState
**file
)
2002 return bdrv_get_block_status_above(bs
, backing_bs(bs
),
2003 sector_num
, nb_sectors
, pnum
, file
);
2006 int coroutine_fn
bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
,
2007 int64_t bytes
, int64_t *pnum
)
2009 BlockDriverState
*file
;
2010 int64_t sector_num
= offset
>> BDRV_SECTOR_BITS
;
2011 int nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
2015 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
2016 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
) && bytes
< INT_MAX
);
2017 ret
= bdrv_get_block_status(bs
, sector_num
, nb_sectors
, &psectors
,
2023 *pnum
= psectors
* BDRV_SECTOR_SIZE
;
2025 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2029 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2031 * Return true if (a prefix of) the given range is allocated in any image
2032 * between BASE and TOP (inclusive). BASE can be NULL to check if the given
2033 * offset is allocated in any image of the chain. Return false otherwise,
2034 * or negative errno on failure.
2036 * 'pnum' is set to the number of bytes (including and immediately
2037 * following the specified offset) that are known to be in the same
2038 * allocated/unallocated state. Note that a subsequent call starting
2039 * at 'offset + *pnum' may return the same allocation status (in other
2040 * words, the result is not necessarily the maximum possible range);
2041 * but 'pnum' will only be 0 when end of file is reached.
2044 int bdrv_is_allocated_above(BlockDriverState
*top
,
2045 BlockDriverState
*base
,
2046 int64_t offset
, int64_t bytes
, int64_t *pnum
)
2048 BlockDriverState
*intermediate
;
2053 while (intermediate
&& intermediate
!= base
) {
2057 ret
= bdrv_is_allocated(intermediate
, offset
, bytes
, &pnum_inter
);
2066 size_inter
= bdrv_getlength(intermediate
);
2067 if (size_inter
< 0) {
2070 if (n
> pnum_inter
&&
2071 (intermediate
== top
|| offset
+ pnum_inter
< size_inter
)) {
2075 intermediate
= backing_bs(intermediate
);
2082 typedef struct BdrvVmstateCo
{
2083 BlockDriverState
*bs
;
2090 static int coroutine_fn
2091 bdrv_co_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
2094 BlockDriver
*drv
= bs
->drv
;
2097 bdrv_inc_in_flight(bs
);
2101 } else if (drv
->bdrv_load_vmstate
) {
2103 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
2105 ret
= drv
->bdrv_save_vmstate(bs
, qiov
, pos
);
2107 } else if (bs
->file
) {
2108 ret
= bdrv_co_rw_vmstate(bs
->file
->bs
, qiov
, pos
, is_read
);
2111 bdrv_dec_in_flight(bs
);
2115 static void coroutine_fn
bdrv_co_rw_vmstate_entry(void *opaque
)
2117 BdrvVmstateCo
*co
= opaque
;
2118 co
->ret
= bdrv_co_rw_vmstate(co
->bs
, co
->qiov
, co
->pos
, co
->is_read
);
2122 bdrv_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
2125 if (qemu_in_coroutine()) {
2126 return bdrv_co_rw_vmstate(bs
, qiov
, pos
, is_read
);
2128 BdrvVmstateCo data
= {
2133 .ret
= -EINPROGRESS
,
2135 Coroutine
*co
= qemu_coroutine_create(bdrv_co_rw_vmstate_entry
, &data
);
2137 bdrv_coroutine_enter(bs
, co
);
2138 BDRV_POLL_WHILE(bs
, data
.ret
== -EINPROGRESS
);
2143 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2144 int64_t pos
, int size
)
2147 struct iovec iov
= {
2148 .iov_base
= (void *) buf
,
2153 qemu_iovec_init_external(&qiov
, &iov
, 1);
2155 ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2163 int bdrv_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2165 return bdrv_rw_vmstate(bs
, qiov
, pos
, false);
2168 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2169 int64_t pos
, int size
)
2172 struct iovec iov
= {
2178 qemu_iovec_init_external(&qiov
, &iov
, 1);
2179 ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2187 int bdrv_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2189 return bdrv_rw_vmstate(bs
, qiov
, pos
, true);
2192 /**************************************************************/
2195 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2198 bdrv_aio_cancel_async(acb
);
2199 while (acb
->refcnt
> 1) {
2200 if (acb
->aiocb_info
->get_aio_context
) {
2201 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2202 } else if (acb
->bs
) {
2203 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2204 * assert that we're not using an I/O thread. Thread-safe
2205 * code should use bdrv_aio_cancel_async exclusively.
2207 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2208 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2213 qemu_aio_unref(acb
);
2216 /* Async version of aio cancel. The caller is not blocked if the acb implements
2217 * cancel_async, otherwise we do nothing and let the request normally complete.
2218 * In either case the completion callback must be called. */
2219 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2221 if (acb
->aiocb_info
->cancel_async
) {
2222 acb
->aiocb_info
->cancel_async(acb
);
2226 /**************************************************************/
2227 /* Coroutine block device emulation */
2229 typedef struct FlushCo
{
2230 BlockDriverState
*bs
;
2235 static void coroutine_fn
bdrv_flush_co_entry(void *opaque
)
2237 FlushCo
*rwco
= opaque
;
2239 rwco
->ret
= bdrv_co_flush(rwco
->bs
);
2242 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2247 bdrv_inc_in_flight(bs
);
2249 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2254 qemu_co_mutex_lock(&bs
->reqs_lock
);
2255 current_gen
= atomic_read(&bs
->write_gen
);
2257 /* Wait until any previous flushes are completed */
2258 while (bs
->active_flush_req
) {
2259 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2262 /* Flushes reach this point in nondecreasing current_gen order. */
2263 bs
->active_flush_req
= true;
2264 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2266 /* Write back all layers by calling one driver function */
2267 if (bs
->drv
->bdrv_co_flush
) {
2268 ret
= bs
->drv
->bdrv_co_flush(bs
);
2272 /* Write back cached data to the OS even with cache=unsafe */
2273 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_OS
);
2274 if (bs
->drv
->bdrv_co_flush_to_os
) {
2275 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2281 /* But don't actually force it to the disk with cache=unsafe */
2282 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2286 /* Check if we really need to flush anything */
2287 if (bs
->flushed_gen
== current_gen
) {
2291 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_DISK
);
2292 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2293 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2294 } else if (bs
->drv
->bdrv_aio_flush
) {
2296 CoroutineIOCompletion co
= {
2297 .coroutine
= qemu_coroutine_self(),
2300 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2304 qemu_coroutine_yield();
2309 * Some block drivers always operate in either writethrough or unsafe
2310 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2311 * know how the server works (because the behaviour is hardcoded or
2312 * depends on server-side configuration), so we can't ensure that
2313 * everything is safe on disk. Returning an error doesn't work because
2314 * that would break guests even if the server operates in writethrough
2317 * Let's hope the user knows what he's doing.
2326 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2327 * in the case of cache=unsafe, so there are no useless flushes.
2330 ret
= bs
->file
? bdrv_co_flush(bs
->file
->bs
) : 0;
2332 /* Notify any pending flushes that we have completed */
2334 bs
->flushed_gen
= current_gen
;
2337 qemu_co_mutex_lock(&bs
->reqs_lock
);
2338 bs
->active_flush_req
= false;
2339 /* Return value is ignored - it's ok if wait queue is empty */
2340 qemu_co_queue_next(&bs
->flush_queue
);
2341 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2344 bdrv_dec_in_flight(bs
);
2348 int bdrv_flush(BlockDriverState
*bs
)
2351 FlushCo flush_co
= {
2356 if (qemu_in_coroutine()) {
2357 /* Fast-path if already in coroutine context */
2358 bdrv_flush_co_entry(&flush_co
);
2360 co
= qemu_coroutine_create(bdrv_flush_co_entry
, &flush_co
);
2361 bdrv_coroutine_enter(bs
, co
);
2362 BDRV_POLL_WHILE(bs
, flush_co
.ret
== NOT_DONE
);
2365 return flush_co
.ret
;
2368 typedef struct DiscardCo
{
2369 BlockDriverState
*bs
;
2374 static void coroutine_fn
bdrv_pdiscard_co_entry(void *opaque
)
2376 DiscardCo
*rwco
= opaque
;
2378 rwco
->ret
= bdrv_co_pdiscard(rwco
->bs
, rwco
->offset
, rwco
->bytes
);
2381 int coroutine_fn
bdrv_co_pdiscard(BlockDriverState
*bs
, int64_t offset
,
2384 BdrvTrackedRequest req
;
2385 int max_pdiscard
, ret
;
2386 int head
, tail
, align
;
2392 if (bdrv_has_readonly_bitmaps(bs
)) {
2396 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
2399 } else if (bs
->read_only
) {
2402 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
2404 /* Do nothing if disabled. */
2405 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2409 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2413 /* Discard is advisory, but some devices track and coalesce
2414 * unaligned requests, so we must pass everything down rather than
2415 * round here. Still, most devices will just silently ignore
2416 * unaligned requests (by returning -ENOTSUP), so we must fragment
2417 * the request accordingly. */
2418 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
2419 assert(align
% bs
->bl
.request_alignment
== 0);
2420 head
= offset
% align
;
2421 tail
= (offset
+ bytes
) % align
;
2423 bdrv_inc_in_flight(bs
);
2424 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
2426 ret
= notifier_with_return_list_notify(&bs
->before_write_notifiers
, &req
);
2431 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT_MAX
),
2433 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
2439 /* Make small requests to get to alignment boundaries. */
2440 num
= MIN(bytes
, align
- head
);
2441 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
2442 num
%= bs
->bl
.request_alignment
;
2444 head
= (head
+ num
) % align
;
2445 assert(num
< max_pdiscard
);
2448 /* Shorten the request to the last aligned cluster. */
2450 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
2451 tail
> bs
->bl
.request_alignment
) {
2452 tail
%= bs
->bl
.request_alignment
;
2456 /* limit request size */
2457 if (num
> max_pdiscard
) {
2461 if (bs
->drv
->bdrv_co_pdiscard
) {
2462 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
2465 CoroutineIOCompletion co
= {
2466 .coroutine
= qemu_coroutine_self(),
2469 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
2470 bdrv_co_io_em_complete
, &co
);
2475 qemu_coroutine_yield();
2479 if (ret
&& ret
!= -ENOTSUP
) {
2488 atomic_inc(&bs
->write_gen
);
2489 bdrv_set_dirty(bs
, req
.offset
, req
.bytes
);
2490 tracked_request_end(&req
);
2491 bdrv_dec_in_flight(bs
);
2495 int bdrv_pdiscard(BlockDriverState
*bs
, int64_t offset
, int bytes
)
2505 if (qemu_in_coroutine()) {
2506 /* Fast-path if already in coroutine context */
2507 bdrv_pdiscard_co_entry(&rwco
);
2509 co
= qemu_coroutine_create(bdrv_pdiscard_co_entry
, &rwco
);
2510 bdrv_coroutine_enter(bs
, co
);
2511 BDRV_POLL_WHILE(bs
, rwco
.ret
== NOT_DONE
);
2517 int bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
2519 BlockDriver
*drv
= bs
->drv
;
2520 CoroutineIOCompletion co
= {
2521 .coroutine
= qemu_coroutine_self(),
2525 bdrv_inc_in_flight(bs
);
2526 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
2531 if (drv
->bdrv_co_ioctl
) {
2532 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
2534 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
2539 qemu_coroutine_yield();
2542 bdrv_dec_in_flight(bs
);
2546 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2548 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
2551 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
2553 return memset(qemu_blockalign(bs
, size
), 0, size
);
2556 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
2558 size_t align
= bdrv_opt_mem_align(bs
);
2560 /* Ensure that NULL is never returned on success */
2566 return qemu_try_memalign(align
, size
);
2569 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
2571 void *mem
= qemu_try_blockalign(bs
, size
);
2574 memset(mem
, 0, size
);
2581 * Check if all memory in this vector is sector aligned.
2583 bool bdrv_qiov_is_aligned(BlockDriverState
*bs
, QEMUIOVector
*qiov
)
2586 size_t alignment
= bdrv_min_mem_align(bs
);
2588 for (i
= 0; i
< qiov
->niov
; i
++) {
2589 if ((uintptr_t) qiov
->iov
[i
].iov_base
% alignment
) {
2592 if (qiov
->iov
[i
].iov_len
% alignment
) {
2600 void bdrv_add_before_write_notifier(BlockDriverState
*bs
,
2601 NotifierWithReturn
*notifier
)
2603 notifier_with_return_list_add(&bs
->before_write_notifiers
, notifier
);
2606 void bdrv_io_plug(BlockDriverState
*bs
)
2610 QLIST_FOREACH(child
, &bs
->children
, next
) {
2611 bdrv_io_plug(child
->bs
);
2614 if (atomic_fetch_inc(&bs
->io_plugged
) == 0) {
2615 BlockDriver
*drv
= bs
->drv
;
2616 if (drv
&& drv
->bdrv_io_plug
) {
2617 drv
->bdrv_io_plug(bs
);
2622 void bdrv_io_unplug(BlockDriverState
*bs
)
2626 assert(bs
->io_plugged
);
2627 if (atomic_fetch_dec(&bs
->io_plugged
) == 1) {
2628 BlockDriver
*drv
= bs
->drv
;
2629 if (drv
&& drv
->bdrv_io_unplug
) {
2630 drv
->bdrv_io_unplug(bs
);
2634 QLIST_FOREACH(child
, &bs
->children
, next
) {
2635 bdrv_io_unplug(child
->bs
);