mirror: Check job_is_cancelled() earlier
[qemu/armbru.git] / block / io.c
blob18d345a87af3cdf7c28ea887bc70b403f28f64ce
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/write-threshold.h"
34 #include "qemu/cutils.h"
35 #include "qapi/error.h"
36 #include "qemu/error-report.h"
37 #include "qemu/main-loop.h"
38 #include "sysemu/replay.h"
40 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
41 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
43 static void bdrv_parent_cb_resize(BlockDriverState *bs);
44 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
45 int64_t offset, int64_t bytes, BdrvRequestFlags flags);
47 static void bdrv_parent_drained_begin(BlockDriverState *bs, BdrvChild *ignore,
48 bool ignore_bds_parents)
50 BdrvChild *c, *next;
52 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
53 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
54 continue;
56 bdrv_parent_drained_begin_single(c, false);
60 static void bdrv_parent_drained_end_single_no_poll(BdrvChild *c,
61 int *drained_end_counter)
63 assert(c->parent_quiesce_counter > 0);
64 c->parent_quiesce_counter--;
65 if (c->klass->drained_end) {
66 c->klass->drained_end(c, drained_end_counter);
70 void bdrv_parent_drained_end_single(BdrvChild *c)
72 int drained_end_counter = 0;
73 bdrv_parent_drained_end_single_no_poll(c, &drained_end_counter);
74 BDRV_POLL_WHILE(c->bs, qatomic_read(&drained_end_counter) > 0);
77 static void bdrv_parent_drained_end(BlockDriverState *bs, BdrvChild *ignore,
78 bool ignore_bds_parents,
79 int *drained_end_counter)
81 BdrvChild *c;
83 QLIST_FOREACH(c, &bs->parents, next_parent) {
84 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
85 continue;
87 bdrv_parent_drained_end_single_no_poll(c, drained_end_counter);
91 static bool bdrv_parent_drained_poll_single(BdrvChild *c)
93 if (c->klass->drained_poll) {
94 return c->klass->drained_poll(c);
96 return false;
99 static bool bdrv_parent_drained_poll(BlockDriverState *bs, BdrvChild *ignore,
100 bool ignore_bds_parents)
102 BdrvChild *c, *next;
103 bool busy = false;
105 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
106 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
107 continue;
109 busy |= bdrv_parent_drained_poll_single(c);
112 return busy;
115 void bdrv_parent_drained_begin_single(BdrvChild *c, bool poll)
117 c->parent_quiesce_counter++;
118 if (c->klass->drained_begin) {
119 c->klass->drained_begin(c);
121 if (poll) {
122 BDRV_POLL_WHILE(c->bs, bdrv_parent_drained_poll_single(c));
126 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
128 dst->pdiscard_alignment = MAX(dst->pdiscard_alignment,
129 src->pdiscard_alignment);
130 dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
131 dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer);
132 dst->max_hw_transfer = MIN_NON_ZERO(dst->max_hw_transfer,
133 src->max_hw_transfer);
134 dst->opt_mem_alignment = MAX(dst->opt_mem_alignment,
135 src->opt_mem_alignment);
136 dst->min_mem_alignment = MAX(dst->min_mem_alignment,
137 src->min_mem_alignment);
138 dst->max_iov = MIN_NON_ZERO(dst->max_iov, src->max_iov);
141 typedef struct BdrvRefreshLimitsState {
142 BlockDriverState *bs;
143 BlockLimits old_bl;
144 } BdrvRefreshLimitsState;
146 static void bdrv_refresh_limits_abort(void *opaque)
148 BdrvRefreshLimitsState *s = opaque;
150 s->bs->bl = s->old_bl;
153 static TransactionActionDrv bdrv_refresh_limits_drv = {
154 .abort = bdrv_refresh_limits_abort,
155 .clean = g_free,
158 /* @tran is allowed to be NULL, in this case no rollback is possible. */
159 void bdrv_refresh_limits(BlockDriverState *bs, Transaction *tran, Error **errp)
161 ERRP_GUARD();
162 BlockDriver *drv = bs->drv;
163 BdrvChild *c;
164 bool have_limits;
166 if (tran) {
167 BdrvRefreshLimitsState *s = g_new(BdrvRefreshLimitsState, 1);
168 *s = (BdrvRefreshLimitsState) {
169 .bs = bs,
170 .old_bl = bs->bl,
172 tran_add(tran, &bdrv_refresh_limits_drv, s);
175 memset(&bs->bl, 0, sizeof(bs->bl));
177 if (!drv) {
178 return;
181 /* Default alignment based on whether driver has byte interface */
182 bs->bl.request_alignment = (drv->bdrv_co_preadv ||
183 drv->bdrv_aio_preadv ||
184 drv->bdrv_co_preadv_part) ? 1 : 512;
186 /* Take some limits from the children as a default */
187 have_limits = false;
188 QLIST_FOREACH(c, &bs->children, next) {
189 if (c->role & (BDRV_CHILD_DATA | BDRV_CHILD_FILTERED | BDRV_CHILD_COW))
191 bdrv_refresh_limits(c->bs, tran, errp);
192 if (*errp) {
193 return;
195 bdrv_merge_limits(&bs->bl, &c->bs->bl);
196 have_limits = true;
200 if (!have_limits) {
201 bs->bl.min_mem_alignment = 512;
202 bs->bl.opt_mem_alignment = qemu_real_host_page_size;
204 /* Safe default since most protocols use readv()/writev()/etc */
205 bs->bl.max_iov = IOV_MAX;
208 /* Then let the driver override it */
209 if (drv->bdrv_refresh_limits) {
210 drv->bdrv_refresh_limits(bs, errp);
211 if (*errp) {
212 return;
216 if (bs->bl.request_alignment > BDRV_MAX_ALIGNMENT) {
217 error_setg(errp, "Driver requires too large request alignment");
222 * The copy-on-read flag is actually a reference count so multiple users may
223 * use the feature without worrying about clobbering its previous state.
224 * Copy-on-read stays enabled until all users have called to disable it.
226 void bdrv_enable_copy_on_read(BlockDriverState *bs)
228 qatomic_inc(&bs->copy_on_read);
231 void bdrv_disable_copy_on_read(BlockDriverState *bs)
233 int old = qatomic_fetch_dec(&bs->copy_on_read);
234 assert(old >= 1);
237 typedef struct {
238 Coroutine *co;
239 BlockDriverState *bs;
240 bool done;
241 bool begin;
242 bool recursive;
243 bool poll;
244 BdrvChild *parent;
245 bool ignore_bds_parents;
246 int *drained_end_counter;
247 } BdrvCoDrainData;
249 static void coroutine_fn bdrv_drain_invoke_entry(void *opaque)
251 BdrvCoDrainData *data = opaque;
252 BlockDriverState *bs = data->bs;
254 if (data->begin) {
255 bs->drv->bdrv_co_drain_begin(bs);
256 } else {
257 bs->drv->bdrv_co_drain_end(bs);
260 /* Set data->done and decrement drained_end_counter before bdrv_wakeup() */
261 qatomic_mb_set(&data->done, true);
262 if (!data->begin) {
263 qatomic_dec(data->drained_end_counter);
265 bdrv_dec_in_flight(bs);
267 g_free(data);
270 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
271 static void bdrv_drain_invoke(BlockDriverState *bs, bool begin,
272 int *drained_end_counter)
274 BdrvCoDrainData *data;
276 if (!bs->drv || (begin && !bs->drv->bdrv_co_drain_begin) ||
277 (!begin && !bs->drv->bdrv_co_drain_end)) {
278 return;
281 data = g_new(BdrvCoDrainData, 1);
282 *data = (BdrvCoDrainData) {
283 .bs = bs,
284 .done = false,
285 .begin = begin,
286 .drained_end_counter = drained_end_counter,
289 if (!begin) {
290 qatomic_inc(drained_end_counter);
293 /* Make sure the driver callback completes during the polling phase for
294 * drain_begin. */
295 bdrv_inc_in_flight(bs);
296 data->co = qemu_coroutine_create(bdrv_drain_invoke_entry, data);
297 aio_co_schedule(bdrv_get_aio_context(bs), data->co);
300 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
301 bool bdrv_drain_poll(BlockDriverState *bs, bool recursive,
302 BdrvChild *ignore_parent, bool ignore_bds_parents)
304 BdrvChild *child, *next;
306 if (bdrv_parent_drained_poll(bs, ignore_parent, ignore_bds_parents)) {
307 return true;
310 if (qatomic_read(&bs->in_flight)) {
311 return true;
314 if (recursive) {
315 assert(!ignore_bds_parents);
316 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
317 if (bdrv_drain_poll(child->bs, recursive, child, false)) {
318 return true;
323 return false;
326 static bool bdrv_drain_poll_top_level(BlockDriverState *bs, bool recursive,
327 BdrvChild *ignore_parent)
329 return bdrv_drain_poll(bs, recursive, ignore_parent, false);
332 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
333 BdrvChild *parent, bool ignore_bds_parents,
334 bool poll);
335 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
336 BdrvChild *parent, bool ignore_bds_parents,
337 int *drained_end_counter);
339 static void bdrv_co_drain_bh_cb(void *opaque)
341 BdrvCoDrainData *data = opaque;
342 Coroutine *co = data->co;
343 BlockDriverState *bs = data->bs;
345 if (bs) {
346 AioContext *ctx = bdrv_get_aio_context(bs);
347 aio_context_acquire(ctx);
348 bdrv_dec_in_flight(bs);
349 if (data->begin) {
350 assert(!data->drained_end_counter);
351 bdrv_do_drained_begin(bs, data->recursive, data->parent,
352 data->ignore_bds_parents, data->poll);
353 } else {
354 assert(!data->poll);
355 bdrv_do_drained_end(bs, data->recursive, data->parent,
356 data->ignore_bds_parents,
357 data->drained_end_counter);
359 aio_context_release(ctx);
360 } else {
361 assert(data->begin);
362 bdrv_drain_all_begin();
365 data->done = true;
366 aio_co_wake(co);
369 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs,
370 bool begin, bool recursive,
371 BdrvChild *parent,
372 bool ignore_bds_parents,
373 bool poll,
374 int *drained_end_counter)
376 BdrvCoDrainData data;
377 Coroutine *self = qemu_coroutine_self();
378 AioContext *ctx = bdrv_get_aio_context(bs);
379 AioContext *co_ctx = qemu_coroutine_get_aio_context(self);
381 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
382 * other coroutines run if they were queued by aio_co_enter(). */
384 assert(qemu_in_coroutine());
385 data = (BdrvCoDrainData) {
386 .co = self,
387 .bs = bs,
388 .done = false,
389 .begin = begin,
390 .recursive = recursive,
391 .parent = parent,
392 .ignore_bds_parents = ignore_bds_parents,
393 .poll = poll,
394 .drained_end_counter = drained_end_counter,
397 if (bs) {
398 bdrv_inc_in_flight(bs);
402 * Temporarily drop the lock across yield or we would get deadlocks.
403 * bdrv_co_drain_bh_cb() reaquires the lock as needed.
405 * When we yield below, the lock for the current context will be
406 * released, so if this is actually the lock that protects bs, don't drop
407 * it a second time.
409 if (ctx != co_ctx) {
410 aio_context_release(ctx);
412 replay_bh_schedule_oneshot_event(ctx, bdrv_co_drain_bh_cb, &data);
414 qemu_coroutine_yield();
415 /* If we are resumed from some other event (such as an aio completion or a
416 * timer callback), it is a bug in the caller that should be fixed. */
417 assert(data.done);
419 /* Reaquire the AioContext of bs if we dropped it */
420 if (ctx != co_ctx) {
421 aio_context_acquire(ctx);
425 void bdrv_do_drained_begin_quiesce(BlockDriverState *bs,
426 BdrvChild *parent, bool ignore_bds_parents)
428 assert(!qemu_in_coroutine());
430 /* Stop things in parent-to-child order */
431 if (qatomic_fetch_inc(&bs->quiesce_counter) == 0) {
432 aio_disable_external(bdrv_get_aio_context(bs));
435 bdrv_parent_drained_begin(bs, parent, ignore_bds_parents);
436 bdrv_drain_invoke(bs, true, NULL);
439 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
440 BdrvChild *parent, bool ignore_bds_parents,
441 bool poll)
443 BdrvChild *child, *next;
445 if (qemu_in_coroutine()) {
446 bdrv_co_yield_to_drain(bs, true, recursive, parent, ignore_bds_parents,
447 poll, NULL);
448 return;
451 bdrv_do_drained_begin_quiesce(bs, parent, ignore_bds_parents);
453 if (recursive) {
454 assert(!ignore_bds_parents);
455 bs->recursive_quiesce_counter++;
456 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
457 bdrv_do_drained_begin(child->bs, true, child, ignore_bds_parents,
458 false);
463 * Wait for drained requests to finish.
465 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
466 * call is needed so things in this AioContext can make progress even
467 * though we don't return to the main AioContext loop - this automatically
468 * includes other nodes in the same AioContext and therefore all child
469 * nodes.
471 if (poll) {
472 assert(!ignore_bds_parents);
473 BDRV_POLL_WHILE(bs, bdrv_drain_poll_top_level(bs, recursive, parent));
477 void bdrv_drained_begin(BlockDriverState *bs)
479 bdrv_do_drained_begin(bs, false, NULL, false, true);
482 void bdrv_subtree_drained_begin(BlockDriverState *bs)
484 bdrv_do_drained_begin(bs, true, NULL, false, true);
488 * This function does not poll, nor must any of its recursively called
489 * functions. The *drained_end_counter pointee will be incremented
490 * once for every background operation scheduled, and decremented once
491 * the operation settles. Therefore, the pointer must remain valid
492 * until the pointee reaches 0. That implies that whoever sets up the
493 * pointee has to poll until it is 0.
495 * We use atomic operations to access *drained_end_counter, because
496 * (1) when called from bdrv_set_aio_context_ignore(), the subgraph of
497 * @bs may contain nodes in different AioContexts,
498 * (2) bdrv_drain_all_end() uses the same counter for all nodes,
499 * regardless of which AioContext they are in.
501 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
502 BdrvChild *parent, bool ignore_bds_parents,
503 int *drained_end_counter)
505 BdrvChild *child;
506 int old_quiesce_counter;
508 assert(drained_end_counter != NULL);
510 if (qemu_in_coroutine()) {
511 bdrv_co_yield_to_drain(bs, false, recursive, parent, ignore_bds_parents,
512 false, drained_end_counter);
513 return;
515 assert(bs->quiesce_counter > 0);
517 /* Re-enable things in child-to-parent order */
518 bdrv_drain_invoke(bs, false, drained_end_counter);
519 bdrv_parent_drained_end(bs, parent, ignore_bds_parents,
520 drained_end_counter);
522 old_quiesce_counter = qatomic_fetch_dec(&bs->quiesce_counter);
523 if (old_quiesce_counter == 1) {
524 aio_enable_external(bdrv_get_aio_context(bs));
527 if (recursive) {
528 assert(!ignore_bds_parents);
529 bs->recursive_quiesce_counter--;
530 QLIST_FOREACH(child, &bs->children, next) {
531 bdrv_do_drained_end(child->bs, true, child, ignore_bds_parents,
532 drained_end_counter);
537 void bdrv_drained_end(BlockDriverState *bs)
539 int drained_end_counter = 0;
540 bdrv_do_drained_end(bs, false, NULL, false, &drained_end_counter);
541 BDRV_POLL_WHILE(bs, qatomic_read(&drained_end_counter) > 0);
544 void bdrv_drained_end_no_poll(BlockDriverState *bs, int *drained_end_counter)
546 bdrv_do_drained_end(bs, false, NULL, false, drained_end_counter);
549 void bdrv_subtree_drained_end(BlockDriverState *bs)
551 int drained_end_counter = 0;
552 bdrv_do_drained_end(bs, true, NULL, false, &drained_end_counter);
553 BDRV_POLL_WHILE(bs, qatomic_read(&drained_end_counter) > 0);
556 void bdrv_apply_subtree_drain(BdrvChild *child, BlockDriverState *new_parent)
558 int i;
560 for (i = 0; i < new_parent->recursive_quiesce_counter; i++) {
561 bdrv_do_drained_begin(child->bs, true, child, false, true);
565 void bdrv_unapply_subtree_drain(BdrvChild *child, BlockDriverState *old_parent)
567 int drained_end_counter = 0;
568 int i;
570 for (i = 0; i < old_parent->recursive_quiesce_counter; i++) {
571 bdrv_do_drained_end(child->bs, true, child, false,
572 &drained_end_counter);
575 BDRV_POLL_WHILE(child->bs, qatomic_read(&drained_end_counter) > 0);
579 * Wait for pending requests to complete on a single BlockDriverState subtree,
580 * and suspend block driver's internal I/O until next request arrives.
582 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
583 * AioContext.
585 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
587 assert(qemu_in_coroutine());
588 bdrv_drained_begin(bs);
589 bdrv_drained_end(bs);
592 void bdrv_drain(BlockDriverState *bs)
594 bdrv_drained_begin(bs);
595 bdrv_drained_end(bs);
598 static void bdrv_drain_assert_idle(BlockDriverState *bs)
600 BdrvChild *child, *next;
602 assert(qatomic_read(&bs->in_flight) == 0);
603 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
604 bdrv_drain_assert_idle(child->bs);
608 unsigned int bdrv_drain_all_count = 0;
610 static bool bdrv_drain_all_poll(void)
612 BlockDriverState *bs = NULL;
613 bool result = false;
615 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
616 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
617 while ((bs = bdrv_next_all_states(bs))) {
618 AioContext *aio_context = bdrv_get_aio_context(bs);
619 aio_context_acquire(aio_context);
620 result |= bdrv_drain_poll(bs, false, NULL, true);
621 aio_context_release(aio_context);
624 return result;
628 * Wait for pending requests to complete across all BlockDriverStates
630 * This function does not flush data to disk, use bdrv_flush_all() for that
631 * after calling this function.
633 * This pauses all block jobs and disables external clients. It must
634 * be paired with bdrv_drain_all_end().
636 * NOTE: no new block jobs or BlockDriverStates can be created between
637 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
639 void bdrv_drain_all_begin(void)
641 BlockDriverState *bs = NULL;
643 if (qemu_in_coroutine()) {
644 bdrv_co_yield_to_drain(NULL, true, false, NULL, true, true, NULL);
645 return;
649 * bdrv queue is managed by record/replay,
650 * waiting for finishing the I/O requests may
651 * be infinite
653 if (replay_events_enabled()) {
654 return;
657 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
658 * loop AioContext, so make sure we're in the main context. */
659 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
660 assert(bdrv_drain_all_count < INT_MAX);
661 bdrv_drain_all_count++;
663 /* Quiesce all nodes, without polling in-flight requests yet. The graph
664 * cannot change during this loop. */
665 while ((bs = bdrv_next_all_states(bs))) {
666 AioContext *aio_context = bdrv_get_aio_context(bs);
668 aio_context_acquire(aio_context);
669 bdrv_do_drained_begin(bs, false, NULL, true, false);
670 aio_context_release(aio_context);
673 /* Now poll the in-flight requests */
674 AIO_WAIT_WHILE(NULL, bdrv_drain_all_poll());
676 while ((bs = bdrv_next_all_states(bs))) {
677 bdrv_drain_assert_idle(bs);
681 void bdrv_drain_all_end_quiesce(BlockDriverState *bs)
683 int drained_end_counter = 0;
685 g_assert(bs->quiesce_counter > 0);
686 g_assert(!bs->refcnt);
688 while (bs->quiesce_counter) {
689 bdrv_do_drained_end(bs, false, NULL, true, &drained_end_counter);
691 BDRV_POLL_WHILE(bs, qatomic_read(&drained_end_counter) > 0);
694 void bdrv_drain_all_end(void)
696 BlockDriverState *bs = NULL;
697 int drained_end_counter = 0;
700 * bdrv queue is managed by record/replay,
701 * waiting for finishing the I/O requests may
702 * be endless
704 if (replay_events_enabled()) {
705 return;
708 while ((bs = bdrv_next_all_states(bs))) {
709 AioContext *aio_context = bdrv_get_aio_context(bs);
711 aio_context_acquire(aio_context);
712 bdrv_do_drained_end(bs, false, NULL, true, &drained_end_counter);
713 aio_context_release(aio_context);
716 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
717 AIO_WAIT_WHILE(NULL, qatomic_read(&drained_end_counter) > 0);
719 assert(bdrv_drain_all_count > 0);
720 bdrv_drain_all_count--;
723 void bdrv_drain_all(void)
725 bdrv_drain_all_begin();
726 bdrv_drain_all_end();
730 * Remove an active request from the tracked requests list
732 * This function should be called when a tracked request is completing.
734 static void tracked_request_end(BdrvTrackedRequest *req)
736 if (req->serialising) {
737 qatomic_dec(&req->bs->serialising_in_flight);
740 qemu_co_mutex_lock(&req->bs->reqs_lock);
741 QLIST_REMOVE(req, list);
742 qemu_co_queue_restart_all(&req->wait_queue);
743 qemu_co_mutex_unlock(&req->bs->reqs_lock);
747 * Add an active request to the tracked requests list
749 static void tracked_request_begin(BdrvTrackedRequest *req,
750 BlockDriverState *bs,
751 int64_t offset,
752 int64_t bytes,
753 enum BdrvTrackedRequestType type)
755 bdrv_check_request(offset, bytes, &error_abort);
757 *req = (BdrvTrackedRequest){
758 .bs = bs,
759 .offset = offset,
760 .bytes = bytes,
761 .type = type,
762 .co = qemu_coroutine_self(),
763 .serialising = false,
764 .overlap_offset = offset,
765 .overlap_bytes = bytes,
768 qemu_co_queue_init(&req->wait_queue);
770 qemu_co_mutex_lock(&bs->reqs_lock);
771 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
772 qemu_co_mutex_unlock(&bs->reqs_lock);
775 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
776 int64_t offset, int64_t bytes)
778 bdrv_check_request(offset, bytes, &error_abort);
780 /* aaaa bbbb */
781 if (offset >= req->overlap_offset + req->overlap_bytes) {
782 return false;
784 /* bbbb aaaa */
785 if (req->overlap_offset >= offset + bytes) {
786 return false;
788 return true;
791 /* Called with self->bs->reqs_lock held */
792 static BdrvTrackedRequest *
793 bdrv_find_conflicting_request(BdrvTrackedRequest *self)
795 BdrvTrackedRequest *req;
797 QLIST_FOREACH(req, &self->bs->tracked_requests, list) {
798 if (req == self || (!req->serialising && !self->serialising)) {
799 continue;
801 if (tracked_request_overlaps(req, self->overlap_offset,
802 self->overlap_bytes))
805 * Hitting this means there was a reentrant request, for
806 * example, a block driver issuing nested requests. This must
807 * never happen since it means deadlock.
809 assert(qemu_coroutine_self() != req->co);
812 * If the request is already (indirectly) waiting for us, or
813 * will wait for us as soon as it wakes up, then just go on
814 * (instead of producing a deadlock in the former case).
816 if (!req->waiting_for) {
817 return req;
822 return NULL;
825 /* Called with self->bs->reqs_lock held */
826 static bool coroutine_fn
827 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest *self)
829 BdrvTrackedRequest *req;
830 bool waited = false;
832 while ((req = bdrv_find_conflicting_request(self))) {
833 self->waiting_for = req;
834 qemu_co_queue_wait(&req->wait_queue, &self->bs->reqs_lock);
835 self->waiting_for = NULL;
836 waited = true;
839 return waited;
842 /* Called with req->bs->reqs_lock held */
843 static void tracked_request_set_serialising(BdrvTrackedRequest *req,
844 uint64_t align)
846 int64_t overlap_offset = req->offset & ~(align - 1);
847 int64_t overlap_bytes =
848 ROUND_UP(req->offset + req->bytes, align) - overlap_offset;
850 bdrv_check_request(req->offset, req->bytes, &error_abort);
852 if (!req->serialising) {
853 qatomic_inc(&req->bs->serialising_in_flight);
854 req->serialising = true;
857 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
858 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
862 * Return the tracked request on @bs for the current coroutine, or
863 * NULL if there is none.
865 BdrvTrackedRequest *coroutine_fn bdrv_co_get_self_request(BlockDriverState *bs)
867 BdrvTrackedRequest *req;
868 Coroutine *self = qemu_coroutine_self();
870 QLIST_FOREACH(req, &bs->tracked_requests, list) {
871 if (req->co == self) {
872 return req;
876 return NULL;
880 * Round a region to cluster boundaries
882 void bdrv_round_to_clusters(BlockDriverState *bs,
883 int64_t offset, int64_t bytes,
884 int64_t *cluster_offset,
885 int64_t *cluster_bytes)
887 BlockDriverInfo bdi;
889 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
890 *cluster_offset = offset;
891 *cluster_bytes = bytes;
892 } else {
893 int64_t c = bdi.cluster_size;
894 *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
895 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
899 static int bdrv_get_cluster_size(BlockDriverState *bs)
901 BlockDriverInfo bdi;
902 int ret;
904 ret = bdrv_get_info(bs, &bdi);
905 if (ret < 0 || bdi.cluster_size == 0) {
906 return bs->bl.request_alignment;
907 } else {
908 return bdi.cluster_size;
912 void bdrv_inc_in_flight(BlockDriverState *bs)
914 qatomic_inc(&bs->in_flight);
917 void bdrv_wakeup(BlockDriverState *bs)
919 aio_wait_kick();
922 void bdrv_dec_in_flight(BlockDriverState *bs)
924 qatomic_dec(&bs->in_flight);
925 bdrv_wakeup(bs);
928 static bool coroutine_fn bdrv_wait_serialising_requests(BdrvTrackedRequest *self)
930 BlockDriverState *bs = self->bs;
931 bool waited = false;
933 if (!qatomic_read(&bs->serialising_in_flight)) {
934 return false;
937 qemu_co_mutex_lock(&bs->reqs_lock);
938 waited = bdrv_wait_serialising_requests_locked(self);
939 qemu_co_mutex_unlock(&bs->reqs_lock);
941 return waited;
944 bool coroutine_fn bdrv_make_request_serialising(BdrvTrackedRequest *req,
945 uint64_t align)
947 bool waited;
949 qemu_co_mutex_lock(&req->bs->reqs_lock);
951 tracked_request_set_serialising(req, align);
952 waited = bdrv_wait_serialising_requests_locked(req);
954 qemu_co_mutex_unlock(&req->bs->reqs_lock);
956 return waited;
959 int bdrv_check_qiov_request(int64_t offset, int64_t bytes,
960 QEMUIOVector *qiov, size_t qiov_offset,
961 Error **errp)
964 * Check generic offset/bytes correctness
967 if (offset < 0) {
968 error_setg(errp, "offset is negative: %" PRIi64, offset);
969 return -EIO;
972 if (bytes < 0) {
973 error_setg(errp, "bytes is negative: %" PRIi64, bytes);
974 return -EIO;
977 if (bytes > BDRV_MAX_LENGTH) {
978 error_setg(errp, "bytes(%" PRIi64 ") exceeds maximum(%" PRIi64 ")",
979 bytes, BDRV_MAX_LENGTH);
980 return -EIO;
983 if (offset > BDRV_MAX_LENGTH) {
984 error_setg(errp, "offset(%" PRIi64 ") exceeds maximum(%" PRIi64 ")",
985 offset, BDRV_MAX_LENGTH);
986 return -EIO;
989 if (offset > BDRV_MAX_LENGTH - bytes) {
990 error_setg(errp, "sum of offset(%" PRIi64 ") and bytes(%" PRIi64 ") "
991 "exceeds maximum(%" PRIi64 ")", offset, bytes,
992 BDRV_MAX_LENGTH);
993 return -EIO;
996 if (!qiov) {
997 return 0;
1001 * Check qiov and qiov_offset
1004 if (qiov_offset > qiov->size) {
1005 error_setg(errp, "qiov_offset(%zu) overflow io vector size(%zu)",
1006 qiov_offset, qiov->size);
1007 return -EIO;
1010 if (bytes > qiov->size - qiov_offset) {
1011 error_setg(errp, "bytes(%" PRIi64 ") + qiov_offset(%zu) overflow io "
1012 "vector size(%zu)", bytes, qiov_offset, qiov->size);
1013 return -EIO;
1016 return 0;
1019 int bdrv_check_request(int64_t offset, int64_t bytes, Error **errp)
1021 return bdrv_check_qiov_request(offset, bytes, NULL, 0, errp);
1024 static int bdrv_check_request32(int64_t offset, int64_t bytes,
1025 QEMUIOVector *qiov, size_t qiov_offset)
1027 int ret = bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, NULL);
1028 if (ret < 0) {
1029 return ret;
1032 if (bytes > BDRV_REQUEST_MAX_BYTES) {
1033 return -EIO;
1036 return 0;
1039 int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
1040 int64_t bytes, BdrvRequestFlags flags)
1042 return bdrv_pwritev(child, offset, bytes, NULL,
1043 BDRV_REQ_ZERO_WRITE | flags);
1047 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
1048 * The operation is sped up by checking the block status and only writing
1049 * zeroes to the device if they currently do not return zeroes. Optional
1050 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
1051 * BDRV_REQ_FUA).
1053 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
1055 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
1057 int ret;
1058 int64_t target_size, bytes, offset = 0;
1059 BlockDriverState *bs = child->bs;
1061 target_size = bdrv_getlength(bs);
1062 if (target_size < 0) {
1063 return target_size;
1066 for (;;) {
1067 bytes = MIN(target_size - offset, BDRV_REQUEST_MAX_BYTES);
1068 if (bytes <= 0) {
1069 return 0;
1071 ret = bdrv_block_status(bs, offset, bytes, &bytes, NULL, NULL);
1072 if (ret < 0) {
1073 return ret;
1075 if (ret & BDRV_BLOCK_ZERO) {
1076 offset += bytes;
1077 continue;
1079 ret = bdrv_pwrite_zeroes(child, offset, bytes, flags);
1080 if (ret < 0) {
1081 return ret;
1083 offset += bytes;
1087 /* See bdrv_pwrite() for the return codes */
1088 int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int64_t bytes)
1090 int ret;
1091 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
1093 if (bytes < 0) {
1094 return -EINVAL;
1097 ret = bdrv_preadv(child, offset, bytes, &qiov, 0);
1099 return ret < 0 ? ret : bytes;
1102 /* Return no. of bytes on success or < 0 on error. Important errors are:
1103 -EIO generic I/O error (may happen for all errors)
1104 -ENOMEDIUM No media inserted.
1105 -EINVAL Invalid offset or number of bytes
1106 -EACCES Trying to write a read-only device
1108 int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf,
1109 int64_t bytes)
1111 int ret;
1112 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
1114 if (bytes < 0) {
1115 return -EINVAL;
1118 ret = bdrv_pwritev(child, offset, bytes, &qiov, 0);
1120 return ret < 0 ? ret : bytes;
1124 * Writes to the file and ensures that no writes are reordered across this
1125 * request (acts as a barrier)
1127 * Returns 0 on success, -errno in error cases.
1129 int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
1130 const void *buf, int64_t count)
1132 int ret;
1134 ret = bdrv_pwrite(child, offset, buf, count);
1135 if (ret < 0) {
1136 return ret;
1139 ret = bdrv_flush(child->bs);
1140 if (ret < 0) {
1141 return ret;
1144 return 0;
1147 typedef struct CoroutineIOCompletion {
1148 Coroutine *coroutine;
1149 int ret;
1150 } CoroutineIOCompletion;
1152 static void bdrv_co_io_em_complete(void *opaque, int ret)
1154 CoroutineIOCompletion *co = opaque;
1156 co->ret = ret;
1157 aio_co_wake(co->coroutine);
1160 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
1161 int64_t offset, int64_t bytes,
1162 QEMUIOVector *qiov,
1163 size_t qiov_offset, int flags)
1165 BlockDriver *drv = bs->drv;
1166 int64_t sector_num;
1167 unsigned int nb_sectors;
1168 QEMUIOVector local_qiov;
1169 int ret;
1171 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1172 assert(!(flags & ~BDRV_REQ_MASK));
1173 assert(!(flags & BDRV_REQ_NO_FALLBACK));
1175 if (!drv) {
1176 return -ENOMEDIUM;
1179 if (drv->bdrv_co_preadv_part) {
1180 return drv->bdrv_co_preadv_part(bs, offset, bytes, qiov, qiov_offset,
1181 flags);
1184 if (qiov_offset > 0 || bytes != qiov->size) {
1185 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1186 qiov = &local_qiov;
1189 if (drv->bdrv_co_preadv) {
1190 ret = drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
1191 goto out;
1194 if (drv->bdrv_aio_preadv) {
1195 BlockAIOCB *acb;
1196 CoroutineIOCompletion co = {
1197 .coroutine = qemu_coroutine_self(),
1200 acb = drv->bdrv_aio_preadv(bs, offset, bytes, qiov, flags,
1201 bdrv_co_io_em_complete, &co);
1202 if (acb == NULL) {
1203 ret = -EIO;
1204 goto out;
1205 } else {
1206 qemu_coroutine_yield();
1207 ret = co.ret;
1208 goto out;
1212 sector_num = offset >> BDRV_SECTOR_BITS;
1213 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1215 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1216 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1217 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1218 assert(drv->bdrv_co_readv);
1220 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1222 out:
1223 if (qiov == &local_qiov) {
1224 qemu_iovec_destroy(&local_qiov);
1227 return ret;
1230 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
1231 int64_t offset, int64_t bytes,
1232 QEMUIOVector *qiov,
1233 size_t qiov_offset,
1234 BdrvRequestFlags flags)
1236 BlockDriver *drv = bs->drv;
1237 int64_t sector_num;
1238 unsigned int nb_sectors;
1239 QEMUIOVector local_qiov;
1240 int ret;
1242 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1243 assert(!(flags & ~BDRV_REQ_MASK));
1244 assert(!(flags & BDRV_REQ_NO_FALLBACK));
1246 if (!drv) {
1247 return -ENOMEDIUM;
1250 if (drv->bdrv_co_pwritev_part) {
1251 ret = drv->bdrv_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset,
1252 flags & bs->supported_write_flags);
1253 flags &= ~bs->supported_write_flags;
1254 goto emulate_flags;
1257 if (qiov_offset > 0 || bytes != qiov->size) {
1258 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1259 qiov = &local_qiov;
1262 if (drv->bdrv_co_pwritev) {
1263 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
1264 flags & bs->supported_write_flags);
1265 flags &= ~bs->supported_write_flags;
1266 goto emulate_flags;
1269 if (drv->bdrv_aio_pwritev) {
1270 BlockAIOCB *acb;
1271 CoroutineIOCompletion co = {
1272 .coroutine = qemu_coroutine_self(),
1275 acb = drv->bdrv_aio_pwritev(bs, offset, bytes, qiov,
1276 flags & bs->supported_write_flags,
1277 bdrv_co_io_em_complete, &co);
1278 flags &= ~bs->supported_write_flags;
1279 if (acb == NULL) {
1280 ret = -EIO;
1281 } else {
1282 qemu_coroutine_yield();
1283 ret = co.ret;
1285 goto emulate_flags;
1288 sector_num = offset >> BDRV_SECTOR_BITS;
1289 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1291 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1292 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1293 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1295 assert(drv->bdrv_co_writev);
1296 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov,
1297 flags & bs->supported_write_flags);
1298 flags &= ~bs->supported_write_flags;
1300 emulate_flags:
1301 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
1302 ret = bdrv_co_flush(bs);
1305 if (qiov == &local_qiov) {
1306 qemu_iovec_destroy(&local_qiov);
1309 return ret;
1312 static int coroutine_fn
1313 bdrv_driver_pwritev_compressed(BlockDriverState *bs, int64_t offset,
1314 int64_t bytes, QEMUIOVector *qiov,
1315 size_t qiov_offset)
1317 BlockDriver *drv = bs->drv;
1318 QEMUIOVector local_qiov;
1319 int ret;
1321 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1323 if (!drv) {
1324 return -ENOMEDIUM;
1327 if (!block_driver_can_compress(drv)) {
1328 return -ENOTSUP;
1331 if (drv->bdrv_co_pwritev_compressed_part) {
1332 return drv->bdrv_co_pwritev_compressed_part(bs, offset, bytes,
1333 qiov, qiov_offset);
1336 if (qiov_offset == 0) {
1337 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
1340 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1341 ret = drv->bdrv_co_pwritev_compressed(bs, offset, bytes, &local_qiov);
1342 qemu_iovec_destroy(&local_qiov);
1344 return ret;
1347 static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
1348 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
1349 size_t qiov_offset, int flags)
1351 BlockDriverState *bs = child->bs;
1353 /* Perform I/O through a temporary buffer so that users who scribble over
1354 * their read buffer while the operation is in progress do not end up
1355 * modifying the image file. This is critical for zero-copy guest I/O
1356 * where anything might happen inside guest memory.
1358 void *bounce_buffer = NULL;
1360 BlockDriver *drv = bs->drv;
1361 int64_t cluster_offset;
1362 int64_t cluster_bytes;
1363 int64_t skip_bytes;
1364 int ret;
1365 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1366 BDRV_REQUEST_MAX_BYTES);
1367 int64_t progress = 0;
1368 bool skip_write;
1370 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1372 if (!drv) {
1373 return -ENOMEDIUM;
1377 * Do not write anything when the BDS is inactive. That is not
1378 * allowed, and it would not help.
1380 skip_write = (bs->open_flags & BDRV_O_INACTIVE);
1382 /* FIXME We cannot require callers to have write permissions when all they
1383 * are doing is a read request. If we did things right, write permissions
1384 * would be obtained anyway, but internally by the copy-on-read code. As
1385 * long as it is implemented here rather than in a separate filter driver,
1386 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1387 * it could request permissions. Therefore we have to bypass the permission
1388 * system for the moment. */
1389 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1391 /* Cover entire cluster so no additional backing file I/O is required when
1392 * allocating cluster in the image file. Note that this value may exceed
1393 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1394 * is one reason we loop rather than doing it all at once.
1396 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
1397 skip_bytes = offset - cluster_offset;
1399 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
1400 cluster_offset, cluster_bytes);
1402 while (cluster_bytes) {
1403 int64_t pnum;
1405 if (skip_write) {
1406 ret = 1; /* "already allocated", so nothing will be copied */
1407 pnum = MIN(cluster_bytes, max_transfer);
1408 } else {
1409 ret = bdrv_is_allocated(bs, cluster_offset,
1410 MIN(cluster_bytes, max_transfer), &pnum);
1411 if (ret < 0) {
1413 * Safe to treat errors in querying allocation as if
1414 * unallocated; we'll probably fail again soon on the
1415 * read, but at least that will set a decent errno.
1417 pnum = MIN(cluster_bytes, max_transfer);
1420 /* Stop at EOF if the image ends in the middle of the cluster */
1421 if (ret == 0 && pnum == 0) {
1422 assert(progress >= bytes);
1423 break;
1426 assert(skip_bytes < pnum);
1429 if (ret <= 0) {
1430 QEMUIOVector local_qiov;
1432 /* Must copy-on-read; use the bounce buffer */
1433 pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1434 if (!bounce_buffer) {
1435 int64_t max_we_need = MAX(pnum, cluster_bytes - pnum);
1436 int64_t max_allowed = MIN(max_transfer, MAX_BOUNCE_BUFFER);
1437 int64_t bounce_buffer_len = MIN(max_we_need, max_allowed);
1439 bounce_buffer = qemu_try_blockalign(bs, bounce_buffer_len);
1440 if (!bounce_buffer) {
1441 ret = -ENOMEM;
1442 goto err;
1445 qemu_iovec_init_buf(&local_qiov, bounce_buffer, pnum);
1447 ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1448 &local_qiov, 0, 0);
1449 if (ret < 0) {
1450 goto err;
1453 bdrv_debug_event(bs, BLKDBG_COR_WRITE);
1454 if (drv->bdrv_co_pwrite_zeroes &&
1455 buffer_is_zero(bounce_buffer, pnum)) {
1456 /* FIXME: Should we (perhaps conditionally) be setting
1457 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1458 * that still correctly reads as zero? */
1459 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum,
1460 BDRV_REQ_WRITE_UNCHANGED);
1461 } else {
1462 /* This does not change the data on the disk, it is not
1463 * necessary to flush even in cache=writethrough mode.
1465 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
1466 &local_qiov, 0,
1467 BDRV_REQ_WRITE_UNCHANGED);
1470 if (ret < 0) {
1471 /* It might be okay to ignore write errors for guest
1472 * requests. If this is a deliberate copy-on-read
1473 * then we don't want to ignore the error. Simply
1474 * report it in all cases.
1476 goto err;
1479 if (!(flags & BDRV_REQ_PREFETCH)) {
1480 qemu_iovec_from_buf(qiov, qiov_offset + progress,
1481 bounce_buffer + skip_bytes,
1482 MIN(pnum - skip_bytes, bytes - progress));
1484 } else if (!(flags & BDRV_REQ_PREFETCH)) {
1485 /* Read directly into the destination */
1486 ret = bdrv_driver_preadv(bs, offset + progress,
1487 MIN(pnum - skip_bytes, bytes - progress),
1488 qiov, qiov_offset + progress, 0);
1489 if (ret < 0) {
1490 goto err;
1494 cluster_offset += pnum;
1495 cluster_bytes -= pnum;
1496 progress += pnum - skip_bytes;
1497 skip_bytes = 0;
1499 ret = 0;
1501 err:
1502 qemu_vfree(bounce_buffer);
1503 return ret;
1507 * Forwards an already correctly aligned request to the BlockDriver. This
1508 * handles copy on read, zeroing after EOF, and fragmentation of large
1509 * reads; any other features must be implemented by the caller.
1511 static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
1512 BdrvTrackedRequest *req, int64_t offset, int64_t bytes,
1513 int64_t align, QEMUIOVector *qiov, size_t qiov_offset, int flags)
1515 BlockDriverState *bs = child->bs;
1516 int64_t total_bytes, max_bytes;
1517 int ret = 0;
1518 int64_t bytes_remaining = bytes;
1519 int max_transfer;
1521 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1522 assert(is_power_of_2(align));
1523 assert((offset & (align - 1)) == 0);
1524 assert((bytes & (align - 1)) == 0);
1525 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1526 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1527 align);
1529 /* TODO: We would need a per-BDS .supported_read_flags and
1530 * potential fallback support, if we ever implement any read flags
1531 * to pass through to drivers. For now, there aren't any
1532 * passthrough flags. */
1533 assert(!(flags & ~(BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH)));
1535 /* Handle Copy on Read and associated serialisation */
1536 if (flags & BDRV_REQ_COPY_ON_READ) {
1537 /* If we touch the same cluster it counts as an overlap. This
1538 * guarantees that allocating writes will be serialized and not race
1539 * with each other for the same cluster. For example, in copy-on-read
1540 * it ensures that the CoR read and write operations are atomic and
1541 * guest writes cannot interleave between them. */
1542 bdrv_make_request_serialising(req, bdrv_get_cluster_size(bs));
1543 } else {
1544 bdrv_wait_serialising_requests(req);
1547 if (flags & BDRV_REQ_COPY_ON_READ) {
1548 int64_t pnum;
1550 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1551 flags &= ~BDRV_REQ_COPY_ON_READ;
1553 ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
1554 if (ret < 0) {
1555 goto out;
1558 if (!ret || pnum != bytes) {
1559 ret = bdrv_co_do_copy_on_readv(child, offset, bytes,
1560 qiov, qiov_offset, flags);
1561 goto out;
1562 } else if (flags & BDRV_REQ_PREFETCH) {
1563 goto out;
1567 /* Forward the request to the BlockDriver, possibly fragmenting it */
1568 total_bytes = bdrv_getlength(bs);
1569 if (total_bytes < 0) {
1570 ret = total_bytes;
1571 goto out;
1574 assert(!(flags & ~bs->supported_read_flags));
1576 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1577 if (bytes <= max_bytes && bytes <= max_transfer) {
1578 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, qiov_offset, flags);
1579 goto out;
1582 while (bytes_remaining) {
1583 int64_t num;
1585 if (max_bytes) {
1586 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1587 assert(num);
1589 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1590 num, qiov,
1591 qiov_offset + bytes - bytes_remaining,
1592 flags);
1593 max_bytes -= num;
1594 } else {
1595 num = bytes_remaining;
1596 ret = qemu_iovec_memset(qiov, qiov_offset + bytes - bytes_remaining,
1597 0, bytes_remaining);
1599 if (ret < 0) {
1600 goto out;
1602 bytes_remaining -= num;
1605 out:
1606 return ret < 0 ? ret : 0;
1610 * Request padding
1612 * |<---- align ----->| |<----- align ---->|
1613 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1614 * | | | | | |
1615 * -*----------$-------*-------- ... --------*-----$------------*---
1616 * | | | | | |
1617 * | offset | | end |
1618 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1619 * [buf ... ) [tail_buf )
1621 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1622 * is placed at the beginning of @buf and @tail at the @end.
1624 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1625 * around tail, if tail exists.
1627 * @merge_reads is true for small requests,
1628 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1629 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1631 typedef struct BdrvRequestPadding {
1632 uint8_t *buf;
1633 size_t buf_len;
1634 uint8_t *tail_buf;
1635 size_t head;
1636 size_t tail;
1637 bool merge_reads;
1638 QEMUIOVector local_qiov;
1639 } BdrvRequestPadding;
1641 static bool bdrv_init_padding(BlockDriverState *bs,
1642 int64_t offset, int64_t bytes,
1643 BdrvRequestPadding *pad)
1645 int64_t align = bs->bl.request_alignment;
1646 int64_t sum;
1648 bdrv_check_request(offset, bytes, &error_abort);
1649 assert(align <= INT_MAX); /* documented in block/block_int.h */
1650 assert(align <= SIZE_MAX / 2); /* so we can allocate the buffer */
1652 memset(pad, 0, sizeof(*pad));
1654 pad->head = offset & (align - 1);
1655 pad->tail = ((offset + bytes) & (align - 1));
1656 if (pad->tail) {
1657 pad->tail = align - pad->tail;
1660 if (!pad->head && !pad->tail) {
1661 return false;
1664 assert(bytes); /* Nothing good in aligning zero-length requests */
1666 sum = pad->head + bytes + pad->tail;
1667 pad->buf_len = (sum > align && pad->head && pad->tail) ? 2 * align : align;
1668 pad->buf = qemu_blockalign(bs, pad->buf_len);
1669 pad->merge_reads = sum == pad->buf_len;
1670 if (pad->tail) {
1671 pad->tail_buf = pad->buf + pad->buf_len - align;
1674 return true;
1677 static int bdrv_padding_rmw_read(BdrvChild *child,
1678 BdrvTrackedRequest *req,
1679 BdrvRequestPadding *pad,
1680 bool zero_middle)
1682 QEMUIOVector local_qiov;
1683 BlockDriverState *bs = child->bs;
1684 uint64_t align = bs->bl.request_alignment;
1685 int ret;
1687 assert(req->serialising && pad->buf);
1689 if (pad->head || pad->merge_reads) {
1690 int64_t bytes = pad->merge_reads ? pad->buf_len : align;
1692 qemu_iovec_init_buf(&local_qiov, pad->buf, bytes);
1694 if (pad->head) {
1695 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1697 if (pad->merge_reads && pad->tail) {
1698 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1700 ret = bdrv_aligned_preadv(child, req, req->overlap_offset, bytes,
1701 align, &local_qiov, 0, 0);
1702 if (ret < 0) {
1703 return ret;
1705 if (pad->head) {
1706 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1708 if (pad->merge_reads && pad->tail) {
1709 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1712 if (pad->merge_reads) {
1713 goto zero_mem;
1717 if (pad->tail) {
1718 qemu_iovec_init_buf(&local_qiov, pad->tail_buf, align);
1720 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1721 ret = bdrv_aligned_preadv(
1722 child, req,
1723 req->overlap_offset + req->overlap_bytes - align,
1724 align, align, &local_qiov, 0, 0);
1725 if (ret < 0) {
1726 return ret;
1728 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1731 zero_mem:
1732 if (zero_middle) {
1733 memset(pad->buf + pad->head, 0, pad->buf_len - pad->head - pad->tail);
1736 return 0;
1739 static void bdrv_padding_destroy(BdrvRequestPadding *pad)
1741 if (pad->buf) {
1742 qemu_vfree(pad->buf);
1743 qemu_iovec_destroy(&pad->local_qiov);
1745 memset(pad, 0, sizeof(*pad));
1749 * bdrv_pad_request
1751 * Exchange request parameters with padded request if needed. Don't include RMW
1752 * read of padding, bdrv_padding_rmw_read() should be called separately if
1753 * needed.
1755 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1756 * - on function start they represent original request
1757 * - on failure or when padding is not needed they are unchanged
1758 * - on success when padding is needed they represent padded request
1760 static int bdrv_pad_request(BlockDriverState *bs,
1761 QEMUIOVector **qiov, size_t *qiov_offset,
1762 int64_t *offset, int64_t *bytes,
1763 BdrvRequestPadding *pad, bool *padded)
1765 int ret;
1767 bdrv_check_qiov_request(*offset, *bytes, *qiov, *qiov_offset, &error_abort);
1769 if (!bdrv_init_padding(bs, *offset, *bytes, pad)) {
1770 if (padded) {
1771 *padded = false;
1773 return 0;
1776 ret = qemu_iovec_init_extended(&pad->local_qiov, pad->buf, pad->head,
1777 *qiov, *qiov_offset, *bytes,
1778 pad->buf + pad->buf_len - pad->tail,
1779 pad->tail);
1780 if (ret < 0) {
1781 bdrv_padding_destroy(pad);
1782 return ret;
1784 *bytes += pad->head + pad->tail;
1785 *offset -= pad->head;
1786 *qiov = &pad->local_qiov;
1787 *qiov_offset = 0;
1788 if (padded) {
1789 *padded = true;
1792 return 0;
1795 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1796 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
1797 BdrvRequestFlags flags)
1799 return bdrv_co_preadv_part(child, offset, bytes, qiov, 0, flags);
1802 int coroutine_fn bdrv_co_preadv_part(BdrvChild *child,
1803 int64_t offset, int64_t bytes,
1804 QEMUIOVector *qiov, size_t qiov_offset,
1805 BdrvRequestFlags flags)
1807 BlockDriverState *bs = child->bs;
1808 BdrvTrackedRequest req;
1809 BdrvRequestPadding pad;
1810 int ret;
1812 trace_bdrv_co_preadv_part(bs, offset, bytes, flags);
1814 if (!bdrv_is_inserted(bs)) {
1815 return -ENOMEDIUM;
1818 ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
1819 if (ret < 0) {
1820 return ret;
1823 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
1825 * Aligning zero request is nonsense. Even if driver has special meaning
1826 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1827 * it to driver due to request_alignment.
1829 * Still, no reason to return an error if someone do unaligned
1830 * zero-length read occasionally.
1832 return 0;
1835 bdrv_inc_in_flight(bs);
1837 /* Don't do copy-on-read if we read data before write operation */
1838 if (qatomic_read(&bs->copy_on_read)) {
1839 flags |= BDRV_REQ_COPY_ON_READ;
1842 ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
1843 NULL);
1844 if (ret < 0) {
1845 goto fail;
1848 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1849 ret = bdrv_aligned_preadv(child, &req, offset, bytes,
1850 bs->bl.request_alignment,
1851 qiov, qiov_offset, flags);
1852 tracked_request_end(&req);
1853 bdrv_padding_destroy(&pad);
1855 fail:
1856 bdrv_dec_in_flight(bs);
1858 return ret;
1861 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1862 int64_t offset, int64_t bytes, BdrvRequestFlags flags)
1864 BlockDriver *drv = bs->drv;
1865 QEMUIOVector qiov;
1866 void *buf = NULL;
1867 int ret = 0;
1868 bool need_flush = false;
1869 int head = 0;
1870 int tail = 0;
1872 int64_t max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes,
1873 INT64_MAX);
1874 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1875 bs->bl.request_alignment);
1876 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
1878 bdrv_check_request(offset, bytes, &error_abort);
1880 if (!drv) {
1881 return -ENOMEDIUM;
1884 if ((flags & ~bs->supported_zero_flags) & BDRV_REQ_NO_FALLBACK) {
1885 return -ENOTSUP;
1888 /* Invalidate the cached block-status data range if this write overlaps */
1889 bdrv_bsc_invalidate_range(bs, offset, bytes);
1891 assert(alignment % bs->bl.request_alignment == 0);
1892 head = offset % alignment;
1893 tail = (offset + bytes) % alignment;
1894 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1895 assert(max_write_zeroes >= bs->bl.request_alignment);
1897 while (bytes > 0 && !ret) {
1898 int64_t num = bytes;
1900 /* Align request. Block drivers can expect the "bulk" of the request
1901 * to be aligned, and that unaligned requests do not cross cluster
1902 * boundaries.
1904 if (head) {
1905 /* Make a small request up to the first aligned sector. For
1906 * convenience, limit this request to max_transfer even if
1907 * we don't need to fall back to writes. */
1908 num = MIN(MIN(bytes, max_transfer), alignment - head);
1909 head = (head + num) % alignment;
1910 assert(num < max_write_zeroes);
1911 } else if (tail && num > alignment) {
1912 /* Shorten the request to the last aligned sector. */
1913 num -= tail;
1916 /* limit request size */
1917 if (num > max_write_zeroes) {
1918 num = max_write_zeroes;
1921 ret = -ENOTSUP;
1922 /* First try the efficient write zeroes operation */
1923 if (drv->bdrv_co_pwrite_zeroes) {
1924 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1925 flags & bs->supported_zero_flags);
1926 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1927 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1928 need_flush = true;
1930 } else {
1931 assert(!bs->supported_zero_flags);
1934 if (ret == -ENOTSUP && !(flags & BDRV_REQ_NO_FALLBACK)) {
1935 /* Fall back to bounce buffer if write zeroes is unsupported */
1936 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1938 if ((flags & BDRV_REQ_FUA) &&
1939 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1940 /* No need for bdrv_driver_pwrite() to do a fallback
1941 * flush on each chunk; use just one at the end */
1942 write_flags &= ~BDRV_REQ_FUA;
1943 need_flush = true;
1945 num = MIN(num, max_transfer);
1946 if (buf == NULL) {
1947 buf = qemu_try_blockalign0(bs, num);
1948 if (buf == NULL) {
1949 ret = -ENOMEM;
1950 goto fail;
1953 qemu_iovec_init_buf(&qiov, buf, num);
1955 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, 0, write_flags);
1957 /* Keep bounce buffer around if it is big enough for all
1958 * all future requests.
1960 if (num < max_transfer) {
1961 qemu_vfree(buf);
1962 buf = NULL;
1966 offset += num;
1967 bytes -= num;
1970 fail:
1971 if (ret == 0 && need_flush) {
1972 ret = bdrv_co_flush(bs);
1974 qemu_vfree(buf);
1975 return ret;
1978 static inline int coroutine_fn
1979 bdrv_co_write_req_prepare(BdrvChild *child, int64_t offset, int64_t bytes,
1980 BdrvTrackedRequest *req, int flags)
1982 BlockDriverState *bs = child->bs;
1984 bdrv_check_request(offset, bytes, &error_abort);
1986 if (bdrv_is_read_only(bs)) {
1987 return -EPERM;
1990 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1991 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1992 assert(!(flags & ~BDRV_REQ_MASK));
1993 assert(!((flags & BDRV_REQ_NO_WAIT) && !(flags & BDRV_REQ_SERIALISING)));
1995 if (flags & BDRV_REQ_SERIALISING) {
1996 QEMU_LOCK_GUARD(&bs->reqs_lock);
1998 tracked_request_set_serialising(req, bdrv_get_cluster_size(bs));
2000 if ((flags & BDRV_REQ_NO_WAIT) && bdrv_find_conflicting_request(req)) {
2001 return -EBUSY;
2004 bdrv_wait_serialising_requests_locked(req);
2005 } else {
2006 bdrv_wait_serialising_requests(req);
2009 assert(req->overlap_offset <= offset);
2010 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
2011 assert(offset + bytes <= bs->total_sectors * BDRV_SECTOR_SIZE ||
2012 child->perm & BLK_PERM_RESIZE);
2014 switch (req->type) {
2015 case BDRV_TRACKED_WRITE:
2016 case BDRV_TRACKED_DISCARD:
2017 if (flags & BDRV_REQ_WRITE_UNCHANGED) {
2018 assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
2019 } else {
2020 assert(child->perm & BLK_PERM_WRITE);
2022 bdrv_write_threshold_check_write(bs, offset, bytes);
2023 return 0;
2024 case BDRV_TRACKED_TRUNCATE:
2025 assert(child->perm & BLK_PERM_RESIZE);
2026 return 0;
2027 default:
2028 abort();
2032 static inline void coroutine_fn
2033 bdrv_co_write_req_finish(BdrvChild *child, int64_t offset, int64_t bytes,
2034 BdrvTrackedRequest *req, int ret)
2036 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
2037 BlockDriverState *bs = child->bs;
2039 bdrv_check_request(offset, bytes, &error_abort);
2041 qatomic_inc(&bs->write_gen);
2044 * Discard cannot extend the image, but in error handling cases, such as
2045 * when reverting a qcow2 cluster allocation, the discarded range can pass
2046 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
2047 * here. Instead, just skip it, since semantically a discard request
2048 * beyond EOF cannot expand the image anyway.
2050 if (ret == 0 &&
2051 (req->type == BDRV_TRACKED_TRUNCATE ||
2052 end_sector > bs->total_sectors) &&
2053 req->type != BDRV_TRACKED_DISCARD) {
2054 bs->total_sectors = end_sector;
2055 bdrv_parent_cb_resize(bs);
2056 bdrv_dirty_bitmap_truncate(bs, end_sector << BDRV_SECTOR_BITS);
2058 if (req->bytes) {
2059 switch (req->type) {
2060 case BDRV_TRACKED_WRITE:
2061 stat64_max(&bs->wr_highest_offset, offset + bytes);
2062 /* fall through, to set dirty bits */
2063 case BDRV_TRACKED_DISCARD:
2064 bdrv_set_dirty(bs, offset, bytes);
2065 break;
2066 default:
2067 break;
2073 * Forwards an already correctly aligned write request to the BlockDriver,
2074 * after possibly fragmenting it.
2076 static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
2077 BdrvTrackedRequest *req, int64_t offset, int64_t bytes,
2078 int64_t align, QEMUIOVector *qiov, size_t qiov_offset,
2079 BdrvRequestFlags flags)
2081 BlockDriverState *bs = child->bs;
2082 BlockDriver *drv = bs->drv;
2083 int ret;
2085 int64_t bytes_remaining = bytes;
2086 int max_transfer;
2088 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
2090 if (!drv) {
2091 return -ENOMEDIUM;
2094 if (bdrv_has_readonly_bitmaps(bs)) {
2095 return -EPERM;
2098 assert(is_power_of_2(align));
2099 assert((offset & (align - 1)) == 0);
2100 assert((bytes & (align - 1)) == 0);
2101 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
2102 align);
2104 ret = bdrv_co_write_req_prepare(child, offset, bytes, req, flags);
2106 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
2107 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
2108 qemu_iovec_is_zero(qiov, qiov_offset, bytes)) {
2109 flags |= BDRV_REQ_ZERO_WRITE;
2110 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
2111 flags |= BDRV_REQ_MAY_UNMAP;
2115 if (ret < 0) {
2116 /* Do nothing, write notifier decided to fail this request */
2117 } else if (flags & BDRV_REQ_ZERO_WRITE) {
2118 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
2119 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
2120 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
2121 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes,
2122 qiov, qiov_offset);
2123 } else if (bytes <= max_transfer) {
2124 bdrv_debug_event(bs, BLKDBG_PWRITEV);
2125 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, qiov_offset, flags);
2126 } else {
2127 bdrv_debug_event(bs, BLKDBG_PWRITEV);
2128 while (bytes_remaining) {
2129 int num = MIN(bytes_remaining, max_transfer);
2130 int local_flags = flags;
2132 assert(num);
2133 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
2134 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
2135 /* If FUA is going to be emulated by flush, we only
2136 * need to flush on the last iteration */
2137 local_flags &= ~BDRV_REQ_FUA;
2140 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
2141 num, qiov,
2142 qiov_offset + bytes - bytes_remaining,
2143 local_flags);
2144 if (ret < 0) {
2145 break;
2147 bytes_remaining -= num;
2150 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
2152 if (ret >= 0) {
2153 ret = 0;
2155 bdrv_co_write_req_finish(child, offset, bytes, req, ret);
2157 return ret;
2160 static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
2161 int64_t offset,
2162 int64_t bytes,
2163 BdrvRequestFlags flags,
2164 BdrvTrackedRequest *req)
2166 BlockDriverState *bs = child->bs;
2167 QEMUIOVector local_qiov;
2168 uint64_t align = bs->bl.request_alignment;
2169 int ret = 0;
2170 bool padding;
2171 BdrvRequestPadding pad;
2173 padding = bdrv_init_padding(bs, offset, bytes, &pad);
2174 if (padding) {
2175 bdrv_make_request_serialising(req, align);
2177 bdrv_padding_rmw_read(child, req, &pad, true);
2179 if (pad.head || pad.merge_reads) {
2180 int64_t aligned_offset = offset & ~(align - 1);
2181 int64_t write_bytes = pad.merge_reads ? pad.buf_len : align;
2183 qemu_iovec_init_buf(&local_qiov, pad.buf, write_bytes);
2184 ret = bdrv_aligned_pwritev(child, req, aligned_offset, write_bytes,
2185 align, &local_qiov, 0,
2186 flags & ~BDRV_REQ_ZERO_WRITE);
2187 if (ret < 0 || pad.merge_reads) {
2188 /* Error or all work is done */
2189 goto out;
2191 offset += write_bytes - pad.head;
2192 bytes -= write_bytes - pad.head;
2196 assert(!bytes || (offset & (align - 1)) == 0);
2197 if (bytes >= align) {
2198 /* Write the aligned part in the middle. */
2199 int64_t aligned_bytes = bytes & ~(align - 1);
2200 ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
2201 NULL, 0, flags);
2202 if (ret < 0) {
2203 goto out;
2205 bytes -= aligned_bytes;
2206 offset += aligned_bytes;
2209 assert(!bytes || (offset & (align - 1)) == 0);
2210 if (bytes) {
2211 assert(align == pad.tail + bytes);
2213 qemu_iovec_init_buf(&local_qiov, pad.tail_buf, align);
2214 ret = bdrv_aligned_pwritev(child, req, offset, align, align,
2215 &local_qiov, 0,
2216 flags & ~BDRV_REQ_ZERO_WRITE);
2219 out:
2220 bdrv_padding_destroy(&pad);
2222 return ret;
2226 * Handle a write request in coroutine context
2228 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
2229 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
2230 BdrvRequestFlags flags)
2232 return bdrv_co_pwritev_part(child, offset, bytes, qiov, 0, flags);
2235 int coroutine_fn bdrv_co_pwritev_part(BdrvChild *child,
2236 int64_t offset, int64_t bytes, QEMUIOVector *qiov, size_t qiov_offset,
2237 BdrvRequestFlags flags)
2239 BlockDriverState *bs = child->bs;
2240 BdrvTrackedRequest req;
2241 uint64_t align = bs->bl.request_alignment;
2242 BdrvRequestPadding pad;
2243 int ret;
2244 bool padded = false;
2246 trace_bdrv_co_pwritev_part(child->bs, offset, bytes, flags);
2248 if (!bdrv_is_inserted(bs)) {
2249 return -ENOMEDIUM;
2252 if (flags & BDRV_REQ_ZERO_WRITE) {
2253 ret = bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, NULL);
2254 } else {
2255 ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
2257 if (ret < 0) {
2258 return ret;
2261 /* If the request is misaligned then we can't make it efficient */
2262 if ((flags & BDRV_REQ_NO_FALLBACK) &&
2263 !QEMU_IS_ALIGNED(offset | bytes, align))
2265 return -ENOTSUP;
2268 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
2270 * Aligning zero request is nonsense. Even if driver has special meaning
2271 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2272 * it to driver due to request_alignment.
2274 * Still, no reason to return an error if someone do unaligned
2275 * zero-length write occasionally.
2277 return 0;
2280 if (!(flags & BDRV_REQ_ZERO_WRITE)) {
2282 * Pad request for following read-modify-write cycle.
2283 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2284 * alignment only if there is no ZERO flag.
2286 ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
2287 &padded);
2288 if (ret < 0) {
2289 return ret;
2293 bdrv_inc_in_flight(bs);
2294 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
2296 if (flags & BDRV_REQ_ZERO_WRITE) {
2297 assert(!padded);
2298 ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
2299 goto out;
2302 if (padded) {
2304 * Request was unaligned to request_alignment and therefore
2305 * padded. We are going to do read-modify-write, and must
2306 * serialize the request to prevent interactions of the
2307 * widened region with other transactions.
2309 bdrv_make_request_serialising(&req, align);
2310 bdrv_padding_rmw_read(child, &req, &pad, false);
2313 ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
2314 qiov, qiov_offset, flags);
2316 bdrv_padding_destroy(&pad);
2318 out:
2319 tracked_request_end(&req);
2320 bdrv_dec_in_flight(bs);
2322 return ret;
2325 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
2326 int64_t bytes, BdrvRequestFlags flags)
2328 trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
2330 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
2331 flags &= ~BDRV_REQ_MAY_UNMAP;
2334 return bdrv_co_pwritev(child, offset, bytes, NULL,
2335 BDRV_REQ_ZERO_WRITE | flags);
2339 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2341 int bdrv_flush_all(void)
2343 BdrvNextIterator it;
2344 BlockDriverState *bs = NULL;
2345 int result = 0;
2348 * bdrv queue is managed by record/replay,
2349 * creating new flush request for stopping
2350 * the VM may break the determinism
2352 if (replay_events_enabled()) {
2353 return result;
2356 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
2357 AioContext *aio_context = bdrv_get_aio_context(bs);
2358 int ret;
2360 aio_context_acquire(aio_context);
2361 ret = bdrv_flush(bs);
2362 if (ret < 0 && !result) {
2363 result = ret;
2365 aio_context_release(aio_context);
2368 return result;
2372 * Returns the allocation status of the specified sectors.
2373 * Drivers not implementing the functionality are assumed to not support
2374 * backing files, hence all their sectors are reported as allocated.
2376 * If 'want_zero' is true, the caller is querying for mapping
2377 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2378 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2379 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2381 * If 'offset' is beyond the end of the disk image the return value is
2382 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2384 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2385 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2386 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2388 * 'pnum' is set to the number of bytes (including and immediately
2389 * following the specified offset) that are easily known to be in the
2390 * same allocated/unallocated state. Note that a second call starting
2391 * at the original offset plus returned pnum may have the same status.
2392 * The returned value is non-zero on success except at end-of-file.
2394 * Returns negative errno on failure. Otherwise, if the
2395 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2396 * set to the host mapping and BDS corresponding to the guest offset.
2398 static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
2399 bool want_zero,
2400 int64_t offset, int64_t bytes,
2401 int64_t *pnum, int64_t *map,
2402 BlockDriverState **file)
2404 int64_t total_size;
2405 int64_t n; /* bytes */
2406 int ret;
2407 int64_t local_map = 0;
2408 BlockDriverState *local_file = NULL;
2409 int64_t aligned_offset, aligned_bytes;
2410 uint32_t align;
2411 bool has_filtered_child;
2413 assert(pnum);
2414 *pnum = 0;
2415 total_size = bdrv_getlength(bs);
2416 if (total_size < 0) {
2417 ret = total_size;
2418 goto early_out;
2421 if (offset >= total_size) {
2422 ret = BDRV_BLOCK_EOF;
2423 goto early_out;
2425 if (!bytes) {
2426 ret = 0;
2427 goto early_out;
2430 n = total_size - offset;
2431 if (n < bytes) {
2432 bytes = n;
2435 /* Must be non-NULL or bdrv_getlength() would have failed */
2436 assert(bs->drv);
2437 has_filtered_child = bdrv_filter_child(bs);
2438 if (!bs->drv->bdrv_co_block_status && !has_filtered_child) {
2439 *pnum = bytes;
2440 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2441 if (offset + bytes == total_size) {
2442 ret |= BDRV_BLOCK_EOF;
2444 if (bs->drv->protocol_name) {
2445 ret |= BDRV_BLOCK_OFFSET_VALID;
2446 local_map = offset;
2447 local_file = bs;
2449 goto early_out;
2452 bdrv_inc_in_flight(bs);
2454 /* Round out to request_alignment boundaries */
2455 align = bs->bl.request_alignment;
2456 aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2457 aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2459 if (bs->drv->bdrv_co_block_status) {
2461 * Use the block-status cache only for protocol nodes: Format
2462 * drivers are generally quick to inquire the status, but protocol
2463 * drivers often need to get information from outside of qemu, so
2464 * we do not have control over the actual implementation. There
2465 * have been cases where inquiring the status took an unreasonably
2466 * long time, and we can do nothing in qemu to fix it.
2467 * This is especially problematic for images with large data areas,
2468 * because finding the few holes in them and giving them special
2469 * treatment does not gain much performance. Therefore, we try to
2470 * cache the last-identified data region.
2472 * Second, limiting ourselves to protocol nodes allows us to assume
2473 * the block status for data regions to be DATA | OFFSET_VALID, and
2474 * that the host offset is the same as the guest offset.
2476 * Note that it is possible that external writers zero parts of
2477 * the cached regions without the cache being invalidated, and so
2478 * we may report zeroes as data. This is not catastrophic,
2479 * however, because reporting zeroes as data is fine.
2481 if (QLIST_EMPTY(&bs->children) &&
2482 bdrv_bsc_is_data(bs, aligned_offset, pnum))
2484 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2485 local_file = bs;
2486 local_map = aligned_offset;
2487 } else {
2488 ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2489 aligned_bytes, pnum, &local_map,
2490 &local_file);
2493 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2494 * the cache is queried above. Technically, we do not need to check
2495 * it here; the worst that can happen is that we fill the cache for
2496 * non-protocol nodes, and then it is never used. However, filling
2497 * the cache requires an RCU update, so double check here to avoid
2498 * such an update if possible.
2500 if (ret == (BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID) &&
2501 QLIST_EMPTY(&bs->children))
2504 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2505 * returned local_map value must be the same as the offset we
2506 * have passed (aligned_offset), and local_bs must be the node
2507 * itself.
2508 * Assert this, because we follow this rule when reading from
2509 * the cache (see the `local_file = bs` and
2510 * `local_map = aligned_offset` assignments above), and the
2511 * result the cache delivers must be the same as the driver
2512 * would deliver.
2514 assert(local_file == bs);
2515 assert(local_map == aligned_offset);
2516 bdrv_bsc_fill(bs, aligned_offset, *pnum);
2519 } else {
2520 /* Default code for filters */
2522 local_file = bdrv_filter_bs(bs);
2523 assert(local_file);
2525 *pnum = aligned_bytes;
2526 local_map = aligned_offset;
2527 ret = BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2529 if (ret < 0) {
2530 *pnum = 0;
2531 goto out;
2535 * The driver's result must be a non-zero multiple of request_alignment.
2536 * Clamp pnum and adjust map to original request.
2538 assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2539 align > offset - aligned_offset);
2540 if (ret & BDRV_BLOCK_RECURSE) {
2541 assert(ret & BDRV_BLOCK_DATA);
2542 assert(ret & BDRV_BLOCK_OFFSET_VALID);
2543 assert(!(ret & BDRV_BLOCK_ZERO));
2546 *pnum -= offset - aligned_offset;
2547 if (*pnum > bytes) {
2548 *pnum = bytes;
2550 if (ret & BDRV_BLOCK_OFFSET_VALID) {
2551 local_map += offset - aligned_offset;
2554 if (ret & BDRV_BLOCK_RAW) {
2555 assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2556 ret = bdrv_co_block_status(local_file, want_zero, local_map,
2557 *pnum, pnum, &local_map, &local_file);
2558 goto out;
2561 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2562 ret |= BDRV_BLOCK_ALLOCATED;
2563 } else if (bs->drv->supports_backing) {
2564 BlockDriverState *cow_bs = bdrv_cow_bs(bs);
2566 if (!cow_bs) {
2567 ret |= BDRV_BLOCK_ZERO;
2568 } else if (want_zero) {
2569 int64_t size2 = bdrv_getlength(cow_bs);
2571 if (size2 >= 0 && offset >= size2) {
2572 ret |= BDRV_BLOCK_ZERO;
2577 if (want_zero && ret & BDRV_BLOCK_RECURSE &&
2578 local_file && local_file != bs &&
2579 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2580 (ret & BDRV_BLOCK_OFFSET_VALID)) {
2581 int64_t file_pnum;
2582 int ret2;
2584 ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2585 *pnum, &file_pnum, NULL, NULL);
2586 if (ret2 >= 0) {
2587 /* Ignore errors. This is just providing extra information, it
2588 * is useful but not necessary.
2590 if (ret2 & BDRV_BLOCK_EOF &&
2591 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2593 * It is valid for the format block driver to read
2594 * beyond the end of the underlying file's current
2595 * size; such areas read as zero.
2597 ret |= BDRV_BLOCK_ZERO;
2598 } else {
2599 /* Limit request to the range reported by the protocol driver */
2600 *pnum = file_pnum;
2601 ret |= (ret2 & BDRV_BLOCK_ZERO);
2606 out:
2607 bdrv_dec_in_flight(bs);
2608 if (ret >= 0 && offset + *pnum == total_size) {
2609 ret |= BDRV_BLOCK_EOF;
2611 early_out:
2612 if (file) {
2613 *file = local_file;
2615 if (map) {
2616 *map = local_map;
2618 return ret;
2621 int coroutine_fn
2622 bdrv_co_common_block_status_above(BlockDriverState *bs,
2623 BlockDriverState *base,
2624 bool include_base,
2625 bool want_zero,
2626 int64_t offset,
2627 int64_t bytes,
2628 int64_t *pnum,
2629 int64_t *map,
2630 BlockDriverState **file,
2631 int *depth)
2633 int ret;
2634 BlockDriverState *p;
2635 int64_t eof = 0;
2636 int dummy;
2638 assert(!include_base || base); /* Can't include NULL base */
2640 if (!depth) {
2641 depth = &dummy;
2643 *depth = 0;
2645 if (!include_base && bs == base) {
2646 *pnum = bytes;
2647 return 0;
2650 ret = bdrv_co_block_status(bs, want_zero, offset, bytes, pnum, map, file);
2651 ++*depth;
2652 if (ret < 0 || *pnum == 0 || ret & BDRV_BLOCK_ALLOCATED || bs == base) {
2653 return ret;
2656 if (ret & BDRV_BLOCK_EOF) {
2657 eof = offset + *pnum;
2660 assert(*pnum <= bytes);
2661 bytes = *pnum;
2663 for (p = bdrv_filter_or_cow_bs(bs); include_base || p != base;
2664 p = bdrv_filter_or_cow_bs(p))
2666 ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2667 file);
2668 ++*depth;
2669 if (ret < 0) {
2670 return ret;
2672 if (*pnum == 0) {
2674 * The top layer deferred to this layer, and because this layer is
2675 * short, any zeroes that we synthesize beyond EOF behave as if they
2676 * were allocated at this layer.
2678 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2679 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2680 * below.
2682 assert(ret & BDRV_BLOCK_EOF);
2683 *pnum = bytes;
2684 if (file) {
2685 *file = p;
2687 ret = BDRV_BLOCK_ZERO | BDRV_BLOCK_ALLOCATED;
2688 break;
2690 if (ret & BDRV_BLOCK_ALLOCATED) {
2692 * We've found the node and the status, we must break.
2694 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2695 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2696 * below.
2698 ret &= ~BDRV_BLOCK_EOF;
2699 break;
2702 if (p == base) {
2703 assert(include_base);
2704 break;
2708 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2709 * let's continue the diving.
2711 assert(*pnum <= bytes);
2712 bytes = *pnum;
2715 if (offset + *pnum == eof) {
2716 ret |= BDRV_BLOCK_EOF;
2719 return ret;
2722 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2723 int64_t offset, int64_t bytes, int64_t *pnum,
2724 int64_t *map, BlockDriverState **file)
2726 return bdrv_common_block_status_above(bs, base, false, true, offset, bytes,
2727 pnum, map, file, NULL);
2730 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2731 int64_t *pnum, int64_t *map, BlockDriverState **file)
2733 return bdrv_block_status_above(bs, bdrv_filter_or_cow_bs(bs),
2734 offset, bytes, pnum, map, file);
2738 * Check @bs (and its backing chain) to see if the range defined
2739 * by @offset and @bytes is known to read as zeroes.
2740 * Return 1 if that is the case, 0 otherwise and -errno on error.
2741 * This test is meant to be fast rather than accurate so returning 0
2742 * does not guarantee non-zero data.
2744 int coroutine_fn bdrv_co_is_zero_fast(BlockDriverState *bs, int64_t offset,
2745 int64_t bytes)
2747 int ret;
2748 int64_t pnum = bytes;
2750 if (!bytes) {
2751 return 1;
2754 ret = bdrv_common_block_status_above(bs, NULL, false, false, offset,
2755 bytes, &pnum, NULL, NULL, NULL);
2757 if (ret < 0) {
2758 return ret;
2761 return (pnum == bytes) && (ret & BDRV_BLOCK_ZERO);
2764 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
2765 int64_t bytes, int64_t *pnum)
2767 int ret;
2768 int64_t dummy;
2770 ret = bdrv_common_block_status_above(bs, bs, true, false, offset,
2771 bytes, pnum ? pnum : &dummy, NULL,
2772 NULL, NULL);
2773 if (ret < 0) {
2774 return ret;
2776 return !!(ret & BDRV_BLOCK_ALLOCATED);
2780 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2782 * Return a positive depth if (a prefix of) the given range is allocated
2783 * in any image between BASE and TOP (BASE is only included if include_base
2784 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2785 * BASE can be NULL to check if the given offset is allocated in any
2786 * image of the chain. Return 0 otherwise, or negative errno on
2787 * failure.
2789 * 'pnum' is set to the number of bytes (including and immediately
2790 * following the specified offset) that are known to be in the same
2791 * allocated/unallocated state. Note that a subsequent call starting
2792 * at 'offset + *pnum' may return the same allocation status (in other
2793 * words, the result is not necessarily the maximum possible range);
2794 * but 'pnum' will only be 0 when end of file is reached.
2796 int bdrv_is_allocated_above(BlockDriverState *top,
2797 BlockDriverState *base,
2798 bool include_base, int64_t offset,
2799 int64_t bytes, int64_t *pnum)
2801 int depth;
2802 int ret = bdrv_common_block_status_above(top, base, include_base, false,
2803 offset, bytes, pnum, NULL, NULL,
2804 &depth);
2805 if (ret < 0) {
2806 return ret;
2809 if (ret & BDRV_BLOCK_ALLOCATED) {
2810 return depth;
2812 return 0;
2815 int coroutine_fn
2816 bdrv_co_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2818 BlockDriver *drv = bs->drv;
2819 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2820 int ret;
2822 ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2823 if (ret < 0) {
2824 return ret;
2827 if (!drv) {
2828 return -ENOMEDIUM;
2831 bdrv_inc_in_flight(bs);
2833 if (drv->bdrv_load_vmstate) {
2834 ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2835 } else if (child_bs) {
2836 ret = bdrv_co_readv_vmstate(child_bs, qiov, pos);
2837 } else {
2838 ret = -ENOTSUP;
2841 bdrv_dec_in_flight(bs);
2843 return ret;
2846 int coroutine_fn
2847 bdrv_co_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2849 BlockDriver *drv = bs->drv;
2850 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2851 int ret;
2853 ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2854 if (ret < 0) {
2855 return ret;
2858 if (!drv) {
2859 return -ENOMEDIUM;
2862 bdrv_inc_in_flight(bs);
2864 if (drv->bdrv_save_vmstate) {
2865 ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2866 } else if (child_bs) {
2867 ret = bdrv_co_writev_vmstate(child_bs, qiov, pos);
2868 } else {
2869 ret = -ENOTSUP;
2872 bdrv_dec_in_flight(bs);
2874 return ret;
2877 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2878 int64_t pos, int size)
2880 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2881 int ret = bdrv_writev_vmstate(bs, &qiov, pos);
2883 return ret < 0 ? ret : size;
2886 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2887 int64_t pos, int size)
2889 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2890 int ret = bdrv_readv_vmstate(bs, &qiov, pos);
2892 return ret < 0 ? ret : size;
2895 /**************************************************************/
2896 /* async I/Os */
2898 void bdrv_aio_cancel(BlockAIOCB *acb)
2900 qemu_aio_ref(acb);
2901 bdrv_aio_cancel_async(acb);
2902 while (acb->refcnt > 1) {
2903 if (acb->aiocb_info->get_aio_context) {
2904 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2905 } else if (acb->bs) {
2906 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2907 * assert that we're not using an I/O thread. Thread-safe
2908 * code should use bdrv_aio_cancel_async exclusively.
2910 assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2911 aio_poll(bdrv_get_aio_context(acb->bs), true);
2912 } else {
2913 abort();
2916 qemu_aio_unref(acb);
2919 /* Async version of aio cancel. The caller is not blocked if the acb implements
2920 * cancel_async, otherwise we do nothing and let the request normally complete.
2921 * In either case the completion callback must be called. */
2922 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2924 if (acb->aiocb_info->cancel_async) {
2925 acb->aiocb_info->cancel_async(acb);
2929 /**************************************************************/
2930 /* Coroutine block device emulation */
2932 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2934 BdrvChild *primary_child = bdrv_primary_child(bs);
2935 BdrvChild *child;
2936 int current_gen;
2937 int ret = 0;
2939 bdrv_inc_in_flight(bs);
2941 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2942 bdrv_is_sg(bs)) {
2943 goto early_exit;
2946 qemu_co_mutex_lock(&bs->reqs_lock);
2947 current_gen = qatomic_read(&bs->write_gen);
2949 /* Wait until any previous flushes are completed */
2950 while (bs->active_flush_req) {
2951 qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
2954 /* Flushes reach this point in nondecreasing current_gen order. */
2955 bs->active_flush_req = true;
2956 qemu_co_mutex_unlock(&bs->reqs_lock);
2958 /* Write back all layers by calling one driver function */
2959 if (bs->drv->bdrv_co_flush) {
2960 ret = bs->drv->bdrv_co_flush(bs);
2961 goto out;
2964 /* Write back cached data to the OS even with cache=unsafe */
2965 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_OS);
2966 if (bs->drv->bdrv_co_flush_to_os) {
2967 ret = bs->drv->bdrv_co_flush_to_os(bs);
2968 if (ret < 0) {
2969 goto out;
2973 /* But don't actually force it to the disk with cache=unsafe */
2974 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2975 goto flush_children;
2978 /* Check if we really need to flush anything */
2979 if (bs->flushed_gen == current_gen) {
2980 goto flush_children;
2983 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_DISK);
2984 if (!bs->drv) {
2985 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2986 * (even in case of apparent success) */
2987 ret = -ENOMEDIUM;
2988 goto out;
2990 if (bs->drv->bdrv_co_flush_to_disk) {
2991 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2992 } else if (bs->drv->bdrv_aio_flush) {
2993 BlockAIOCB *acb;
2994 CoroutineIOCompletion co = {
2995 .coroutine = qemu_coroutine_self(),
2998 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2999 if (acb == NULL) {
3000 ret = -EIO;
3001 } else {
3002 qemu_coroutine_yield();
3003 ret = co.ret;
3005 } else {
3007 * Some block drivers always operate in either writethrough or unsafe
3008 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
3009 * know how the server works (because the behaviour is hardcoded or
3010 * depends on server-side configuration), so we can't ensure that
3011 * everything is safe on disk. Returning an error doesn't work because
3012 * that would break guests even if the server operates in writethrough
3013 * mode.
3015 * Let's hope the user knows what he's doing.
3017 ret = 0;
3020 if (ret < 0) {
3021 goto out;
3024 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
3025 * in the case of cache=unsafe, so there are no useless flushes.
3027 flush_children:
3028 ret = 0;
3029 QLIST_FOREACH(child, &bs->children, next) {
3030 if (child->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
3031 int this_child_ret = bdrv_co_flush(child->bs);
3032 if (!ret) {
3033 ret = this_child_ret;
3038 out:
3039 /* Notify any pending flushes that we have completed */
3040 if (ret == 0) {
3041 bs->flushed_gen = current_gen;
3044 qemu_co_mutex_lock(&bs->reqs_lock);
3045 bs->active_flush_req = false;
3046 /* Return value is ignored - it's ok if wait queue is empty */
3047 qemu_co_queue_next(&bs->flush_queue);
3048 qemu_co_mutex_unlock(&bs->reqs_lock);
3050 early_exit:
3051 bdrv_dec_in_flight(bs);
3052 return ret;
3055 int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset,
3056 int64_t bytes)
3058 BdrvTrackedRequest req;
3059 int ret;
3060 int64_t max_pdiscard;
3061 int head, tail, align;
3062 BlockDriverState *bs = child->bs;
3064 if (!bs || !bs->drv || !bdrv_is_inserted(bs)) {
3065 return -ENOMEDIUM;
3068 if (bdrv_has_readonly_bitmaps(bs)) {
3069 return -EPERM;
3072 ret = bdrv_check_request(offset, bytes, NULL);
3073 if (ret < 0) {
3074 return ret;
3077 /* Do nothing if disabled. */
3078 if (!(bs->open_flags & BDRV_O_UNMAP)) {
3079 return 0;
3082 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
3083 return 0;
3086 /* Invalidate the cached block-status data range if this discard overlaps */
3087 bdrv_bsc_invalidate_range(bs, offset, bytes);
3089 /* Discard is advisory, but some devices track and coalesce
3090 * unaligned requests, so we must pass everything down rather than
3091 * round here. Still, most devices will just silently ignore
3092 * unaligned requests (by returning -ENOTSUP), so we must fragment
3093 * the request accordingly. */
3094 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
3095 assert(align % bs->bl.request_alignment == 0);
3096 head = offset % align;
3097 tail = (offset + bytes) % align;
3099 bdrv_inc_in_flight(bs);
3100 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
3102 ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
3103 if (ret < 0) {
3104 goto out;
3107 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT64_MAX),
3108 align);
3109 assert(max_pdiscard >= bs->bl.request_alignment);
3111 while (bytes > 0) {
3112 int64_t num = bytes;
3114 if (head) {
3115 /* Make small requests to get to alignment boundaries. */
3116 num = MIN(bytes, align - head);
3117 if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
3118 num %= bs->bl.request_alignment;
3120 head = (head + num) % align;
3121 assert(num < max_pdiscard);
3122 } else if (tail) {
3123 if (num > align) {
3124 /* Shorten the request to the last aligned cluster. */
3125 num -= tail;
3126 } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
3127 tail > bs->bl.request_alignment) {
3128 tail %= bs->bl.request_alignment;
3129 num -= tail;
3132 /* limit request size */
3133 if (num > max_pdiscard) {
3134 num = max_pdiscard;
3137 if (!bs->drv) {
3138 ret = -ENOMEDIUM;
3139 goto out;
3141 if (bs->drv->bdrv_co_pdiscard) {
3142 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
3143 } else {
3144 BlockAIOCB *acb;
3145 CoroutineIOCompletion co = {
3146 .coroutine = qemu_coroutine_self(),
3149 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
3150 bdrv_co_io_em_complete, &co);
3151 if (acb == NULL) {
3152 ret = -EIO;
3153 goto out;
3154 } else {
3155 qemu_coroutine_yield();
3156 ret = co.ret;
3159 if (ret && ret != -ENOTSUP) {
3160 goto out;
3163 offset += num;
3164 bytes -= num;
3166 ret = 0;
3167 out:
3168 bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
3169 tracked_request_end(&req);
3170 bdrv_dec_in_flight(bs);
3171 return ret;
3174 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
3176 BlockDriver *drv = bs->drv;
3177 CoroutineIOCompletion co = {
3178 .coroutine = qemu_coroutine_self(),
3180 BlockAIOCB *acb;
3182 bdrv_inc_in_flight(bs);
3183 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
3184 co.ret = -ENOTSUP;
3185 goto out;
3188 if (drv->bdrv_co_ioctl) {
3189 co.ret = drv->bdrv_co_ioctl(bs, req, buf);
3190 } else {
3191 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
3192 if (!acb) {
3193 co.ret = -ENOTSUP;
3194 goto out;
3196 qemu_coroutine_yield();
3198 out:
3199 bdrv_dec_in_flight(bs);
3200 return co.ret;
3203 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3205 return qemu_memalign(bdrv_opt_mem_align(bs), size);
3208 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
3210 return memset(qemu_blockalign(bs, size), 0, size);
3213 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
3215 size_t align = bdrv_opt_mem_align(bs);
3217 /* Ensure that NULL is never returned on success */
3218 assert(align > 0);
3219 if (size == 0) {
3220 size = align;
3223 return qemu_try_memalign(align, size);
3226 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
3228 void *mem = qemu_try_blockalign(bs, size);
3230 if (mem) {
3231 memset(mem, 0, size);
3234 return mem;
3238 * Check if all memory in this vector is sector aligned.
3240 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
3242 int i;
3243 size_t alignment = bdrv_min_mem_align(bs);
3245 for (i = 0; i < qiov->niov; i++) {
3246 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
3247 return false;
3249 if (qiov->iov[i].iov_len % alignment) {
3250 return false;
3254 return true;
3257 void bdrv_io_plug(BlockDriverState *bs)
3259 BdrvChild *child;
3261 QLIST_FOREACH(child, &bs->children, next) {
3262 bdrv_io_plug(child->bs);
3265 if (qatomic_fetch_inc(&bs->io_plugged) == 0) {
3266 BlockDriver *drv = bs->drv;
3267 if (drv && drv->bdrv_io_plug) {
3268 drv->bdrv_io_plug(bs);
3273 void bdrv_io_unplug(BlockDriverState *bs)
3275 BdrvChild *child;
3277 assert(bs->io_plugged);
3278 if (qatomic_fetch_dec(&bs->io_plugged) == 1) {
3279 BlockDriver *drv = bs->drv;
3280 if (drv && drv->bdrv_io_unplug) {
3281 drv->bdrv_io_unplug(bs);
3285 QLIST_FOREACH(child, &bs->children, next) {
3286 bdrv_io_unplug(child->bs);
3290 void bdrv_register_buf(BlockDriverState *bs, void *host, size_t size)
3292 BdrvChild *child;
3294 if (bs->drv && bs->drv->bdrv_register_buf) {
3295 bs->drv->bdrv_register_buf(bs, host, size);
3297 QLIST_FOREACH(child, &bs->children, next) {
3298 bdrv_register_buf(child->bs, host, size);
3302 void bdrv_unregister_buf(BlockDriverState *bs, void *host)
3304 BdrvChild *child;
3306 if (bs->drv && bs->drv->bdrv_unregister_buf) {
3307 bs->drv->bdrv_unregister_buf(bs, host);
3309 QLIST_FOREACH(child, &bs->children, next) {
3310 bdrv_unregister_buf(child->bs, host);
3314 static int coroutine_fn bdrv_co_copy_range_internal(
3315 BdrvChild *src, int64_t src_offset, BdrvChild *dst,
3316 int64_t dst_offset, int64_t bytes,
3317 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
3318 bool recurse_src)
3320 BdrvTrackedRequest req;
3321 int ret;
3323 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3324 assert(!(read_flags & BDRV_REQ_NO_FALLBACK));
3325 assert(!(write_flags & BDRV_REQ_NO_FALLBACK));
3327 if (!dst || !dst->bs || !bdrv_is_inserted(dst->bs)) {
3328 return -ENOMEDIUM;
3330 ret = bdrv_check_request32(dst_offset, bytes, NULL, 0);
3331 if (ret) {
3332 return ret;
3334 if (write_flags & BDRV_REQ_ZERO_WRITE) {
3335 return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
3338 if (!src || !src->bs || !bdrv_is_inserted(src->bs)) {
3339 return -ENOMEDIUM;
3341 ret = bdrv_check_request32(src_offset, bytes, NULL, 0);
3342 if (ret) {
3343 return ret;
3346 if (!src->bs->drv->bdrv_co_copy_range_from
3347 || !dst->bs->drv->bdrv_co_copy_range_to
3348 || src->bs->encrypted || dst->bs->encrypted) {
3349 return -ENOTSUP;
3352 if (recurse_src) {
3353 bdrv_inc_in_flight(src->bs);
3354 tracked_request_begin(&req, src->bs, src_offset, bytes,
3355 BDRV_TRACKED_READ);
3357 /* BDRV_REQ_SERIALISING is only for write operation */
3358 assert(!(read_flags & BDRV_REQ_SERIALISING));
3359 bdrv_wait_serialising_requests(&req);
3361 ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
3362 src, src_offset,
3363 dst, dst_offset,
3364 bytes,
3365 read_flags, write_flags);
3367 tracked_request_end(&req);
3368 bdrv_dec_in_flight(src->bs);
3369 } else {
3370 bdrv_inc_in_flight(dst->bs);
3371 tracked_request_begin(&req, dst->bs, dst_offset, bytes,
3372 BDRV_TRACKED_WRITE);
3373 ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3374 write_flags);
3375 if (!ret) {
3376 ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3377 src, src_offset,
3378 dst, dst_offset,
3379 bytes,
3380 read_flags, write_flags);
3382 bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
3383 tracked_request_end(&req);
3384 bdrv_dec_in_flight(dst->bs);
3387 return ret;
3390 /* Copy range from @src to @dst.
3392 * See the comment of bdrv_co_copy_range for the parameter and return value
3393 * semantics. */
3394 int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
3395 BdrvChild *dst, int64_t dst_offset,
3396 int64_t bytes,
3397 BdrvRequestFlags read_flags,
3398 BdrvRequestFlags write_flags)
3400 trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3401 read_flags, write_flags);
3402 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3403 bytes, read_flags, write_flags, true);
3406 /* Copy range from @src to @dst.
3408 * See the comment of bdrv_co_copy_range for the parameter and return value
3409 * semantics. */
3410 int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
3411 BdrvChild *dst, int64_t dst_offset,
3412 int64_t bytes,
3413 BdrvRequestFlags read_flags,
3414 BdrvRequestFlags write_flags)
3416 trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3417 read_flags, write_flags);
3418 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3419 bytes, read_flags, write_flags, false);
3422 int coroutine_fn bdrv_co_copy_range(BdrvChild *src, int64_t src_offset,
3423 BdrvChild *dst, int64_t dst_offset,
3424 int64_t bytes, BdrvRequestFlags read_flags,
3425 BdrvRequestFlags write_flags)
3427 return bdrv_co_copy_range_from(src, src_offset,
3428 dst, dst_offset,
3429 bytes, read_flags, write_flags);
3432 static void bdrv_parent_cb_resize(BlockDriverState *bs)
3434 BdrvChild *c;
3435 QLIST_FOREACH(c, &bs->parents, next_parent) {
3436 if (c->klass->resize) {
3437 c->klass->resize(c);
3443 * Truncate file to 'offset' bytes (needed only for file protocols)
3445 * If 'exact' is true, the file must be resized to exactly the given
3446 * 'offset'. Otherwise, it is sufficient for the node to be at least
3447 * 'offset' bytes in length.
3449 int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset, bool exact,
3450 PreallocMode prealloc, BdrvRequestFlags flags,
3451 Error **errp)
3453 BlockDriverState *bs = child->bs;
3454 BdrvChild *filtered, *backing;
3455 BlockDriver *drv = bs->drv;
3456 BdrvTrackedRequest req;
3457 int64_t old_size, new_bytes;
3458 int ret;
3461 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3462 if (!drv) {
3463 error_setg(errp, "No medium inserted");
3464 return -ENOMEDIUM;
3466 if (offset < 0) {
3467 error_setg(errp, "Image size cannot be negative");
3468 return -EINVAL;
3471 ret = bdrv_check_request(offset, 0, errp);
3472 if (ret < 0) {
3473 return ret;
3476 old_size = bdrv_getlength(bs);
3477 if (old_size < 0) {
3478 error_setg_errno(errp, -old_size, "Failed to get old image size");
3479 return old_size;
3482 if (bdrv_is_read_only(bs)) {
3483 error_setg(errp, "Image is read-only");
3484 return -EACCES;
3487 if (offset > old_size) {
3488 new_bytes = offset - old_size;
3489 } else {
3490 new_bytes = 0;
3493 bdrv_inc_in_flight(bs);
3494 tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3495 BDRV_TRACKED_TRUNCATE);
3497 /* If we are growing the image and potentially using preallocation for the
3498 * new area, we need to make sure that no write requests are made to it
3499 * concurrently or they might be overwritten by preallocation. */
3500 if (new_bytes) {
3501 bdrv_make_request_serialising(&req, 1);
3503 ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3505 if (ret < 0) {
3506 error_setg_errno(errp, -ret,
3507 "Failed to prepare request for truncation");
3508 goto out;
3511 filtered = bdrv_filter_child(bs);
3512 backing = bdrv_cow_child(bs);
3515 * If the image has a backing file that is large enough that it would
3516 * provide data for the new area, we cannot leave it unallocated because
3517 * then the backing file content would become visible. Instead, zero-fill
3518 * the new area.
3520 * Note that if the image has a backing file, but was opened without the
3521 * backing file, taking care of keeping things consistent with that backing
3522 * file is the user's responsibility.
3524 if (new_bytes && backing) {
3525 int64_t backing_len;
3527 backing_len = bdrv_getlength(backing->bs);
3528 if (backing_len < 0) {
3529 ret = backing_len;
3530 error_setg_errno(errp, -ret, "Could not get backing file size");
3531 goto out;
3534 if (backing_len > old_size) {
3535 flags |= BDRV_REQ_ZERO_WRITE;
3539 if (drv->bdrv_co_truncate) {
3540 if (flags & ~bs->supported_truncate_flags) {
3541 error_setg(errp, "Block driver does not support requested flags");
3542 ret = -ENOTSUP;
3543 goto out;
3545 ret = drv->bdrv_co_truncate(bs, offset, exact, prealloc, flags, errp);
3546 } else if (filtered) {
3547 ret = bdrv_co_truncate(filtered, offset, exact, prealloc, flags, errp);
3548 } else {
3549 error_setg(errp, "Image format driver does not support resize");
3550 ret = -ENOTSUP;
3551 goto out;
3553 if (ret < 0) {
3554 goto out;
3557 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3558 if (ret < 0) {
3559 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3560 } else {
3561 offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3563 /* It's possible that truncation succeeded but refresh_total_sectors
3564 * failed, but the latter doesn't affect how we should finish the request.
3565 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3566 bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3568 out:
3569 tracked_request_end(&req);
3570 bdrv_dec_in_flight(bs);
3572 return ret;
3575 void bdrv_cancel_in_flight(BlockDriverState *bs)
3577 if (!bs || !bs->drv) {
3578 return;
3581 if (bs->drv->bdrv_cancel_in_flight) {
3582 bs->drv->bdrv_cancel_in_flight(bs);