block/io: bdrv_wait_serialising_requests_locked: drop extra bs arg
[qemu/kevin.git] / block / io.c
blobd7015378a314f5794c43d18f772c923d7cc98596
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 "qemu/cutils.h"
34 #include "qapi/error.h"
35 #include "qemu/error-report.h"
36 #include "qemu/main-loop.h"
37 #include "sysemu/replay.h"
39 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
40 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
42 static void bdrv_parent_cb_resize(BlockDriverState *bs);
43 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
44 int64_t offset, int bytes, BdrvRequestFlags flags);
46 static void bdrv_parent_drained_begin(BlockDriverState *bs, BdrvChild *ignore,
47 bool ignore_bds_parents)
49 BdrvChild *c, *next;
51 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
52 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
53 continue;
55 bdrv_parent_drained_begin_single(c, false);
59 static void bdrv_parent_drained_end_single_no_poll(BdrvChild *c,
60 int *drained_end_counter)
62 assert(c->parent_quiesce_counter > 0);
63 c->parent_quiesce_counter--;
64 if (c->klass->drained_end) {
65 c->klass->drained_end(c, drained_end_counter);
69 void bdrv_parent_drained_end_single(BdrvChild *c)
71 int drained_end_counter = 0;
72 bdrv_parent_drained_end_single_no_poll(c, &drained_end_counter);
73 BDRV_POLL_WHILE(c->bs, qatomic_read(&drained_end_counter) > 0);
76 static void bdrv_parent_drained_end(BlockDriverState *bs, BdrvChild *ignore,
77 bool ignore_bds_parents,
78 int *drained_end_counter)
80 BdrvChild *c;
82 QLIST_FOREACH(c, &bs->parents, next_parent) {
83 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
84 continue;
86 bdrv_parent_drained_end_single_no_poll(c, drained_end_counter);
90 static bool bdrv_parent_drained_poll_single(BdrvChild *c)
92 if (c->klass->drained_poll) {
93 return c->klass->drained_poll(c);
95 return false;
98 static bool bdrv_parent_drained_poll(BlockDriverState *bs, BdrvChild *ignore,
99 bool ignore_bds_parents)
101 BdrvChild *c, *next;
102 bool busy = false;
104 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
105 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
106 continue;
108 busy |= bdrv_parent_drained_poll_single(c);
111 return busy;
114 void bdrv_parent_drained_begin_single(BdrvChild *c, bool poll)
116 c->parent_quiesce_counter++;
117 if (c->klass->drained_begin) {
118 c->klass->drained_begin(c);
120 if (poll) {
121 BDRV_POLL_WHILE(c->bs, bdrv_parent_drained_poll_single(c));
125 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
127 dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
128 dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_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);
136 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
138 ERRP_GUARD();
139 BlockDriver *drv = bs->drv;
140 BdrvChild *c;
141 bool have_limits;
143 memset(&bs->bl, 0, sizeof(bs->bl));
145 if (!drv) {
146 return;
149 /* Default alignment based on whether driver has byte interface */
150 bs->bl.request_alignment = (drv->bdrv_co_preadv ||
151 drv->bdrv_aio_preadv ||
152 drv->bdrv_co_preadv_part) ? 1 : 512;
154 /* Take some limits from the children as a default */
155 have_limits = false;
156 QLIST_FOREACH(c, &bs->children, next) {
157 if (c->role & (BDRV_CHILD_DATA | BDRV_CHILD_FILTERED | BDRV_CHILD_COW))
159 bdrv_refresh_limits(c->bs, errp);
160 if (*errp) {
161 return;
163 bdrv_merge_limits(&bs->bl, &c->bs->bl);
164 have_limits = true;
168 if (!have_limits) {
169 bs->bl.min_mem_alignment = 512;
170 bs->bl.opt_mem_alignment = qemu_real_host_page_size;
172 /* Safe default since most protocols use readv()/writev()/etc */
173 bs->bl.max_iov = IOV_MAX;
176 /* Then let the driver override it */
177 if (drv->bdrv_refresh_limits) {
178 drv->bdrv_refresh_limits(bs, errp);
179 if (*errp) {
180 return;
184 if (bs->bl.request_alignment > BDRV_MAX_ALIGNMENT) {
185 error_setg(errp, "Driver requires too large request alignment");
190 * The copy-on-read flag is actually a reference count so multiple users may
191 * use the feature without worrying about clobbering its previous state.
192 * Copy-on-read stays enabled until all users have called to disable it.
194 void bdrv_enable_copy_on_read(BlockDriverState *bs)
196 qatomic_inc(&bs->copy_on_read);
199 void bdrv_disable_copy_on_read(BlockDriverState *bs)
201 int old = qatomic_fetch_dec(&bs->copy_on_read);
202 assert(old >= 1);
205 typedef struct {
206 Coroutine *co;
207 BlockDriverState *bs;
208 bool done;
209 bool begin;
210 bool recursive;
211 bool poll;
212 BdrvChild *parent;
213 bool ignore_bds_parents;
214 int *drained_end_counter;
215 } BdrvCoDrainData;
217 static void coroutine_fn bdrv_drain_invoke_entry(void *opaque)
219 BdrvCoDrainData *data = opaque;
220 BlockDriverState *bs = data->bs;
222 if (data->begin) {
223 bs->drv->bdrv_co_drain_begin(bs);
224 } else {
225 bs->drv->bdrv_co_drain_end(bs);
228 /* Set data->done and decrement drained_end_counter before bdrv_wakeup() */
229 qatomic_mb_set(&data->done, true);
230 if (!data->begin) {
231 qatomic_dec(data->drained_end_counter);
233 bdrv_dec_in_flight(bs);
235 g_free(data);
238 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
239 static void bdrv_drain_invoke(BlockDriverState *bs, bool begin,
240 int *drained_end_counter)
242 BdrvCoDrainData *data;
244 if (!bs->drv || (begin && !bs->drv->bdrv_co_drain_begin) ||
245 (!begin && !bs->drv->bdrv_co_drain_end)) {
246 return;
249 data = g_new(BdrvCoDrainData, 1);
250 *data = (BdrvCoDrainData) {
251 .bs = bs,
252 .done = false,
253 .begin = begin,
254 .drained_end_counter = drained_end_counter,
257 if (!begin) {
258 qatomic_inc(drained_end_counter);
261 /* Make sure the driver callback completes during the polling phase for
262 * drain_begin. */
263 bdrv_inc_in_flight(bs);
264 data->co = qemu_coroutine_create(bdrv_drain_invoke_entry, data);
265 aio_co_schedule(bdrv_get_aio_context(bs), data->co);
268 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
269 bool bdrv_drain_poll(BlockDriverState *bs, bool recursive,
270 BdrvChild *ignore_parent, bool ignore_bds_parents)
272 BdrvChild *child, *next;
274 if (bdrv_parent_drained_poll(bs, ignore_parent, ignore_bds_parents)) {
275 return true;
278 if (qatomic_read(&bs->in_flight)) {
279 return true;
282 if (recursive) {
283 assert(!ignore_bds_parents);
284 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
285 if (bdrv_drain_poll(child->bs, recursive, child, false)) {
286 return true;
291 return false;
294 static bool bdrv_drain_poll_top_level(BlockDriverState *bs, bool recursive,
295 BdrvChild *ignore_parent)
297 return bdrv_drain_poll(bs, recursive, ignore_parent, false);
300 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
301 BdrvChild *parent, bool ignore_bds_parents,
302 bool poll);
303 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
304 BdrvChild *parent, bool ignore_bds_parents,
305 int *drained_end_counter);
307 static void bdrv_co_drain_bh_cb(void *opaque)
309 BdrvCoDrainData *data = opaque;
310 Coroutine *co = data->co;
311 BlockDriverState *bs = data->bs;
313 if (bs) {
314 AioContext *ctx = bdrv_get_aio_context(bs);
315 aio_context_acquire(ctx);
316 bdrv_dec_in_flight(bs);
317 if (data->begin) {
318 assert(!data->drained_end_counter);
319 bdrv_do_drained_begin(bs, data->recursive, data->parent,
320 data->ignore_bds_parents, data->poll);
321 } else {
322 assert(!data->poll);
323 bdrv_do_drained_end(bs, data->recursive, data->parent,
324 data->ignore_bds_parents,
325 data->drained_end_counter);
327 aio_context_release(ctx);
328 } else {
329 assert(data->begin);
330 bdrv_drain_all_begin();
333 data->done = true;
334 aio_co_wake(co);
337 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs,
338 bool begin, bool recursive,
339 BdrvChild *parent,
340 bool ignore_bds_parents,
341 bool poll,
342 int *drained_end_counter)
344 BdrvCoDrainData data;
345 Coroutine *self = qemu_coroutine_self();
346 AioContext *ctx = bdrv_get_aio_context(bs);
347 AioContext *co_ctx = qemu_coroutine_get_aio_context(self);
349 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
350 * other coroutines run if they were queued by aio_co_enter(). */
352 assert(qemu_in_coroutine());
353 data = (BdrvCoDrainData) {
354 .co = self,
355 .bs = bs,
356 .done = false,
357 .begin = begin,
358 .recursive = recursive,
359 .parent = parent,
360 .ignore_bds_parents = ignore_bds_parents,
361 .poll = poll,
362 .drained_end_counter = drained_end_counter,
365 if (bs) {
366 bdrv_inc_in_flight(bs);
370 * Temporarily drop the lock across yield or we would get deadlocks.
371 * bdrv_co_drain_bh_cb() reaquires the lock as needed.
373 * When we yield below, the lock for the current context will be
374 * released, so if this is actually the lock that protects bs, don't drop
375 * it a second time.
377 if (ctx != co_ctx) {
378 aio_context_release(ctx);
380 replay_bh_schedule_oneshot_event(ctx, bdrv_co_drain_bh_cb, &data);
382 qemu_coroutine_yield();
383 /* If we are resumed from some other event (such as an aio completion or a
384 * timer callback), it is a bug in the caller that should be fixed. */
385 assert(data.done);
387 /* Reaquire the AioContext of bs if we dropped it */
388 if (ctx != co_ctx) {
389 aio_context_acquire(ctx);
393 void bdrv_do_drained_begin_quiesce(BlockDriverState *bs,
394 BdrvChild *parent, bool ignore_bds_parents)
396 assert(!qemu_in_coroutine());
398 /* Stop things in parent-to-child order */
399 if (qatomic_fetch_inc(&bs->quiesce_counter) == 0) {
400 aio_disable_external(bdrv_get_aio_context(bs));
403 bdrv_parent_drained_begin(bs, parent, ignore_bds_parents);
404 bdrv_drain_invoke(bs, true, NULL);
407 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
408 BdrvChild *parent, bool ignore_bds_parents,
409 bool poll)
411 BdrvChild *child, *next;
413 if (qemu_in_coroutine()) {
414 bdrv_co_yield_to_drain(bs, true, recursive, parent, ignore_bds_parents,
415 poll, NULL);
416 return;
419 bdrv_do_drained_begin_quiesce(bs, parent, ignore_bds_parents);
421 if (recursive) {
422 assert(!ignore_bds_parents);
423 bs->recursive_quiesce_counter++;
424 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
425 bdrv_do_drained_begin(child->bs, true, child, ignore_bds_parents,
426 false);
431 * Wait for drained requests to finish.
433 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
434 * call is needed so things in this AioContext can make progress even
435 * though we don't return to the main AioContext loop - this automatically
436 * includes other nodes in the same AioContext and therefore all child
437 * nodes.
439 if (poll) {
440 assert(!ignore_bds_parents);
441 BDRV_POLL_WHILE(bs, bdrv_drain_poll_top_level(bs, recursive, parent));
445 void bdrv_drained_begin(BlockDriverState *bs)
447 bdrv_do_drained_begin(bs, false, NULL, false, true);
450 void bdrv_subtree_drained_begin(BlockDriverState *bs)
452 bdrv_do_drained_begin(bs, true, NULL, false, true);
456 * This function does not poll, nor must any of its recursively called
457 * functions. The *drained_end_counter pointee will be incremented
458 * once for every background operation scheduled, and decremented once
459 * the operation settles. Therefore, the pointer must remain valid
460 * until the pointee reaches 0. That implies that whoever sets up the
461 * pointee has to poll until it is 0.
463 * We use atomic operations to access *drained_end_counter, because
464 * (1) when called from bdrv_set_aio_context_ignore(), the subgraph of
465 * @bs may contain nodes in different AioContexts,
466 * (2) bdrv_drain_all_end() uses the same counter for all nodes,
467 * regardless of which AioContext they are in.
469 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
470 BdrvChild *parent, bool ignore_bds_parents,
471 int *drained_end_counter)
473 BdrvChild *child;
474 int old_quiesce_counter;
476 assert(drained_end_counter != NULL);
478 if (qemu_in_coroutine()) {
479 bdrv_co_yield_to_drain(bs, false, recursive, parent, ignore_bds_parents,
480 false, drained_end_counter);
481 return;
483 assert(bs->quiesce_counter > 0);
485 /* Re-enable things in child-to-parent order */
486 bdrv_drain_invoke(bs, false, drained_end_counter);
487 bdrv_parent_drained_end(bs, parent, ignore_bds_parents,
488 drained_end_counter);
490 old_quiesce_counter = qatomic_fetch_dec(&bs->quiesce_counter);
491 if (old_quiesce_counter == 1) {
492 aio_enable_external(bdrv_get_aio_context(bs));
495 if (recursive) {
496 assert(!ignore_bds_parents);
497 bs->recursive_quiesce_counter--;
498 QLIST_FOREACH(child, &bs->children, next) {
499 bdrv_do_drained_end(child->bs, true, child, ignore_bds_parents,
500 drained_end_counter);
505 void bdrv_drained_end(BlockDriverState *bs)
507 int drained_end_counter = 0;
508 bdrv_do_drained_end(bs, false, NULL, false, &drained_end_counter);
509 BDRV_POLL_WHILE(bs, qatomic_read(&drained_end_counter) > 0);
512 void bdrv_drained_end_no_poll(BlockDriverState *bs, int *drained_end_counter)
514 bdrv_do_drained_end(bs, false, NULL, false, drained_end_counter);
517 void bdrv_subtree_drained_end(BlockDriverState *bs)
519 int drained_end_counter = 0;
520 bdrv_do_drained_end(bs, true, NULL, false, &drained_end_counter);
521 BDRV_POLL_WHILE(bs, qatomic_read(&drained_end_counter) > 0);
524 void bdrv_apply_subtree_drain(BdrvChild *child, BlockDriverState *new_parent)
526 int i;
528 for (i = 0; i < new_parent->recursive_quiesce_counter; i++) {
529 bdrv_do_drained_begin(child->bs, true, child, false, true);
533 void bdrv_unapply_subtree_drain(BdrvChild *child, BlockDriverState *old_parent)
535 int drained_end_counter = 0;
536 int i;
538 for (i = 0; i < old_parent->recursive_quiesce_counter; i++) {
539 bdrv_do_drained_end(child->bs, true, child, false,
540 &drained_end_counter);
543 BDRV_POLL_WHILE(child->bs, qatomic_read(&drained_end_counter) > 0);
547 * Wait for pending requests to complete on a single BlockDriverState subtree,
548 * and suspend block driver's internal I/O until next request arrives.
550 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
551 * AioContext.
553 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
555 assert(qemu_in_coroutine());
556 bdrv_drained_begin(bs);
557 bdrv_drained_end(bs);
560 void bdrv_drain(BlockDriverState *bs)
562 bdrv_drained_begin(bs);
563 bdrv_drained_end(bs);
566 static void bdrv_drain_assert_idle(BlockDriverState *bs)
568 BdrvChild *child, *next;
570 assert(qatomic_read(&bs->in_flight) == 0);
571 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
572 bdrv_drain_assert_idle(child->bs);
576 unsigned int bdrv_drain_all_count = 0;
578 static bool bdrv_drain_all_poll(void)
580 BlockDriverState *bs = NULL;
581 bool result = false;
583 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
584 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
585 while ((bs = bdrv_next_all_states(bs))) {
586 AioContext *aio_context = bdrv_get_aio_context(bs);
587 aio_context_acquire(aio_context);
588 result |= bdrv_drain_poll(bs, false, NULL, true);
589 aio_context_release(aio_context);
592 return result;
596 * Wait for pending requests to complete across all BlockDriverStates
598 * This function does not flush data to disk, use bdrv_flush_all() for that
599 * after calling this function.
601 * This pauses all block jobs and disables external clients. It must
602 * be paired with bdrv_drain_all_end().
604 * NOTE: no new block jobs or BlockDriverStates can be created between
605 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
607 void bdrv_drain_all_begin(void)
609 BlockDriverState *bs = NULL;
611 if (qemu_in_coroutine()) {
612 bdrv_co_yield_to_drain(NULL, true, false, NULL, true, true, NULL);
613 return;
617 * bdrv queue is managed by record/replay,
618 * waiting for finishing the I/O requests may
619 * be infinite
621 if (replay_events_enabled()) {
622 return;
625 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
626 * loop AioContext, so make sure we're in the main context. */
627 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
628 assert(bdrv_drain_all_count < INT_MAX);
629 bdrv_drain_all_count++;
631 /* Quiesce all nodes, without polling in-flight requests yet. The graph
632 * cannot change during this loop. */
633 while ((bs = bdrv_next_all_states(bs))) {
634 AioContext *aio_context = bdrv_get_aio_context(bs);
636 aio_context_acquire(aio_context);
637 bdrv_do_drained_begin(bs, false, NULL, true, false);
638 aio_context_release(aio_context);
641 /* Now poll the in-flight requests */
642 AIO_WAIT_WHILE(NULL, bdrv_drain_all_poll());
644 while ((bs = bdrv_next_all_states(bs))) {
645 bdrv_drain_assert_idle(bs);
649 void bdrv_drain_all_end_quiesce(BlockDriverState *bs)
651 int drained_end_counter = 0;
653 g_assert(bs->quiesce_counter > 0);
654 g_assert(!bs->refcnt);
656 while (bs->quiesce_counter) {
657 bdrv_do_drained_end(bs, false, NULL, true, &drained_end_counter);
659 BDRV_POLL_WHILE(bs, qatomic_read(&drained_end_counter) > 0);
662 void bdrv_drain_all_end(void)
664 BlockDriverState *bs = NULL;
665 int drained_end_counter = 0;
668 * bdrv queue is managed by record/replay,
669 * waiting for finishing the I/O requests may
670 * be endless
672 if (replay_events_enabled()) {
673 return;
676 while ((bs = bdrv_next_all_states(bs))) {
677 AioContext *aio_context = bdrv_get_aio_context(bs);
679 aio_context_acquire(aio_context);
680 bdrv_do_drained_end(bs, false, NULL, true, &drained_end_counter);
681 aio_context_release(aio_context);
684 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
685 AIO_WAIT_WHILE(NULL, qatomic_read(&drained_end_counter) > 0);
687 assert(bdrv_drain_all_count > 0);
688 bdrv_drain_all_count--;
691 void bdrv_drain_all(void)
693 bdrv_drain_all_begin();
694 bdrv_drain_all_end();
698 * Remove an active request from the tracked requests list
700 * This function should be called when a tracked request is completing.
702 static void tracked_request_end(BdrvTrackedRequest *req)
704 if (req->serialising) {
705 qatomic_dec(&req->bs->serialising_in_flight);
708 qemu_co_mutex_lock(&req->bs->reqs_lock);
709 QLIST_REMOVE(req, list);
710 qemu_co_queue_restart_all(&req->wait_queue);
711 qemu_co_mutex_unlock(&req->bs->reqs_lock);
715 * Add an active request to the tracked requests list
717 static void tracked_request_begin(BdrvTrackedRequest *req,
718 BlockDriverState *bs,
719 int64_t offset,
720 uint64_t bytes,
721 enum BdrvTrackedRequestType type)
723 assert(bytes <= INT64_MAX && offset <= INT64_MAX - bytes);
725 *req = (BdrvTrackedRequest){
726 .bs = bs,
727 .offset = offset,
728 .bytes = bytes,
729 .type = type,
730 .co = qemu_coroutine_self(),
731 .serialising = false,
732 .overlap_offset = offset,
733 .overlap_bytes = bytes,
736 qemu_co_queue_init(&req->wait_queue);
738 qemu_co_mutex_lock(&bs->reqs_lock);
739 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
740 qemu_co_mutex_unlock(&bs->reqs_lock);
743 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
744 int64_t offset, uint64_t bytes)
746 /* aaaa bbbb */
747 if (offset >= req->overlap_offset + req->overlap_bytes) {
748 return false;
750 /* bbbb aaaa */
751 if (req->overlap_offset >= offset + bytes) {
752 return false;
754 return true;
757 /* Called with self->bs->reqs_lock held */
758 static BdrvTrackedRequest *
759 bdrv_find_conflicting_request(BdrvTrackedRequest *self)
761 BdrvTrackedRequest *req;
763 QLIST_FOREACH(req, &self->bs->tracked_requests, list) {
764 if (req == self || (!req->serialising && !self->serialising)) {
765 continue;
767 if (tracked_request_overlaps(req, self->overlap_offset,
768 self->overlap_bytes))
771 * Hitting this means there was a reentrant request, for
772 * example, a block driver issuing nested requests. This must
773 * never happen since it means deadlock.
775 assert(qemu_coroutine_self() != req->co);
778 * If the request is already (indirectly) waiting for us, or
779 * will wait for us as soon as it wakes up, then just go on
780 * (instead of producing a deadlock in the former case).
782 if (!req->waiting_for) {
783 return req;
788 return NULL;
791 /* Called with self->bs->reqs_lock held */
792 static bool coroutine_fn
793 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest *self)
795 BdrvTrackedRequest *req;
796 bool waited = false;
798 while ((req = bdrv_find_conflicting_request(self))) {
799 self->waiting_for = req;
800 qemu_co_queue_wait(&req->wait_queue, &self->bs->reqs_lock);
801 self->waiting_for = NULL;
802 waited = true;
805 return waited;
808 bool bdrv_mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
810 BlockDriverState *bs = req->bs;
811 int64_t overlap_offset = req->offset & ~(align - 1);
812 uint64_t overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
813 - overlap_offset;
814 bool waited;
816 qemu_co_mutex_lock(&bs->reqs_lock);
817 if (!req->serialising) {
818 qatomic_inc(&req->bs->serialising_in_flight);
819 req->serialising = true;
822 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
823 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
824 waited = bdrv_wait_serialising_requests_locked(req);
825 qemu_co_mutex_unlock(&bs->reqs_lock);
826 return waited;
830 * Return the tracked request on @bs for the current coroutine, or
831 * NULL if there is none.
833 BdrvTrackedRequest *coroutine_fn bdrv_co_get_self_request(BlockDriverState *bs)
835 BdrvTrackedRequest *req;
836 Coroutine *self = qemu_coroutine_self();
838 QLIST_FOREACH(req, &bs->tracked_requests, list) {
839 if (req->co == self) {
840 return req;
844 return NULL;
848 * Round a region to cluster boundaries
850 void bdrv_round_to_clusters(BlockDriverState *bs,
851 int64_t offset, int64_t bytes,
852 int64_t *cluster_offset,
853 int64_t *cluster_bytes)
855 BlockDriverInfo bdi;
857 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
858 *cluster_offset = offset;
859 *cluster_bytes = bytes;
860 } else {
861 int64_t c = bdi.cluster_size;
862 *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
863 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
867 static int bdrv_get_cluster_size(BlockDriverState *bs)
869 BlockDriverInfo bdi;
870 int ret;
872 ret = bdrv_get_info(bs, &bdi);
873 if (ret < 0 || bdi.cluster_size == 0) {
874 return bs->bl.request_alignment;
875 } else {
876 return bdi.cluster_size;
880 void bdrv_inc_in_flight(BlockDriverState *bs)
882 qatomic_inc(&bs->in_flight);
885 void bdrv_wakeup(BlockDriverState *bs)
887 aio_wait_kick();
890 void bdrv_dec_in_flight(BlockDriverState *bs)
892 qatomic_dec(&bs->in_flight);
893 bdrv_wakeup(bs);
896 static bool coroutine_fn bdrv_wait_serialising_requests(BdrvTrackedRequest *self)
898 BlockDriverState *bs = self->bs;
899 bool waited = false;
901 if (!qatomic_read(&bs->serialising_in_flight)) {
902 return false;
905 qemu_co_mutex_lock(&bs->reqs_lock);
906 waited = bdrv_wait_serialising_requests_locked(self);
907 qemu_co_mutex_unlock(&bs->reqs_lock);
909 return waited;
912 int bdrv_check_request(int64_t offset, int64_t bytes)
914 if (offset < 0 || bytes < 0) {
915 return -EIO;
918 if (bytes > BDRV_MAX_LENGTH) {
919 return -EIO;
922 if (offset > BDRV_MAX_LENGTH - bytes) {
923 return -EIO;
926 return 0;
929 static int bdrv_check_request32(int64_t offset, int64_t bytes)
931 int ret = bdrv_check_request(offset, bytes);
932 if (ret < 0) {
933 return ret;
936 if (bytes > BDRV_REQUEST_MAX_BYTES) {
937 return -EIO;
940 return 0;
943 int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
944 int bytes, BdrvRequestFlags flags)
946 return bdrv_pwritev(child, offset, bytes, NULL,
947 BDRV_REQ_ZERO_WRITE | flags);
951 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
952 * The operation is sped up by checking the block status and only writing
953 * zeroes to the device if they currently do not return zeroes. Optional
954 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
955 * BDRV_REQ_FUA).
957 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
959 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
961 int ret;
962 int64_t target_size, bytes, offset = 0;
963 BlockDriverState *bs = child->bs;
965 target_size = bdrv_getlength(bs);
966 if (target_size < 0) {
967 return target_size;
970 for (;;) {
971 bytes = MIN(target_size - offset, BDRV_REQUEST_MAX_BYTES);
972 if (bytes <= 0) {
973 return 0;
975 ret = bdrv_block_status(bs, offset, bytes, &bytes, NULL, NULL);
976 if (ret < 0) {
977 return ret;
979 if (ret & BDRV_BLOCK_ZERO) {
980 offset += bytes;
981 continue;
983 ret = bdrv_pwrite_zeroes(child, offset, bytes, flags);
984 if (ret < 0) {
985 return ret;
987 offset += bytes;
991 /* See bdrv_pwrite() for the return codes */
992 int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int bytes)
994 int ret;
995 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
997 if (bytes < 0) {
998 return -EINVAL;
1001 ret = bdrv_preadv(child, offset, bytes, &qiov, 0);
1003 return ret < 0 ? ret : bytes;
1006 /* Return no. of bytes on success or < 0 on error. Important errors are:
1007 -EIO generic I/O error (may happen for all errors)
1008 -ENOMEDIUM No media inserted.
1009 -EINVAL Invalid offset or number of bytes
1010 -EACCES Trying to write a read-only device
1012 int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf, int bytes)
1014 int ret;
1015 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
1017 if (bytes < 0) {
1018 return -EINVAL;
1021 ret = bdrv_pwritev(child, offset, bytes, &qiov, 0);
1023 return ret < 0 ? ret : bytes;
1027 * Writes to the file and ensures that no writes are reordered across this
1028 * request (acts as a barrier)
1030 * Returns 0 on success, -errno in error cases.
1032 int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
1033 const void *buf, int count)
1035 int ret;
1037 ret = bdrv_pwrite(child, offset, buf, count);
1038 if (ret < 0) {
1039 return ret;
1042 ret = bdrv_flush(child->bs);
1043 if (ret < 0) {
1044 return ret;
1047 return 0;
1050 typedef struct CoroutineIOCompletion {
1051 Coroutine *coroutine;
1052 int ret;
1053 } CoroutineIOCompletion;
1055 static void bdrv_co_io_em_complete(void *opaque, int ret)
1057 CoroutineIOCompletion *co = opaque;
1059 co->ret = ret;
1060 aio_co_wake(co->coroutine);
1063 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
1064 uint64_t offset, uint64_t bytes,
1065 QEMUIOVector *qiov,
1066 size_t qiov_offset, int flags)
1068 BlockDriver *drv = bs->drv;
1069 int64_t sector_num;
1070 unsigned int nb_sectors;
1071 QEMUIOVector local_qiov;
1072 int ret;
1074 assert(!(flags & ~BDRV_REQ_MASK));
1075 assert(!(flags & BDRV_REQ_NO_FALLBACK));
1077 if (!drv) {
1078 return -ENOMEDIUM;
1081 if (drv->bdrv_co_preadv_part) {
1082 return drv->bdrv_co_preadv_part(bs, offset, bytes, qiov, qiov_offset,
1083 flags);
1086 if (qiov_offset > 0 || bytes != qiov->size) {
1087 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1088 qiov = &local_qiov;
1091 if (drv->bdrv_co_preadv) {
1092 ret = drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
1093 goto out;
1096 if (drv->bdrv_aio_preadv) {
1097 BlockAIOCB *acb;
1098 CoroutineIOCompletion co = {
1099 .coroutine = qemu_coroutine_self(),
1102 acb = drv->bdrv_aio_preadv(bs, offset, bytes, qiov, flags,
1103 bdrv_co_io_em_complete, &co);
1104 if (acb == NULL) {
1105 ret = -EIO;
1106 goto out;
1107 } else {
1108 qemu_coroutine_yield();
1109 ret = co.ret;
1110 goto out;
1114 sector_num = offset >> BDRV_SECTOR_BITS;
1115 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1117 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1118 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1119 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1120 assert(drv->bdrv_co_readv);
1122 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1124 out:
1125 if (qiov == &local_qiov) {
1126 qemu_iovec_destroy(&local_qiov);
1129 return ret;
1132 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
1133 uint64_t offset, uint64_t bytes,
1134 QEMUIOVector *qiov,
1135 size_t qiov_offset, int flags)
1137 BlockDriver *drv = bs->drv;
1138 int64_t sector_num;
1139 unsigned int nb_sectors;
1140 QEMUIOVector local_qiov;
1141 int ret;
1143 assert(!(flags & ~BDRV_REQ_MASK));
1144 assert(!(flags & BDRV_REQ_NO_FALLBACK));
1146 if (!drv) {
1147 return -ENOMEDIUM;
1150 if (drv->bdrv_co_pwritev_part) {
1151 ret = drv->bdrv_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset,
1152 flags & bs->supported_write_flags);
1153 flags &= ~bs->supported_write_flags;
1154 goto emulate_flags;
1157 if (qiov_offset > 0 || bytes != qiov->size) {
1158 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1159 qiov = &local_qiov;
1162 if (drv->bdrv_co_pwritev) {
1163 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
1164 flags & bs->supported_write_flags);
1165 flags &= ~bs->supported_write_flags;
1166 goto emulate_flags;
1169 if (drv->bdrv_aio_pwritev) {
1170 BlockAIOCB *acb;
1171 CoroutineIOCompletion co = {
1172 .coroutine = qemu_coroutine_self(),
1175 acb = drv->bdrv_aio_pwritev(bs, offset, bytes, qiov,
1176 flags & bs->supported_write_flags,
1177 bdrv_co_io_em_complete, &co);
1178 flags &= ~bs->supported_write_flags;
1179 if (acb == NULL) {
1180 ret = -EIO;
1181 } else {
1182 qemu_coroutine_yield();
1183 ret = co.ret;
1185 goto emulate_flags;
1188 sector_num = offset >> BDRV_SECTOR_BITS;
1189 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1191 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1192 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1193 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1195 assert(drv->bdrv_co_writev);
1196 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov,
1197 flags & bs->supported_write_flags);
1198 flags &= ~bs->supported_write_flags;
1200 emulate_flags:
1201 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
1202 ret = bdrv_co_flush(bs);
1205 if (qiov == &local_qiov) {
1206 qemu_iovec_destroy(&local_qiov);
1209 return ret;
1212 static int coroutine_fn
1213 bdrv_driver_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1214 uint64_t bytes, QEMUIOVector *qiov,
1215 size_t qiov_offset)
1217 BlockDriver *drv = bs->drv;
1218 QEMUIOVector local_qiov;
1219 int ret;
1221 if (!drv) {
1222 return -ENOMEDIUM;
1225 if (!block_driver_can_compress(drv)) {
1226 return -ENOTSUP;
1229 if (drv->bdrv_co_pwritev_compressed_part) {
1230 return drv->bdrv_co_pwritev_compressed_part(bs, offset, bytes,
1231 qiov, qiov_offset);
1234 if (qiov_offset == 0) {
1235 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
1238 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1239 ret = drv->bdrv_co_pwritev_compressed(bs, offset, bytes, &local_qiov);
1240 qemu_iovec_destroy(&local_qiov);
1242 return ret;
1245 static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
1246 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1247 size_t qiov_offset, int flags)
1249 BlockDriverState *bs = child->bs;
1251 /* Perform I/O through a temporary buffer so that users who scribble over
1252 * their read buffer while the operation is in progress do not end up
1253 * modifying the image file. This is critical for zero-copy guest I/O
1254 * where anything might happen inside guest memory.
1256 void *bounce_buffer = NULL;
1258 BlockDriver *drv = bs->drv;
1259 int64_t cluster_offset;
1260 int64_t cluster_bytes;
1261 size_t skip_bytes;
1262 int ret;
1263 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1264 BDRV_REQUEST_MAX_BYTES);
1265 unsigned int progress = 0;
1266 bool skip_write;
1268 if (!drv) {
1269 return -ENOMEDIUM;
1273 * Do not write anything when the BDS is inactive. That is not
1274 * allowed, and it would not help.
1276 skip_write = (bs->open_flags & BDRV_O_INACTIVE);
1278 /* FIXME We cannot require callers to have write permissions when all they
1279 * are doing is a read request. If we did things right, write permissions
1280 * would be obtained anyway, but internally by the copy-on-read code. As
1281 * long as it is implemented here rather than in a separate filter driver,
1282 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1283 * it could request permissions. Therefore we have to bypass the permission
1284 * system for the moment. */
1285 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1287 /* Cover entire cluster so no additional backing file I/O is required when
1288 * allocating cluster in the image file. Note that this value may exceed
1289 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1290 * is one reason we loop rather than doing it all at once.
1292 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
1293 skip_bytes = offset - cluster_offset;
1295 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
1296 cluster_offset, cluster_bytes);
1298 while (cluster_bytes) {
1299 int64_t pnum;
1301 if (skip_write) {
1302 ret = 1; /* "already allocated", so nothing will be copied */
1303 pnum = MIN(cluster_bytes, max_transfer);
1304 } else {
1305 ret = bdrv_is_allocated(bs, cluster_offset,
1306 MIN(cluster_bytes, max_transfer), &pnum);
1307 if (ret < 0) {
1309 * Safe to treat errors in querying allocation as if
1310 * unallocated; we'll probably fail again soon on the
1311 * read, but at least that will set a decent errno.
1313 pnum = MIN(cluster_bytes, max_transfer);
1316 /* Stop at EOF if the image ends in the middle of the cluster */
1317 if (ret == 0 && pnum == 0) {
1318 assert(progress >= bytes);
1319 break;
1322 assert(skip_bytes < pnum);
1325 if (ret <= 0) {
1326 QEMUIOVector local_qiov;
1328 /* Must copy-on-read; use the bounce buffer */
1329 pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1330 if (!bounce_buffer) {
1331 int64_t max_we_need = MAX(pnum, cluster_bytes - pnum);
1332 int64_t max_allowed = MIN(max_transfer, MAX_BOUNCE_BUFFER);
1333 int64_t bounce_buffer_len = MIN(max_we_need, max_allowed);
1335 bounce_buffer = qemu_try_blockalign(bs, bounce_buffer_len);
1336 if (!bounce_buffer) {
1337 ret = -ENOMEM;
1338 goto err;
1341 qemu_iovec_init_buf(&local_qiov, bounce_buffer, pnum);
1343 ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1344 &local_qiov, 0, 0);
1345 if (ret < 0) {
1346 goto err;
1349 bdrv_debug_event(bs, BLKDBG_COR_WRITE);
1350 if (drv->bdrv_co_pwrite_zeroes &&
1351 buffer_is_zero(bounce_buffer, pnum)) {
1352 /* FIXME: Should we (perhaps conditionally) be setting
1353 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1354 * that still correctly reads as zero? */
1355 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum,
1356 BDRV_REQ_WRITE_UNCHANGED);
1357 } else {
1358 /* This does not change the data on the disk, it is not
1359 * necessary to flush even in cache=writethrough mode.
1361 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
1362 &local_qiov, 0,
1363 BDRV_REQ_WRITE_UNCHANGED);
1366 if (ret < 0) {
1367 /* It might be okay to ignore write errors for guest
1368 * requests. If this is a deliberate copy-on-read
1369 * then we don't want to ignore the error. Simply
1370 * report it in all cases.
1372 goto err;
1375 if (!(flags & BDRV_REQ_PREFETCH)) {
1376 qemu_iovec_from_buf(qiov, qiov_offset + progress,
1377 bounce_buffer + skip_bytes,
1378 MIN(pnum - skip_bytes, bytes - progress));
1380 } else if (!(flags & BDRV_REQ_PREFETCH)) {
1381 /* Read directly into the destination */
1382 ret = bdrv_driver_preadv(bs, offset + progress,
1383 MIN(pnum - skip_bytes, bytes - progress),
1384 qiov, qiov_offset + progress, 0);
1385 if (ret < 0) {
1386 goto err;
1390 cluster_offset += pnum;
1391 cluster_bytes -= pnum;
1392 progress += pnum - skip_bytes;
1393 skip_bytes = 0;
1395 ret = 0;
1397 err:
1398 qemu_vfree(bounce_buffer);
1399 return ret;
1403 * Forwards an already correctly aligned request to the BlockDriver. This
1404 * handles copy on read, zeroing after EOF, and fragmentation of large
1405 * reads; any other features must be implemented by the caller.
1407 static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
1408 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1409 int64_t align, QEMUIOVector *qiov, size_t qiov_offset, int flags)
1411 BlockDriverState *bs = child->bs;
1412 int64_t total_bytes, max_bytes;
1413 int ret = 0;
1414 uint64_t bytes_remaining = bytes;
1415 int max_transfer;
1417 assert(is_power_of_2(align));
1418 assert((offset & (align - 1)) == 0);
1419 assert((bytes & (align - 1)) == 0);
1420 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1421 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1422 align);
1424 /* TODO: We would need a per-BDS .supported_read_flags and
1425 * potential fallback support, if we ever implement any read flags
1426 * to pass through to drivers. For now, there aren't any
1427 * passthrough flags. */
1428 assert(!(flags & ~(BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH)));
1430 /* Handle Copy on Read and associated serialisation */
1431 if (flags & BDRV_REQ_COPY_ON_READ) {
1432 /* If we touch the same cluster it counts as an overlap. This
1433 * guarantees that allocating writes will be serialized and not race
1434 * with each other for the same cluster. For example, in copy-on-read
1435 * it ensures that the CoR read and write operations are atomic and
1436 * guest writes cannot interleave between them. */
1437 bdrv_mark_request_serialising(req, bdrv_get_cluster_size(bs));
1438 } else {
1439 bdrv_wait_serialising_requests(req);
1442 if (flags & BDRV_REQ_COPY_ON_READ) {
1443 int64_t pnum;
1445 ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
1446 if (ret < 0) {
1447 goto out;
1450 if (!ret || pnum != bytes) {
1451 ret = bdrv_co_do_copy_on_readv(child, offset, bytes,
1452 qiov, qiov_offset, flags);
1453 goto out;
1454 } else if (flags & BDRV_REQ_PREFETCH) {
1455 goto out;
1459 /* Forward the request to the BlockDriver, possibly fragmenting it */
1460 total_bytes = bdrv_getlength(bs);
1461 if (total_bytes < 0) {
1462 ret = total_bytes;
1463 goto out;
1466 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1467 if (bytes <= max_bytes && bytes <= max_transfer) {
1468 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, qiov_offset, 0);
1469 goto out;
1472 while (bytes_remaining) {
1473 int num;
1475 if (max_bytes) {
1476 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1477 assert(num);
1479 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1480 num, qiov,
1481 qiov_offset + bytes - bytes_remaining, 0);
1482 max_bytes -= num;
1483 } else {
1484 num = bytes_remaining;
1485 ret = qemu_iovec_memset(qiov, qiov_offset + bytes - bytes_remaining,
1486 0, bytes_remaining);
1488 if (ret < 0) {
1489 goto out;
1491 bytes_remaining -= num;
1494 out:
1495 return ret < 0 ? ret : 0;
1499 * Request padding
1501 * |<---- align ----->| |<----- align ---->|
1502 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1503 * | | | | | |
1504 * -*----------$-------*-------- ... --------*-----$------------*---
1505 * | | | | | |
1506 * | offset | | end |
1507 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1508 * [buf ... ) [tail_buf )
1510 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1511 * is placed at the beginning of @buf and @tail at the @end.
1513 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1514 * around tail, if tail exists.
1516 * @merge_reads is true for small requests,
1517 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1518 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1520 typedef struct BdrvRequestPadding {
1521 uint8_t *buf;
1522 size_t buf_len;
1523 uint8_t *tail_buf;
1524 size_t head;
1525 size_t tail;
1526 bool merge_reads;
1527 QEMUIOVector local_qiov;
1528 } BdrvRequestPadding;
1530 static bool bdrv_init_padding(BlockDriverState *bs,
1531 int64_t offset, int64_t bytes,
1532 BdrvRequestPadding *pad)
1534 uint64_t align = bs->bl.request_alignment;
1535 size_t sum;
1537 memset(pad, 0, sizeof(*pad));
1539 pad->head = offset & (align - 1);
1540 pad->tail = ((offset + bytes) & (align - 1));
1541 if (pad->tail) {
1542 pad->tail = align - pad->tail;
1545 if (!pad->head && !pad->tail) {
1546 return false;
1549 assert(bytes); /* Nothing good in aligning zero-length requests */
1551 sum = pad->head + bytes + pad->tail;
1552 pad->buf_len = (sum > align && pad->head && pad->tail) ? 2 * align : align;
1553 pad->buf = qemu_blockalign(bs, pad->buf_len);
1554 pad->merge_reads = sum == pad->buf_len;
1555 if (pad->tail) {
1556 pad->tail_buf = pad->buf + pad->buf_len - align;
1559 return true;
1562 static int bdrv_padding_rmw_read(BdrvChild *child,
1563 BdrvTrackedRequest *req,
1564 BdrvRequestPadding *pad,
1565 bool zero_middle)
1567 QEMUIOVector local_qiov;
1568 BlockDriverState *bs = child->bs;
1569 uint64_t align = bs->bl.request_alignment;
1570 int ret;
1572 assert(req->serialising && pad->buf);
1574 if (pad->head || pad->merge_reads) {
1575 uint64_t bytes = pad->merge_reads ? pad->buf_len : align;
1577 qemu_iovec_init_buf(&local_qiov, pad->buf, bytes);
1579 if (pad->head) {
1580 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1582 if (pad->merge_reads && pad->tail) {
1583 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1585 ret = bdrv_aligned_preadv(child, req, req->overlap_offset, bytes,
1586 align, &local_qiov, 0, 0);
1587 if (ret < 0) {
1588 return ret;
1590 if (pad->head) {
1591 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1593 if (pad->merge_reads && pad->tail) {
1594 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1597 if (pad->merge_reads) {
1598 goto zero_mem;
1602 if (pad->tail) {
1603 qemu_iovec_init_buf(&local_qiov, pad->tail_buf, align);
1605 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1606 ret = bdrv_aligned_preadv(
1607 child, req,
1608 req->overlap_offset + req->overlap_bytes - align,
1609 align, align, &local_qiov, 0, 0);
1610 if (ret < 0) {
1611 return ret;
1613 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1616 zero_mem:
1617 if (zero_middle) {
1618 memset(pad->buf + pad->head, 0, pad->buf_len - pad->head - pad->tail);
1621 return 0;
1624 static void bdrv_padding_destroy(BdrvRequestPadding *pad)
1626 if (pad->buf) {
1627 qemu_vfree(pad->buf);
1628 qemu_iovec_destroy(&pad->local_qiov);
1633 * bdrv_pad_request
1635 * Exchange request parameters with padded request if needed. Don't include RMW
1636 * read of padding, bdrv_padding_rmw_read() should be called separately if
1637 * needed.
1639 * All parameters except @bs are in-out: they represent original request at
1640 * function call and padded (if padding needed) at function finish.
1642 * Function always succeeds.
1644 static bool bdrv_pad_request(BlockDriverState *bs,
1645 QEMUIOVector **qiov, size_t *qiov_offset,
1646 int64_t *offset, unsigned int *bytes,
1647 BdrvRequestPadding *pad)
1649 if (!bdrv_init_padding(bs, *offset, *bytes, pad)) {
1650 return false;
1653 qemu_iovec_init_extended(&pad->local_qiov, pad->buf, pad->head,
1654 *qiov, *qiov_offset, *bytes,
1655 pad->buf + pad->buf_len - pad->tail, pad->tail);
1656 *bytes += pad->head + pad->tail;
1657 *offset -= pad->head;
1658 *qiov = &pad->local_qiov;
1659 *qiov_offset = 0;
1661 return true;
1664 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1665 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1666 BdrvRequestFlags flags)
1668 return bdrv_co_preadv_part(child, offset, bytes, qiov, 0, flags);
1671 int coroutine_fn bdrv_co_preadv_part(BdrvChild *child,
1672 int64_t offset, unsigned int bytes,
1673 QEMUIOVector *qiov, size_t qiov_offset,
1674 BdrvRequestFlags flags)
1676 BlockDriverState *bs = child->bs;
1677 BdrvTrackedRequest req;
1678 BdrvRequestPadding pad;
1679 int ret;
1681 trace_bdrv_co_preadv(bs, offset, bytes, flags);
1683 if (!bdrv_is_inserted(bs)) {
1684 return -ENOMEDIUM;
1687 ret = bdrv_check_request32(offset, bytes);
1688 if (ret < 0) {
1689 return ret;
1692 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
1694 * Aligning zero request is nonsense. Even if driver has special meaning
1695 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1696 * it to driver due to request_alignment.
1698 * Still, no reason to return an error if someone do unaligned
1699 * zero-length read occasionally.
1701 return 0;
1704 bdrv_inc_in_flight(bs);
1706 /* Don't do copy-on-read if we read data before write operation */
1707 if (qatomic_read(&bs->copy_on_read)) {
1708 flags |= BDRV_REQ_COPY_ON_READ;
1711 bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad);
1713 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1714 ret = bdrv_aligned_preadv(child, &req, offset, bytes,
1715 bs->bl.request_alignment,
1716 qiov, qiov_offset, flags);
1717 tracked_request_end(&req);
1718 bdrv_dec_in_flight(bs);
1720 bdrv_padding_destroy(&pad);
1722 return ret;
1725 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1726 int64_t offset, int bytes, BdrvRequestFlags flags)
1728 BlockDriver *drv = bs->drv;
1729 QEMUIOVector qiov;
1730 void *buf = NULL;
1731 int ret = 0;
1732 bool need_flush = false;
1733 int head = 0;
1734 int tail = 0;
1736 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
1737 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1738 bs->bl.request_alignment);
1739 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
1741 if (!drv) {
1742 return -ENOMEDIUM;
1745 if ((flags & ~bs->supported_zero_flags) & BDRV_REQ_NO_FALLBACK) {
1746 return -ENOTSUP;
1749 assert(alignment % bs->bl.request_alignment == 0);
1750 head = offset % alignment;
1751 tail = (offset + bytes) % alignment;
1752 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1753 assert(max_write_zeroes >= bs->bl.request_alignment);
1755 while (bytes > 0 && !ret) {
1756 int num = bytes;
1758 /* Align request. Block drivers can expect the "bulk" of the request
1759 * to be aligned, and that unaligned requests do not cross cluster
1760 * boundaries.
1762 if (head) {
1763 /* Make a small request up to the first aligned sector. For
1764 * convenience, limit this request to max_transfer even if
1765 * we don't need to fall back to writes. */
1766 num = MIN(MIN(bytes, max_transfer), alignment - head);
1767 head = (head + num) % alignment;
1768 assert(num < max_write_zeroes);
1769 } else if (tail && num > alignment) {
1770 /* Shorten the request to the last aligned sector. */
1771 num -= tail;
1774 /* limit request size */
1775 if (num > max_write_zeroes) {
1776 num = max_write_zeroes;
1779 ret = -ENOTSUP;
1780 /* First try the efficient write zeroes operation */
1781 if (drv->bdrv_co_pwrite_zeroes) {
1782 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1783 flags & bs->supported_zero_flags);
1784 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1785 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1786 need_flush = true;
1788 } else {
1789 assert(!bs->supported_zero_flags);
1792 if (ret == -ENOTSUP && !(flags & BDRV_REQ_NO_FALLBACK)) {
1793 /* Fall back to bounce buffer if write zeroes is unsupported */
1794 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1796 if ((flags & BDRV_REQ_FUA) &&
1797 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1798 /* No need for bdrv_driver_pwrite() to do a fallback
1799 * flush on each chunk; use just one at the end */
1800 write_flags &= ~BDRV_REQ_FUA;
1801 need_flush = true;
1803 num = MIN(num, max_transfer);
1804 if (buf == NULL) {
1805 buf = qemu_try_blockalign0(bs, num);
1806 if (buf == NULL) {
1807 ret = -ENOMEM;
1808 goto fail;
1811 qemu_iovec_init_buf(&qiov, buf, num);
1813 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, 0, write_flags);
1815 /* Keep bounce buffer around if it is big enough for all
1816 * all future requests.
1818 if (num < max_transfer) {
1819 qemu_vfree(buf);
1820 buf = NULL;
1824 offset += num;
1825 bytes -= num;
1828 fail:
1829 if (ret == 0 && need_flush) {
1830 ret = bdrv_co_flush(bs);
1832 qemu_vfree(buf);
1833 return ret;
1836 static inline int coroutine_fn
1837 bdrv_co_write_req_prepare(BdrvChild *child, int64_t offset, uint64_t bytes,
1838 BdrvTrackedRequest *req, int flags)
1840 BlockDriverState *bs = child->bs;
1841 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1843 if (bs->read_only) {
1844 return -EPERM;
1847 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1848 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1849 assert(!(flags & ~BDRV_REQ_MASK));
1851 if (flags & BDRV_REQ_SERIALISING) {
1852 bdrv_mark_request_serialising(req, bdrv_get_cluster_size(bs));
1853 } else {
1854 bdrv_wait_serialising_requests(req);
1857 assert(req->overlap_offset <= offset);
1858 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1859 assert(end_sector <= bs->total_sectors || child->perm & BLK_PERM_RESIZE);
1861 switch (req->type) {
1862 case BDRV_TRACKED_WRITE:
1863 case BDRV_TRACKED_DISCARD:
1864 if (flags & BDRV_REQ_WRITE_UNCHANGED) {
1865 assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1866 } else {
1867 assert(child->perm & BLK_PERM_WRITE);
1869 return notifier_with_return_list_notify(&bs->before_write_notifiers,
1870 req);
1871 case BDRV_TRACKED_TRUNCATE:
1872 assert(child->perm & BLK_PERM_RESIZE);
1873 return 0;
1874 default:
1875 abort();
1879 static inline void coroutine_fn
1880 bdrv_co_write_req_finish(BdrvChild *child, int64_t offset, uint64_t bytes,
1881 BdrvTrackedRequest *req, int ret)
1883 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1884 BlockDriverState *bs = child->bs;
1886 qatomic_inc(&bs->write_gen);
1889 * Discard cannot extend the image, but in error handling cases, such as
1890 * when reverting a qcow2 cluster allocation, the discarded range can pass
1891 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1892 * here. Instead, just skip it, since semantically a discard request
1893 * beyond EOF cannot expand the image anyway.
1895 if (ret == 0 &&
1896 (req->type == BDRV_TRACKED_TRUNCATE ||
1897 end_sector > bs->total_sectors) &&
1898 req->type != BDRV_TRACKED_DISCARD) {
1899 bs->total_sectors = end_sector;
1900 bdrv_parent_cb_resize(bs);
1901 bdrv_dirty_bitmap_truncate(bs, end_sector << BDRV_SECTOR_BITS);
1903 if (req->bytes) {
1904 switch (req->type) {
1905 case BDRV_TRACKED_WRITE:
1906 stat64_max(&bs->wr_highest_offset, offset + bytes);
1907 /* fall through, to set dirty bits */
1908 case BDRV_TRACKED_DISCARD:
1909 bdrv_set_dirty(bs, offset, bytes);
1910 break;
1911 default:
1912 break;
1918 * Forwards an already correctly aligned write request to the BlockDriver,
1919 * after possibly fragmenting it.
1921 static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
1922 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1923 int64_t align, QEMUIOVector *qiov, size_t qiov_offset, int flags)
1925 BlockDriverState *bs = child->bs;
1926 BlockDriver *drv = bs->drv;
1927 int ret;
1929 uint64_t bytes_remaining = bytes;
1930 int max_transfer;
1932 if (!drv) {
1933 return -ENOMEDIUM;
1936 if (bdrv_has_readonly_bitmaps(bs)) {
1937 return -EPERM;
1940 assert(is_power_of_2(align));
1941 assert((offset & (align - 1)) == 0);
1942 assert((bytes & (align - 1)) == 0);
1943 assert(!qiov || qiov_offset + bytes <= qiov->size);
1944 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1945 align);
1947 ret = bdrv_co_write_req_prepare(child, offset, bytes, req, flags);
1949 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1950 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
1951 qemu_iovec_is_zero(qiov, qiov_offset, bytes)) {
1952 flags |= BDRV_REQ_ZERO_WRITE;
1953 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1954 flags |= BDRV_REQ_MAY_UNMAP;
1958 if (ret < 0) {
1959 /* Do nothing, write notifier decided to fail this request */
1960 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1961 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1962 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
1963 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
1964 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes,
1965 qiov, qiov_offset);
1966 } else if (bytes <= max_transfer) {
1967 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1968 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, qiov_offset, flags);
1969 } else {
1970 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1971 while (bytes_remaining) {
1972 int num = MIN(bytes_remaining, max_transfer);
1973 int local_flags = flags;
1975 assert(num);
1976 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
1977 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1978 /* If FUA is going to be emulated by flush, we only
1979 * need to flush on the last iteration */
1980 local_flags &= ~BDRV_REQ_FUA;
1983 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
1984 num, qiov,
1985 qiov_offset + bytes - bytes_remaining,
1986 local_flags);
1987 if (ret < 0) {
1988 break;
1990 bytes_remaining -= num;
1993 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1995 if (ret >= 0) {
1996 ret = 0;
1998 bdrv_co_write_req_finish(child, offset, bytes, req, ret);
2000 return ret;
2003 static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
2004 int64_t offset,
2005 unsigned int bytes,
2006 BdrvRequestFlags flags,
2007 BdrvTrackedRequest *req)
2009 BlockDriverState *bs = child->bs;
2010 QEMUIOVector local_qiov;
2011 uint64_t align = bs->bl.request_alignment;
2012 int ret = 0;
2013 bool padding;
2014 BdrvRequestPadding pad;
2016 padding = bdrv_init_padding(bs, offset, bytes, &pad);
2017 if (padding) {
2018 bdrv_mark_request_serialising(req, align);
2020 bdrv_padding_rmw_read(child, req, &pad, true);
2022 if (pad.head || pad.merge_reads) {
2023 int64_t aligned_offset = offset & ~(align - 1);
2024 int64_t write_bytes = pad.merge_reads ? pad.buf_len : align;
2026 qemu_iovec_init_buf(&local_qiov, pad.buf, write_bytes);
2027 ret = bdrv_aligned_pwritev(child, req, aligned_offset, write_bytes,
2028 align, &local_qiov, 0,
2029 flags & ~BDRV_REQ_ZERO_WRITE);
2030 if (ret < 0 || pad.merge_reads) {
2031 /* Error or all work is done */
2032 goto out;
2034 offset += write_bytes - pad.head;
2035 bytes -= write_bytes - pad.head;
2039 assert(!bytes || (offset & (align - 1)) == 0);
2040 if (bytes >= align) {
2041 /* Write the aligned part in the middle. */
2042 uint64_t aligned_bytes = bytes & ~(align - 1);
2043 ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
2044 NULL, 0, flags);
2045 if (ret < 0) {
2046 goto out;
2048 bytes -= aligned_bytes;
2049 offset += aligned_bytes;
2052 assert(!bytes || (offset & (align - 1)) == 0);
2053 if (bytes) {
2054 assert(align == pad.tail + bytes);
2056 qemu_iovec_init_buf(&local_qiov, pad.tail_buf, align);
2057 ret = bdrv_aligned_pwritev(child, req, offset, align, align,
2058 &local_qiov, 0,
2059 flags & ~BDRV_REQ_ZERO_WRITE);
2062 out:
2063 bdrv_padding_destroy(&pad);
2065 return ret;
2069 * Handle a write request in coroutine context
2071 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
2072 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
2073 BdrvRequestFlags flags)
2075 return bdrv_co_pwritev_part(child, offset, bytes, qiov, 0, flags);
2078 int coroutine_fn bdrv_co_pwritev_part(BdrvChild *child,
2079 int64_t offset, unsigned int bytes, QEMUIOVector *qiov, size_t qiov_offset,
2080 BdrvRequestFlags flags)
2082 BlockDriverState *bs = child->bs;
2083 BdrvTrackedRequest req;
2084 uint64_t align = bs->bl.request_alignment;
2085 BdrvRequestPadding pad;
2086 int ret;
2088 trace_bdrv_co_pwritev(child->bs, offset, bytes, flags);
2090 if (!bdrv_is_inserted(bs)) {
2091 return -ENOMEDIUM;
2094 ret = bdrv_check_request32(offset, bytes);
2095 if (ret < 0) {
2096 return ret;
2099 /* If the request is misaligned then we can't make it efficient */
2100 if ((flags & BDRV_REQ_NO_FALLBACK) &&
2101 !QEMU_IS_ALIGNED(offset | bytes, align))
2103 return -ENOTSUP;
2106 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
2108 * Aligning zero request is nonsense. Even if driver has special meaning
2109 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2110 * it to driver due to request_alignment.
2112 * Still, no reason to return an error if someone do unaligned
2113 * zero-length write occasionally.
2115 return 0;
2118 bdrv_inc_in_flight(bs);
2120 * Align write if necessary by performing a read-modify-write cycle.
2121 * Pad qiov with the read parts and be sure to have a tracked request not
2122 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
2124 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
2126 if (flags & BDRV_REQ_ZERO_WRITE) {
2127 ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
2128 goto out;
2131 if (bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad)) {
2132 bdrv_mark_request_serialising(&req, align);
2133 bdrv_padding_rmw_read(child, &req, &pad, false);
2136 ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
2137 qiov, qiov_offset, flags);
2139 bdrv_padding_destroy(&pad);
2141 out:
2142 tracked_request_end(&req);
2143 bdrv_dec_in_flight(bs);
2145 return ret;
2148 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
2149 int bytes, BdrvRequestFlags flags)
2151 trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
2153 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
2154 flags &= ~BDRV_REQ_MAY_UNMAP;
2157 return bdrv_co_pwritev(child, offset, bytes, NULL,
2158 BDRV_REQ_ZERO_WRITE | flags);
2162 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2164 int bdrv_flush_all(void)
2166 BdrvNextIterator it;
2167 BlockDriverState *bs = NULL;
2168 int result = 0;
2171 * bdrv queue is managed by record/replay,
2172 * creating new flush request for stopping
2173 * the VM may break the determinism
2175 if (replay_events_enabled()) {
2176 return result;
2179 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
2180 AioContext *aio_context = bdrv_get_aio_context(bs);
2181 int ret;
2183 aio_context_acquire(aio_context);
2184 ret = bdrv_flush(bs);
2185 if (ret < 0 && !result) {
2186 result = ret;
2188 aio_context_release(aio_context);
2191 return result;
2195 * Returns the allocation status of the specified sectors.
2196 * Drivers not implementing the functionality are assumed to not support
2197 * backing files, hence all their sectors are reported as allocated.
2199 * If 'want_zero' is true, the caller is querying for mapping
2200 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2201 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2202 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2204 * If 'offset' is beyond the end of the disk image the return value is
2205 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2207 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2208 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2209 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2211 * 'pnum' is set to the number of bytes (including and immediately
2212 * following the specified offset) that are easily known to be in the
2213 * same allocated/unallocated state. Note that a second call starting
2214 * at the original offset plus returned pnum may have the same status.
2215 * The returned value is non-zero on success except at end-of-file.
2217 * Returns negative errno on failure. Otherwise, if the
2218 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2219 * set to the host mapping and BDS corresponding to the guest offset.
2221 static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
2222 bool want_zero,
2223 int64_t offset, int64_t bytes,
2224 int64_t *pnum, int64_t *map,
2225 BlockDriverState **file)
2227 int64_t total_size;
2228 int64_t n; /* bytes */
2229 int ret;
2230 int64_t local_map = 0;
2231 BlockDriverState *local_file = NULL;
2232 int64_t aligned_offset, aligned_bytes;
2233 uint32_t align;
2234 bool has_filtered_child;
2236 assert(pnum);
2237 *pnum = 0;
2238 total_size = bdrv_getlength(bs);
2239 if (total_size < 0) {
2240 ret = total_size;
2241 goto early_out;
2244 if (offset >= total_size) {
2245 ret = BDRV_BLOCK_EOF;
2246 goto early_out;
2248 if (!bytes) {
2249 ret = 0;
2250 goto early_out;
2253 n = total_size - offset;
2254 if (n < bytes) {
2255 bytes = n;
2258 /* Must be non-NULL or bdrv_getlength() would have failed */
2259 assert(bs->drv);
2260 has_filtered_child = bdrv_filter_child(bs);
2261 if (!bs->drv->bdrv_co_block_status && !has_filtered_child) {
2262 *pnum = bytes;
2263 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2264 if (offset + bytes == total_size) {
2265 ret |= BDRV_BLOCK_EOF;
2267 if (bs->drv->protocol_name) {
2268 ret |= BDRV_BLOCK_OFFSET_VALID;
2269 local_map = offset;
2270 local_file = bs;
2272 goto early_out;
2275 bdrv_inc_in_flight(bs);
2277 /* Round out to request_alignment boundaries */
2278 align = bs->bl.request_alignment;
2279 aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2280 aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2282 if (bs->drv->bdrv_co_block_status) {
2283 ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2284 aligned_bytes, pnum, &local_map,
2285 &local_file);
2286 } else {
2287 /* Default code for filters */
2289 local_file = bdrv_filter_bs(bs);
2290 assert(local_file);
2292 *pnum = aligned_bytes;
2293 local_map = aligned_offset;
2294 ret = BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2296 if (ret < 0) {
2297 *pnum = 0;
2298 goto out;
2302 * The driver's result must be a non-zero multiple of request_alignment.
2303 * Clamp pnum and adjust map to original request.
2305 assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2306 align > offset - aligned_offset);
2307 if (ret & BDRV_BLOCK_RECURSE) {
2308 assert(ret & BDRV_BLOCK_DATA);
2309 assert(ret & BDRV_BLOCK_OFFSET_VALID);
2310 assert(!(ret & BDRV_BLOCK_ZERO));
2313 *pnum -= offset - aligned_offset;
2314 if (*pnum > bytes) {
2315 *pnum = bytes;
2317 if (ret & BDRV_BLOCK_OFFSET_VALID) {
2318 local_map += offset - aligned_offset;
2321 if (ret & BDRV_BLOCK_RAW) {
2322 assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2323 ret = bdrv_co_block_status(local_file, want_zero, local_map,
2324 *pnum, pnum, &local_map, &local_file);
2325 goto out;
2328 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2329 ret |= BDRV_BLOCK_ALLOCATED;
2330 } else if (bs->drv->supports_backing) {
2331 BlockDriverState *cow_bs = bdrv_cow_bs(bs);
2333 if (!cow_bs) {
2334 ret |= BDRV_BLOCK_ZERO;
2335 } else if (want_zero) {
2336 int64_t size2 = bdrv_getlength(cow_bs);
2338 if (size2 >= 0 && offset >= size2) {
2339 ret |= BDRV_BLOCK_ZERO;
2344 if (want_zero && ret & BDRV_BLOCK_RECURSE &&
2345 local_file && local_file != bs &&
2346 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2347 (ret & BDRV_BLOCK_OFFSET_VALID)) {
2348 int64_t file_pnum;
2349 int ret2;
2351 ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2352 *pnum, &file_pnum, NULL, NULL);
2353 if (ret2 >= 0) {
2354 /* Ignore errors. This is just providing extra information, it
2355 * is useful but not necessary.
2357 if (ret2 & BDRV_BLOCK_EOF &&
2358 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2360 * It is valid for the format block driver to read
2361 * beyond the end of the underlying file's current
2362 * size; such areas read as zero.
2364 ret |= BDRV_BLOCK_ZERO;
2365 } else {
2366 /* Limit request to the range reported by the protocol driver */
2367 *pnum = file_pnum;
2368 ret |= (ret2 & BDRV_BLOCK_ZERO);
2373 out:
2374 bdrv_dec_in_flight(bs);
2375 if (ret >= 0 && offset + *pnum == total_size) {
2376 ret |= BDRV_BLOCK_EOF;
2378 early_out:
2379 if (file) {
2380 *file = local_file;
2382 if (map) {
2383 *map = local_map;
2385 return ret;
2388 int coroutine_fn
2389 bdrv_co_common_block_status_above(BlockDriverState *bs,
2390 BlockDriverState *base,
2391 bool include_base,
2392 bool want_zero,
2393 int64_t offset,
2394 int64_t bytes,
2395 int64_t *pnum,
2396 int64_t *map,
2397 BlockDriverState **file,
2398 int *depth)
2400 int ret;
2401 BlockDriverState *p;
2402 int64_t eof = 0;
2403 int dummy;
2405 assert(!include_base || base); /* Can't include NULL base */
2407 if (!depth) {
2408 depth = &dummy;
2410 *depth = 0;
2412 if (!include_base && bs == base) {
2413 *pnum = bytes;
2414 return 0;
2417 ret = bdrv_co_block_status(bs, want_zero, offset, bytes, pnum, map, file);
2418 ++*depth;
2419 if (ret < 0 || *pnum == 0 || ret & BDRV_BLOCK_ALLOCATED || bs == base) {
2420 return ret;
2423 if (ret & BDRV_BLOCK_EOF) {
2424 eof = offset + *pnum;
2427 assert(*pnum <= bytes);
2428 bytes = *pnum;
2430 for (p = bdrv_filter_or_cow_bs(bs); include_base || p != base;
2431 p = bdrv_filter_or_cow_bs(p))
2433 ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2434 file);
2435 ++*depth;
2436 if (ret < 0) {
2437 return ret;
2439 if (*pnum == 0) {
2441 * The top layer deferred to this layer, and because this layer is
2442 * short, any zeroes that we synthesize beyond EOF behave as if they
2443 * were allocated at this layer.
2445 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2446 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2447 * below.
2449 assert(ret & BDRV_BLOCK_EOF);
2450 *pnum = bytes;
2451 if (file) {
2452 *file = p;
2454 ret = BDRV_BLOCK_ZERO | BDRV_BLOCK_ALLOCATED;
2455 break;
2457 if (ret & BDRV_BLOCK_ALLOCATED) {
2459 * We've found the node and the status, we must break.
2461 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2462 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2463 * below.
2465 ret &= ~BDRV_BLOCK_EOF;
2466 break;
2469 if (p == base) {
2470 assert(include_base);
2471 break;
2475 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2476 * let's continue the diving.
2478 assert(*pnum <= bytes);
2479 bytes = *pnum;
2482 if (offset + *pnum == eof) {
2483 ret |= BDRV_BLOCK_EOF;
2486 return ret;
2489 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2490 int64_t offset, int64_t bytes, int64_t *pnum,
2491 int64_t *map, BlockDriverState **file)
2493 return bdrv_common_block_status_above(bs, base, false, true, offset, bytes,
2494 pnum, map, file, NULL);
2497 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2498 int64_t *pnum, int64_t *map, BlockDriverState **file)
2500 return bdrv_block_status_above(bs, bdrv_filter_or_cow_bs(bs),
2501 offset, bytes, pnum, map, file);
2505 * Check @bs (and its backing chain) to see if the range defined
2506 * by @offset and @bytes is known to read as zeroes.
2507 * Return 1 if that is the case, 0 otherwise and -errno on error.
2508 * This test is meant to be fast rather than accurate so returning 0
2509 * does not guarantee non-zero data.
2511 int coroutine_fn bdrv_co_is_zero_fast(BlockDriverState *bs, int64_t offset,
2512 int64_t bytes)
2514 int ret;
2515 int64_t pnum = bytes;
2517 if (!bytes) {
2518 return 1;
2521 ret = bdrv_common_block_status_above(bs, NULL, false, false, offset,
2522 bytes, &pnum, NULL, NULL, NULL);
2524 if (ret < 0) {
2525 return ret;
2528 return (pnum == bytes) && (ret & BDRV_BLOCK_ZERO);
2531 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
2532 int64_t bytes, int64_t *pnum)
2534 int ret;
2535 int64_t dummy;
2537 ret = bdrv_common_block_status_above(bs, bs, true, false, offset,
2538 bytes, pnum ? pnum : &dummy, NULL,
2539 NULL, NULL);
2540 if (ret < 0) {
2541 return ret;
2543 return !!(ret & BDRV_BLOCK_ALLOCATED);
2547 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2549 * Return a positive depth if (a prefix of) the given range is allocated
2550 * in any image between BASE and TOP (BASE is only included if include_base
2551 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2552 * BASE can be NULL to check if the given offset is allocated in any
2553 * image of the chain. Return 0 otherwise, or negative errno on
2554 * failure.
2556 * 'pnum' is set to the number of bytes (including and immediately
2557 * following the specified offset) that are known to be in the same
2558 * allocated/unallocated state. Note that a subsequent call starting
2559 * at 'offset + *pnum' may return the same allocation status (in other
2560 * words, the result is not necessarily the maximum possible range);
2561 * but 'pnum' will only be 0 when end of file is reached.
2563 int bdrv_is_allocated_above(BlockDriverState *top,
2564 BlockDriverState *base,
2565 bool include_base, int64_t offset,
2566 int64_t bytes, int64_t *pnum)
2568 int depth;
2569 int ret = bdrv_common_block_status_above(top, base, include_base, false,
2570 offset, bytes, pnum, NULL, NULL,
2571 &depth);
2572 if (ret < 0) {
2573 return ret;
2576 if (ret & BDRV_BLOCK_ALLOCATED) {
2577 return depth;
2579 return 0;
2582 int coroutine_fn
2583 bdrv_co_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2585 BlockDriver *drv = bs->drv;
2586 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2587 int ret = -ENOTSUP;
2589 if (!drv) {
2590 return -ENOMEDIUM;
2593 bdrv_inc_in_flight(bs);
2595 if (drv->bdrv_load_vmstate) {
2596 ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2597 } else if (child_bs) {
2598 ret = bdrv_co_readv_vmstate(child_bs, qiov, pos);
2601 bdrv_dec_in_flight(bs);
2603 return ret;
2606 int coroutine_fn
2607 bdrv_co_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2609 BlockDriver *drv = bs->drv;
2610 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2611 int ret = -ENOTSUP;
2613 if (!drv) {
2614 return -ENOMEDIUM;
2617 bdrv_inc_in_flight(bs);
2619 if (drv->bdrv_save_vmstate) {
2620 ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2621 } else if (child_bs) {
2622 ret = bdrv_co_writev_vmstate(child_bs, qiov, pos);
2625 bdrv_dec_in_flight(bs);
2627 return ret;
2630 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2631 int64_t pos, int size)
2633 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2634 int ret = bdrv_writev_vmstate(bs, &qiov, pos);
2636 return ret < 0 ? ret : size;
2639 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2640 int64_t pos, int size)
2642 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2643 int ret = bdrv_readv_vmstate(bs, &qiov, pos);
2645 return ret < 0 ? ret : size;
2648 /**************************************************************/
2649 /* async I/Os */
2651 void bdrv_aio_cancel(BlockAIOCB *acb)
2653 qemu_aio_ref(acb);
2654 bdrv_aio_cancel_async(acb);
2655 while (acb->refcnt > 1) {
2656 if (acb->aiocb_info->get_aio_context) {
2657 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2658 } else if (acb->bs) {
2659 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2660 * assert that we're not using an I/O thread. Thread-safe
2661 * code should use bdrv_aio_cancel_async exclusively.
2663 assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2664 aio_poll(bdrv_get_aio_context(acb->bs), true);
2665 } else {
2666 abort();
2669 qemu_aio_unref(acb);
2672 /* Async version of aio cancel. The caller is not blocked if the acb implements
2673 * cancel_async, otherwise we do nothing and let the request normally complete.
2674 * In either case the completion callback must be called. */
2675 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2677 if (acb->aiocb_info->cancel_async) {
2678 acb->aiocb_info->cancel_async(acb);
2682 /**************************************************************/
2683 /* Coroutine block device emulation */
2685 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2687 BdrvChild *primary_child = bdrv_primary_child(bs);
2688 BdrvChild *child;
2689 int current_gen;
2690 int ret = 0;
2692 bdrv_inc_in_flight(bs);
2694 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2695 bdrv_is_sg(bs)) {
2696 goto early_exit;
2699 qemu_co_mutex_lock(&bs->reqs_lock);
2700 current_gen = qatomic_read(&bs->write_gen);
2702 /* Wait until any previous flushes are completed */
2703 while (bs->active_flush_req) {
2704 qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
2707 /* Flushes reach this point in nondecreasing current_gen order. */
2708 bs->active_flush_req = true;
2709 qemu_co_mutex_unlock(&bs->reqs_lock);
2711 /* Write back all layers by calling one driver function */
2712 if (bs->drv->bdrv_co_flush) {
2713 ret = bs->drv->bdrv_co_flush(bs);
2714 goto out;
2717 /* Write back cached data to the OS even with cache=unsafe */
2718 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_OS);
2719 if (bs->drv->bdrv_co_flush_to_os) {
2720 ret = bs->drv->bdrv_co_flush_to_os(bs);
2721 if (ret < 0) {
2722 goto out;
2726 /* But don't actually force it to the disk with cache=unsafe */
2727 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2728 goto flush_children;
2731 /* Check if we really need to flush anything */
2732 if (bs->flushed_gen == current_gen) {
2733 goto flush_children;
2736 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_DISK);
2737 if (!bs->drv) {
2738 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2739 * (even in case of apparent success) */
2740 ret = -ENOMEDIUM;
2741 goto out;
2743 if (bs->drv->bdrv_co_flush_to_disk) {
2744 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2745 } else if (bs->drv->bdrv_aio_flush) {
2746 BlockAIOCB *acb;
2747 CoroutineIOCompletion co = {
2748 .coroutine = qemu_coroutine_self(),
2751 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2752 if (acb == NULL) {
2753 ret = -EIO;
2754 } else {
2755 qemu_coroutine_yield();
2756 ret = co.ret;
2758 } else {
2760 * Some block drivers always operate in either writethrough or unsafe
2761 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2762 * know how the server works (because the behaviour is hardcoded or
2763 * depends on server-side configuration), so we can't ensure that
2764 * everything is safe on disk. Returning an error doesn't work because
2765 * that would break guests even if the server operates in writethrough
2766 * mode.
2768 * Let's hope the user knows what he's doing.
2770 ret = 0;
2773 if (ret < 0) {
2774 goto out;
2777 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2778 * in the case of cache=unsafe, so there are no useless flushes.
2780 flush_children:
2781 ret = 0;
2782 QLIST_FOREACH(child, &bs->children, next) {
2783 if (child->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2784 int this_child_ret = bdrv_co_flush(child->bs);
2785 if (!ret) {
2786 ret = this_child_ret;
2791 out:
2792 /* Notify any pending flushes that we have completed */
2793 if (ret == 0) {
2794 bs->flushed_gen = current_gen;
2797 qemu_co_mutex_lock(&bs->reqs_lock);
2798 bs->active_flush_req = false;
2799 /* Return value is ignored - it's ok if wait queue is empty */
2800 qemu_co_queue_next(&bs->flush_queue);
2801 qemu_co_mutex_unlock(&bs->reqs_lock);
2803 early_exit:
2804 bdrv_dec_in_flight(bs);
2805 return ret;
2808 int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset,
2809 int64_t bytes)
2811 BdrvTrackedRequest req;
2812 int max_pdiscard, ret;
2813 int head, tail, align;
2814 BlockDriverState *bs = child->bs;
2816 if (!bs || !bs->drv || !bdrv_is_inserted(bs)) {
2817 return -ENOMEDIUM;
2820 if (bdrv_has_readonly_bitmaps(bs)) {
2821 return -EPERM;
2824 ret = bdrv_check_request(offset, bytes);
2825 if (ret < 0) {
2826 return ret;
2829 /* Do nothing if disabled. */
2830 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2831 return 0;
2834 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
2835 return 0;
2838 /* Discard is advisory, but some devices track and coalesce
2839 * unaligned requests, so we must pass everything down rather than
2840 * round here. Still, most devices will just silently ignore
2841 * unaligned requests (by returning -ENOTSUP), so we must fragment
2842 * the request accordingly. */
2843 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
2844 assert(align % bs->bl.request_alignment == 0);
2845 head = offset % align;
2846 tail = (offset + bytes) % align;
2848 bdrv_inc_in_flight(bs);
2849 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
2851 ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
2852 if (ret < 0) {
2853 goto out;
2856 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),
2857 align);
2858 assert(max_pdiscard >= bs->bl.request_alignment);
2860 while (bytes > 0) {
2861 int64_t num = bytes;
2863 if (head) {
2864 /* Make small requests to get to alignment boundaries. */
2865 num = MIN(bytes, align - head);
2866 if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
2867 num %= bs->bl.request_alignment;
2869 head = (head + num) % align;
2870 assert(num < max_pdiscard);
2871 } else if (tail) {
2872 if (num > align) {
2873 /* Shorten the request to the last aligned cluster. */
2874 num -= tail;
2875 } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
2876 tail > bs->bl.request_alignment) {
2877 tail %= bs->bl.request_alignment;
2878 num -= tail;
2881 /* limit request size */
2882 if (num > max_pdiscard) {
2883 num = max_pdiscard;
2886 if (!bs->drv) {
2887 ret = -ENOMEDIUM;
2888 goto out;
2890 if (bs->drv->bdrv_co_pdiscard) {
2891 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
2892 } else {
2893 BlockAIOCB *acb;
2894 CoroutineIOCompletion co = {
2895 .coroutine = qemu_coroutine_self(),
2898 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
2899 bdrv_co_io_em_complete, &co);
2900 if (acb == NULL) {
2901 ret = -EIO;
2902 goto out;
2903 } else {
2904 qemu_coroutine_yield();
2905 ret = co.ret;
2908 if (ret && ret != -ENOTSUP) {
2909 goto out;
2912 offset += num;
2913 bytes -= num;
2915 ret = 0;
2916 out:
2917 bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
2918 tracked_request_end(&req);
2919 bdrv_dec_in_flight(bs);
2920 return ret;
2923 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
2925 BlockDriver *drv = bs->drv;
2926 CoroutineIOCompletion co = {
2927 .coroutine = qemu_coroutine_self(),
2929 BlockAIOCB *acb;
2931 bdrv_inc_in_flight(bs);
2932 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
2933 co.ret = -ENOTSUP;
2934 goto out;
2937 if (drv->bdrv_co_ioctl) {
2938 co.ret = drv->bdrv_co_ioctl(bs, req, buf);
2939 } else {
2940 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2941 if (!acb) {
2942 co.ret = -ENOTSUP;
2943 goto out;
2945 qemu_coroutine_yield();
2947 out:
2948 bdrv_dec_in_flight(bs);
2949 return co.ret;
2952 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2954 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2957 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2959 return memset(qemu_blockalign(bs, size), 0, size);
2962 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2964 size_t align = bdrv_opt_mem_align(bs);
2966 /* Ensure that NULL is never returned on success */
2967 assert(align > 0);
2968 if (size == 0) {
2969 size = align;
2972 return qemu_try_memalign(align, size);
2975 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2977 void *mem = qemu_try_blockalign(bs, size);
2979 if (mem) {
2980 memset(mem, 0, size);
2983 return mem;
2987 * Check if all memory in this vector is sector aligned.
2989 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2991 int i;
2992 size_t alignment = bdrv_min_mem_align(bs);
2994 for (i = 0; i < qiov->niov; i++) {
2995 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2996 return false;
2998 if (qiov->iov[i].iov_len % alignment) {
2999 return false;
3003 return true;
3006 void bdrv_add_before_write_notifier(BlockDriverState *bs,
3007 NotifierWithReturn *notifier)
3009 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
3012 void bdrv_io_plug(BlockDriverState *bs)
3014 BdrvChild *child;
3016 QLIST_FOREACH(child, &bs->children, next) {
3017 bdrv_io_plug(child->bs);
3020 if (qatomic_fetch_inc(&bs->io_plugged) == 0) {
3021 BlockDriver *drv = bs->drv;
3022 if (drv && drv->bdrv_io_plug) {
3023 drv->bdrv_io_plug(bs);
3028 void bdrv_io_unplug(BlockDriverState *bs)
3030 BdrvChild *child;
3032 assert(bs->io_plugged);
3033 if (qatomic_fetch_dec(&bs->io_plugged) == 1) {
3034 BlockDriver *drv = bs->drv;
3035 if (drv && drv->bdrv_io_unplug) {
3036 drv->bdrv_io_unplug(bs);
3040 QLIST_FOREACH(child, &bs->children, next) {
3041 bdrv_io_unplug(child->bs);
3045 void bdrv_register_buf(BlockDriverState *bs, void *host, size_t size)
3047 BdrvChild *child;
3049 if (bs->drv && bs->drv->bdrv_register_buf) {
3050 bs->drv->bdrv_register_buf(bs, host, size);
3052 QLIST_FOREACH(child, &bs->children, next) {
3053 bdrv_register_buf(child->bs, host, size);
3057 void bdrv_unregister_buf(BlockDriverState *bs, void *host)
3059 BdrvChild *child;
3061 if (bs->drv && bs->drv->bdrv_unregister_buf) {
3062 bs->drv->bdrv_unregister_buf(bs, host);
3064 QLIST_FOREACH(child, &bs->children, next) {
3065 bdrv_unregister_buf(child->bs, host);
3069 static int coroutine_fn bdrv_co_copy_range_internal(
3070 BdrvChild *src, uint64_t src_offset, BdrvChild *dst,
3071 uint64_t dst_offset, uint64_t bytes,
3072 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
3073 bool recurse_src)
3075 BdrvTrackedRequest req;
3076 int ret;
3078 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3079 assert(!(read_flags & BDRV_REQ_NO_FALLBACK));
3080 assert(!(write_flags & BDRV_REQ_NO_FALLBACK));
3082 if (!dst || !dst->bs || !bdrv_is_inserted(dst->bs)) {
3083 return -ENOMEDIUM;
3085 ret = bdrv_check_request32(dst_offset, bytes);
3086 if (ret) {
3087 return ret;
3089 if (write_flags & BDRV_REQ_ZERO_WRITE) {
3090 return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
3093 if (!src || !src->bs || !bdrv_is_inserted(src->bs)) {
3094 return -ENOMEDIUM;
3096 ret = bdrv_check_request32(src_offset, bytes);
3097 if (ret) {
3098 return ret;
3101 if (!src->bs->drv->bdrv_co_copy_range_from
3102 || !dst->bs->drv->bdrv_co_copy_range_to
3103 || src->bs->encrypted || dst->bs->encrypted) {
3104 return -ENOTSUP;
3107 if (recurse_src) {
3108 bdrv_inc_in_flight(src->bs);
3109 tracked_request_begin(&req, src->bs, src_offset, bytes,
3110 BDRV_TRACKED_READ);
3112 /* BDRV_REQ_SERIALISING is only for write operation */
3113 assert(!(read_flags & BDRV_REQ_SERIALISING));
3114 bdrv_wait_serialising_requests(&req);
3116 ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
3117 src, src_offset,
3118 dst, dst_offset,
3119 bytes,
3120 read_flags, write_flags);
3122 tracked_request_end(&req);
3123 bdrv_dec_in_flight(src->bs);
3124 } else {
3125 bdrv_inc_in_flight(dst->bs);
3126 tracked_request_begin(&req, dst->bs, dst_offset, bytes,
3127 BDRV_TRACKED_WRITE);
3128 ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3129 write_flags);
3130 if (!ret) {
3131 ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3132 src, src_offset,
3133 dst, dst_offset,
3134 bytes,
3135 read_flags, write_flags);
3137 bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
3138 tracked_request_end(&req);
3139 bdrv_dec_in_flight(dst->bs);
3142 return ret;
3145 /* Copy range from @src to @dst.
3147 * See the comment of bdrv_co_copy_range for the parameter and return value
3148 * semantics. */
3149 int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, uint64_t src_offset,
3150 BdrvChild *dst, uint64_t dst_offset,
3151 uint64_t bytes,
3152 BdrvRequestFlags read_flags,
3153 BdrvRequestFlags write_flags)
3155 trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3156 read_flags, write_flags);
3157 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3158 bytes, read_flags, write_flags, true);
3161 /* Copy range from @src to @dst.
3163 * See the comment of bdrv_co_copy_range for the parameter and return value
3164 * semantics. */
3165 int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, uint64_t src_offset,
3166 BdrvChild *dst, uint64_t dst_offset,
3167 uint64_t bytes,
3168 BdrvRequestFlags read_flags,
3169 BdrvRequestFlags write_flags)
3171 trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3172 read_flags, write_flags);
3173 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3174 bytes, read_flags, write_flags, false);
3177 int coroutine_fn bdrv_co_copy_range(BdrvChild *src, uint64_t src_offset,
3178 BdrvChild *dst, uint64_t dst_offset,
3179 uint64_t bytes, BdrvRequestFlags read_flags,
3180 BdrvRequestFlags write_flags)
3182 return bdrv_co_copy_range_from(src, src_offset,
3183 dst, dst_offset,
3184 bytes, read_flags, write_flags);
3187 static void bdrv_parent_cb_resize(BlockDriverState *bs)
3189 BdrvChild *c;
3190 QLIST_FOREACH(c, &bs->parents, next_parent) {
3191 if (c->klass->resize) {
3192 c->klass->resize(c);
3198 * Truncate file to 'offset' bytes (needed only for file protocols)
3200 * If 'exact' is true, the file must be resized to exactly the given
3201 * 'offset'. Otherwise, it is sufficient for the node to be at least
3202 * 'offset' bytes in length.
3204 int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset, bool exact,
3205 PreallocMode prealloc, BdrvRequestFlags flags,
3206 Error **errp)
3208 BlockDriverState *bs = child->bs;
3209 BdrvChild *filtered, *backing;
3210 BlockDriver *drv = bs->drv;
3211 BdrvTrackedRequest req;
3212 int64_t old_size, new_bytes;
3213 int ret;
3216 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3217 if (!drv) {
3218 error_setg(errp, "No medium inserted");
3219 return -ENOMEDIUM;
3221 if (offset < 0) {
3222 error_setg(errp, "Image size cannot be negative");
3223 return -EINVAL;
3226 ret = bdrv_check_request(offset, 0);
3227 if (ret < 0) {
3228 error_setg(errp, "Required too big image size, it must be not greater "
3229 "than %" PRId64, BDRV_MAX_LENGTH);
3230 return ret;
3233 old_size = bdrv_getlength(bs);
3234 if (old_size < 0) {
3235 error_setg_errno(errp, -old_size, "Failed to get old image size");
3236 return old_size;
3239 if (offset > old_size) {
3240 new_bytes = offset - old_size;
3241 } else {
3242 new_bytes = 0;
3245 bdrv_inc_in_flight(bs);
3246 tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3247 BDRV_TRACKED_TRUNCATE);
3249 /* If we are growing the image and potentially using preallocation for the
3250 * new area, we need to make sure that no write requests are made to it
3251 * concurrently or they might be overwritten by preallocation. */
3252 if (new_bytes) {
3253 bdrv_mark_request_serialising(&req, 1);
3255 if (bs->read_only) {
3256 error_setg(errp, "Image is read-only");
3257 ret = -EACCES;
3258 goto out;
3260 ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3262 if (ret < 0) {
3263 error_setg_errno(errp, -ret,
3264 "Failed to prepare request for truncation");
3265 goto out;
3268 filtered = bdrv_filter_child(bs);
3269 backing = bdrv_cow_child(bs);
3272 * If the image has a backing file that is large enough that it would
3273 * provide data for the new area, we cannot leave it unallocated because
3274 * then the backing file content would become visible. Instead, zero-fill
3275 * the new area.
3277 * Note that if the image has a backing file, but was opened without the
3278 * backing file, taking care of keeping things consistent with that backing
3279 * file is the user's responsibility.
3281 if (new_bytes && backing) {
3282 int64_t backing_len;
3284 backing_len = bdrv_getlength(backing->bs);
3285 if (backing_len < 0) {
3286 ret = backing_len;
3287 error_setg_errno(errp, -ret, "Could not get backing file size");
3288 goto out;
3291 if (backing_len > old_size) {
3292 flags |= BDRV_REQ_ZERO_WRITE;
3296 if (drv->bdrv_co_truncate) {
3297 if (flags & ~bs->supported_truncate_flags) {
3298 error_setg(errp, "Block driver does not support requested flags");
3299 ret = -ENOTSUP;
3300 goto out;
3302 ret = drv->bdrv_co_truncate(bs, offset, exact, prealloc, flags, errp);
3303 } else if (filtered) {
3304 ret = bdrv_co_truncate(filtered, offset, exact, prealloc, flags, errp);
3305 } else {
3306 error_setg(errp, "Image format driver does not support resize");
3307 ret = -ENOTSUP;
3308 goto out;
3310 if (ret < 0) {
3311 goto out;
3314 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3315 if (ret < 0) {
3316 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3317 } else {
3318 offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3320 /* It's possible that truncation succeeded but refresh_total_sectors
3321 * failed, but the latter doesn't affect how we should finish the request.
3322 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3323 bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3325 out:
3326 tracked_request_end(&req);
3327 bdrv_dec_in_flight(bs);
3329 return ret;