target/hexagon: fix = vs. == mishap
[qemu/kevin.git] / block / io.c
blob58557f2f96f0754d961554b1b6d1201e4aae7688
1 /*
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
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "trace.h"
27 #include "sysemu/block-backend.h"
28 #include "block/aio-wait.h"
29 #include "block/blockjob.h"
30 #include "block/blockjob_int.h"
31 #include "block/block_int.h"
32 #include "block/coroutines.h"
33 #include "block/dirty-bitmap.h"
34 #include "block/write-threshold.h"
35 #include "qemu/cutils.h"
36 #include "qemu/memalign.h"
37 #include "qapi/error.h"
38 #include "qemu/error-report.h"
39 #include "qemu/main-loop.h"
40 #include "sysemu/replay.h"
42 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
43 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
45 static void bdrv_parent_cb_resize(BlockDriverState *bs);
46 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
47 int64_t offset, int64_t bytes, BdrvRequestFlags flags);
49 static void bdrv_parent_drained_begin(BlockDriverState *bs, BdrvChild *ignore)
51 BdrvChild *c, *next;
53 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
54 if (c == ignore) {
55 continue;
57 bdrv_parent_drained_begin_single(c);
61 void bdrv_parent_drained_end_single(BdrvChild *c)
63 IO_OR_GS_CODE();
65 assert(c->quiesced_parent);
66 c->quiesced_parent = false;
68 if (c->klass->drained_end) {
69 c->klass->drained_end(c);
73 static void bdrv_parent_drained_end(BlockDriverState *bs, BdrvChild *ignore)
75 BdrvChild *c;
77 QLIST_FOREACH(c, &bs->parents, next_parent) {
78 if (c == ignore) {
79 continue;
81 bdrv_parent_drained_end_single(c);
85 bool bdrv_parent_drained_poll_single(BdrvChild *c)
87 if (c->klass->drained_poll) {
88 return c->klass->drained_poll(c);
90 return false;
93 static bool bdrv_parent_drained_poll(BlockDriverState *bs, BdrvChild *ignore,
94 bool ignore_bds_parents)
96 BdrvChild *c, *next;
97 bool busy = false;
99 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
100 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
101 continue;
103 busy |= bdrv_parent_drained_poll_single(c);
106 return busy;
109 void bdrv_parent_drained_begin_single(BdrvChild *c)
111 IO_OR_GS_CODE();
113 assert(!c->quiesced_parent);
114 c->quiesced_parent = true;
116 if (c->klass->drained_begin) {
117 c->klass->drained_begin(c);
121 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
123 dst->pdiscard_alignment = MAX(dst->pdiscard_alignment,
124 src->pdiscard_alignment);
125 dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
126 dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer);
127 dst->max_hw_transfer = MIN_NON_ZERO(dst->max_hw_transfer,
128 src->max_hw_transfer);
129 dst->opt_mem_alignment = MAX(dst->opt_mem_alignment,
130 src->opt_mem_alignment);
131 dst->min_mem_alignment = MAX(dst->min_mem_alignment,
132 src->min_mem_alignment);
133 dst->max_iov = MIN_NON_ZERO(dst->max_iov, src->max_iov);
134 dst->max_hw_iov = MIN_NON_ZERO(dst->max_hw_iov, src->max_hw_iov);
137 typedef struct BdrvRefreshLimitsState {
138 BlockDriverState *bs;
139 BlockLimits old_bl;
140 } BdrvRefreshLimitsState;
142 static void bdrv_refresh_limits_abort(void *opaque)
144 BdrvRefreshLimitsState *s = opaque;
146 s->bs->bl = s->old_bl;
149 static TransactionActionDrv bdrv_refresh_limits_drv = {
150 .abort = bdrv_refresh_limits_abort,
151 .clean = g_free,
154 /* @tran is allowed to be NULL, in this case no rollback is possible. */
155 void bdrv_refresh_limits(BlockDriverState *bs, Transaction *tran, Error **errp)
157 ERRP_GUARD();
158 BlockDriver *drv = bs->drv;
159 BdrvChild *c;
160 bool have_limits;
162 GLOBAL_STATE_CODE();
164 if (tran) {
165 BdrvRefreshLimitsState *s = g_new(BdrvRefreshLimitsState, 1);
166 *s = (BdrvRefreshLimitsState) {
167 .bs = bs,
168 .old_bl = bs->bl,
170 tran_add(tran, &bdrv_refresh_limits_drv, s);
173 memset(&bs->bl, 0, sizeof(bs->bl));
175 if (!drv) {
176 return;
179 /* Default alignment based on whether driver has byte interface */
180 bs->bl.request_alignment = (drv->bdrv_co_preadv ||
181 drv->bdrv_aio_preadv ||
182 drv->bdrv_co_preadv_part) ? 1 : 512;
184 /* Take some limits from the children as a default */
185 have_limits = false;
186 QLIST_FOREACH(c, &bs->children, next) {
187 if (c->role & (BDRV_CHILD_DATA | BDRV_CHILD_FILTERED | BDRV_CHILD_COW))
189 bdrv_merge_limits(&bs->bl, &c->bs->bl);
190 have_limits = true;
193 if (c->role & BDRV_CHILD_FILTERED) {
194 bs->bl.has_variable_length |= c->bs->bl.has_variable_length;
198 if (!have_limits) {
199 bs->bl.min_mem_alignment = 512;
200 bs->bl.opt_mem_alignment = qemu_real_host_page_size();
202 /* Safe default since most protocols use readv()/writev()/etc */
203 bs->bl.max_iov = IOV_MAX;
206 /* Then let the driver override it */
207 if (drv->bdrv_refresh_limits) {
208 drv->bdrv_refresh_limits(bs, errp);
209 if (*errp) {
210 return;
214 if (bs->bl.request_alignment > BDRV_MAX_ALIGNMENT) {
215 error_setg(errp, "Driver requires too large request alignment");
220 * The copy-on-read flag is actually a reference count so multiple users may
221 * use the feature without worrying about clobbering its previous state.
222 * Copy-on-read stays enabled until all users have called to disable it.
224 void bdrv_enable_copy_on_read(BlockDriverState *bs)
226 IO_CODE();
227 qatomic_inc(&bs->copy_on_read);
230 void bdrv_disable_copy_on_read(BlockDriverState *bs)
232 int old = qatomic_fetch_dec(&bs->copy_on_read);
233 IO_CODE();
234 assert(old >= 1);
237 typedef struct {
238 Coroutine *co;
239 BlockDriverState *bs;
240 bool done;
241 bool begin;
242 bool poll;
243 BdrvChild *parent;
244 } BdrvCoDrainData;
246 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
247 bool bdrv_drain_poll(BlockDriverState *bs, BdrvChild *ignore_parent,
248 bool ignore_bds_parents)
250 IO_OR_GS_CODE();
252 if (bdrv_parent_drained_poll(bs, ignore_parent, ignore_bds_parents)) {
253 return true;
256 if (qatomic_read(&bs->in_flight)) {
257 return true;
260 return false;
263 static bool bdrv_drain_poll_top_level(BlockDriverState *bs,
264 BdrvChild *ignore_parent)
266 return bdrv_drain_poll(bs, ignore_parent, false);
269 static void bdrv_do_drained_begin(BlockDriverState *bs, BdrvChild *parent,
270 bool poll);
271 static void bdrv_do_drained_end(BlockDriverState *bs, BdrvChild *parent);
273 static void bdrv_co_drain_bh_cb(void *opaque)
275 BdrvCoDrainData *data = opaque;
276 Coroutine *co = data->co;
277 BlockDriverState *bs = data->bs;
279 if (bs) {
280 AioContext *ctx = bdrv_get_aio_context(bs);
281 aio_context_acquire(ctx);
282 bdrv_dec_in_flight(bs);
283 if (data->begin) {
284 bdrv_do_drained_begin(bs, data->parent, data->poll);
285 } else {
286 assert(!data->poll);
287 bdrv_do_drained_end(bs, data->parent);
289 aio_context_release(ctx);
290 } else {
291 assert(data->begin);
292 bdrv_drain_all_begin();
295 data->done = true;
296 aio_co_wake(co);
299 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs,
300 bool begin,
301 BdrvChild *parent,
302 bool poll)
304 BdrvCoDrainData data;
305 Coroutine *self = qemu_coroutine_self();
306 AioContext *ctx = bdrv_get_aio_context(bs);
307 AioContext *co_ctx = qemu_coroutine_get_aio_context(self);
309 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
310 * other coroutines run if they were queued by aio_co_enter(). */
312 assert(qemu_in_coroutine());
313 data = (BdrvCoDrainData) {
314 .co = self,
315 .bs = bs,
316 .done = false,
317 .begin = begin,
318 .parent = parent,
319 .poll = poll,
322 if (bs) {
323 bdrv_inc_in_flight(bs);
327 * Temporarily drop the lock across yield or we would get deadlocks.
328 * bdrv_co_drain_bh_cb() reaquires the lock as needed.
330 * When we yield below, the lock for the current context will be
331 * released, so if this is actually the lock that protects bs, don't drop
332 * it a second time.
334 if (ctx != co_ctx) {
335 aio_context_release(ctx);
337 replay_bh_schedule_oneshot_event(ctx, bdrv_co_drain_bh_cb, &data);
339 qemu_coroutine_yield();
340 /* If we are resumed from some other event (such as an aio completion or a
341 * timer callback), it is a bug in the caller that should be fixed. */
342 assert(data.done);
344 /* Reaquire the AioContext of bs if we dropped it */
345 if (ctx != co_ctx) {
346 aio_context_acquire(ctx);
350 static void bdrv_do_drained_begin(BlockDriverState *bs, BdrvChild *parent,
351 bool poll)
353 IO_OR_GS_CODE();
355 if (qemu_in_coroutine()) {
356 bdrv_co_yield_to_drain(bs, true, parent, poll);
357 return;
360 /* Stop things in parent-to-child order */
361 if (qatomic_fetch_inc(&bs->quiesce_counter) == 0) {
362 aio_disable_external(bdrv_get_aio_context(bs));
363 bdrv_parent_drained_begin(bs, parent);
364 if (bs->drv && bs->drv->bdrv_drain_begin) {
365 bs->drv->bdrv_drain_begin(bs);
370 * Wait for drained requests to finish.
372 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
373 * call is needed so things in this AioContext can make progress even
374 * though we don't return to the main AioContext loop - this automatically
375 * includes other nodes in the same AioContext and therefore all child
376 * nodes.
378 if (poll) {
379 BDRV_POLL_WHILE(bs, bdrv_drain_poll_top_level(bs, parent));
383 void bdrv_do_drained_begin_quiesce(BlockDriverState *bs, BdrvChild *parent)
385 bdrv_do_drained_begin(bs, parent, false);
388 void bdrv_drained_begin(BlockDriverState *bs)
390 IO_OR_GS_CODE();
391 bdrv_do_drained_begin(bs, NULL, true);
395 * This function does not poll, nor must any of its recursively called
396 * functions.
398 static void bdrv_do_drained_end(BlockDriverState *bs, BdrvChild *parent)
400 int old_quiesce_counter;
402 if (qemu_in_coroutine()) {
403 bdrv_co_yield_to_drain(bs, false, parent, false);
404 return;
406 assert(bs->quiesce_counter > 0);
408 /* Re-enable things in child-to-parent order */
409 old_quiesce_counter = qatomic_fetch_dec(&bs->quiesce_counter);
410 if (old_quiesce_counter == 1) {
411 if (bs->drv && bs->drv->bdrv_drain_end) {
412 bs->drv->bdrv_drain_end(bs);
414 bdrv_parent_drained_end(bs, parent);
415 aio_enable_external(bdrv_get_aio_context(bs));
419 void bdrv_drained_end(BlockDriverState *bs)
421 IO_OR_GS_CODE();
422 bdrv_do_drained_end(bs, NULL);
425 void bdrv_drain(BlockDriverState *bs)
427 IO_OR_GS_CODE();
428 bdrv_drained_begin(bs);
429 bdrv_drained_end(bs);
432 static void bdrv_drain_assert_idle(BlockDriverState *bs)
434 BdrvChild *child, *next;
436 assert(qatomic_read(&bs->in_flight) == 0);
437 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
438 bdrv_drain_assert_idle(child->bs);
442 unsigned int bdrv_drain_all_count = 0;
444 static bool bdrv_drain_all_poll(void)
446 BlockDriverState *bs = NULL;
447 bool result = false;
448 GLOBAL_STATE_CODE();
450 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
451 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
452 while ((bs = bdrv_next_all_states(bs))) {
453 AioContext *aio_context = bdrv_get_aio_context(bs);
454 aio_context_acquire(aio_context);
455 result |= bdrv_drain_poll(bs, NULL, true);
456 aio_context_release(aio_context);
459 return result;
463 * Wait for pending requests to complete across all BlockDriverStates
465 * This function does not flush data to disk, use bdrv_flush_all() for that
466 * after calling this function.
468 * This pauses all block jobs and disables external clients. It must
469 * be paired with bdrv_drain_all_end().
471 * NOTE: no new block jobs or BlockDriverStates can be created between
472 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
474 void bdrv_drain_all_begin_nopoll(void)
476 BlockDriverState *bs = NULL;
477 GLOBAL_STATE_CODE();
480 * bdrv queue is managed by record/replay,
481 * waiting for finishing the I/O requests may
482 * be infinite
484 if (replay_events_enabled()) {
485 return;
488 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
489 * loop AioContext, so make sure we're in the main context. */
490 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
491 assert(bdrv_drain_all_count < INT_MAX);
492 bdrv_drain_all_count++;
494 /* Quiesce all nodes, without polling in-flight requests yet. The graph
495 * cannot change during this loop. */
496 while ((bs = bdrv_next_all_states(bs))) {
497 AioContext *aio_context = bdrv_get_aio_context(bs);
499 aio_context_acquire(aio_context);
500 bdrv_do_drained_begin(bs, NULL, false);
501 aio_context_release(aio_context);
505 void bdrv_drain_all_begin(void)
507 BlockDriverState *bs = NULL;
509 if (qemu_in_coroutine()) {
510 bdrv_co_yield_to_drain(NULL, true, NULL, true);
511 return;
515 * bdrv queue is managed by record/replay,
516 * waiting for finishing the I/O requests may
517 * be infinite
519 if (replay_events_enabled()) {
520 return;
523 bdrv_drain_all_begin_nopoll();
525 /* Now poll the in-flight requests */
526 AIO_WAIT_WHILE_UNLOCKED(NULL, bdrv_drain_all_poll());
528 while ((bs = bdrv_next_all_states(bs))) {
529 bdrv_drain_assert_idle(bs);
533 void bdrv_drain_all_end_quiesce(BlockDriverState *bs)
535 GLOBAL_STATE_CODE();
537 g_assert(bs->quiesce_counter > 0);
538 g_assert(!bs->refcnt);
540 while (bs->quiesce_counter) {
541 bdrv_do_drained_end(bs, NULL);
545 void bdrv_drain_all_end(void)
547 BlockDriverState *bs = NULL;
548 GLOBAL_STATE_CODE();
551 * bdrv queue is managed by record/replay,
552 * waiting for finishing the I/O requests may
553 * be endless
555 if (replay_events_enabled()) {
556 return;
559 while ((bs = bdrv_next_all_states(bs))) {
560 AioContext *aio_context = bdrv_get_aio_context(bs);
562 aio_context_acquire(aio_context);
563 bdrv_do_drained_end(bs, NULL);
564 aio_context_release(aio_context);
567 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
568 assert(bdrv_drain_all_count > 0);
569 bdrv_drain_all_count--;
572 void bdrv_drain_all(void)
574 GLOBAL_STATE_CODE();
575 bdrv_drain_all_begin();
576 bdrv_drain_all_end();
580 * Remove an active request from the tracked requests list
582 * This function should be called when a tracked request is completing.
584 static void coroutine_fn tracked_request_end(BdrvTrackedRequest *req)
586 if (req->serialising) {
587 qatomic_dec(&req->bs->serialising_in_flight);
590 qemu_co_mutex_lock(&req->bs->reqs_lock);
591 QLIST_REMOVE(req, list);
592 qemu_co_queue_restart_all(&req->wait_queue);
593 qemu_co_mutex_unlock(&req->bs->reqs_lock);
597 * Add an active request to the tracked requests list
599 static void coroutine_fn tracked_request_begin(BdrvTrackedRequest *req,
600 BlockDriverState *bs,
601 int64_t offset,
602 int64_t bytes,
603 enum BdrvTrackedRequestType type)
605 bdrv_check_request(offset, bytes, &error_abort);
607 *req = (BdrvTrackedRequest){
608 .bs = bs,
609 .offset = offset,
610 .bytes = bytes,
611 .type = type,
612 .co = qemu_coroutine_self(),
613 .serialising = false,
614 .overlap_offset = offset,
615 .overlap_bytes = bytes,
618 qemu_co_queue_init(&req->wait_queue);
620 qemu_co_mutex_lock(&bs->reqs_lock);
621 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
622 qemu_co_mutex_unlock(&bs->reqs_lock);
625 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
626 int64_t offset, int64_t bytes)
628 bdrv_check_request(offset, bytes, &error_abort);
630 /* aaaa bbbb */
631 if (offset >= req->overlap_offset + req->overlap_bytes) {
632 return false;
634 /* bbbb aaaa */
635 if (req->overlap_offset >= offset + bytes) {
636 return false;
638 return true;
641 /* Called with self->bs->reqs_lock held */
642 static coroutine_fn BdrvTrackedRequest *
643 bdrv_find_conflicting_request(BdrvTrackedRequest *self)
645 BdrvTrackedRequest *req;
647 QLIST_FOREACH(req, &self->bs->tracked_requests, list) {
648 if (req == self || (!req->serialising && !self->serialising)) {
649 continue;
651 if (tracked_request_overlaps(req, self->overlap_offset,
652 self->overlap_bytes))
655 * Hitting this means there was a reentrant request, for
656 * example, a block driver issuing nested requests. This must
657 * never happen since it means deadlock.
659 assert(qemu_coroutine_self() != req->co);
662 * If the request is already (indirectly) waiting for us, or
663 * will wait for us as soon as it wakes up, then just go on
664 * (instead of producing a deadlock in the former case).
666 if (!req->waiting_for) {
667 return req;
672 return NULL;
675 /* Called with self->bs->reqs_lock held */
676 static void coroutine_fn
677 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest *self)
679 BdrvTrackedRequest *req;
681 while ((req = bdrv_find_conflicting_request(self))) {
682 self->waiting_for = req;
683 qemu_co_queue_wait(&req->wait_queue, &self->bs->reqs_lock);
684 self->waiting_for = NULL;
688 /* Called with req->bs->reqs_lock held */
689 static void tracked_request_set_serialising(BdrvTrackedRequest *req,
690 uint64_t align)
692 int64_t overlap_offset = req->offset & ~(align - 1);
693 int64_t overlap_bytes =
694 ROUND_UP(req->offset + req->bytes, align) - overlap_offset;
696 bdrv_check_request(req->offset, req->bytes, &error_abort);
698 if (!req->serialising) {
699 qatomic_inc(&req->bs->serialising_in_flight);
700 req->serialising = true;
703 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
704 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
708 * Return the tracked request on @bs for the current coroutine, or
709 * NULL if there is none.
711 BdrvTrackedRequest *coroutine_fn bdrv_co_get_self_request(BlockDriverState *bs)
713 BdrvTrackedRequest *req;
714 Coroutine *self = qemu_coroutine_self();
715 IO_CODE();
717 QLIST_FOREACH(req, &bs->tracked_requests, list) {
718 if (req->co == self) {
719 return req;
723 return NULL;
727 * Round a region to cluster boundaries
729 void coroutine_fn GRAPH_RDLOCK
730 bdrv_round_to_clusters(BlockDriverState *bs, int64_t offset, int64_t bytes,
731 int64_t *cluster_offset, int64_t *cluster_bytes)
733 BlockDriverInfo bdi;
734 IO_CODE();
735 if (bdrv_co_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
736 *cluster_offset = offset;
737 *cluster_bytes = bytes;
738 } else {
739 int64_t c = bdi.cluster_size;
740 *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
741 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
745 static int coroutine_fn GRAPH_RDLOCK bdrv_get_cluster_size(BlockDriverState *bs)
747 BlockDriverInfo bdi;
748 int ret;
750 ret = bdrv_co_get_info(bs, &bdi);
751 if (ret < 0 || bdi.cluster_size == 0) {
752 return bs->bl.request_alignment;
753 } else {
754 return bdi.cluster_size;
758 void bdrv_inc_in_flight(BlockDriverState *bs)
760 IO_CODE();
761 qatomic_inc(&bs->in_flight);
764 void bdrv_wakeup(BlockDriverState *bs)
766 IO_CODE();
767 aio_wait_kick();
770 void bdrv_dec_in_flight(BlockDriverState *bs)
772 IO_CODE();
773 qatomic_dec(&bs->in_flight);
774 bdrv_wakeup(bs);
777 static void coroutine_fn
778 bdrv_wait_serialising_requests(BdrvTrackedRequest *self)
780 BlockDriverState *bs = self->bs;
782 if (!qatomic_read(&bs->serialising_in_flight)) {
783 return;
786 qemu_co_mutex_lock(&bs->reqs_lock);
787 bdrv_wait_serialising_requests_locked(self);
788 qemu_co_mutex_unlock(&bs->reqs_lock);
791 void coroutine_fn bdrv_make_request_serialising(BdrvTrackedRequest *req,
792 uint64_t align)
794 IO_CODE();
796 qemu_co_mutex_lock(&req->bs->reqs_lock);
798 tracked_request_set_serialising(req, align);
799 bdrv_wait_serialising_requests_locked(req);
801 qemu_co_mutex_unlock(&req->bs->reqs_lock);
804 int bdrv_check_qiov_request(int64_t offset, int64_t bytes,
805 QEMUIOVector *qiov, size_t qiov_offset,
806 Error **errp)
809 * Check generic offset/bytes correctness
812 if (offset < 0) {
813 error_setg(errp, "offset is negative: %" PRIi64, offset);
814 return -EIO;
817 if (bytes < 0) {
818 error_setg(errp, "bytes is negative: %" PRIi64, bytes);
819 return -EIO;
822 if (bytes > BDRV_MAX_LENGTH) {
823 error_setg(errp, "bytes(%" PRIi64 ") exceeds maximum(%" PRIi64 ")",
824 bytes, BDRV_MAX_LENGTH);
825 return -EIO;
828 if (offset > BDRV_MAX_LENGTH) {
829 error_setg(errp, "offset(%" PRIi64 ") exceeds maximum(%" PRIi64 ")",
830 offset, BDRV_MAX_LENGTH);
831 return -EIO;
834 if (offset > BDRV_MAX_LENGTH - bytes) {
835 error_setg(errp, "sum of offset(%" PRIi64 ") and bytes(%" PRIi64 ") "
836 "exceeds maximum(%" PRIi64 ")", offset, bytes,
837 BDRV_MAX_LENGTH);
838 return -EIO;
841 if (!qiov) {
842 return 0;
846 * Check qiov and qiov_offset
849 if (qiov_offset > qiov->size) {
850 error_setg(errp, "qiov_offset(%zu) overflow io vector size(%zu)",
851 qiov_offset, qiov->size);
852 return -EIO;
855 if (bytes > qiov->size - qiov_offset) {
856 error_setg(errp, "bytes(%" PRIi64 ") + qiov_offset(%zu) overflow io "
857 "vector size(%zu)", bytes, qiov_offset, qiov->size);
858 return -EIO;
861 return 0;
864 int bdrv_check_request(int64_t offset, int64_t bytes, Error **errp)
866 return bdrv_check_qiov_request(offset, bytes, NULL, 0, errp);
869 static int bdrv_check_request32(int64_t offset, int64_t bytes,
870 QEMUIOVector *qiov, size_t qiov_offset)
872 int ret = bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, NULL);
873 if (ret < 0) {
874 return ret;
877 if (bytes > BDRV_REQUEST_MAX_BYTES) {
878 return -EIO;
881 return 0;
885 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
886 * The operation is sped up by checking the block status and only writing
887 * zeroes to the device if they currently do not return zeroes. Optional
888 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
889 * BDRV_REQ_FUA).
891 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
893 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
895 int ret;
896 int64_t target_size, bytes, offset = 0;
897 BlockDriverState *bs = child->bs;
898 IO_CODE();
900 target_size = bdrv_getlength(bs);
901 if (target_size < 0) {
902 return target_size;
905 for (;;) {
906 bytes = MIN(target_size - offset, BDRV_REQUEST_MAX_BYTES);
907 if (bytes <= 0) {
908 return 0;
910 ret = bdrv_block_status(bs, offset, bytes, &bytes, NULL, NULL);
911 if (ret < 0) {
912 return ret;
914 if (ret & BDRV_BLOCK_ZERO) {
915 offset += bytes;
916 continue;
918 ret = bdrv_pwrite_zeroes(child, offset, bytes, flags);
919 if (ret < 0) {
920 return ret;
922 offset += bytes;
927 * Writes to the file and ensures that no writes are reordered across this
928 * request (acts as a barrier)
930 * Returns 0 on success, -errno in error cases.
932 int coroutine_fn bdrv_co_pwrite_sync(BdrvChild *child, int64_t offset,
933 int64_t bytes, const void *buf,
934 BdrvRequestFlags flags)
936 int ret;
937 IO_CODE();
938 assert_bdrv_graph_readable();
940 ret = bdrv_co_pwrite(child, offset, bytes, buf, flags);
941 if (ret < 0) {
942 return ret;
945 ret = bdrv_co_flush(child->bs);
946 if (ret < 0) {
947 return ret;
950 return 0;
953 typedef struct CoroutineIOCompletion {
954 Coroutine *coroutine;
955 int ret;
956 } CoroutineIOCompletion;
958 static void bdrv_co_io_em_complete(void *opaque, int ret)
960 CoroutineIOCompletion *co = opaque;
962 co->ret = ret;
963 aio_co_wake(co->coroutine);
966 static int coroutine_fn GRAPH_RDLOCK
967 bdrv_driver_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
968 QEMUIOVector *qiov, size_t qiov_offset, int flags)
970 BlockDriver *drv = bs->drv;
971 int64_t sector_num;
972 unsigned int nb_sectors;
973 QEMUIOVector local_qiov;
974 int ret;
975 assert_bdrv_graph_readable();
977 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
978 assert(!(flags & ~bs->supported_read_flags));
980 if (!drv) {
981 return -ENOMEDIUM;
984 if (drv->bdrv_co_preadv_part) {
985 return drv->bdrv_co_preadv_part(bs, offset, bytes, qiov, qiov_offset,
986 flags);
989 if (qiov_offset > 0 || bytes != qiov->size) {
990 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
991 qiov = &local_qiov;
994 if (drv->bdrv_co_preadv) {
995 ret = drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
996 goto out;
999 if (drv->bdrv_aio_preadv) {
1000 BlockAIOCB *acb;
1001 CoroutineIOCompletion co = {
1002 .coroutine = qemu_coroutine_self(),
1005 acb = drv->bdrv_aio_preadv(bs, offset, bytes, qiov, flags,
1006 bdrv_co_io_em_complete, &co);
1007 if (acb == NULL) {
1008 ret = -EIO;
1009 goto out;
1010 } else {
1011 qemu_coroutine_yield();
1012 ret = co.ret;
1013 goto out;
1017 sector_num = offset >> BDRV_SECTOR_BITS;
1018 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1020 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1021 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1022 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1023 assert(drv->bdrv_co_readv);
1025 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1027 out:
1028 if (qiov == &local_qiov) {
1029 qemu_iovec_destroy(&local_qiov);
1032 return ret;
1035 static int coroutine_fn GRAPH_RDLOCK
1036 bdrv_driver_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
1037 QEMUIOVector *qiov, size_t qiov_offset,
1038 BdrvRequestFlags flags)
1040 BlockDriver *drv = bs->drv;
1041 bool emulate_fua = false;
1042 int64_t sector_num;
1043 unsigned int nb_sectors;
1044 QEMUIOVector local_qiov;
1045 int ret;
1046 assert_bdrv_graph_readable();
1048 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1050 if (!drv) {
1051 return -ENOMEDIUM;
1054 if ((flags & BDRV_REQ_FUA) &&
1055 (~bs->supported_write_flags & BDRV_REQ_FUA)) {
1056 flags &= ~BDRV_REQ_FUA;
1057 emulate_fua = true;
1060 flags &= bs->supported_write_flags;
1062 if (drv->bdrv_co_pwritev_part) {
1063 ret = drv->bdrv_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset,
1064 flags);
1065 goto emulate_flags;
1068 if (qiov_offset > 0 || bytes != qiov->size) {
1069 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1070 qiov = &local_qiov;
1073 if (drv->bdrv_co_pwritev) {
1074 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov, flags);
1075 goto emulate_flags;
1078 if (drv->bdrv_aio_pwritev) {
1079 BlockAIOCB *acb;
1080 CoroutineIOCompletion co = {
1081 .coroutine = qemu_coroutine_self(),
1084 acb = drv->bdrv_aio_pwritev(bs, offset, bytes, qiov, flags,
1085 bdrv_co_io_em_complete, &co);
1086 if (acb == NULL) {
1087 ret = -EIO;
1088 } else {
1089 qemu_coroutine_yield();
1090 ret = co.ret;
1092 goto emulate_flags;
1095 sector_num = offset >> BDRV_SECTOR_BITS;
1096 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1098 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1099 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1100 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1102 assert(drv->bdrv_co_writev);
1103 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov, flags);
1105 emulate_flags:
1106 if (ret == 0 && emulate_fua) {
1107 ret = bdrv_co_flush(bs);
1110 if (qiov == &local_qiov) {
1111 qemu_iovec_destroy(&local_qiov);
1114 return ret;
1117 static int coroutine_fn GRAPH_RDLOCK
1118 bdrv_driver_pwritev_compressed(BlockDriverState *bs, int64_t offset,
1119 int64_t bytes, QEMUIOVector *qiov,
1120 size_t qiov_offset)
1122 BlockDriver *drv = bs->drv;
1123 QEMUIOVector local_qiov;
1124 int ret;
1125 assert_bdrv_graph_readable();
1127 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1129 if (!drv) {
1130 return -ENOMEDIUM;
1133 if (!block_driver_can_compress(drv)) {
1134 return -ENOTSUP;
1137 if (drv->bdrv_co_pwritev_compressed_part) {
1138 return drv->bdrv_co_pwritev_compressed_part(bs, offset, bytes,
1139 qiov, qiov_offset);
1142 if (qiov_offset == 0) {
1143 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
1146 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1147 ret = drv->bdrv_co_pwritev_compressed(bs, offset, bytes, &local_qiov);
1148 qemu_iovec_destroy(&local_qiov);
1150 return ret;
1153 static int coroutine_fn GRAPH_RDLOCK
1154 bdrv_co_do_copy_on_readv(BdrvChild *child, int64_t offset, int64_t bytes,
1155 QEMUIOVector *qiov, size_t qiov_offset, int flags)
1157 BlockDriverState *bs = child->bs;
1159 /* Perform I/O through a temporary buffer so that users who scribble over
1160 * their read buffer while the operation is in progress do not end up
1161 * modifying the image file. This is critical for zero-copy guest I/O
1162 * where anything might happen inside guest memory.
1164 void *bounce_buffer = NULL;
1166 BlockDriver *drv = bs->drv;
1167 int64_t cluster_offset;
1168 int64_t cluster_bytes;
1169 int64_t skip_bytes;
1170 int ret;
1171 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1172 BDRV_REQUEST_MAX_BYTES);
1173 int64_t progress = 0;
1174 bool skip_write;
1176 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1178 if (!drv) {
1179 return -ENOMEDIUM;
1183 * Do not write anything when the BDS is inactive. That is not
1184 * allowed, and it would not help.
1186 skip_write = (bs->open_flags & BDRV_O_INACTIVE);
1188 /* FIXME We cannot require callers to have write permissions when all they
1189 * are doing is a read request. If we did things right, write permissions
1190 * would be obtained anyway, but internally by the copy-on-read code. As
1191 * long as it is implemented here rather than in a separate filter driver,
1192 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1193 * it could request permissions. Therefore we have to bypass the permission
1194 * system for the moment. */
1195 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1197 /* Cover entire cluster so no additional backing file I/O is required when
1198 * allocating cluster in the image file. Note that this value may exceed
1199 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1200 * is one reason we loop rather than doing it all at once.
1202 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
1203 skip_bytes = offset - cluster_offset;
1205 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
1206 cluster_offset, cluster_bytes);
1208 while (cluster_bytes) {
1209 int64_t pnum;
1211 if (skip_write) {
1212 ret = 1; /* "already allocated", so nothing will be copied */
1213 pnum = MIN(cluster_bytes, max_transfer);
1214 } else {
1215 ret = bdrv_is_allocated(bs, cluster_offset,
1216 MIN(cluster_bytes, max_transfer), &pnum);
1217 if (ret < 0) {
1219 * Safe to treat errors in querying allocation as if
1220 * unallocated; we'll probably fail again soon on the
1221 * read, but at least that will set a decent errno.
1223 pnum = MIN(cluster_bytes, max_transfer);
1226 /* Stop at EOF if the image ends in the middle of the cluster */
1227 if (ret == 0 && pnum == 0) {
1228 assert(progress >= bytes);
1229 break;
1232 assert(skip_bytes < pnum);
1235 if (ret <= 0) {
1236 QEMUIOVector local_qiov;
1238 /* Must copy-on-read; use the bounce buffer */
1239 pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1240 if (!bounce_buffer) {
1241 int64_t max_we_need = MAX(pnum, cluster_bytes - pnum);
1242 int64_t max_allowed = MIN(max_transfer, MAX_BOUNCE_BUFFER);
1243 int64_t bounce_buffer_len = MIN(max_we_need, max_allowed);
1245 bounce_buffer = qemu_try_blockalign(bs, bounce_buffer_len);
1246 if (!bounce_buffer) {
1247 ret = -ENOMEM;
1248 goto err;
1251 qemu_iovec_init_buf(&local_qiov, bounce_buffer, pnum);
1253 ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1254 &local_qiov, 0, 0);
1255 if (ret < 0) {
1256 goto err;
1259 bdrv_co_debug_event(bs, BLKDBG_COR_WRITE);
1260 if (drv->bdrv_co_pwrite_zeroes &&
1261 buffer_is_zero(bounce_buffer, pnum)) {
1262 /* FIXME: Should we (perhaps conditionally) be setting
1263 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1264 * that still correctly reads as zero? */
1265 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum,
1266 BDRV_REQ_WRITE_UNCHANGED);
1267 } else {
1268 /* This does not change the data on the disk, it is not
1269 * necessary to flush even in cache=writethrough mode.
1271 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
1272 &local_qiov, 0,
1273 BDRV_REQ_WRITE_UNCHANGED);
1276 if (ret < 0) {
1277 /* It might be okay to ignore write errors for guest
1278 * requests. If this is a deliberate copy-on-read
1279 * then we don't want to ignore the error. Simply
1280 * report it in all cases.
1282 goto err;
1285 if (!(flags & BDRV_REQ_PREFETCH)) {
1286 qemu_iovec_from_buf(qiov, qiov_offset + progress,
1287 bounce_buffer + skip_bytes,
1288 MIN(pnum - skip_bytes, bytes - progress));
1290 } else if (!(flags & BDRV_REQ_PREFETCH)) {
1291 /* Read directly into the destination */
1292 ret = bdrv_driver_preadv(bs, offset + progress,
1293 MIN(pnum - skip_bytes, bytes - progress),
1294 qiov, qiov_offset + progress, 0);
1295 if (ret < 0) {
1296 goto err;
1300 cluster_offset += pnum;
1301 cluster_bytes -= pnum;
1302 progress += pnum - skip_bytes;
1303 skip_bytes = 0;
1305 ret = 0;
1307 err:
1308 qemu_vfree(bounce_buffer);
1309 return ret;
1313 * Forwards an already correctly aligned request to the BlockDriver. This
1314 * handles copy on read, zeroing after EOF, and fragmentation of large
1315 * reads; any other features must be implemented by the caller.
1317 static int coroutine_fn GRAPH_RDLOCK
1318 bdrv_aligned_preadv(BdrvChild *child, BdrvTrackedRequest *req,
1319 int64_t offset, int64_t bytes, int64_t align,
1320 QEMUIOVector *qiov, size_t qiov_offset, int flags)
1322 BlockDriverState *bs = child->bs;
1323 int64_t total_bytes, max_bytes;
1324 int ret = 0;
1325 int64_t bytes_remaining = bytes;
1326 int max_transfer;
1328 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1329 assert(is_power_of_2(align));
1330 assert((offset & (align - 1)) == 0);
1331 assert((bytes & (align - 1)) == 0);
1332 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1333 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1334 align);
1337 * TODO: We would need a per-BDS .supported_read_flags and
1338 * potential fallback support, if we ever implement any read flags
1339 * to pass through to drivers. For now, there aren't any
1340 * passthrough flags except the BDRV_REQ_REGISTERED_BUF optimization hint.
1342 assert(!(flags & ~(BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH |
1343 BDRV_REQ_REGISTERED_BUF)));
1345 /* Handle Copy on Read and associated serialisation */
1346 if (flags & BDRV_REQ_COPY_ON_READ) {
1347 /* If we touch the same cluster it counts as an overlap. This
1348 * guarantees that allocating writes will be serialized and not race
1349 * with each other for the same cluster. For example, in copy-on-read
1350 * it ensures that the CoR read and write operations are atomic and
1351 * guest writes cannot interleave between them. */
1352 bdrv_make_request_serialising(req, bdrv_get_cluster_size(bs));
1353 } else {
1354 bdrv_wait_serialising_requests(req);
1357 if (flags & BDRV_REQ_COPY_ON_READ) {
1358 int64_t pnum;
1360 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1361 flags &= ~BDRV_REQ_COPY_ON_READ;
1363 ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
1364 if (ret < 0) {
1365 goto out;
1368 if (!ret || pnum != bytes) {
1369 ret = bdrv_co_do_copy_on_readv(child, offset, bytes,
1370 qiov, qiov_offset, flags);
1371 goto out;
1372 } else if (flags & BDRV_REQ_PREFETCH) {
1373 goto out;
1377 /* Forward the request to the BlockDriver, possibly fragmenting it */
1378 total_bytes = bdrv_getlength(bs);
1379 if (total_bytes < 0) {
1380 ret = total_bytes;
1381 goto out;
1384 assert(!(flags & ~(bs->supported_read_flags | BDRV_REQ_REGISTERED_BUF)));
1386 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1387 if (bytes <= max_bytes && bytes <= max_transfer) {
1388 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, qiov_offset, flags);
1389 goto out;
1392 while (bytes_remaining) {
1393 int64_t num;
1395 if (max_bytes) {
1396 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1397 assert(num);
1399 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1400 num, qiov,
1401 qiov_offset + bytes - bytes_remaining,
1402 flags);
1403 max_bytes -= num;
1404 } else {
1405 num = bytes_remaining;
1406 ret = qemu_iovec_memset(qiov, qiov_offset + bytes - bytes_remaining,
1407 0, bytes_remaining);
1409 if (ret < 0) {
1410 goto out;
1412 bytes_remaining -= num;
1415 out:
1416 return ret < 0 ? ret : 0;
1420 * Request padding
1422 * |<---- align ----->| |<----- align ---->|
1423 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1424 * | | | | | |
1425 * -*----------$-------*-------- ... --------*-----$------------*---
1426 * | | | | | |
1427 * | offset | | end |
1428 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1429 * [buf ... ) [tail_buf )
1431 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1432 * is placed at the beginning of @buf and @tail at the @end.
1434 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1435 * around tail, if tail exists.
1437 * @merge_reads is true for small requests,
1438 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1439 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1441 typedef struct BdrvRequestPadding {
1442 uint8_t *buf;
1443 size_t buf_len;
1444 uint8_t *tail_buf;
1445 size_t head;
1446 size_t tail;
1447 bool merge_reads;
1448 QEMUIOVector local_qiov;
1449 } BdrvRequestPadding;
1451 static bool bdrv_init_padding(BlockDriverState *bs,
1452 int64_t offset, int64_t bytes,
1453 BdrvRequestPadding *pad)
1455 int64_t align = bs->bl.request_alignment;
1456 int64_t sum;
1458 bdrv_check_request(offset, bytes, &error_abort);
1459 assert(align <= INT_MAX); /* documented in block/block_int.h */
1460 assert(align <= SIZE_MAX / 2); /* so we can allocate the buffer */
1462 memset(pad, 0, sizeof(*pad));
1464 pad->head = offset & (align - 1);
1465 pad->tail = ((offset + bytes) & (align - 1));
1466 if (pad->tail) {
1467 pad->tail = align - pad->tail;
1470 if (!pad->head && !pad->tail) {
1471 return false;
1474 assert(bytes); /* Nothing good in aligning zero-length requests */
1476 sum = pad->head + bytes + pad->tail;
1477 pad->buf_len = (sum > align && pad->head && pad->tail) ? 2 * align : align;
1478 pad->buf = qemu_blockalign(bs, pad->buf_len);
1479 pad->merge_reads = sum == pad->buf_len;
1480 if (pad->tail) {
1481 pad->tail_buf = pad->buf + pad->buf_len - align;
1484 return true;
1487 static int coroutine_fn GRAPH_RDLOCK
1488 bdrv_padding_rmw_read(BdrvChild *child, BdrvTrackedRequest *req,
1489 BdrvRequestPadding *pad, bool zero_middle)
1491 QEMUIOVector local_qiov;
1492 BlockDriverState *bs = child->bs;
1493 uint64_t align = bs->bl.request_alignment;
1494 int ret;
1496 assert(req->serialising && pad->buf);
1498 if (pad->head || pad->merge_reads) {
1499 int64_t bytes = pad->merge_reads ? pad->buf_len : align;
1501 qemu_iovec_init_buf(&local_qiov, pad->buf, bytes);
1503 if (pad->head) {
1504 bdrv_co_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1506 if (pad->merge_reads && pad->tail) {
1507 bdrv_co_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1509 ret = bdrv_aligned_preadv(child, req, req->overlap_offset, bytes,
1510 align, &local_qiov, 0, 0);
1511 if (ret < 0) {
1512 return ret;
1514 if (pad->head) {
1515 bdrv_co_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1517 if (pad->merge_reads && pad->tail) {
1518 bdrv_co_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1521 if (pad->merge_reads) {
1522 goto zero_mem;
1526 if (pad->tail) {
1527 qemu_iovec_init_buf(&local_qiov, pad->tail_buf, align);
1529 bdrv_co_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1530 ret = bdrv_aligned_preadv(
1531 child, req,
1532 req->overlap_offset + req->overlap_bytes - align,
1533 align, align, &local_qiov, 0, 0);
1534 if (ret < 0) {
1535 return ret;
1537 bdrv_co_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1540 zero_mem:
1541 if (zero_middle) {
1542 memset(pad->buf + pad->head, 0, pad->buf_len - pad->head - pad->tail);
1545 return 0;
1548 static void bdrv_padding_destroy(BdrvRequestPadding *pad)
1550 if (pad->buf) {
1551 qemu_vfree(pad->buf);
1552 qemu_iovec_destroy(&pad->local_qiov);
1554 memset(pad, 0, sizeof(*pad));
1558 * bdrv_pad_request
1560 * Exchange request parameters with padded request if needed. Don't include RMW
1561 * read of padding, bdrv_padding_rmw_read() should be called separately if
1562 * needed.
1564 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1565 * - on function start they represent original request
1566 * - on failure or when padding is not needed they are unchanged
1567 * - on success when padding is needed they represent padded request
1569 static int bdrv_pad_request(BlockDriverState *bs,
1570 QEMUIOVector **qiov, size_t *qiov_offset,
1571 int64_t *offset, int64_t *bytes,
1572 BdrvRequestPadding *pad, bool *padded,
1573 BdrvRequestFlags *flags)
1575 int ret;
1577 bdrv_check_qiov_request(*offset, *bytes, *qiov, *qiov_offset, &error_abort);
1579 if (!bdrv_init_padding(bs, *offset, *bytes, pad)) {
1580 if (padded) {
1581 *padded = false;
1583 return 0;
1586 ret = qemu_iovec_init_extended(&pad->local_qiov, pad->buf, pad->head,
1587 *qiov, *qiov_offset, *bytes,
1588 pad->buf + pad->buf_len - pad->tail,
1589 pad->tail);
1590 if (ret < 0) {
1591 bdrv_padding_destroy(pad);
1592 return ret;
1594 *bytes += pad->head + pad->tail;
1595 *offset -= pad->head;
1596 *qiov = &pad->local_qiov;
1597 *qiov_offset = 0;
1598 if (padded) {
1599 *padded = true;
1601 if (flags) {
1602 /* Can't use optimization hint with bounce buffer */
1603 *flags &= ~BDRV_REQ_REGISTERED_BUF;
1606 return 0;
1609 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1610 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
1611 BdrvRequestFlags flags)
1613 IO_CODE();
1614 return bdrv_co_preadv_part(child, offset, bytes, qiov, 0, flags);
1617 int coroutine_fn bdrv_co_preadv_part(BdrvChild *child,
1618 int64_t offset, int64_t bytes,
1619 QEMUIOVector *qiov, size_t qiov_offset,
1620 BdrvRequestFlags flags)
1622 BlockDriverState *bs = child->bs;
1623 BdrvTrackedRequest req;
1624 BdrvRequestPadding pad;
1625 int ret;
1626 IO_CODE();
1628 trace_bdrv_co_preadv_part(bs, offset, bytes, flags);
1630 if (!bdrv_co_is_inserted(bs)) {
1631 return -ENOMEDIUM;
1634 ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
1635 if (ret < 0) {
1636 return ret;
1639 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
1641 * Aligning zero request is nonsense. Even if driver has special meaning
1642 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1643 * it to driver due to request_alignment.
1645 * Still, no reason to return an error if someone do unaligned
1646 * zero-length read occasionally.
1648 return 0;
1651 bdrv_inc_in_flight(bs);
1653 /* Don't do copy-on-read if we read data before write operation */
1654 if (qatomic_read(&bs->copy_on_read)) {
1655 flags |= BDRV_REQ_COPY_ON_READ;
1658 ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
1659 NULL, &flags);
1660 if (ret < 0) {
1661 goto fail;
1664 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1665 ret = bdrv_aligned_preadv(child, &req, offset, bytes,
1666 bs->bl.request_alignment,
1667 qiov, qiov_offset, flags);
1668 tracked_request_end(&req);
1669 bdrv_padding_destroy(&pad);
1671 fail:
1672 bdrv_dec_in_flight(bs);
1674 return ret;
1677 static int coroutine_fn GRAPH_RDLOCK
1678 bdrv_co_do_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
1679 BdrvRequestFlags flags)
1681 BlockDriver *drv = bs->drv;
1682 QEMUIOVector qiov;
1683 void *buf = NULL;
1684 int ret = 0;
1685 bool need_flush = false;
1686 int head = 0;
1687 int tail = 0;
1689 int64_t max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes,
1690 INT64_MAX);
1691 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1692 bs->bl.request_alignment);
1693 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
1695 assert_bdrv_graph_readable();
1696 bdrv_check_request(offset, bytes, &error_abort);
1698 if (!drv) {
1699 return -ENOMEDIUM;
1702 if ((flags & ~bs->supported_zero_flags) & BDRV_REQ_NO_FALLBACK) {
1703 return -ENOTSUP;
1706 /* By definition there is no user buffer so this flag doesn't make sense */
1707 if (flags & BDRV_REQ_REGISTERED_BUF) {
1708 return -EINVAL;
1711 /* Invalidate the cached block-status data range if this write overlaps */
1712 bdrv_bsc_invalidate_range(bs, offset, bytes);
1714 assert(alignment % bs->bl.request_alignment == 0);
1715 head = offset % alignment;
1716 tail = (offset + bytes) % alignment;
1717 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1718 assert(max_write_zeroes >= bs->bl.request_alignment);
1720 while (bytes > 0 && !ret) {
1721 int64_t num = bytes;
1723 /* Align request. Block drivers can expect the "bulk" of the request
1724 * to be aligned, and that unaligned requests do not cross cluster
1725 * boundaries.
1727 if (head) {
1728 /* Make a small request up to the first aligned sector. For
1729 * convenience, limit this request to max_transfer even if
1730 * we don't need to fall back to writes. */
1731 num = MIN(MIN(bytes, max_transfer), alignment - head);
1732 head = (head + num) % alignment;
1733 assert(num < max_write_zeroes);
1734 } else if (tail && num > alignment) {
1735 /* Shorten the request to the last aligned sector. */
1736 num -= tail;
1739 /* limit request size */
1740 if (num > max_write_zeroes) {
1741 num = max_write_zeroes;
1744 ret = -ENOTSUP;
1745 /* First try the efficient write zeroes operation */
1746 if (drv->bdrv_co_pwrite_zeroes) {
1747 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1748 flags & bs->supported_zero_flags);
1749 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1750 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1751 need_flush = true;
1753 } else {
1754 assert(!bs->supported_zero_flags);
1757 if (ret == -ENOTSUP && !(flags & BDRV_REQ_NO_FALLBACK)) {
1758 /* Fall back to bounce buffer if write zeroes is unsupported */
1759 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1761 if ((flags & BDRV_REQ_FUA) &&
1762 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1763 /* No need for bdrv_driver_pwrite() to do a fallback
1764 * flush on each chunk; use just one at the end */
1765 write_flags &= ~BDRV_REQ_FUA;
1766 need_flush = true;
1768 num = MIN(num, max_transfer);
1769 if (buf == NULL) {
1770 buf = qemu_try_blockalign0(bs, num);
1771 if (buf == NULL) {
1772 ret = -ENOMEM;
1773 goto fail;
1776 qemu_iovec_init_buf(&qiov, buf, num);
1778 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, 0, write_flags);
1780 /* Keep bounce buffer around if it is big enough for all
1781 * all future requests.
1783 if (num < max_transfer) {
1784 qemu_vfree(buf);
1785 buf = NULL;
1789 offset += num;
1790 bytes -= num;
1793 fail:
1794 if (ret == 0 && need_flush) {
1795 ret = bdrv_co_flush(bs);
1797 qemu_vfree(buf);
1798 return ret;
1801 static inline int coroutine_fn GRAPH_RDLOCK
1802 bdrv_co_write_req_prepare(BdrvChild *child, int64_t offset, int64_t bytes,
1803 BdrvTrackedRequest *req, int flags)
1805 BlockDriverState *bs = child->bs;
1807 bdrv_check_request(offset, bytes, &error_abort);
1809 if (bdrv_is_read_only(bs)) {
1810 return -EPERM;
1813 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1814 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1815 assert(!(flags & ~BDRV_REQ_MASK));
1816 assert(!((flags & BDRV_REQ_NO_WAIT) && !(flags & BDRV_REQ_SERIALISING)));
1818 if (flags & BDRV_REQ_SERIALISING) {
1819 QEMU_LOCK_GUARD(&bs->reqs_lock);
1821 tracked_request_set_serialising(req, bdrv_get_cluster_size(bs));
1823 if ((flags & BDRV_REQ_NO_WAIT) && bdrv_find_conflicting_request(req)) {
1824 return -EBUSY;
1827 bdrv_wait_serialising_requests_locked(req);
1828 } else {
1829 bdrv_wait_serialising_requests(req);
1832 assert(req->overlap_offset <= offset);
1833 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1834 assert(offset + bytes <= bs->total_sectors * BDRV_SECTOR_SIZE ||
1835 child->perm & BLK_PERM_RESIZE);
1837 switch (req->type) {
1838 case BDRV_TRACKED_WRITE:
1839 case BDRV_TRACKED_DISCARD:
1840 if (flags & BDRV_REQ_WRITE_UNCHANGED) {
1841 assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1842 } else {
1843 assert(child->perm & BLK_PERM_WRITE);
1845 bdrv_write_threshold_check_write(bs, offset, bytes);
1846 return 0;
1847 case BDRV_TRACKED_TRUNCATE:
1848 assert(child->perm & BLK_PERM_RESIZE);
1849 return 0;
1850 default:
1851 abort();
1855 static inline void coroutine_fn
1856 bdrv_co_write_req_finish(BdrvChild *child, int64_t offset, int64_t bytes,
1857 BdrvTrackedRequest *req, int ret)
1859 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1860 BlockDriverState *bs = child->bs;
1862 bdrv_check_request(offset, bytes, &error_abort);
1864 qatomic_inc(&bs->write_gen);
1867 * Discard cannot extend the image, but in error handling cases, such as
1868 * when reverting a qcow2 cluster allocation, the discarded range can pass
1869 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1870 * here. Instead, just skip it, since semantically a discard request
1871 * beyond EOF cannot expand the image anyway.
1873 if (ret == 0 &&
1874 (req->type == BDRV_TRACKED_TRUNCATE ||
1875 end_sector > bs->total_sectors) &&
1876 req->type != BDRV_TRACKED_DISCARD) {
1877 bs->total_sectors = end_sector;
1878 bdrv_parent_cb_resize(bs);
1879 bdrv_dirty_bitmap_truncate(bs, end_sector << BDRV_SECTOR_BITS);
1881 if (req->bytes) {
1882 switch (req->type) {
1883 case BDRV_TRACKED_WRITE:
1884 stat64_max(&bs->wr_highest_offset, offset + bytes);
1885 /* fall through, to set dirty bits */
1886 case BDRV_TRACKED_DISCARD:
1887 bdrv_set_dirty(bs, offset, bytes);
1888 break;
1889 default:
1890 break;
1896 * Forwards an already correctly aligned write request to the BlockDriver,
1897 * after possibly fragmenting it.
1899 static int coroutine_fn GRAPH_RDLOCK
1900 bdrv_aligned_pwritev(BdrvChild *child, BdrvTrackedRequest *req,
1901 int64_t offset, int64_t bytes, int64_t align,
1902 QEMUIOVector *qiov, size_t qiov_offset,
1903 BdrvRequestFlags flags)
1905 BlockDriverState *bs = child->bs;
1906 BlockDriver *drv = bs->drv;
1907 int ret;
1909 int64_t bytes_remaining = bytes;
1910 int max_transfer;
1912 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1914 if (!drv) {
1915 return -ENOMEDIUM;
1918 if (bdrv_has_readonly_bitmaps(bs)) {
1919 return -EPERM;
1922 assert(is_power_of_2(align));
1923 assert((offset & (align - 1)) == 0);
1924 assert((bytes & (align - 1)) == 0);
1925 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1926 align);
1928 ret = bdrv_co_write_req_prepare(child, offset, bytes, req, flags);
1930 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1931 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
1932 qemu_iovec_is_zero(qiov, qiov_offset, bytes)) {
1933 flags |= BDRV_REQ_ZERO_WRITE;
1934 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1935 flags |= BDRV_REQ_MAY_UNMAP;
1938 /* Can't use optimization hint with bufferless zero write */
1939 flags &= ~BDRV_REQ_REGISTERED_BUF;
1942 if (ret < 0) {
1943 /* Do nothing, write notifier decided to fail this request */
1944 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1945 bdrv_co_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1946 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
1947 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
1948 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes,
1949 qiov, qiov_offset);
1950 } else if (bytes <= max_transfer) {
1951 bdrv_co_debug_event(bs, BLKDBG_PWRITEV);
1952 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, qiov_offset, flags);
1953 } else {
1954 bdrv_co_debug_event(bs, BLKDBG_PWRITEV);
1955 while (bytes_remaining) {
1956 int num = MIN(bytes_remaining, max_transfer);
1957 int local_flags = flags;
1959 assert(num);
1960 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
1961 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1962 /* If FUA is going to be emulated by flush, we only
1963 * need to flush on the last iteration */
1964 local_flags &= ~BDRV_REQ_FUA;
1967 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
1968 num, qiov,
1969 qiov_offset + bytes - bytes_remaining,
1970 local_flags);
1971 if (ret < 0) {
1972 break;
1974 bytes_remaining -= num;
1977 bdrv_co_debug_event(bs, BLKDBG_PWRITEV_DONE);
1979 if (ret >= 0) {
1980 ret = 0;
1982 bdrv_co_write_req_finish(child, offset, bytes, req, ret);
1984 return ret;
1987 static int coroutine_fn GRAPH_RDLOCK
1988 bdrv_co_do_zero_pwritev(BdrvChild *child, int64_t offset, int64_t bytes,
1989 BdrvRequestFlags flags, BdrvTrackedRequest *req)
1991 BlockDriverState *bs = child->bs;
1992 QEMUIOVector local_qiov;
1993 uint64_t align = bs->bl.request_alignment;
1994 int ret = 0;
1995 bool padding;
1996 BdrvRequestPadding pad;
1998 /* This flag doesn't make sense for padding or zero writes */
1999 flags &= ~BDRV_REQ_REGISTERED_BUF;
2001 padding = bdrv_init_padding(bs, offset, bytes, &pad);
2002 if (padding) {
2003 assert(!(flags & BDRV_REQ_NO_WAIT));
2004 bdrv_make_request_serialising(req, align);
2006 bdrv_padding_rmw_read(child, req, &pad, true);
2008 if (pad.head || pad.merge_reads) {
2009 int64_t aligned_offset = offset & ~(align - 1);
2010 int64_t write_bytes = pad.merge_reads ? pad.buf_len : align;
2012 qemu_iovec_init_buf(&local_qiov, pad.buf, write_bytes);
2013 ret = bdrv_aligned_pwritev(child, req, aligned_offset, write_bytes,
2014 align, &local_qiov, 0,
2015 flags & ~BDRV_REQ_ZERO_WRITE);
2016 if (ret < 0 || pad.merge_reads) {
2017 /* Error or all work is done */
2018 goto out;
2020 offset += write_bytes - pad.head;
2021 bytes -= write_bytes - pad.head;
2025 assert(!bytes || (offset & (align - 1)) == 0);
2026 if (bytes >= align) {
2027 /* Write the aligned part in the middle. */
2028 int64_t aligned_bytes = bytes & ~(align - 1);
2029 ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
2030 NULL, 0, flags);
2031 if (ret < 0) {
2032 goto out;
2034 bytes -= aligned_bytes;
2035 offset += aligned_bytes;
2038 assert(!bytes || (offset & (align - 1)) == 0);
2039 if (bytes) {
2040 assert(align == pad.tail + bytes);
2042 qemu_iovec_init_buf(&local_qiov, pad.tail_buf, align);
2043 ret = bdrv_aligned_pwritev(child, req, offset, align, align,
2044 &local_qiov, 0,
2045 flags & ~BDRV_REQ_ZERO_WRITE);
2048 out:
2049 bdrv_padding_destroy(&pad);
2051 return ret;
2055 * Handle a write request in coroutine context
2057 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
2058 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
2059 BdrvRequestFlags flags)
2061 IO_CODE();
2062 return bdrv_co_pwritev_part(child, offset, bytes, qiov, 0, flags);
2065 int coroutine_fn bdrv_co_pwritev_part(BdrvChild *child,
2066 int64_t offset, int64_t bytes, QEMUIOVector *qiov, size_t qiov_offset,
2067 BdrvRequestFlags flags)
2069 BlockDriverState *bs = child->bs;
2070 BdrvTrackedRequest req;
2071 uint64_t align = bs->bl.request_alignment;
2072 BdrvRequestPadding pad;
2073 int ret;
2074 bool padded = false;
2075 IO_CODE();
2077 trace_bdrv_co_pwritev_part(child->bs, offset, bytes, flags);
2079 if (!bdrv_co_is_inserted(bs)) {
2080 return -ENOMEDIUM;
2083 if (flags & BDRV_REQ_ZERO_WRITE) {
2084 ret = bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, NULL);
2085 } else {
2086 ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
2088 if (ret < 0) {
2089 return ret;
2092 /* If the request is misaligned then we can't make it efficient */
2093 if ((flags & BDRV_REQ_NO_FALLBACK) &&
2094 !QEMU_IS_ALIGNED(offset | bytes, align))
2096 return -ENOTSUP;
2099 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
2101 * Aligning zero request is nonsense. Even if driver has special meaning
2102 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2103 * it to driver due to request_alignment.
2105 * Still, no reason to return an error if someone do unaligned
2106 * zero-length write occasionally.
2108 return 0;
2111 if (!(flags & BDRV_REQ_ZERO_WRITE)) {
2113 * Pad request for following read-modify-write cycle.
2114 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2115 * alignment only if there is no ZERO flag.
2117 ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
2118 &padded, &flags);
2119 if (ret < 0) {
2120 return ret;
2124 bdrv_inc_in_flight(bs);
2125 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
2127 if (flags & BDRV_REQ_ZERO_WRITE) {
2128 assert(!padded);
2129 ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
2130 goto out;
2133 if (padded) {
2135 * Request was unaligned to request_alignment and therefore
2136 * padded. We are going to do read-modify-write, and must
2137 * serialize the request to prevent interactions of the
2138 * widened region with other transactions.
2140 assert(!(flags & BDRV_REQ_NO_WAIT));
2141 bdrv_make_request_serialising(&req, align);
2142 bdrv_padding_rmw_read(child, &req, &pad, false);
2145 ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
2146 qiov, qiov_offset, flags);
2148 bdrv_padding_destroy(&pad);
2150 out:
2151 tracked_request_end(&req);
2152 bdrv_dec_in_flight(bs);
2154 return ret;
2157 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
2158 int64_t bytes, BdrvRequestFlags flags)
2160 IO_CODE();
2161 trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
2162 assert_bdrv_graph_readable();
2164 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
2165 flags &= ~BDRV_REQ_MAY_UNMAP;
2168 return bdrv_co_pwritev(child, offset, bytes, NULL,
2169 BDRV_REQ_ZERO_WRITE | flags);
2173 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2175 int bdrv_flush_all(void)
2177 BdrvNextIterator it;
2178 BlockDriverState *bs = NULL;
2179 int result = 0;
2181 GLOBAL_STATE_CODE();
2184 * bdrv queue is managed by record/replay,
2185 * creating new flush request for stopping
2186 * the VM may break the determinism
2188 if (replay_events_enabled()) {
2189 return result;
2192 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
2193 AioContext *aio_context = bdrv_get_aio_context(bs);
2194 int ret;
2196 aio_context_acquire(aio_context);
2197 ret = bdrv_flush(bs);
2198 if (ret < 0 && !result) {
2199 result = ret;
2201 aio_context_release(aio_context);
2204 return result;
2208 * Returns the allocation status of the specified sectors.
2209 * Drivers not implementing the functionality are assumed to not support
2210 * backing files, hence all their sectors are reported as allocated.
2212 * If 'want_zero' is true, the caller is querying for mapping
2213 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2214 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2215 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2217 * If 'offset' is beyond the end of the disk image the return value is
2218 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2220 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2221 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2222 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2224 * 'pnum' is set to the number of bytes (including and immediately
2225 * following the specified offset) that are easily known to be in the
2226 * same allocated/unallocated state. Note that a second call starting
2227 * at the original offset plus returned pnum may have the same status.
2228 * The returned value is non-zero on success except at end-of-file.
2230 * Returns negative errno on failure. Otherwise, if the
2231 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2232 * set to the host mapping and BDS corresponding to the guest offset.
2234 static int coroutine_fn GRAPH_RDLOCK
2235 bdrv_co_block_status(BlockDriverState *bs, bool want_zero,
2236 int64_t offset, int64_t bytes,
2237 int64_t *pnum, int64_t *map, BlockDriverState **file)
2239 int64_t total_size;
2240 int64_t n; /* bytes */
2241 int ret;
2242 int64_t local_map = 0;
2243 BlockDriverState *local_file = NULL;
2244 int64_t aligned_offset, aligned_bytes;
2245 uint32_t align;
2246 bool has_filtered_child;
2248 assert(pnum);
2249 assert_bdrv_graph_readable();
2250 *pnum = 0;
2251 total_size = bdrv_getlength(bs);
2252 if (total_size < 0) {
2253 ret = total_size;
2254 goto early_out;
2257 if (offset >= total_size) {
2258 ret = BDRV_BLOCK_EOF;
2259 goto early_out;
2261 if (!bytes) {
2262 ret = 0;
2263 goto early_out;
2266 n = total_size - offset;
2267 if (n < bytes) {
2268 bytes = n;
2271 /* Must be non-NULL or bdrv_getlength() would have failed */
2272 assert(bs->drv);
2273 has_filtered_child = bdrv_filter_child(bs);
2274 if (!bs->drv->bdrv_co_block_status && !has_filtered_child) {
2275 *pnum = bytes;
2276 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2277 if (offset + bytes == total_size) {
2278 ret |= BDRV_BLOCK_EOF;
2280 if (bs->drv->protocol_name) {
2281 ret |= BDRV_BLOCK_OFFSET_VALID;
2282 local_map = offset;
2283 local_file = bs;
2285 goto early_out;
2288 bdrv_inc_in_flight(bs);
2290 /* Round out to request_alignment boundaries */
2291 align = bs->bl.request_alignment;
2292 aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2293 aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2295 if (bs->drv->bdrv_co_block_status) {
2297 * Use the block-status cache only for protocol nodes: Format
2298 * drivers are generally quick to inquire the status, but protocol
2299 * drivers often need to get information from outside of qemu, so
2300 * we do not have control over the actual implementation. There
2301 * have been cases where inquiring the status took an unreasonably
2302 * long time, and we can do nothing in qemu to fix it.
2303 * This is especially problematic for images with large data areas,
2304 * because finding the few holes in them and giving them special
2305 * treatment does not gain much performance. Therefore, we try to
2306 * cache the last-identified data region.
2308 * Second, limiting ourselves to protocol nodes allows us to assume
2309 * the block status for data regions to be DATA | OFFSET_VALID, and
2310 * that the host offset is the same as the guest offset.
2312 * Note that it is possible that external writers zero parts of
2313 * the cached regions without the cache being invalidated, and so
2314 * we may report zeroes as data. This is not catastrophic,
2315 * however, because reporting zeroes as data is fine.
2317 if (QLIST_EMPTY(&bs->children) &&
2318 bdrv_bsc_is_data(bs, aligned_offset, pnum))
2320 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2321 local_file = bs;
2322 local_map = aligned_offset;
2323 } else {
2324 ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2325 aligned_bytes, pnum, &local_map,
2326 &local_file);
2329 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2330 * the cache is queried above. Technically, we do not need to check
2331 * it here; the worst that can happen is that we fill the cache for
2332 * non-protocol nodes, and then it is never used. However, filling
2333 * the cache requires an RCU update, so double check here to avoid
2334 * such an update if possible.
2336 * Check want_zero, because we only want to update the cache when we
2337 * have accurate information about what is zero and what is data.
2339 if (want_zero &&
2340 ret == (BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID) &&
2341 QLIST_EMPTY(&bs->children))
2344 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2345 * returned local_map value must be the same as the offset we
2346 * have passed (aligned_offset), and local_bs must be the node
2347 * itself.
2348 * Assert this, because we follow this rule when reading from
2349 * the cache (see the `local_file = bs` and
2350 * `local_map = aligned_offset` assignments above), and the
2351 * result the cache delivers must be the same as the driver
2352 * would deliver.
2354 assert(local_file == bs);
2355 assert(local_map == aligned_offset);
2356 bdrv_bsc_fill(bs, aligned_offset, *pnum);
2359 } else {
2360 /* Default code for filters */
2362 local_file = bdrv_filter_bs(bs);
2363 assert(local_file);
2365 *pnum = aligned_bytes;
2366 local_map = aligned_offset;
2367 ret = BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2369 if (ret < 0) {
2370 *pnum = 0;
2371 goto out;
2375 * The driver's result must be a non-zero multiple of request_alignment.
2376 * Clamp pnum and adjust map to original request.
2378 assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2379 align > offset - aligned_offset);
2380 if (ret & BDRV_BLOCK_RECURSE) {
2381 assert(ret & BDRV_BLOCK_DATA);
2382 assert(ret & BDRV_BLOCK_OFFSET_VALID);
2383 assert(!(ret & BDRV_BLOCK_ZERO));
2386 *pnum -= offset - aligned_offset;
2387 if (*pnum > bytes) {
2388 *pnum = bytes;
2390 if (ret & BDRV_BLOCK_OFFSET_VALID) {
2391 local_map += offset - aligned_offset;
2394 if (ret & BDRV_BLOCK_RAW) {
2395 assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2396 ret = bdrv_co_block_status(local_file, want_zero, local_map,
2397 *pnum, pnum, &local_map, &local_file);
2398 goto out;
2401 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2402 ret |= BDRV_BLOCK_ALLOCATED;
2403 } else if (bs->drv->supports_backing) {
2404 BlockDriverState *cow_bs = bdrv_cow_bs(bs);
2406 if (!cow_bs) {
2407 ret |= BDRV_BLOCK_ZERO;
2408 } else if (want_zero) {
2409 int64_t size2 = bdrv_getlength(cow_bs);
2411 if (size2 >= 0 && offset >= size2) {
2412 ret |= BDRV_BLOCK_ZERO;
2417 if (want_zero && ret & BDRV_BLOCK_RECURSE &&
2418 local_file && local_file != bs &&
2419 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2420 (ret & BDRV_BLOCK_OFFSET_VALID)) {
2421 int64_t file_pnum;
2422 int ret2;
2424 ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2425 *pnum, &file_pnum, NULL, NULL);
2426 if (ret2 >= 0) {
2427 /* Ignore errors. This is just providing extra information, it
2428 * is useful but not necessary.
2430 if (ret2 & BDRV_BLOCK_EOF &&
2431 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2433 * It is valid for the format block driver to read
2434 * beyond the end of the underlying file's current
2435 * size; such areas read as zero.
2437 ret |= BDRV_BLOCK_ZERO;
2438 } else {
2439 /* Limit request to the range reported by the protocol driver */
2440 *pnum = file_pnum;
2441 ret |= (ret2 & BDRV_BLOCK_ZERO);
2446 out:
2447 bdrv_dec_in_flight(bs);
2448 if (ret >= 0 && offset + *pnum == total_size) {
2449 ret |= BDRV_BLOCK_EOF;
2451 early_out:
2452 if (file) {
2453 *file = local_file;
2455 if (map) {
2456 *map = local_map;
2458 return ret;
2461 int coroutine_fn
2462 bdrv_co_common_block_status_above(BlockDriverState *bs,
2463 BlockDriverState *base,
2464 bool include_base,
2465 bool want_zero,
2466 int64_t offset,
2467 int64_t bytes,
2468 int64_t *pnum,
2469 int64_t *map,
2470 BlockDriverState **file,
2471 int *depth)
2473 int ret;
2474 BlockDriverState *p;
2475 int64_t eof = 0;
2476 int dummy;
2477 IO_CODE();
2479 assert(!include_base || base); /* Can't include NULL base */
2480 assert_bdrv_graph_readable();
2482 if (!depth) {
2483 depth = &dummy;
2485 *depth = 0;
2487 if (!include_base && bs == base) {
2488 *pnum = bytes;
2489 return 0;
2492 ret = bdrv_co_block_status(bs, want_zero, offset, bytes, pnum, map, file);
2493 ++*depth;
2494 if (ret < 0 || *pnum == 0 || ret & BDRV_BLOCK_ALLOCATED || bs == base) {
2495 return ret;
2498 if (ret & BDRV_BLOCK_EOF) {
2499 eof = offset + *pnum;
2502 assert(*pnum <= bytes);
2503 bytes = *pnum;
2505 for (p = bdrv_filter_or_cow_bs(bs); include_base || p != base;
2506 p = bdrv_filter_or_cow_bs(p))
2508 ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2509 file);
2510 ++*depth;
2511 if (ret < 0) {
2512 return ret;
2514 if (*pnum == 0) {
2516 * The top layer deferred to this layer, and because this layer is
2517 * short, any zeroes that we synthesize beyond EOF behave as if they
2518 * were allocated at this layer.
2520 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2521 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2522 * below.
2524 assert(ret & BDRV_BLOCK_EOF);
2525 *pnum = bytes;
2526 if (file) {
2527 *file = p;
2529 ret = BDRV_BLOCK_ZERO | BDRV_BLOCK_ALLOCATED;
2530 break;
2532 if (ret & BDRV_BLOCK_ALLOCATED) {
2534 * We've found the node and the status, we must break.
2536 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2537 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2538 * below.
2540 ret &= ~BDRV_BLOCK_EOF;
2541 break;
2544 if (p == base) {
2545 assert(include_base);
2546 break;
2550 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2551 * let's continue the diving.
2553 assert(*pnum <= bytes);
2554 bytes = *pnum;
2557 if (offset + *pnum == eof) {
2558 ret |= BDRV_BLOCK_EOF;
2561 return ret;
2564 int coroutine_fn bdrv_co_block_status_above(BlockDriverState *bs,
2565 BlockDriverState *base,
2566 int64_t offset, int64_t bytes,
2567 int64_t *pnum, int64_t *map,
2568 BlockDriverState **file)
2570 IO_CODE();
2571 return bdrv_co_common_block_status_above(bs, base, false, true, offset,
2572 bytes, pnum, map, file, NULL);
2575 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2576 int64_t offset, int64_t bytes, int64_t *pnum,
2577 int64_t *map, BlockDriverState **file)
2579 IO_CODE();
2580 return bdrv_common_block_status_above(bs, base, false, true, offset, bytes,
2581 pnum, map, file, NULL);
2584 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2585 int64_t *pnum, int64_t *map, BlockDriverState **file)
2587 IO_CODE();
2588 return bdrv_block_status_above(bs, bdrv_filter_or_cow_bs(bs),
2589 offset, bytes, pnum, map, file);
2593 * Check @bs (and its backing chain) to see if the range defined
2594 * by @offset and @bytes is known to read as zeroes.
2595 * Return 1 if that is the case, 0 otherwise and -errno on error.
2596 * This test is meant to be fast rather than accurate so returning 0
2597 * does not guarantee non-zero data.
2599 int coroutine_fn bdrv_co_is_zero_fast(BlockDriverState *bs, int64_t offset,
2600 int64_t bytes)
2602 int ret;
2603 int64_t pnum = bytes;
2604 IO_CODE();
2606 if (!bytes) {
2607 return 1;
2610 ret = bdrv_co_common_block_status_above(bs, NULL, false, false, offset,
2611 bytes, &pnum, NULL, NULL, NULL);
2613 if (ret < 0) {
2614 return ret;
2617 return (pnum == bytes) && (ret & BDRV_BLOCK_ZERO);
2620 int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t offset,
2621 int64_t bytes, int64_t *pnum)
2623 int ret;
2624 int64_t dummy;
2625 IO_CODE();
2627 ret = bdrv_co_common_block_status_above(bs, bs, true, false, offset,
2628 bytes, pnum ? pnum : &dummy, NULL,
2629 NULL, NULL);
2630 if (ret < 0) {
2631 return ret;
2633 return !!(ret & BDRV_BLOCK_ALLOCATED);
2636 int bdrv_is_allocated(BlockDriverState *bs, int64_t offset, int64_t bytes,
2637 int64_t *pnum)
2639 int ret;
2640 int64_t dummy;
2641 IO_CODE();
2643 ret = bdrv_common_block_status_above(bs, bs, true, false, offset,
2644 bytes, pnum ? pnum : &dummy, NULL,
2645 NULL, NULL);
2646 if (ret < 0) {
2647 return ret;
2649 return !!(ret & BDRV_BLOCK_ALLOCATED);
2652 /* See bdrv_is_allocated_above for documentation */
2653 int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
2654 BlockDriverState *base,
2655 bool include_base, int64_t offset,
2656 int64_t bytes, int64_t *pnum)
2658 int depth;
2659 int ret;
2660 IO_CODE();
2662 ret = bdrv_co_common_block_status_above(top, base, include_base, false,
2663 offset, bytes, pnum, NULL, NULL,
2664 &depth);
2665 if (ret < 0) {
2666 return ret;
2669 if (ret & BDRV_BLOCK_ALLOCATED) {
2670 return depth;
2672 return 0;
2676 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2678 * Return a positive depth if (a prefix of) the given range is allocated
2679 * in any image between BASE and TOP (BASE is only included if include_base
2680 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2681 * BASE can be NULL to check if the given offset is allocated in any
2682 * image of the chain. Return 0 otherwise, or negative errno on
2683 * failure.
2685 * 'pnum' is set to the number of bytes (including and immediately
2686 * following the specified offset) that are known to be in the same
2687 * allocated/unallocated state. Note that a subsequent call starting
2688 * at 'offset + *pnum' may return the same allocation status (in other
2689 * words, the result is not necessarily the maximum possible range);
2690 * but 'pnum' will only be 0 when end of file is reached.
2692 int bdrv_is_allocated_above(BlockDriverState *top,
2693 BlockDriverState *base,
2694 bool include_base, int64_t offset,
2695 int64_t bytes, int64_t *pnum)
2697 int depth;
2698 int ret;
2699 IO_CODE();
2701 ret = bdrv_common_block_status_above(top, base, include_base, false,
2702 offset, bytes, pnum, NULL, NULL,
2703 &depth);
2704 if (ret < 0) {
2705 return ret;
2708 if (ret & BDRV_BLOCK_ALLOCATED) {
2709 return depth;
2711 return 0;
2714 int coroutine_fn
2715 bdrv_co_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2717 BlockDriver *drv = bs->drv;
2718 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2719 int ret;
2720 IO_CODE();
2721 assert_bdrv_graph_readable();
2723 ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2724 if (ret < 0) {
2725 return ret;
2728 if (!drv) {
2729 return -ENOMEDIUM;
2732 bdrv_inc_in_flight(bs);
2734 if (drv->bdrv_co_load_vmstate) {
2735 ret = drv->bdrv_co_load_vmstate(bs, qiov, pos);
2736 } else if (child_bs) {
2737 ret = bdrv_co_readv_vmstate(child_bs, qiov, pos);
2738 } else {
2739 ret = -ENOTSUP;
2742 bdrv_dec_in_flight(bs);
2744 return ret;
2747 int coroutine_fn
2748 bdrv_co_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2750 BlockDriver *drv = bs->drv;
2751 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2752 int ret;
2753 IO_CODE();
2754 assert_bdrv_graph_readable();
2756 ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2757 if (ret < 0) {
2758 return ret;
2761 if (!drv) {
2762 return -ENOMEDIUM;
2765 bdrv_inc_in_flight(bs);
2767 if (drv->bdrv_co_save_vmstate) {
2768 ret = drv->bdrv_co_save_vmstate(bs, qiov, pos);
2769 } else if (child_bs) {
2770 ret = bdrv_co_writev_vmstate(child_bs, qiov, pos);
2771 } else {
2772 ret = -ENOTSUP;
2775 bdrv_dec_in_flight(bs);
2777 return ret;
2780 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2781 int64_t pos, int size)
2783 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2784 int ret = bdrv_writev_vmstate(bs, &qiov, pos);
2785 IO_CODE();
2787 return ret < 0 ? ret : size;
2790 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2791 int64_t pos, int size)
2793 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2794 int ret = bdrv_readv_vmstate(bs, &qiov, pos);
2795 IO_CODE();
2797 return ret < 0 ? ret : size;
2800 /**************************************************************/
2801 /* async I/Os */
2803 void bdrv_aio_cancel(BlockAIOCB *acb)
2805 IO_CODE();
2806 qemu_aio_ref(acb);
2807 bdrv_aio_cancel_async(acb);
2808 while (acb->refcnt > 1) {
2809 if (acb->aiocb_info->get_aio_context) {
2810 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2811 } else if (acb->bs) {
2812 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2813 * assert that we're not using an I/O thread. Thread-safe
2814 * code should use bdrv_aio_cancel_async exclusively.
2816 assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2817 aio_poll(bdrv_get_aio_context(acb->bs), true);
2818 } else {
2819 abort();
2822 qemu_aio_unref(acb);
2825 /* Async version of aio cancel. The caller is not blocked if the acb implements
2826 * cancel_async, otherwise we do nothing and let the request normally complete.
2827 * In either case the completion callback must be called. */
2828 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2830 IO_CODE();
2831 if (acb->aiocb_info->cancel_async) {
2832 acb->aiocb_info->cancel_async(acb);
2836 /**************************************************************/
2837 /* Coroutine block device emulation */
2839 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2841 BdrvChild *primary_child = bdrv_primary_child(bs);
2842 BdrvChild *child;
2843 int current_gen;
2844 int ret = 0;
2845 IO_CODE();
2847 assert_bdrv_graph_readable();
2848 bdrv_inc_in_flight(bs);
2850 if (!bdrv_co_is_inserted(bs) || bdrv_is_read_only(bs) ||
2851 bdrv_is_sg(bs)) {
2852 goto early_exit;
2855 qemu_co_mutex_lock(&bs->reqs_lock);
2856 current_gen = qatomic_read(&bs->write_gen);
2858 /* Wait until any previous flushes are completed */
2859 while (bs->active_flush_req) {
2860 qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
2863 /* Flushes reach this point in nondecreasing current_gen order. */
2864 bs->active_flush_req = true;
2865 qemu_co_mutex_unlock(&bs->reqs_lock);
2867 /* Write back all layers by calling one driver function */
2868 if (bs->drv->bdrv_co_flush) {
2869 ret = bs->drv->bdrv_co_flush(bs);
2870 goto out;
2873 /* Write back cached data to the OS even with cache=unsafe */
2874 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_OS);
2875 if (bs->drv->bdrv_co_flush_to_os) {
2876 ret = bs->drv->bdrv_co_flush_to_os(bs);
2877 if (ret < 0) {
2878 goto out;
2882 /* But don't actually force it to the disk with cache=unsafe */
2883 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2884 goto flush_children;
2887 /* Check if we really need to flush anything */
2888 if (bs->flushed_gen == current_gen) {
2889 goto flush_children;
2892 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_DISK);
2893 if (!bs->drv) {
2894 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2895 * (even in case of apparent success) */
2896 ret = -ENOMEDIUM;
2897 goto out;
2899 if (bs->drv->bdrv_co_flush_to_disk) {
2900 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2901 } else if (bs->drv->bdrv_aio_flush) {
2902 BlockAIOCB *acb;
2903 CoroutineIOCompletion co = {
2904 .coroutine = qemu_coroutine_self(),
2907 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2908 if (acb == NULL) {
2909 ret = -EIO;
2910 } else {
2911 qemu_coroutine_yield();
2912 ret = co.ret;
2914 } else {
2916 * Some block drivers always operate in either writethrough or unsafe
2917 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2918 * know how the server works (because the behaviour is hardcoded or
2919 * depends on server-side configuration), so we can't ensure that
2920 * everything is safe on disk. Returning an error doesn't work because
2921 * that would break guests even if the server operates in writethrough
2922 * mode.
2924 * Let's hope the user knows what he's doing.
2926 ret = 0;
2929 if (ret < 0) {
2930 goto out;
2933 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2934 * in the case of cache=unsafe, so there are no useless flushes.
2936 flush_children:
2937 ret = 0;
2938 QLIST_FOREACH(child, &bs->children, next) {
2939 if (child->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2940 int this_child_ret = bdrv_co_flush(child->bs);
2941 if (!ret) {
2942 ret = this_child_ret;
2947 out:
2948 /* Notify any pending flushes that we have completed */
2949 if (ret == 0) {
2950 bs->flushed_gen = current_gen;
2953 qemu_co_mutex_lock(&bs->reqs_lock);
2954 bs->active_flush_req = false;
2955 /* Return value is ignored - it's ok if wait queue is empty */
2956 qemu_co_queue_next(&bs->flush_queue);
2957 qemu_co_mutex_unlock(&bs->reqs_lock);
2959 early_exit:
2960 bdrv_dec_in_flight(bs);
2961 return ret;
2964 int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset,
2965 int64_t bytes)
2967 BdrvTrackedRequest req;
2968 int ret;
2969 int64_t max_pdiscard;
2970 int head, tail, align;
2971 BlockDriverState *bs = child->bs;
2972 IO_CODE();
2973 assert_bdrv_graph_readable();
2975 if (!bs || !bs->drv || !bdrv_co_is_inserted(bs)) {
2976 return -ENOMEDIUM;
2979 if (bdrv_has_readonly_bitmaps(bs)) {
2980 return -EPERM;
2983 ret = bdrv_check_request(offset, bytes, NULL);
2984 if (ret < 0) {
2985 return ret;
2988 /* Do nothing if disabled. */
2989 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2990 return 0;
2993 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
2994 return 0;
2997 /* Invalidate the cached block-status data range if this discard overlaps */
2998 bdrv_bsc_invalidate_range(bs, offset, bytes);
3000 /* Discard is advisory, but some devices track and coalesce
3001 * unaligned requests, so we must pass everything down rather than
3002 * round here. Still, most devices will just silently ignore
3003 * unaligned requests (by returning -ENOTSUP), so we must fragment
3004 * the request accordingly. */
3005 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
3006 assert(align % bs->bl.request_alignment == 0);
3007 head = offset % align;
3008 tail = (offset + bytes) % align;
3010 bdrv_inc_in_flight(bs);
3011 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
3013 ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
3014 if (ret < 0) {
3015 goto out;
3018 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT64_MAX),
3019 align);
3020 assert(max_pdiscard >= bs->bl.request_alignment);
3022 while (bytes > 0) {
3023 int64_t num = bytes;
3025 if (head) {
3026 /* Make small requests to get to alignment boundaries. */
3027 num = MIN(bytes, align - head);
3028 if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
3029 num %= bs->bl.request_alignment;
3031 head = (head + num) % align;
3032 assert(num < max_pdiscard);
3033 } else if (tail) {
3034 if (num > align) {
3035 /* Shorten the request to the last aligned cluster. */
3036 num -= tail;
3037 } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
3038 tail > bs->bl.request_alignment) {
3039 tail %= bs->bl.request_alignment;
3040 num -= tail;
3043 /* limit request size */
3044 if (num > max_pdiscard) {
3045 num = max_pdiscard;
3048 if (!bs->drv) {
3049 ret = -ENOMEDIUM;
3050 goto out;
3052 if (bs->drv->bdrv_co_pdiscard) {
3053 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
3054 } else {
3055 BlockAIOCB *acb;
3056 CoroutineIOCompletion co = {
3057 .coroutine = qemu_coroutine_self(),
3060 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
3061 bdrv_co_io_em_complete, &co);
3062 if (acb == NULL) {
3063 ret = -EIO;
3064 goto out;
3065 } else {
3066 qemu_coroutine_yield();
3067 ret = co.ret;
3070 if (ret && ret != -ENOTSUP) {
3071 goto out;
3074 offset += num;
3075 bytes -= num;
3077 ret = 0;
3078 out:
3079 bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
3080 tracked_request_end(&req);
3081 bdrv_dec_in_flight(bs);
3082 return ret;
3085 int coroutine_fn bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
3087 BlockDriver *drv = bs->drv;
3088 CoroutineIOCompletion co = {
3089 .coroutine = qemu_coroutine_self(),
3091 BlockAIOCB *acb;
3092 IO_CODE();
3093 assert_bdrv_graph_readable();
3095 bdrv_inc_in_flight(bs);
3096 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
3097 co.ret = -ENOTSUP;
3098 goto out;
3101 if (drv->bdrv_co_ioctl) {
3102 co.ret = drv->bdrv_co_ioctl(bs, req, buf);
3103 } else {
3104 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
3105 if (!acb) {
3106 co.ret = -ENOTSUP;
3107 goto out;
3109 qemu_coroutine_yield();
3111 out:
3112 bdrv_dec_in_flight(bs);
3113 return co.ret;
3116 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3118 IO_CODE();
3119 return qemu_memalign(bdrv_opt_mem_align(bs), size);
3122 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
3124 IO_CODE();
3125 return memset(qemu_blockalign(bs, size), 0, size);
3128 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
3130 size_t align = bdrv_opt_mem_align(bs);
3131 IO_CODE();
3133 /* Ensure that NULL is never returned on success */
3134 assert(align > 0);
3135 if (size == 0) {
3136 size = align;
3139 return qemu_try_memalign(align, size);
3142 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
3144 void *mem = qemu_try_blockalign(bs, size);
3145 IO_CODE();
3147 if (mem) {
3148 memset(mem, 0, size);
3151 return mem;
3154 void coroutine_fn bdrv_co_io_plug(BlockDriverState *bs)
3156 BdrvChild *child;
3157 IO_CODE();
3158 assert_bdrv_graph_readable();
3160 QLIST_FOREACH(child, &bs->children, next) {
3161 bdrv_co_io_plug(child->bs);
3164 if (qatomic_fetch_inc(&bs->io_plugged) == 0) {
3165 BlockDriver *drv = bs->drv;
3166 if (drv && drv->bdrv_co_io_plug) {
3167 drv->bdrv_co_io_plug(bs);
3172 void coroutine_fn bdrv_co_io_unplug(BlockDriverState *bs)
3174 BdrvChild *child;
3175 IO_CODE();
3176 assert_bdrv_graph_readable();
3178 assert(bs->io_plugged);
3179 if (qatomic_fetch_dec(&bs->io_plugged) == 1) {
3180 BlockDriver *drv = bs->drv;
3181 if (drv && drv->bdrv_co_io_unplug) {
3182 drv->bdrv_co_io_unplug(bs);
3186 QLIST_FOREACH(child, &bs->children, next) {
3187 bdrv_co_io_unplug(child->bs);
3191 /* Helper that undoes bdrv_register_buf() when it fails partway through */
3192 static void GRAPH_RDLOCK
3193 bdrv_register_buf_rollback(BlockDriverState *bs, void *host, size_t size,
3194 BdrvChild *final_child)
3196 BdrvChild *child;
3198 GLOBAL_STATE_CODE();
3199 assert_bdrv_graph_readable();
3201 QLIST_FOREACH(child, &bs->children, next) {
3202 if (child == final_child) {
3203 break;
3206 bdrv_unregister_buf(child->bs, host, size);
3209 if (bs->drv && bs->drv->bdrv_unregister_buf) {
3210 bs->drv->bdrv_unregister_buf(bs, host, size);
3214 bool bdrv_register_buf(BlockDriverState *bs, void *host, size_t size,
3215 Error **errp)
3217 BdrvChild *child;
3219 GLOBAL_STATE_CODE();
3220 GRAPH_RDLOCK_GUARD_MAINLOOP();
3222 if (bs->drv && bs->drv->bdrv_register_buf) {
3223 if (!bs->drv->bdrv_register_buf(bs, host, size, errp)) {
3224 return false;
3227 QLIST_FOREACH(child, &bs->children, next) {
3228 if (!bdrv_register_buf(child->bs, host, size, errp)) {
3229 bdrv_register_buf_rollback(bs, host, size, child);
3230 return false;
3233 return true;
3236 void bdrv_unregister_buf(BlockDriverState *bs, void *host, size_t size)
3238 BdrvChild *child;
3240 GLOBAL_STATE_CODE();
3241 GRAPH_RDLOCK_GUARD_MAINLOOP();
3243 if (bs->drv && bs->drv->bdrv_unregister_buf) {
3244 bs->drv->bdrv_unregister_buf(bs, host, size);
3246 QLIST_FOREACH(child, &bs->children, next) {
3247 bdrv_unregister_buf(child->bs, host, size);
3251 static int coroutine_fn GRAPH_RDLOCK bdrv_co_copy_range_internal(
3252 BdrvChild *src, int64_t src_offset, BdrvChild *dst,
3253 int64_t dst_offset, int64_t bytes,
3254 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
3255 bool recurse_src)
3257 BdrvTrackedRequest req;
3258 int ret;
3259 assert_bdrv_graph_readable();
3261 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3262 assert(!(read_flags & BDRV_REQ_NO_FALLBACK));
3263 assert(!(write_flags & BDRV_REQ_NO_FALLBACK));
3264 assert(!(read_flags & BDRV_REQ_NO_WAIT));
3265 assert(!(write_flags & BDRV_REQ_NO_WAIT));
3267 if (!dst || !dst->bs || !bdrv_co_is_inserted(dst->bs)) {
3268 return -ENOMEDIUM;
3270 ret = bdrv_check_request32(dst_offset, bytes, NULL, 0);
3271 if (ret) {
3272 return ret;
3274 if (write_flags & BDRV_REQ_ZERO_WRITE) {
3275 return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
3278 if (!src || !src->bs || !bdrv_co_is_inserted(src->bs)) {
3279 return -ENOMEDIUM;
3281 ret = bdrv_check_request32(src_offset, bytes, NULL, 0);
3282 if (ret) {
3283 return ret;
3286 if (!src->bs->drv->bdrv_co_copy_range_from
3287 || !dst->bs->drv->bdrv_co_copy_range_to
3288 || src->bs->encrypted || dst->bs->encrypted) {
3289 return -ENOTSUP;
3292 if (recurse_src) {
3293 bdrv_inc_in_flight(src->bs);
3294 tracked_request_begin(&req, src->bs, src_offset, bytes,
3295 BDRV_TRACKED_READ);
3297 /* BDRV_REQ_SERIALISING is only for write operation */
3298 assert(!(read_flags & BDRV_REQ_SERIALISING));
3299 bdrv_wait_serialising_requests(&req);
3301 ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
3302 src, src_offset,
3303 dst, dst_offset,
3304 bytes,
3305 read_flags, write_flags);
3307 tracked_request_end(&req);
3308 bdrv_dec_in_flight(src->bs);
3309 } else {
3310 bdrv_inc_in_flight(dst->bs);
3311 tracked_request_begin(&req, dst->bs, dst_offset, bytes,
3312 BDRV_TRACKED_WRITE);
3313 ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3314 write_flags);
3315 if (!ret) {
3316 ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3317 src, src_offset,
3318 dst, dst_offset,
3319 bytes,
3320 read_flags, write_flags);
3322 bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
3323 tracked_request_end(&req);
3324 bdrv_dec_in_flight(dst->bs);
3327 return ret;
3330 /* Copy range from @src to @dst.
3332 * See the comment of bdrv_co_copy_range for the parameter and return value
3333 * semantics. */
3334 int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
3335 BdrvChild *dst, int64_t dst_offset,
3336 int64_t bytes,
3337 BdrvRequestFlags read_flags,
3338 BdrvRequestFlags write_flags)
3340 IO_CODE();
3341 assert_bdrv_graph_readable();
3342 trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3343 read_flags, write_flags);
3344 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3345 bytes, read_flags, write_flags, true);
3348 /* Copy range from @src to @dst.
3350 * See the comment of bdrv_co_copy_range for the parameter and return value
3351 * semantics. */
3352 int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
3353 BdrvChild *dst, int64_t dst_offset,
3354 int64_t bytes,
3355 BdrvRequestFlags read_flags,
3356 BdrvRequestFlags write_flags)
3358 IO_CODE();
3359 assert_bdrv_graph_readable();
3360 trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3361 read_flags, write_flags);
3362 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3363 bytes, read_flags, write_flags, false);
3366 int coroutine_fn bdrv_co_copy_range(BdrvChild *src, int64_t src_offset,
3367 BdrvChild *dst, int64_t dst_offset,
3368 int64_t bytes, BdrvRequestFlags read_flags,
3369 BdrvRequestFlags write_flags)
3371 IO_CODE();
3372 assert_bdrv_graph_readable();
3374 return bdrv_co_copy_range_from(src, src_offset,
3375 dst, dst_offset,
3376 bytes, read_flags, write_flags);
3379 static void bdrv_parent_cb_resize(BlockDriverState *bs)
3381 BdrvChild *c;
3382 QLIST_FOREACH(c, &bs->parents, next_parent) {
3383 if (c->klass->resize) {
3384 c->klass->resize(c);
3390 * Truncate file to 'offset' bytes (needed only for file protocols)
3392 * If 'exact' is true, the file must be resized to exactly the given
3393 * 'offset'. Otherwise, it is sufficient for the node to be at least
3394 * 'offset' bytes in length.
3396 int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset, bool exact,
3397 PreallocMode prealloc, BdrvRequestFlags flags,
3398 Error **errp)
3400 BlockDriverState *bs = child->bs;
3401 BdrvChild *filtered, *backing;
3402 BlockDriver *drv = bs->drv;
3403 BdrvTrackedRequest req;
3404 int64_t old_size, new_bytes;
3405 int ret;
3406 IO_CODE();
3407 assert_bdrv_graph_readable();
3409 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3410 if (!drv) {
3411 error_setg(errp, "No medium inserted");
3412 return -ENOMEDIUM;
3414 if (offset < 0) {
3415 error_setg(errp, "Image size cannot be negative");
3416 return -EINVAL;
3419 ret = bdrv_check_request(offset, 0, errp);
3420 if (ret < 0) {
3421 return ret;
3424 old_size = bdrv_getlength(bs);
3425 if (old_size < 0) {
3426 error_setg_errno(errp, -old_size, "Failed to get old image size");
3427 return old_size;
3430 if (bdrv_is_read_only(bs)) {
3431 error_setg(errp, "Image is read-only");
3432 return -EACCES;
3435 if (offset > old_size) {
3436 new_bytes = offset - old_size;
3437 } else {
3438 new_bytes = 0;
3441 bdrv_inc_in_flight(bs);
3442 tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3443 BDRV_TRACKED_TRUNCATE);
3445 /* If we are growing the image and potentially using preallocation for the
3446 * new area, we need to make sure that no write requests are made to it
3447 * concurrently or they might be overwritten by preallocation. */
3448 if (new_bytes) {
3449 bdrv_make_request_serialising(&req, 1);
3451 ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3453 if (ret < 0) {
3454 error_setg_errno(errp, -ret,
3455 "Failed to prepare request for truncation");
3456 goto out;
3459 filtered = bdrv_filter_child(bs);
3460 backing = bdrv_cow_child(bs);
3463 * If the image has a backing file that is large enough that it would
3464 * provide data for the new area, we cannot leave it unallocated because
3465 * then the backing file content would become visible. Instead, zero-fill
3466 * the new area.
3468 * Note that if the image has a backing file, but was opened without the
3469 * backing file, taking care of keeping things consistent with that backing
3470 * file is the user's responsibility.
3472 if (new_bytes && backing) {
3473 int64_t backing_len;
3475 backing_len = bdrv_co_getlength(backing->bs);
3476 if (backing_len < 0) {
3477 ret = backing_len;
3478 error_setg_errno(errp, -ret, "Could not get backing file size");
3479 goto out;
3482 if (backing_len > old_size) {
3483 flags |= BDRV_REQ_ZERO_WRITE;
3487 if (drv->bdrv_co_truncate) {
3488 if (flags & ~bs->supported_truncate_flags) {
3489 error_setg(errp, "Block driver does not support requested flags");
3490 ret = -ENOTSUP;
3491 goto out;
3493 ret = drv->bdrv_co_truncate(bs, offset, exact, prealloc, flags, errp);
3494 } else if (filtered) {
3495 ret = bdrv_co_truncate(filtered, offset, exact, prealloc, flags, errp);
3496 } else {
3497 error_setg(errp, "Image format driver does not support resize");
3498 ret = -ENOTSUP;
3499 goto out;
3501 if (ret < 0) {
3502 goto out;
3505 ret = bdrv_co_refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3506 if (ret < 0) {
3507 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3508 } else {
3509 offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3512 * It's possible that truncation succeeded but bdrv_refresh_total_sectors
3513 * failed, but the latter doesn't affect how we should finish the request.
3514 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled.
3516 bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3518 out:
3519 tracked_request_end(&req);
3520 bdrv_dec_in_flight(bs);
3522 return ret;
3525 void bdrv_cancel_in_flight(BlockDriverState *bs)
3527 GLOBAL_STATE_CODE();
3528 if (!bs || !bs->drv) {
3529 return;
3532 if (bs->drv->bdrv_cancel_in_flight) {
3533 bs->drv->bdrv_cancel_in_flight(bs);
3537 int coroutine_fn
3538 bdrv_co_preadv_snapshot(BdrvChild *child, int64_t offset, int64_t bytes,
3539 QEMUIOVector *qiov, size_t qiov_offset)
3541 BlockDriverState *bs = child->bs;
3542 BlockDriver *drv = bs->drv;
3543 int ret;
3544 IO_CODE();
3545 assert_bdrv_graph_readable();
3547 if (!drv) {
3548 return -ENOMEDIUM;
3551 if (!drv->bdrv_co_preadv_snapshot) {
3552 return -ENOTSUP;
3555 bdrv_inc_in_flight(bs);
3556 ret = drv->bdrv_co_preadv_snapshot(bs, offset, bytes, qiov, qiov_offset);
3557 bdrv_dec_in_flight(bs);
3559 return ret;
3562 int coroutine_fn
3563 bdrv_co_snapshot_block_status(BlockDriverState *bs,
3564 bool want_zero, int64_t offset, int64_t bytes,
3565 int64_t *pnum, int64_t *map,
3566 BlockDriverState **file)
3568 BlockDriver *drv = bs->drv;
3569 int ret;
3570 IO_CODE();
3571 assert_bdrv_graph_readable();
3573 if (!drv) {
3574 return -ENOMEDIUM;
3577 if (!drv->bdrv_co_snapshot_block_status) {
3578 return -ENOTSUP;
3581 bdrv_inc_in_flight(bs);
3582 ret = drv->bdrv_co_snapshot_block_status(bs, want_zero, offset, bytes,
3583 pnum, map, file);
3584 bdrv_dec_in_flight(bs);
3586 return ret;
3589 int coroutine_fn
3590 bdrv_co_pdiscard_snapshot(BlockDriverState *bs, int64_t offset, int64_t bytes)
3592 BlockDriver *drv = bs->drv;
3593 int ret;
3594 IO_CODE();
3595 assert_bdrv_graph_readable();
3597 if (!drv) {
3598 return -ENOMEDIUM;
3601 if (!drv->bdrv_co_pdiscard_snapshot) {
3602 return -ENOTSUP;
3605 bdrv_inc_in_flight(bs);
3606 ret = drv->bdrv_co_pdiscard_snapshot(bs, offset, bytes);
3607 bdrv_dec_in_flight(bs);
3609 return ret;