hw/dma: sifive_pdma: don't set Control.error if 0 bytes to transfer
[qemu/ar7.git] / block / io.c
blob99ee182ca449c89572a3a1701653b6fa922891e5
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 static 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, int flags)
1235 BlockDriver *drv = bs->drv;
1236 int64_t sector_num;
1237 unsigned int nb_sectors;
1238 QEMUIOVector local_qiov;
1239 int ret;
1241 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1242 assert(!(flags & ~BDRV_REQ_MASK));
1243 assert(!(flags & BDRV_REQ_NO_FALLBACK));
1245 if (!drv) {
1246 return -ENOMEDIUM;
1249 if (drv->bdrv_co_pwritev_part) {
1250 ret = drv->bdrv_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset,
1251 flags & bs->supported_write_flags);
1252 flags &= ~bs->supported_write_flags;
1253 goto emulate_flags;
1256 if (qiov_offset > 0 || bytes != qiov->size) {
1257 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1258 qiov = &local_qiov;
1261 if (drv->bdrv_co_pwritev) {
1262 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
1263 flags & bs->supported_write_flags);
1264 flags &= ~bs->supported_write_flags;
1265 goto emulate_flags;
1268 if (drv->bdrv_aio_pwritev) {
1269 BlockAIOCB *acb;
1270 CoroutineIOCompletion co = {
1271 .coroutine = qemu_coroutine_self(),
1274 acb = drv->bdrv_aio_pwritev(bs, offset, bytes, qiov,
1275 flags & bs->supported_write_flags,
1276 bdrv_co_io_em_complete, &co);
1277 flags &= ~bs->supported_write_flags;
1278 if (acb == NULL) {
1279 ret = -EIO;
1280 } else {
1281 qemu_coroutine_yield();
1282 ret = co.ret;
1284 goto emulate_flags;
1287 sector_num = offset >> BDRV_SECTOR_BITS;
1288 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1290 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1291 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1292 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1294 assert(drv->bdrv_co_writev);
1295 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov,
1296 flags & bs->supported_write_flags);
1297 flags &= ~bs->supported_write_flags;
1299 emulate_flags:
1300 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
1301 ret = bdrv_co_flush(bs);
1304 if (qiov == &local_qiov) {
1305 qemu_iovec_destroy(&local_qiov);
1308 return ret;
1311 static int coroutine_fn
1312 bdrv_driver_pwritev_compressed(BlockDriverState *bs, int64_t offset,
1313 int64_t bytes, QEMUIOVector *qiov,
1314 size_t qiov_offset)
1316 BlockDriver *drv = bs->drv;
1317 QEMUIOVector local_qiov;
1318 int ret;
1320 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1322 if (!drv) {
1323 return -ENOMEDIUM;
1326 if (!block_driver_can_compress(drv)) {
1327 return -ENOTSUP;
1330 if (drv->bdrv_co_pwritev_compressed_part) {
1331 return drv->bdrv_co_pwritev_compressed_part(bs, offset, bytes,
1332 qiov, qiov_offset);
1335 if (qiov_offset == 0) {
1336 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
1339 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1340 ret = drv->bdrv_co_pwritev_compressed(bs, offset, bytes, &local_qiov);
1341 qemu_iovec_destroy(&local_qiov);
1343 return ret;
1346 static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
1347 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
1348 size_t qiov_offset, int flags)
1350 BlockDriverState *bs = child->bs;
1352 /* Perform I/O through a temporary buffer so that users who scribble over
1353 * their read buffer while the operation is in progress do not end up
1354 * modifying the image file. This is critical for zero-copy guest I/O
1355 * where anything might happen inside guest memory.
1357 void *bounce_buffer = NULL;
1359 BlockDriver *drv = bs->drv;
1360 int64_t cluster_offset;
1361 int64_t cluster_bytes;
1362 int64_t skip_bytes;
1363 int ret;
1364 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1365 BDRV_REQUEST_MAX_BYTES);
1366 int64_t progress = 0;
1367 bool skip_write;
1369 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1371 if (!drv) {
1372 return -ENOMEDIUM;
1376 * Do not write anything when the BDS is inactive. That is not
1377 * allowed, and it would not help.
1379 skip_write = (bs->open_flags & BDRV_O_INACTIVE);
1381 /* FIXME We cannot require callers to have write permissions when all they
1382 * are doing is a read request. If we did things right, write permissions
1383 * would be obtained anyway, but internally by the copy-on-read code. As
1384 * long as it is implemented here rather than in a separate filter driver,
1385 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1386 * it could request permissions. Therefore we have to bypass the permission
1387 * system for the moment. */
1388 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1390 /* Cover entire cluster so no additional backing file I/O is required when
1391 * allocating cluster in the image file. Note that this value may exceed
1392 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1393 * is one reason we loop rather than doing it all at once.
1395 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
1396 skip_bytes = offset - cluster_offset;
1398 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
1399 cluster_offset, cluster_bytes);
1401 while (cluster_bytes) {
1402 int64_t pnum;
1404 if (skip_write) {
1405 ret = 1; /* "already allocated", so nothing will be copied */
1406 pnum = MIN(cluster_bytes, max_transfer);
1407 } else {
1408 ret = bdrv_is_allocated(bs, cluster_offset,
1409 MIN(cluster_bytes, max_transfer), &pnum);
1410 if (ret < 0) {
1412 * Safe to treat errors in querying allocation as if
1413 * unallocated; we'll probably fail again soon on the
1414 * read, but at least that will set a decent errno.
1416 pnum = MIN(cluster_bytes, max_transfer);
1419 /* Stop at EOF if the image ends in the middle of the cluster */
1420 if (ret == 0 && pnum == 0) {
1421 assert(progress >= bytes);
1422 break;
1425 assert(skip_bytes < pnum);
1428 if (ret <= 0) {
1429 QEMUIOVector local_qiov;
1431 /* Must copy-on-read; use the bounce buffer */
1432 pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1433 if (!bounce_buffer) {
1434 int64_t max_we_need = MAX(pnum, cluster_bytes - pnum);
1435 int64_t max_allowed = MIN(max_transfer, MAX_BOUNCE_BUFFER);
1436 int64_t bounce_buffer_len = MIN(max_we_need, max_allowed);
1438 bounce_buffer = qemu_try_blockalign(bs, bounce_buffer_len);
1439 if (!bounce_buffer) {
1440 ret = -ENOMEM;
1441 goto err;
1444 qemu_iovec_init_buf(&local_qiov, bounce_buffer, pnum);
1446 ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1447 &local_qiov, 0, 0);
1448 if (ret < 0) {
1449 goto err;
1452 bdrv_debug_event(bs, BLKDBG_COR_WRITE);
1453 if (drv->bdrv_co_pwrite_zeroes &&
1454 buffer_is_zero(bounce_buffer, pnum)) {
1455 /* FIXME: Should we (perhaps conditionally) be setting
1456 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1457 * that still correctly reads as zero? */
1458 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum,
1459 BDRV_REQ_WRITE_UNCHANGED);
1460 } else {
1461 /* This does not change the data on the disk, it is not
1462 * necessary to flush even in cache=writethrough mode.
1464 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
1465 &local_qiov, 0,
1466 BDRV_REQ_WRITE_UNCHANGED);
1469 if (ret < 0) {
1470 /* It might be okay to ignore write errors for guest
1471 * requests. If this is a deliberate copy-on-read
1472 * then we don't want to ignore the error. Simply
1473 * report it in all cases.
1475 goto err;
1478 if (!(flags & BDRV_REQ_PREFETCH)) {
1479 qemu_iovec_from_buf(qiov, qiov_offset + progress,
1480 bounce_buffer + skip_bytes,
1481 MIN(pnum - skip_bytes, bytes - progress));
1483 } else if (!(flags & BDRV_REQ_PREFETCH)) {
1484 /* Read directly into the destination */
1485 ret = bdrv_driver_preadv(bs, offset + progress,
1486 MIN(pnum - skip_bytes, bytes - progress),
1487 qiov, qiov_offset + progress, 0);
1488 if (ret < 0) {
1489 goto err;
1493 cluster_offset += pnum;
1494 cluster_bytes -= pnum;
1495 progress += pnum - skip_bytes;
1496 skip_bytes = 0;
1498 ret = 0;
1500 err:
1501 qemu_vfree(bounce_buffer);
1502 return ret;
1506 * Forwards an already correctly aligned request to the BlockDriver. This
1507 * handles copy on read, zeroing after EOF, and fragmentation of large
1508 * reads; any other features must be implemented by the caller.
1510 static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
1511 BdrvTrackedRequest *req, int64_t offset, int64_t bytes,
1512 int64_t align, QEMUIOVector *qiov, size_t qiov_offset, int flags)
1514 BlockDriverState *bs = child->bs;
1515 int64_t total_bytes, max_bytes;
1516 int ret = 0;
1517 int64_t bytes_remaining = bytes;
1518 int max_transfer;
1520 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1521 assert(is_power_of_2(align));
1522 assert((offset & (align - 1)) == 0);
1523 assert((bytes & (align - 1)) == 0);
1524 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1525 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1526 align);
1528 /* TODO: We would need a per-BDS .supported_read_flags and
1529 * potential fallback support, if we ever implement any read flags
1530 * to pass through to drivers. For now, there aren't any
1531 * passthrough flags. */
1532 assert(!(flags & ~(BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH)));
1534 /* Handle Copy on Read and associated serialisation */
1535 if (flags & BDRV_REQ_COPY_ON_READ) {
1536 /* If we touch the same cluster it counts as an overlap. This
1537 * guarantees that allocating writes will be serialized and not race
1538 * with each other for the same cluster. For example, in copy-on-read
1539 * it ensures that the CoR read and write operations are atomic and
1540 * guest writes cannot interleave between them. */
1541 bdrv_make_request_serialising(req, bdrv_get_cluster_size(bs));
1542 } else {
1543 bdrv_wait_serialising_requests(req);
1546 if (flags & BDRV_REQ_COPY_ON_READ) {
1547 int64_t pnum;
1549 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1550 flags &= ~BDRV_REQ_COPY_ON_READ;
1552 ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
1553 if (ret < 0) {
1554 goto out;
1557 if (!ret || pnum != bytes) {
1558 ret = bdrv_co_do_copy_on_readv(child, offset, bytes,
1559 qiov, qiov_offset, flags);
1560 goto out;
1561 } else if (flags & BDRV_REQ_PREFETCH) {
1562 goto out;
1566 /* Forward the request to the BlockDriver, possibly fragmenting it */
1567 total_bytes = bdrv_getlength(bs);
1568 if (total_bytes < 0) {
1569 ret = total_bytes;
1570 goto out;
1573 assert(!(flags & ~bs->supported_read_flags));
1575 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1576 if (bytes <= max_bytes && bytes <= max_transfer) {
1577 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, qiov_offset, flags);
1578 goto out;
1581 while (bytes_remaining) {
1582 int64_t num;
1584 if (max_bytes) {
1585 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1586 assert(num);
1588 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1589 num, qiov,
1590 qiov_offset + bytes - bytes_remaining,
1591 flags);
1592 max_bytes -= num;
1593 } else {
1594 num = bytes_remaining;
1595 ret = qemu_iovec_memset(qiov, qiov_offset + bytes - bytes_remaining,
1596 0, bytes_remaining);
1598 if (ret < 0) {
1599 goto out;
1601 bytes_remaining -= num;
1604 out:
1605 return ret < 0 ? ret : 0;
1609 * Request padding
1611 * |<---- align ----->| |<----- align ---->|
1612 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1613 * | | | | | |
1614 * -*----------$-------*-------- ... --------*-----$------------*---
1615 * | | | | | |
1616 * | offset | | end |
1617 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1618 * [buf ... ) [tail_buf )
1620 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1621 * is placed at the beginning of @buf and @tail at the @end.
1623 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1624 * around tail, if tail exists.
1626 * @merge_reads is true for small requests,
1627 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1628 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1630 typedef struct BdrvRequestPadding {
1631 uint8_t *buf;
1632 size_t buf_len;
1633 uint8_t *tail_buf;
1634 size_t head;
1635 size_t tail;
1636 bool merge_reads;
1637 QEMUIOVector local_qiov;
1638 } BdrvRequestPadding;
1640 static bool bdrv_init_padding(BlockDriverState *bs,
1641 int64_t offset, int64_t bytes,
1642 BdrvRequestPadding *pad)
1644 int64_t align = bs->bl.request_alignment;
1645 int64_t sum;
1647 bdrv_check_request(offset, bytes, &error_abort);
1648 assert(align <= INT_MAX); /* documented in block/block_int.h */
1649 assert(align <= SIZE_MAX / 2); /* so we can allocate the buffer */
1651 memset(pad, 0, sizeof(*pad));
1653 pad->head = offset & (align - 1);
1654 pad->tail = ((offset + bytes) & (align - 1));
1655 if (pad->tail) {
1656 pad->tail = align - pad->tail;
1659 if (!pad->head && !pad->tail) {
1660 return false;
1663 assert(bytes); /* Nothing good in aligning zero-length requests */
1665 sum = pad->head + bytes + pad->tail;
1666 pad->buf_len = (sum > align && pad->head && pad->tail) ? 2 * align : align;
1667 pad->buf = qemu_blockalign(bs, pad->buf_len);
1668 pad->merge_reads = sum == pad->buf_len;
1669 if (pad->tail) {
1670 pad->tail_buf = pad->buf + pad->buf_len - align;
1673 return true;
1676 static int bdrv_padding_rmw_read(BdrvChild *child,
1677 BdrvTrackedRequest *req,
1678 BdrvRequestPadding *pad,
1679 bool zero_middle)
1681 QEMUIOVector local_qiov;
1682 BlockDriverState *bs = child->bs;
1683 uint64_t align = bs->bl.request_alignment;
1684 int ret;
1686 assert(req->serialising && pad->buf);
1688 if (pad->head || pad->merge_reads) {
1689 int64_t bytes = pad->merge_reads ? pad->buf_len : align;
1691 qemu_iovec_init_buf(&local_qiov, pad->buf, bytes);
1693 if (pad->head) {
1694 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1696 if (pad->merge_reads && pad->tail) {
1697 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1699 ret = bdrv_aligned_preadv(child, req, req->overlap_offset, bytes,
1700 align, &local_qiov, 0, 0);
1701 if (ret < 0) {
1702 return ret;
1704 if (pad->head) {
1705 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1707 if (pad->merge_reads && pad->tail) {
1708 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1711 if (pad->merge_reads) {
1712 goto zero_mem;
1716 if (pad->tail) {
1717 qemu_iovec_init_buf(&local_qiov, pad->tail_buf, align);
1719 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1720 ret = bdrv_aligned_preadv(
1721 child, req,
1722 req->overlap_offset + req->overlap_bytes - align,
1723 align, align, &local_qiov, 0, 0);
1724 if (ret < 0) {
1725 return ret;
1727 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1730 zero_mem:
1731 if (zero_middle) {
1732 memset(pad->buf + pad->head, 0, pad->buf_len - pad->head - pad->tail);
1735 return 0;
1738 static void bdrv_padding_destroy(BdrvRequestPadding *pad)
1740 if (pad->buf) {
1741 qemu_vfree(pad->buf);
1742 qemu_iovec_destroy(&pad->local_qiov);
1744 memset(pad, 0, sizeof(*pad));
1748 * bdrv_pad_request
1750 * Exchange request parameters with padded request if needed. Don't include RMW
1751 * read of padding, bdrv_padding_rmw_read() should be called separately if
1752 * needed.
1754 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1755 * - on function start they represent original request
1756 * - on failure or when padding is not needed they are unchanged
1757 * - on success when padding is needed they represent padded request
1759 static int bdrv_pad_request(BlockDriverState *bs,
1760 QEMUIOVector **qiov, size_t *qiov_offset,
1761 int64_t *offset, int64_t *bytes,
1762 BdrvRequestPadding *pad, bool *padded)
1764 int ret;
1766 bdrv_check_qiov_request(*offset, *bytes, *qiov, *qiov_offset, &error_abort);
1768 if (!bdrv_init_padding(bs, *offset, *bytes, pad)) {
1769 if (padded) {
1770 *padded = false;
1772 return 0;
1775 ret = qemu_iovec_init_extended(&pad->local_qiov, pad->buf, pad->head,
1776 *qiov, *qiov_offset, *bytes,
1777 pad->buf + pad->buf_len - pad->tail,
1778 pad->tail);
1779 if (ret < 0) {
1780 bdrv_padding_destroy(pad);
1781 return ret;
1783 *bytes += pad->head + pad->tail;
1784 *offset -= pad->head;
1785 *qiov = &pad->local_qiov;
1786 *qiov_offset = 0;
1787 if (padded) {
1788 *padded = true;
1791 return 0;
1794 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1795 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
1796 BdrvRequestFlags flags)
1798 return bdrv_co_preadv_part(child, offset, bytes, qiov, 0, flags);
1801 int coroutine_fn bdrv_co_preadv_part(BdrvChild *child,
1802 int64_t offset, int64_t bytes,
1803 QEMUIOVector *qiov, size_t qiov_offset,
1804 BdrvRequestFlags flags)
1806 BlockDriverState *bs = child->bs;
1807 BdrvTrackedRequest req;
1808 BdrvRequestPadding pad;
1809 int ret;
1811 trace_bdrv_co_preadv_part(bs, offset, bytes, flags);
1813 if (!bdrv_is_inserted(bs)) {
1814 return -ENOMEDIUM;
1817 ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
1818 if (ret < 0) {
1819 return ret;
1822 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
1824 * Aligning zero request is nonsense. Even if driver has special meaning
1825 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1826 * it to driver due to request_alignment.
1828 * Still, no reason to return an error if someone do unaligned
1829 * zero-length read occasionally.
1831 return 0;
1834 bdrv_inc_in_flight(bs);
1836 /* Don't do copy-on-read if we read data before write operation */
1837 if (qatomic_read(&bs->copy_on_read)) {
1838 flags |= BDRV_REQ_COPY_ON_READ;
1841 ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
1842 NULL);
1843 if (ret < 0) {
1844 goto fail;
1847 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1848 ret = bdrv_aligned_preadv(child, &req, offset, bytes,
1849 bs->bl.request_alignment,
1850 qiov, qiov_offset, flags);
1851 tracked_request_end(&req);
1852 bdrv_padding_destroy(&pad);
1854 fail:
1855 bdrv_dec_in_flight(bs);
1857 return ret;
1860 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1861 int64_t offset, int64_t bytes, BdrvRequestFlags flags)
1863 BlockDriver *drv = bs->drv;
1864 QEMUIOVector qiov;
1865 void *buf = NULL;
1866 int ret = 0;
1867 bool need_flush = false;
1868 int head = 0;
1869 int tail = 0;
1871 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
1872 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1873 bs->bl.request_alignment);
1874 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
1876 bdrv_check_request(offset, bytes, &error_abort);
1878 if (!drv) {
1879 return -ENOMEDIUM;
1882 if ((flags & ~bs->supported_zero_flags) & BDRV_REQ_NO_FALLBACK) {
1883 return -ENOTSUP;
1886 /* Invalidate the cached block-status data range if this write overlaps */
1887 bdrv_bsc_invalidate_range(bs, offset, bytes);
1889 assert(alignment % bs->bl.request_alignment == 0);
1890 head = offset % alignment;
1891 tail = (offset + bytes) % alignment;
1892 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1893 assert(max_write_zeroes >= bs->bl.request_alignment);
1895 while (bytes > 0 && !ret) {
1896 int64_t num = bytes;
1898 /* Align request. Block drivers can expect the "bulk" of the request
1899 * to be aligned, and that unaligned requests do not cross cluster
1900 * boundaries.
1902 if (head) {
1903 /* Make a small request up to the first aligned sector. For
1904 * convenience, limit this request to max_transfer even if
1905 * we don't need to fall back to writes. */
1906 num = MIN(MIN(bytes, max_transfer), alignment - head);
1907 head = (head + num) % alignment;
1908 assert(num < max_write_zeroes);
1909 } else if (tail && num > alignment) {
1910 /* Shorten the request to the last aligned sector. */
1911 num -= tail;
1914 /* limit request size */
1915 if (num > max_write_zeroes) {
1916 num = max_write_zeroes;
1919 ret = -ENOTSUP;
1920 /* First try the efficient write zeroes operation */
1921 if (drv->bdrv_co_pwrite_zeroes) {
1922 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1923 flags & bs->supported_zero_flags);
1924 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1925 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1926 need_flush = true;
1928 } else {
1929 assert(!bs->supported_zero_flags);
1932 if (ret == -ENOTSUP && !(flags & BDRV_REQ_NO_FALLBACK)) {
1933 /* Fall back to bounce buffer if write zeroes is unsupported */
1934 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1936 if ((flags & BDRV_REQ_FUA) &&
1937 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1938 /* No need for bdrv_driver_pwrite() to do a fallback
1939 * flush on each chunk; use just one at the end */
1940 write_flags &= ~BDRV_REQ_FUA;
1941 need_flush = true;
1943 num = MIN(num, max_transfer);
1944 if (buf == NULL) {
1945 buf = qemu_try_blockalign0(bs, num);
1946 if (buf == NULL) {
1947 ret = -ENOMEM;
1948 goto fail;
1951 qemu_iovec_init_buf(&qiov, buf, num);
1953 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, 0, write_flags);
1955 /* Keep bounce buffer around if it is big enough for all
1956 * all future requests.
1958 if (num < max_transfer) {
1959 qemu_vfree(buf);
1960 buf = NULL;
1964 offset += num;
1965 bytes -= num;
1968 fail:
1969 if (ret == 0 && need_flush) {
1970 ret = bdrv_co_flush(bs);
1972 qemu_vfree(buf);
1973 return ret;
1976 static inline int coroutine_fn
1977 bdrv_co_write_req_prepare(BdrvChild *child, int64_t offset, int64_t bytes,
1978 BdrvTrackedRequest *req, int flags)
1980 BlockDriverState *bs = child->bs;
1982 bdrv_check_request(offset, bytes, &error_abort);
1984 if (bdrv_is_read_only(bs)) {
1985 return -EPERM;
1988 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1989 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1990 assert(!(flags & ~BDRV_REQ_MASK));
1991 assert(!((flags & BDRV_REQ_NO_WAIT) && !(flags & BDRV_REQ_SERIALISING)));
1993 if (flags & BDRV_REQ_SERIALISING) {
1994 QEMU_LOCK_GUARD(&bs->reqs_lock);
1996 tracked_request_set_serialising(req, bdrv_get_cluster_size(bs));
1998 if ((flags & BDRV_REQ_NO_WAIT) && bdrv_find_conflicting_request(req)) {
1999 return -EBUSY;
2002 bdrv_wait_serialising_requests_locked(req);
2003 } else {
2004 bdrv_wait_serialising_requests(req);
2007 assert(req->overlap_offset <= offset);
2008 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
2009 assert(offset + bytes <= bs->total_sectors * BDRV_SECTOR_SIZE ||
2010 child->perm & BLK_PERM_RESIZE);
2012 switch (req->type) {
2013 case BDRV_TRACKED_WRITE:
2014 case BDRV_TRACKED_DISCARD:
2015 if (flags & BDRV_REQ_WRITE_UNCHANGED) {
2016 assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
2017 } else {
2018 assert(child->perm & BLK_PERM_WRITE);
2020 bdrv_write_threshold_check_write(bs, offset, bytes);
2021 return 0;
2022 case BDRV_TRACKED_TRUNCATE:
2023 assert(child->perm & BLK_PERM_RESIZE);
2024 return 0;
2025 default:
2026 abort();
2030 static inline void coroutine_fn
2031 bdrv_co_write_req_finish(BdrvChild *child, int64_t offset, int64_t bytes,
2032 BdrvTrackedRequest *req, int ret)
2034 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
2035 BlockDriverState *bs = child->bs;
2037 bdrv_check_request(offset, bytes, &error_abort);
2039 qatomic_inc(&bs->write_gen);
2042 * Discard cannot extend the image, but in error handling cases, such as
2043 * when reverting a qcow2 cluster allocation, the discarded range can pass
2044 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
2045 * here. Instead, just skip it, since semantically a discard request
2046 * beyond EOF cannot expand the image anyway.
2048 if (ret == 0 &&
2049 (req->type == BDRV_TRACKED_TRUNCATE ||
2050 end_sector > bs->total_sectors) &&
2051 req->type != BDRV_TRACKED_DISCARD) {
2052 bs->total_sectors = end_sector;
2053 bdrv_parent_cb_resize(bs);
2054 bdrv_dirty_bitmap_truncate(bs, end_sector << BDRV_SECTOR_BITS);
2056 if (req->bytes) {
2057 switch (req->type) {
2058 case BDRV_TRACKED_WRITE:
2059 stat64_max(&bs->wr_highest_offset, offset + bytes);
2060 /* fall through, to set dirty bits */
2061 case BDRV_TRACKED_DISCARD:
2062 bdrv_set_dirty(bs, offset, bytes);
2063 break;
2064 default:
2065 break;
2071 * Forwards an already correctly aligned write request to the BlockDriver,
2072 * after possibly fragmenting it.
2074 static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
2075 BdrvTrackedRequest *req, int64_t offset, int64_t bytes,
2076 int64_t align, QEMUIOVector *qiov, size_t qiov_offset, int flags)
2078 BlockDriverState *bs = child->bs;
2079 BlockDriver *drv = bs->drv;
2080 int ret;
2082 int64_t bytes_remaining = bytes;
2083 int max_transfer;
2085 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
2087 if (!drv) {
2088 return -ENOMEDIUM;
2091 if (bdrv_has_readonly_bitmaps(bs)) {
2092 return -EPERM;
2095 assert(is_power_of_2(align));
2096 assert((offset & (align - 1)) == 0);
2097 assert((bytes & (align - 1)) == 0);
2098 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
2099 align);
2101 ret = bdrv_co_write_req_prepare(child, offset, bytes, req, flags);
2103 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
2104 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
2105 qemu_iovec_is_zero(qiov, qiov_offset, bytes)) {
2106 flags |= BDRV_REQ_ZERO_WRITE;
2107 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
2108 flags |= BDRV_REQ_MAY_UNMAP;
2112 if (ret < 0) {
2113 /* Do nothing, write notifier decided to fail this request */
2114 } else if (flags & BDRV_REQ_ZERO_WRITE) {
2115 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
2116 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
2117 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
2118 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes,
2119 qiov, qiov_offset);
2120 } else if (bytes <= max_transfer) {
2121 bdrv_debug_event(bs, BLKDBG_PWRITEV);
2122 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, qiov_offset, flags);
2123 } else {
2124 bdrv_debug_event(bs, BLKDBG_PWRITEV);
2125 while (bytes_remaining) {
2126 int num = MIN(bytes_remaining, max_transfer);
2127 int local_flags = flags;
2129 assert(num);
2130 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
2131 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
2132 /* If FUA is going to be emulated by flush, we only
2133 * need to flush on the last iteration */
2134 local_flags &= ~BDRV_REQ_FUA;
2137 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
2138 num, qiov,
2139 qiov_offset + bytes - bytes_remaining,
2140 local_flags);
2141 if (ret < 0) {
2142 break;
2144 bytes_remaining -= num;
2147 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
2149 if (ret >= 0) {
2150 ret = 0;
2152 bdrv_co_write_req_finish(child, offset, bytes, req, ret);
2154 return ret;
2157 static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
2158 int64_t offset,
2159 int64_t bytes,
2160 BdrvRequestFlags flags,
2161 BdrvTrackedRequest *req)
2163 BlockDriverState *bs = child->bs;
2164 QEMUIOVector local_qiov;
2165 uint64_t align = bs->bl.request_alignment;
2166 int ret = 0;
2167 bool padding;
2168 BdrvRequestPadding pad;
2170 padding = bdrv_init_padding(bs, offset, bytes, &pad);
2171 if (padding) {
2172 bdrv_make_request_serialising(req, align);
2174 bdrv_padding_rmw_read(child, req, &pad, true);
2176 if (pad.head || pad.merge_reads) {
2177 int64_t aligned_offset = offset & ~(align - 1);
2178 int64_t write_bytes = pad.merge_reads ? pad.buf_len : align;
2180 qemu_iovec_init_buf(&local_qiov, pad.buf, write_bytes);
2181 ret = bdrv_aligned_pwritev(child, req, aligned_offset, write_bytes,
2182 align, &local_qiov, 0,
2183 flags & ~BDRV_REQ_ZERO_WRITE);
2184 if (ret < 0 || pad.merge_reads) {
2185 /* Error or all work is done */
2186 goto out;
2188 offset += write_bytes - pad.head;
2189 bytes -= write_bytes - pad.head;
2193 assert(!bytes || (offset & (align - 1)) == 0);
2194 if (bytes >= align) {
2195 /* Write the aligned part in the middle. */
2196 int64_t aligned_bytes = bytes & ~(align - 1);
2197 ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
2198 NULL, 0, flags);
2199 if (ret < 0) {
2200 goto out;
2202 bytes -= aligned_bytes;
2203 offset += aligned_bytes;
2206 assert(!bytes || (offset & (align - 1)) == 0);
2207 if (bytes) {
2208 assert(align == pad.tail + bytes);
2210 qemu_iovec_init_buf(&local_qiov, pad.tail_buf, align);
2211 ret = bdrv_aligned_pwritev(child, req, offset, align, align,
2212 &local_qiov, 0,
2213 flags & ~BDRV_REQ_ZERO_WRITE);
2216 out:
2217 bdrv_padding_destroy(&pad);
2219 return ret;
2223 * Handle a write request in coroutine context
2225 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
2226 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
2227 BdrvRequestFlags flags)
2229 return bdrv_co_pwritev_part(child, offset, bytes, qiov, 0, flags);
2232 int coroutine_fn bdrv_co_pwritev_part(BdrvChild *child,
2233 int64_t offset, int64_t bytes, QEMUIOVector *qiov, size_t qiov_offset,
2234 BdrvRequestFlags flags)
2236 BlockDriverState *bs = child->bs;
2237 BdrvTrackedRequest req;
2238 uint64_t align = bs->bl.request_alignment;
2239 BdrvRequestPadding pad;
2240 int ret;
2241 bool padded = false;
2243 trace_bdrv_co_pwritev_part(child->bs, offset, bytes, flags);
2245 if (!bdrv_is_inserted(bs)) {
2246 return -ENOMEDIUM;
2249 ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
2250 if (ret < 0) {
2251 return ret;
2254 /* If the request is misaligned then we can't make it efficient */
2255 if ((flags & BDRV_REQ_NO_FALLBACK) &&
2256 !QEMU_IS_ALIGNED(offset | bytes, align))
2258 return -ENOTSUP;
2261 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
2263 * Aligning zero request is nonsense. Even if driver has special meaning
2264 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2265 * it to driver due to request_alignment.
2267 * Still, no reason to return an error if someone do unaligned
2268 * zero-length write occasionally.
2270 return 0;
2273 if (!(flags & BDRV_REQ_ZERO_WRITE)) {
2275 * Pad request for following read-modify-write cycle.
2276 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2277 * alignment only if there is no ZERO flag.
2279 ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
2280 &padded);
2281 if (ret < 0) {
2282 return ret;
2286 bdrv_inc_in_flight(bs);
2287 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
2289 if (flags & BDRV_REQ_ZERO_WRITE) {
2290 assert(!padded);
2291 ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
2292 goto out;
2295 if (padded) {
2297 * Request was unaligned to request_alignment and therefore
2298 * padded. We are going to do read-modify-write, and must
2299 * serialize the request to prevent interactions of the
2300 * widened region with other transactions.
2302 bdrv_make_request_serialising(&req, align);
2303 bdrv_padding_rmw_read(child, &req, &pad, false);
2306 ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
2307 qiov, qiov_offset, flags);
2309 bdrv_padding_destroy(&pad);
2311 out:
2312 tracked_request_end(&req);
2313 bdrv_dec_in_flight(bs);
2315 return ret;
2318 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
2319 int64_t bytes, BdrvRequestFlags flags)
2321 trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
2323 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
2324 flags &= ~BDRV_REQ_MAY_UNMAP;
2327 return bdrv_co_pwritev(child, offset, bytes, NULL,
2328 BDRV_REQ_ZERO_WRITE | flags);
2332 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2334 int bdrv_flush_all(void)
2336 BdrvNextIterator it;
2337 BlockDriverState *bs = NULL;
2338 int result = 0;
2341 * bdrv queue is managed by record/replay,
2342 * creating new flush request for stopping
2343 * the VM may break the determinism
2345 if (replay_events_enabled()) {
2346 return result;
2349 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
2350 AioContext *aio_context = bdrv_get_aio_context(bs);
2351 int ret;
2353 aio_context_acquire(aio_context);
2354 ret = bdrv_flush(bs);
2355 if (ret < 0 && !result) {
2356 result = ret;
2358 aio_context_release(aio_context);
2361 return result;
2365 * Returns the allocation status of the specified sectors.
2366 * Drivers not implementing the functionality are assumed to not support
2367 * backing files, hence all their sectors are reported as allocated.
2369 * If 'want_zero' is true, the caller is querying for mapping
2370 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2371 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2372 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2374 * If 'offset' is beyond the end of the disk image the return value is
2375 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2377 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2378 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2379 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2381 * 'pnum' is set to the number of bytes (including and immediately
2382 * following the specified offset) that are easily known to be in the
2383 * same allocated/unallocated state. Note that a second call starting
2384 * at the original offset plus returned pnum may have the same status.
2385 * The returned value is non-zero on success except at end-of-file.
2387 * Returns negative errno on failure. Otherwise, if the
2388 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2389 * set to the host mapping and BDS corresponding to the guest offset.
2391 static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
2392 bool want_zero,
2393 int64_t offset, int64_t bytes,
2394 int64_t *pnum, int64_t *map,
2395 BlockDriverState **file)
2397 int64_t total_size;
2398 int64_t n; /* bytes */
2399 int ret;
2400 int64_t local_map = 0;
2401 BlockDriverState *local_file = NULL;
2402 int64_t aligned_offset, aligned_bytes;
2403 uint32_t align;
2404 bool has_filtered_child;
2406 assert(pnum);
2407 *pnum = 0;
2408 total_size = bdrv_getlength(bs);
2409 if (total_size < 0) {
2410 ret = total_size;
2411 goto early_out;
2414 if (offset >= total_size) {
2415 ret = BDRV_BLOCK_EOF;
2416 goto early_out;
2418 if (!bytes) {
2419 ret = 0;
2420 goto early_out;
2423 n = total_size - offset;
2424 if (n < bytes) {
2425 bytes = n;
2428 /* Must be non-NULL or bdrv_getlength() would have failed */
2429 assert(bs->drv);
2430 has_filtered_child = bdrv_filter_child(bs);
2431 if (!bs->drv->bdrv_co_block_status && !has_filtered_child) {
2432 *pnum = bytes;
2433 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2434 if (offset + bytes == total_size) {
2435 ret |= BDRV_BLOCK_EOF;
2437 if (bs->drv->protocol_name) {
2438 ret |= BDRV_BLOCK_OFFSET_VALID;
2439 local_map = offset;
2440 local_file = bs;
2442 goto early_out;
2445 bdrv_inc_in_flight(bs);
2447 /* Round out to request_alignment boundaries */
2448 align = bs->bl.request_alignment;
2449 aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2450 aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2452 if (bs->drv->bdrv_co_block_status) {
2454 * Use the block-status cache only for protocol nodes: Format
2455 * drivers are generally quick to inquire the status, but protocol
2456 * drivers often need to get information from outside of qemu, so
2457 * we do not have control over the actual implementation. There
2458 * have been cases where inquiring the status took an unreasonably
2459 * long time, and we can do nothing in qemu to fix it.
2460 * This is especially problematic for images with large data areas,
2461 * because finding the few holes in them and giving them special
2462 * treatment does not gain much performance. Therefore, we try to
2463 * cache the last-identified data region.
2465 * Second, limiting ourselves to protocol nodes allows us to assume
2466 * the block status for data regions to be DATA | OFFSET_VALID, and
2467 * that the host offset is the same as the guest offset.
2469 * Note that it is possible that external writers zero parts of
2470 * the cached regions without the cache being invalidated, and so
2471 * we may report zeroes as data. This is not catastrophic,
2472 * however, because reporting zeroes as data is fine.
2474 if (QLIST_EMPTY(&bs->children) &&
2475 bdrv_bsc_is_data(bs, aligned_offset, pnum))
2477 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2478 local_file = bs;
2479 local_map = aligned_offset;
2480 } else {
2481 ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2482 aligned_bytes, pnum, &local_map,
2483 &local_file);
2486 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2487 * the cache is queried above. Technically, we do not need to check
2488 * it here; the worst that can happen is that we fill the cache for
2489 * non-protocol nodes, and then it is never used. However, filling
2490 * the cache requires an RCU update, so double check here to avoid
2491 * such an update if possible.
2493 if (ret == (BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID) &&
2494 QLIST_EMPTY(&bs->children))
2497 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2498 * returned local_map value must be the same as the offset we
2499 * have passed (aligned_offset), and local_bs must be the node
2500 * itself.
2501 * Assert this, because we follow this rule when reading from
2502 * the cache (see the `local_file = bs` and
2503 * `local_map = aligned_offset` assignments above), and the
2504 * result the cache delivers must be the same as the driver
2505 * would deliver.
2507 assert(local_file == bs);
2508 assert(local_map == aligned_offset);
2509 bdrv_bsc_fill(bs, aligned_offset, *pnum);
2512 } else {
2513 /* Default code for filters */
2515 local_file = bdrv_filter_bs(bs);
2516 assert(local_file);
2518 *pnum = aligned_bytes;
2519 local_map = aligned_offset;
2520 ret = BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2522 if (ret < 0) {
2523 *pnum = 0;
2524 goto out;
2528 * The driver's result must be a non-zero multiple of request_alignment.
2529 * Clamp pnum and adjust map to original request.
2531 assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2532 align > offset - aligned_offset);
2533 if (ret & BDRV_BLOCK_RECURSE) {
2534 assert(ret & BDRV_BLOCK_DATA);
2535 assert(ret & BDRV_BLOCK_OFFSET_VALID);
2536 assert(!(ret & BDRV_BLOCK_ZERO));
2539 *pnum -= offset - aligned_offset;
2540 if (*pnum > bytes) {
2541 *pnum = bytes;
2543 if (ret & BDRV_BLOCK_OFFSET_VALID) {
2544 local_map += offset - aligned_offset;
2547 if (ret & BDRV_BLOCK_RAW) {
2548 assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2549 ret = bdrv_co_block_status(local_file, want_zero, local_map,
2550 *pnum, pnum, &local_map, &local_file);
2551 goto out;
2554 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2555 ret |= BDRV_BLOCK_ALLOCATED;
2556 } else if (bs->drv->supports_backing) {
2557 BlockDriverState *cow_bs = bdrv_cow_bs(bs);
2559 if (!cow_bs) {
2560 ret |= BDRV_BLOCK_ZERO;
2561 } else if (want_zero) {
2562 int64_t size2 = bdrv_getlength(cow_bs);
2564 if (size2 >= 0 && offset >= size2) {
2565 ret |= BDRV_BLOCK_ZERO;
2570 if (want_zero && ret & BDRV_BLOCK_RECURSE &&
2571 local_file && local_file != bs &&
2572 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2573 (ret & BDRV_BLOCK_OFFSET_VALID)) {
2574 int64_t file_pnum;
2575 int ret2;
2577 ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2578 *pnum, &file_pnum, NULL, NULL);
2579 if (ret2 >= 0) {
2580 /* Ignore errors. This is just providing extra information, it
2581 * is useful but not necessary.
2583 if (ret2 & BDRV_BLOCK_EOF &&
2584 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2586 * It is valid for the format block driver to read
2587 * beyond the end of the underlying file's current
2588 * size; such areas read as zero.
2590 ret |= BDRV_BLOCK_ZERO;
2591 } else {
2592 /* Limit request to the range reported by the protocol driver */
2593 *pnum = file_pnum;
2594 ret |= (ret2 & BDRV_BLOCK_ZERO);
2599 out:
2600 bdrv_dec_in_flight(bs);
2601 if (ret >= 0 && offset + *pnum == total_size) {
2602 ret |= BDRV_BLOCK_EOF;
2604 early_out:
2605 if (file) {
2606 *file = local_file;
2608 if (map) {
2609 *map = local_map;
2611 return ret;
2614 int coroutine_fn
2615 bdrv_co_common_block_status_above(BlockDriverState *bs,
2616 BlockDriverState *base,
2617 bool include_base,
2618 bool want_zero,
2619 int64_t offset,
2620 int64_t bytes,
2621 int64_t *pnum,
2622 int64_t *map,
2623 BlockDriverState **file,
2624 int *depth)
2626 int ret;
2627 BlockDriverState *p;
2628 int64_t eof = 0;
2629 int dummy;
2631 assert(!include_base || base); /* Can't include NULL base */
2633 if (!depth) {
2634 depth = &dummy;
2636 *depth = 0;
2638 if (!include_base && bs == base) {
2639 *pnum = bytes;
2640 return 0;
2643 ret = bdrv_co_block_status(bs, want_zero, offset, bytes, pnum, map, file);
2644 ++*depth;
2645 if (ret < 0 || *pnum == 0 || ret & BDRV_BLOCK_ALLOCATED || bs == base) {
2646 return ret;
2649 if (ret & BDRV_BLOCK_EOF) {
2650 eof = offset + *pnum;
2653 assert(*pnum <= bytes);
2654 bytes = *pnum;
2656 for (p = bdrv_filter_or_cow_bs(bs); include_base || p != base;
2657 p = bdrv_filter_or_cow_bs(p))
2659 ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2660 file);
2661 ++*depth;
2662 if (ret < 0) {
2663 return ret;
2665 if (*pnum == 0) {
2667 * The top layer deferred to this layer, and because this layer is
2668 * short, any zeroes that we synthesize beyond EOF behave as if they
2669 * were allocated at this layer.
2671 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2672 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2673 * below.
2675 assert(ret & BDRV_BLOCK_EOF);
2676 *pnum = bytes;
2677 if (file) {
2678 *file = p;
2680 ret = BDRV_BLOCK_ZERO | BDRV_BLOCK_ALLOCATED;
2681 break;
2683 if (ret & BDRV_BLOCK_ALLOCATED) {
2685 * We've found the node and the status, we must break.
2687 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2688 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2689 * below.
2691 ret &= ~BDRV_BLOCK_EOF;
2692 break;
2695 if (p == base) {
2696 assert(include_base);
2697 break;
2701 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2702 * let's continue the diving.
2704 assert(*pnum <= bytes);
2705 bytes = *pnum;
2708 if (offset + *pnum == eof) {
2709 ret |= BDRV_BLOCK_EOF;
2712 return ret;
2715 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2716 int64_t offset, int64_t bytes, int64_t *pnum,
2717 int64_t *map, BlockDriverState **file)
2719 return bdrv_common_block_status_above(bs, base, false, true, offset, bytes,
2720 pnum, map, file, NULL);
2723 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2724 int64_t *pnum, int64_t *map, BlockDriverState **file)
2726 return bdrv_block_status_above(bs, bdrv_filter_or_cow_bs(bs),
2727 offset, bytes, pnum, map, file);
2731 * Check @bs (and its backing chain) to see if the range defined
2732 * by @offset and @bytes is known to read as zeroes.
2733 * Return 1 if that is the case, 0 otherwise and -errno on error.
2734 * This test is meant to be fast rather than accurate so returning 0
2735 * does not guarantee non-zero data.
2737 int coroutine_fn bdrv_co_is_zero_fast(BlockDriverState *bs, int64_t offset,
2738 int64_t bytes)
2740 int ret;
2741 int64_t pnum = bytes;
2743 if (!bytes) {
2744 return 1;
2747 ret = bdrv_common_block_status_above(bs, NULL, false, false, offset,
2748 bytes, &pnum, NULL, NULL, NULL);
2750 if (ret < 0) {
2751 return ret;
2754 return (pnum == bytes) && (ret & BDRV_BLOCK_ZERO);
2757 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
2758 int64_t bytes, int64_t *pnum)
2760 int ret;
2761 int64_t dummy;
2763 ret = bdrv_common_block_status_above(bs, bs, true, false, offset,
2764 bytes, pnum ? pnum : &dummy, NULL,
2765 NULL, NULL);
2766 if (ret < 0) {
2767 return ret;
2769 return !!(ret & BDRV_BLOCK_ALLOCATED);
2773 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2775 * Return a positive depth if (a prefix of) the given range is allocated
2776 * in any image between BASE and TOP (BASE is only included if include_base
2777 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2778 * BASE can be NULL to check if the given offset is allocated in any
2779 * image of the chain. Return 0 otherwise, or negative errno on
2780 * failure.
2782 * 'pnum' is set to the number of bytes (including and immediately
2783 * following the specified offset) that are known to be in the same
2784 * allocated/unallocated state. Note that a subsequent call starting
2785 * at 'offset + *pnum' may return the same allocation status (in other
2786 * words, the result is not necessarily the maximum possible range);
2787 * but 'pnum' will only be 0 when end of file is reached.
2789 int bdrv_is_allocated_above(BlockDriverState *top,
2790 BlockDriverState *base,
2791 bool include_base, int64_t offset,
2792 int64_t bytes, int64_t *pnum)
2794 int depth;
2795 int ret = bdrv_common_block_status_above(top, base, include_base, false,
2796 offset, bytes, pnum, NULL, NULL,
2797 &depth);
2798 if (ret < 0) {
2799 return ret;
2802 if (ret & BDRV_BLOCK_ALLOCATED) {
2803 return depth;
2805 return 0;
2808 int coroutine_fn
2809 bdrv_co_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2811 BlockDriver *drv = bs->drv;
2812 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2813 int ret = -ENOTSUP;
2815 if (!drv) {
2816 return -ENOMEDIUM;
2819 bdrv_inc_in_flight(bs);
2821 if (drv->bdrv_load_vmstate) {
2822 ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2823 } else if (child_bs) {
2824 ret = bdrv_co_readv_vmstate(child_bs, qiov, pos);
2827 bdrv_dec_in_flight(bs);
2829 return ret;
2832 int coroutine_fn
2833 bdrv_co_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2835 BlockDriver *drv = bs->drv;
2836 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2837 int ret = -ENOTSUP;
2839 if (!drv) {
2840 return -ENOMEDIUM;
2843 bdrv_inc_in_flight(bs);
2845 if (drv->bdrv_save_vmstate) {
2846 ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2847 } else if (child_bs) {
2848 ret = bdrv_co_writev_vmstate(child_bs, qiov, pos);
2851 bdrv_dec_in_flight(bs);
2853 return ret;
2856 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2857 int64_t pos, int size)
2859 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2860 int ret = bdrv_writev_vmstate(bs, &qiov, pos);
2862 return ret < 0 ? ret : size;
2865 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2866 int64_t pos, int size)
2868 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2869 int ret = bdrv_readv_vmstate(bs, &qiov, pos);
2871 return ret < 0 ? ret : size;
2874 /**************************************************************/
2875 /* async I/Os */
2877 void bdrv_aio_cancel(BlockAIOCB *acb)
2879 qemu_aio_ref(acb);
2880 bdrv_aio_cancel_async(acb);
2881 while (acb->refcnt > 1) {
2882 if (acb->aiocb_info->get_aio_context) {
2883 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2884 } else if (acb->bs) {
2885 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2886 * assert that we're not using an I/O thread. Thread-safe
2887 * code should use bdrv_aio_cancel_async exclusively.
2889 assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2890 aio_poll(bdrv_get_aio_context(acb->bs), true);
2891 } else {
2892 abort();
2895 qemu_aio_unref(acb);
2898 /* Async version of aio cancel. The caller is not blocked if the acb implements
2899 * cancel_async, otherwise we do nothing and let the request normally complete.
2900 * In either case the completion callback must be called. */
2901 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2903 if (acb->aiocb_info->cancel_async) {
2904 acb->aiocb_info->cancel_async(acb);
2908 /**************************************************************/
2909 /* Coroutine block device emulation */
2911 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2913 BdrvChild *primary_child = bdrv_primary_child(bs);
2914 BdrvChild *child;
2915 int current_gen;
2916 int ret = 0;
2918 bdrv_inc_in_flight(bs);
2920 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2921 bdrv_is_sg(bs)) {
2922 goto early_exit;
2925 qemu_co_mutex_lock(&bs->reqs_lock);
2926 current_gen = qatomic_read(&bs->write_gen);
2928 /* Wait until any previous flushes are completed */
2929 while (bs->active_flush_req) {
2930 qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
2933 /* Flushes reach this point in nondecreasing current_gen order. */
2934 bs->active_flush_req = true;
2935 qemu_co_mutex_unlock(&bs->reqs_lock);
2937 /* Write back all layers by calling one driver function */
2938 if (bs->drv->bdrv_co_flush) {
2939 ret = bs->drv->bdrv_co_flush(bs);
2940 goto out;
2943 /* Write back cached data to the OS even with cache=unsafe */
2944 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_OS);
2945 if (bs->drv->bdrv_co_flush_to_os) {
2946 ret = bs->drv->bdrv_co_flush_to_os(bs);
2947 if (ret < 0) {
2948 goto out;
2952 /* But don't actually force it to the disk with cache=unsafe */
2953 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2954 goto flush_children;
2957 /* Check if we really need to flush anything */
2958 if (bs->flushed_gen == current_gen) {
2959 goto flush_children;
2962 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_DISK);
2963 if (!bs->drv) {
2964 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2965 * (even in case of apparent success) */
2966 ret = -ENOMEDIUM;
2967 goto out;
2969 if (bs->drv->bdrv_co_flush_to_disk) {
2970 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2971 } else if (bs->drv->bdrv_aio_flush) {
2972 BlockAIOCB *acb;
2973 CoroutineIOCompletion co = {
2974 .coroutine = qemu_coroutine_self(),
2977 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2978 if (acb == NULL) {
2979 ret = -EIO;
2980 } else {
2981 qemu_coroutine_yield();
2982 ret = co.ret;
2984 } else {
2986 * Some block drivers always operate in either writethrough or unsafe
2987 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2988 * know how the server works (because the behaviour is hardcoded or
2989 * depends on server-side configuration), so we can't ensure that
2990 * everything is safe on disk. Returning an error doesn't work because
2991 * that would break guests even if the server operates in writethrough
2992 * mode.
2994 * Let's hope the user knows what he's doing.
2996 ret = 0;
2999 if (ret < 0) {
3000 goto out;
3003 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
3004 * in the case of cache=unsafe, so there are no useless flushes.
3006 flush_children:
3007 ret = 0;
3008 QLIST_FOREACH(child, &bs->children, next) {
3009 if (child->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
3010 int this_child_ret = bdrv_co_flush(child->bs);
3011 if (!ret) {
3012 ret = this_child_ret;
3017 out:
3018 /* Notify any pending flushes that we have completed */
3019 if (ret == 0) {
3020 bs->flushed_gen = current_gen;
3023 qemu_co_mutex_lock(&bs->reqs_lock);
3024 bs->active_flush_req = false;
3025 /* Return value is ignored - it's ok if wait queue is empty */
3026 qemu_co_queue_next(&bs->flush_queue);
3027 qemu_co_mutex_unlock(&bs->reqs_lock);
3029 early_exit:
3030 bdrv_dec_in_flight(bs);
3031 return ret;
3034 int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset,
3035 int64_t bytes)
3037 BdrvTrackedRequest req;
3038 int max_pdiscard, ret;
3039 int head, tail, align;
3040 BlockDriverState *bs = child->bs;
3042 if (!bs || !bs->drv || !bdrv_is_inserted(bs)) {
3043 return -ENOMEDIUM;
3046 if (bdrv_has_readonly_bitmaps(bs)) {
3047 return -EPERM;
3050 ret = bdrv_check_request(offset, bytes, NULL);
3051 if (ret < 0) {
3052 return ret;
3055 /* Do nothing if disabled. */
3056 if (!(bs->open_flags & BDRV_O_UNMAP)) {
3057 return 0;
3060 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
3061 return 0;
3064 /* Invalidate the cached block-status data range if this discard overlaps */
3065 bdrv_bsc_invalidate_range(bs, offset, bytes);
3067 /* Discard is advisory, but some devices track and coalesce
3068 * unaligned requests, so we must pass everything down rather than
3069 * round here. Still, most devices will just silently ignore
3070 * unaligned requests (by returning -ENOTSUP), so we must fragment
3071 * the request accordingly. */
3072 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
3073 assert(align % bs->bl.request_alignment == 0);
3074 head = offset % align;
3075 tail = (offset + bytes) % align;
3077 bdrv_inc_in_flight(bs);
3078 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
3080 ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
3081 if (ret < 0) {
3082 goto out;
3085 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),
3086 align);
3087 assert(max_pdiscard >= bs->bl.request_alignment);
3089 while (bytes > 0) {
3090 int64_t num = bytes;
3092 if (head) {
3093 /* Make small requests to get to alignment boundaries. */
3094 num = MIN(bytes, align - head);
3095 if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
3096 num %= bs->bl.request_alignment;
3098 head = (head + num) % align;
3099 assert(num < max_pdiscard);
3100 } else if (tail) {
3101 if (num > align) {
3102 /* Shorten the request to the last aligned cluster. */
3103 num -= tail;
3104 } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
3105 tail > bs->bl.request_alignment) {
3106 tail %= bs->bl.request_alignment;
3107 num -= tail;
3110 /* limit request size */
3111 if (num > max_pdiscard) {
3112 num = max_pdiscard;
3115 if (!bs->drv) {
3116 ret = -ENOMEDIUM;
3117 goto out;
3119 if (bs->drv->bdrv_co_pdiscard) {
3120 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
3121 } else {
3122 BlockAIOCB *acb;
3123 CoroutineIOCompletion co = {
3124 .coroutine = qemu_coroutine_self(),
3127 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
3128 bdrv_co_io_em_complete, &co);
3129 if (acb == NULL) {
3130 ret = -EIO;
3131 goto out;
3132 } else {
3133 qemu_coroutine_yield();
3134 ret = co.ret;
3137 if (ret && ret != -ENOTSUP) {
3138 goto out;
3141 offset += num;
3142 bytes -= num;
3144 ret = 0;
3145 out:
3146 bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
3147 tracked_request_end(&req);
3148 bdrv_dec_in_flight(bs);
3149 return ret;
3152 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
3154 BlockDriver *drv = bs->drv;
3155 CoroutineIOCompletion co = {
3156 .coroutine = qemu_coroutine_self(),
3158 BlockAIOCB *acb;
3160 bdrv_inc_in_flight(bs);
3161 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
3162 co.ret = -ENOTSUP;
3163 goto out;
3166 if (drv->bdrv_co_ioctl) {
3167 co.ret = drv->bdrv_co_ioctl(bs, req, buf);
3168 } else {
3169 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
3170 if (!acb) {
3171 co.ret = -ENOTSUP;
3172 goto out;
3174 qemu_coroutine_yield();
3176 out:
3177 bdrv_dec_in_flight(bs);
3178 return co.ret;
3181 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3183 return qemu_memalign(bdrv_opt_mem_align(bs), size);
3186 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
3188 return memset(qemu_blockalign(bs, size), 0, size);
3191 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
3193 size_t align = bdrv_opt_mem_align(bs);
3195 /* Ensure that NULL is never returned on success */
3196 assert(align > 0);
3197 if (size == 0) {
3198 size = align;
3201 return qemu_try_memalign(align, size);
3204 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
3206 void *mem = qemu_try_blockalign(bs, size);
3208 if (mem) {
3209 memset(mem, 0, size);
3212 return mem;
3216 * Check if all memory in this vector is sector aligned.
3218 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
3220 int i;
3221 size_t alignment = bdrv_min_mem_align(bs);
3223 for (i = 0; i < qiov->niov; i++) {
3224 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
3225 return false;
3227 if (qiov->iov[i].iov_len % alignment) {
3228 return false;
3232 return true;
3235 void bdrv_io_plug(BlockDriverState *bs)
3237 BdrvChild *child;
3239 QLIST_FOREACH(child, &bs->children, next) {
3240 bdrv_io_plug(child->bs);
3243 if (qatomic_fetch_inc(&bs->io_plugged) == 0) {
3244 BlockDriver *drv = bs->drv;
3245 if (drv && drv->bdrv_io_plug) {
3246 drv->bdrv_io_plug(bs);
3251 void bdrv_io_unplug(BlockDriverState *bs)
3253 BdrvChild *child;
3255 assert(bs->io_plugged);
3256 if (qatomic_fetch_dec(&bs->io_plugged) == 1) {
3257 BlockDriver *drv = bs->drv;
3258 if (drv && drv->bdrv_io_unplug) {
3259 drv->bdrv_io_unplug(bs);
3263 QLIST_FOREACH(child, &bs->children, next) {
3264 bdrv_io_unplug(child->bs);
3268 void bdrv_register_buf(BlockDriverState *bs, void *host, size_t size)
3270 BdrvChild *child;
3272 if (bs->drv && bs->drv->bdrv_register_buf) {
3273 bs->drv->bdrv_register_buf(bs, host, size);
3275 QLIST_FOREACH(child, &bs->children, next) {
3276 bdrv_register_buf(child->bs, host, size);
3280 void bdrv_unregister_buf(BlockDriverState *bs, void *host)
3282 BdrvChild *child;
3284 if (bs->drv && bs->drv->bdrv_unregister_buf) {
3285 bs->drv->bdrv_unregister_buf(bs, host);
3287 QLIST_FOREACH(child, &bs->children, next) {
3288 bdrv_unregister_buf(child->bs, host);
3292 static int coroutine_fn bdrv_co_copy_range_internal(
3293 BdrvChild *src, int64_t src_offset, BdrvChild *dst,
3294 int64_t dst_offset, int64_t bytes,
3295 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
3296 bool recurse_src)
3298 BdrvTrackedRequest req;
3299 int ret;
3301 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3302 assert(!(read_flags & BDRV_REQ_NO_FALLBACK));
3303 assert(!(write_flags & BDRV_REQ_NO_FALLBACK));
3305 if (!dst || !dst->bs || !bdrv_is_inserted(dst->bs)) {
3306 return -ENOMEDIUM;
3308 ret = bdrv_check_request32(dst_offset, bytes, NULL, 0);
3309 if (ret) {
3310 return ret;
3312 if (write_flags & BDRV_REQ_ZERO_WRITE) {
3313 return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
3316 if (!src || !src->bs || !bdrv_is_inserted(src->bs)) {
3317 return -ENOMEDIUM;
3319 ret = bdrv_check_request32(src_offset, bytes, NULL, 0);
3320 if (ret) {
3321 return ret;
3324 if (!src->bs->drv->bdrv_co_copy_range_from
3325 || !dst->bs->drv->bdrv_co_copy_range_to
3326 || src->bs->encrypted || dst->bs->encrypted) {
3327 return -ENOTSUP;
3330 if (recurse_src) {
3331 bdrv_inc_in_flight(src->bs);
3332 tracked_request_begin(&req, src->bs, src_offset, bytes,
3333 BDRV_TRACKED_READ);
3335 /* BDRV_REQ_SERIALISING is only for write operation */
3336 assert(!(read_flags & BDRV_REQ_SERIALISING));
3337 bdrv_wait_serialising_requests(&req);
3339 ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
3340 src, src_offset,
3341 dst, dst_offset,
3342 bytes,
3343 read_flags, write_flags);
3345 tracked_request_end(&req);
3346 bdrv_dec_in_flight(src->bs);
3347 } else {
3348 bdrv_inc_in_flight(dst->bs);
3349 tracked_request_begin(&req, dst->bs, dst_offset, bytes,
3350 BDRV_TRACKED_WRITE);
3351 ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3352 write_flags);
3353 if (!ret) {
3354 ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3355 src, src_offset,
3356 dst, dst_offset,
3357 bytes,
3358 read_flags, write_flags);
3360 bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
3361 tracked_request_end(&req);
3362 bdrv_dec_in_flight(dst->bs);
3365 return ret;
3368 /* Copy range from @src to @dst.
3370 * See the comment of bdrv_co_copy_range for the parameter and return value
3371 * semantics. */
3372 int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
3373 BdrvChild *dst, int64_t dst_offset,
3374 int64_t bytes,
3375 BdrvRequestFlags read_flags,
3376 BdrvRequestFlags write_flags)
3378 trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3379 read_flags, write_flags);
3380 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3381 bytes, read_flags, write_flags, true);
3384 /* Copy range from @src to @dst.
3386 * See the comment of bdrv_co_copy_range for the parameter and return value
3387 * semantics. */
3388 int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
3389 BdrvChild *dst, int64_t dst_offset,
3390 int64_t bytes,
3391 BdrvRequestFlags read_flags,
3392 BdrvRequestFlags write_flags)
3394 trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3395 read_flags, write_flags);
3396 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3397 bytes, read_flags, write_flags, false);
3400 int coroutine_fn bdrv_co_copy_range(BdrvChild *src, int64_t src_offset,
3401 BdrvChild *dst, int64_t dst_offset,
3402 int64_t bytes, BdrvRequestFlags read_flags,
3403 BdrvRequestFlags write_flags)
3405 return bdrv_co_copy_range_from(src, src_offset,
3406 dst, dst_offset,
3407 bytes, read_flags, write_flags);
3410 static void bdrv_parent_cb_resize(BlockDriverState *bs)
3412 BdrvChild *c;
3413 QLIST_FOREACH(c, &bs->parents, next_parent) {
3414 if (c->klass->resize) {
3415 c->klass->resize(c);
3421 * Truncate file to 'offset' bytes (needed only for file protocols)
3423 * If 'exact' is true, the file must be resized to exactly the given
3424 * 'offset'. Otherwise, it is sufficient for the node to be at least
3425 * 'offset' bytes in length.
3427 int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset, bool exact,
3428 PreallocMode prealloc, BdrvRequestFlags flags,
3429 Error **errp)
3431 BlockDriverState *bs = child->bs;
3432 BdrvChild *filtered, *backing;
3433 BlockDriver *drv = bs->drv;
3434 BdrvTrackedRequest req;
3435 int64_t old_size, new_bytes;
3436 int ret;
3439 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3440 if (!drv) {
3441 error_setg(errp, "No medium inserted");
3442 return -ENOMEDIUM;
3444 if (offset < 0) {
3445 error_setg(errp, "Image size cannot be negative");
3446 return -EINVAL;
3449 ret = bdrv_check_request(offset, 0, errp);
3450 if (ret < 0) {
3451 return ret;
3454 old_size = bdrv_getlength(bs);
3455 if (old_size < 0) {
3456 error_setg_errno(errp, -old_size, "Failed to get old image size");
3457 return old_size;
3460 if (bdrv_is_read_only(bs)) {
3461 error_setg(errp, "Image is read-only");
3462 return -EACCES;
3465 if (offset > old_size) {
3466 new_bytes = offset - old_size;
3467 } else {
3468 new_bytes = 0;
3471 bdrv_inc_in_flight(bs);
3472 tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3473 BDRV_TRACKED_TRUNCATE);
3475 /* If we are growing the image and potentially using preallocation for the
3476 * new area, we need to make sure that no write requests are made to it
3477 * concurrently or they might be overwritten by preallocation. */
3478 if (new_bytes) {
3479 bdrv_make_request_serialising(&req, 1);
3481 ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3483 if (ret < 0) {
3484 error_setg_errno(errp, -ret,
3485 "Failed to prepare request for truncation");
3486 goto out;
3489 filtered = bdrv_filter_child(bs);
3490 backing = bdrv_cow_child(bs);
3493 * If the image has a backing file that is large enough that it would
3494 * provide data for the new area, we cannot leave it unallocated because
3495 * then the backing file content would become visible. Instead, zero-fill
3496 * the new area.
3498 * Note that if the image has a backing file, but was opened without the
3499 * backing file, taking care of keeping things consistent with that backing
3500 * file is the user's responsibility.
3502 if (new_bytes && backing) {
3503 int64_t backing_len;
3505 backing_len = bdrv_getlength(backing->bs);
3506 if (backing_len < 0) {
3507 ret = backing_len;
3508 error_setg_errno(errp, -ret, "Could not get backing file size");
3509 goto out;
3512 if (backing_len > old_size) {
3513 flags |= BDRV_REQ_ZERO_WRITE;
3517 if (drv->bdrv_co_truncate) {
3518 if (flags & ~bs->supported_truncate_flags) {
3519 error_setg(errp, "Block driver does not support requested flags");
3520 ret = -ENOTSUP;
3521 goto out;
3523 ret = drv->bdrv_co_truncate(bs, offset, exact, prealloc, flags, errp);
3524 } else if (filtered) {
3525 ret = bdrv_co_truncate(filtered, offset, exact, prealloc, flags, errp);
3526 } else {
3527 error_setg(errp, "Image format driver does not support resize");
3528 ret = -ENOTSUP;
3529 goto out;
3531 if (ret < 0) {
3532 goto out;
3535 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3536 if (ret < 0) {
3537 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3538 } else {
3539 offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3541 /* It's possible that truncation succeeded but refresh_total_sectors
3542 * failed, but the latter doesn't affect how we should finish the request.
3543 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3544 bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3546 out:
3547 tracked_request_end(&req);
3548 bdrv_dec_in_flight(bs);
3550 return ret;
3553 void bdrv_cancel_in_flight(BlockDriverState *bs)
3555 if (!bs || !bs->drv) {
3556 return;
3559 if (bs->drv->bdrv_cancel_in_flight) {
3560 bs->drv->bdrv_cancel_in_flight(bs);