block: Remove error messages in bdrv_make_zero()
[qemu/ar7.git] / block / io.c
blob952372c2bb3112fcc2ede9c2ff3e8ed1dc5f99cf
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 "qemu/cutils.h"
33 #include "qapi/error.h"
34 #include "qemu/error-report.h"
36 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
38 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
39 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
41 static void bdrv_parent_cb_resize(BlockDriverState *bs);
42 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
43 int64_t offset, int bytes, BdrvRequestFlags flags);
45 void bdrv_parent_drained_begin(BlockDriverState *bs, BdrvChild *ignore,
46 bool ignore_bds_parents)
48 BdrvChild *c, *next;
50 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
51 if (c == ignore || (ignore_bds_parents && c->role->parent_is_bds)) {
52 continue;
54 bdrv_parent_drained_begin_single(c, false);
58 void bdrv_parent_drained_end(BlockDriverState *bs, BdrvChild *ignore,
59 bool ignore_bds_parents)
61 BdrvChild *c, *next;
63 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
64 if (c == ignore || (ignore_bds_parents && c->role->parent_is_bds)) {
65 continue;
67 if (c->role->drained_end) {
68 c->role->drained_end(c);
73 static bool bdrv_parent_drained_poll_single(BdrvChild *c)
75 if (c->role->drained_poll) {
76 return c->role->drained_poll(c);
78 return false;
81 static bool bdrv_parent_drained_poll(BlockDriverState *bs, BdrvChild *ignore,
82 bool ignore_bds_parents)
84 BdrvChild *c, *next;
85 bool busy = false;
87 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
88 if (c == ignore || (ignore_bds_parents && c->role->parent_is_bds)) {
89 continue;
91 busy |= bdrv_parent_drained_poll_single(c);
94 return busy;
97 void bdrv_parent_drained_begin_single(BdrvChild *c, bool poll)
99 if (c->role->drained_begin) {
100 c->role->drained_begin(c);
102 if (poll) {
103 BDRV_POLL_WHILE(c->bs, bdrv_parent_drained_poll_single(c));
107 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
109 dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
110 dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer);
111 dst->opt_mem_alignment = MAX(dst->opt_mem_alignment,
112 src->opt_mem_alignment);
113 dst->min_mem_alignment = MAX(dst->min_mem_alignment,
114 src->min_mem_alignment);
115 dst->max_iov = MIN_NON_ZERO(dst->max_iov, src->max_iov);
118 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
120 BlockDriver *drv = bs->drv;
121 Error *local_err = NULL;
123 memset(&bs->bl, 0, sizeof(bs->bl));
125 if (!drv) {
126 return;
129 /* Default alignment based on whether driver has byte interface */
130 bs->bl.request_alignment = (drv->bdrv_co_preadv ||
131 drv->bdrv_aio_preadv) ? 1 : 512;
133 /* Take some limits from the children as a default */
134 if (bs->file) {
135 bdrv_refresh_limits(bs->file->bs, &local_err);
136 if (local_err) {
137 error_propagate(errp, local_err);
138 return;
140 bdrv_merge_limits(&bs->bl, &bs->file->bs->bl);
141 } else {
142 bs->bl.min_mem_alignment = 512;
143 bs->bl.opt_mem_alignment = getpagesize();
145 /* Safe default since most protocols use readv()/writev()/etc */
146 bs->bl.max_iov = IOV_MAX;
149 if (bs->backing) {
150 bdrv_refresh_limits(bs->backing->bs, &local_err);
151 if (local_err) {
152 error_propagate(errp, local_err);
153 return;
155 bdrv_merge_limits(&bs->bl, &bs->backing->bs->bl);
158 /* Then let the driver override it */
159 if (drv->bdrv_refresh_limits) {
160 drv->bdrv_refresh_limits(bs, errp);
165 * The copy-on-read flag is actually a reference count so multiple users may
166 * use the feature without worrying about clobbering its previous state.
167 * Copy-on-read stays enabled until all users have called to disable it.
169 void bdrv_enable_copy_on_read(BlockDriverState *bs)
171 atomic_inc(&bs->copy_on_read);
174 void bdrv_disable_copy_on_read(BlockDriverState *bs)
176 int old = atomic_fetch_dec(&bs->copy_on_read);
177 assert(old >= 1);
180 typedef struct {
181 Coroutine *co;
182 BlockDriverState *bs;
183 bool done;
184 bool begin;
185 bool recursive;
186 bool poll;
187 BdrvChild *parent;
188 bool ignore_bds_parents;
189 } BdrvCoDrainData;
191 static void coroutine_fn bdrv_drain_invoke_entry(void *opaque)
193 BdrvCoDrainData *data = opaque;
194 BlockDriverState *bs = data->bs;
196 if (data->begin) {
197 bs->drv->bdrv_co_drain_begin(bs);
198 } else {
199 bs->drv->bdrv_co_drain_end(bs);
202 /* Set data->done before reading bs->wakeup. */
203 atomic_mb_set(&data->done, true);
204 bdrv_dec_in_flight(bs);
206 if (data->begin) {
207 g_free(data);
211 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
212 static void bdrv_drain_invoke(BlockDriverState *bs, bool begin)
214 BdrvCoDrainData *data;
216 if (!bs->drv || (begin && !bs->drv->bdrv_co_drain_begin) ||
217 (!begin && !bs->drv->bdrv_co_drain_end)) {
218 return;
221 data = g_new(BdrvCoDrainData, 1);
222 *data = (BdrvCoDrainData) {
223 .bs = bs,
224 .done = false,
225 .begin = begin
228 /* Make sure the driver callback completes during the polling phase for
229 * drain_begin. */
230 bdrv_inc_in_flight(bs);
231 data->co = qemu_coroutine_create(bdrv_drain_invoke_entry, data);
232 aio_co_schedule(bdrv_get_aio_context(bs), data->co);
234 if (!begin) {
235 BDRV_POLL_WHILE(bs, !data->done);
236 g_free(data);
240 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
241 bool bdrv_drain_poll(BlockDriverState *bs, bool recursive,
242 BdrvChild *ignore_parent, bool ignore_bds_parents)
244 BdrvChild *child, *next;
246 if (bdrv_parent_drained_poll(bs, ignore_parent, ignore_bds_parents)) {
247 return true;
250 if (atomic_read(&bs->in_flight)) {
251 return true;
254 if (recursive) {
255 assert(!ignore_bds_parents);
256 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
257 if (bdrv_drain_poll(child->bs, recursive, child, false)) {
258 return true;
263 return false;
266 static bool bdrv_drain_poll_top_level(BlockDriverState *bs, bool recursive,
267 BdrvChild *ignore_parent)
269 return bdrv_drain_poll(bs, recursive, ignore_parent, false);
272 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
273 BdrvChild *parent, bool ignore_bds_parents,
274 bool poll);
275 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
276 BdrvChild *parent, bool ignore_bds_parents);
278 static void bdrv_co_drain_bh_cb(void *opaque)
280 BdrvCoDrainData *data = opaque;
281 Coroutine *co = data->co;
282 BlockDriverState *bs = data->bs;
284 if (bs) {
285 AioContext *ctx = bdrv_get_aio_context(bs);
286 AioContext *co_ctx = qemu_coroutine_get_aio_context(co);
289 * When the coroutine yielded, the lock for its home context was
290 * released, so we need to re-acquire it here. If it explicitly
291 * acquired a different context, the lock is still held and we don't
292 * want to lock it a second time (or AIO_WAIT_WHILE() would hang).
294 if (ctx == co_ctx) {
295 aio_context_acquire(ctx);
297 bdrv_dec_in_flight(bs);
298 if (data->begin) {
299 bdrv_do_drained_begin(bs, data->recursive, data->parent,
300 data->ignore_bds_parents, data->poll);
301 } else {
302 bdrv_do_drained_end(bs, data->recursive, data->parent,
303 data->ignore_bds_parents);
305 if (ctx == co_ctx) {
306 aio_context_release(ctx);
308 } else {
309 assert(data->begin);
310 bdrv_drain_all_begin();
313 data->done = true;
314 aio_co_wake(co);
317 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs,
318 bool begin, bool recursive,
319 BdrvChild *parent,
320 bool ignore_bds_parents,
321 bool poll)
323 BdrvCoDrainData data;
325 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
326 * other coroutines run if they were queued by aio_co_enter(). */
328 assert(qemu_in_coroutine());
329 data = (BdrvCoDrainData) {
330 .co = qemu_coroutine_self(),
331 .bs = bs,
332 .done = false,
333 .begin = begin,
334 .recursive = recursive,
335 .parent = parent,
336 .ignore_bds_parents = ignore_bds_parents,
337 .poll = poll,
339 if (bs) {
340 bdrv_inc_in_flight(bs);
342 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs),
343 bdrv_co_drain_bh_cb, &data);
345 qemu_coroutine_yield();
346 /* If we are resumed from some other event (such as an aio completion or a
347 * timer callback), it is a bug in the caller that should be fixed. */
348 assert(data.done);
351 void bdrv_do_drained_begin_quiesce(BlockDriverState *bs,
352 BdrvChild *parent, bool ignore_bds_parents)
354 assert(!qemu_in_coroutine());
356 /* Stop things in parent-to-child order */
357 if (atomic_fetch_inc(&bs->quiesce_counter) == 0) {
358 aio_disable_external(bdrv_get_aio_context(bs));
361 bdrv_parent_drained_begin(bs, parent, ignore_bds_parents);
362 bdrv_drain_invoke(bs, true);
365 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
366 BdrvChild *parent, bool ignore_bds_parents,
367 bool poll)
369 BdrvChild *child, *next;
371 if (qemu_in_coroutine()) {
372 bdrv_co_yield_to_drain(bs, true, recursive, parent, ignore_bds_parents,
373 poll);
374 return;
377 bdrv_do_drained_begin_quiesce(bs, parent, ignore_bds_parents);
379 if (recursive) {
380 assert(!ignore_bds_parents);
381 bs->recursive_quiesce_counter++;
382 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
383 bdrv_do_drained_begin(child->bs, true, child, ignore_bds_parents,
384 false);
389 * Wait for drained requests to finish.
391 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
392 * call is needed so things in this AioContext can make progress even
393 * though we don't return to the main AioContext loop - this automatically
394 * includes other nodes in the same AioContext and therefore all child
395 * nodes.
397 if (poll) {
398 assert(!ignore_bds_parents);
399 BDRV_POLL_WHILE(bs, bdrv_drain_poll_top_level(bs, recursive, parent));
403 void bdrv_drained_begin(BlockDriverState *bs)
405 bdrv_do_drained_begin(bs, false, NULL, false, true);
408 void bdrv_subtree_drained_begin(BlockDriverState *bs)
410 bdrv_do_drained_begin(bs, true, NULL, false, true);
413 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
414 BdrvChild *parent, bool ignore_bds_parents)
416 BdrvChild *child, *next;
417 int old_quiesce_counter;
419 if (qemu_in_coroutine()) {
420 bdrv_co_yield_to_drain(bs, false, recursive, parent, ignore_bds_parents,
421 false);
422 return;
424 assert(bs->quiesce_counter > 0);
425 old_quiesce_counter = atomic_fetch_dec(&bs->quiesce_counter);
427 /* Re-enable things in child-to-parent order */
428 bdrv_drain_invoke(bs, false);
429 bdrv_parent_drained_end(bs, parent, ignore_bds_parents);
430 if (old_quiesce_counter == 1) {
431 aio_enable_external(bdrv_get_aio_context(bs));
434 if (recursive) {
435 assert(!ignore_bds_parents);
436 bs->recursive_quiesce_counter--;
437 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
438 bdrv_do_drained_end(child->bs, true, child, ignore_bds_parents);
443 void bdrv_drained_end(BlockDriverState *bs)
445 bdrv_do_drained_end(bs, false, NULL, false);
448 void bdrv_subtree_drained_end(BlockDriverState *bs)
450 bdrv_do_drained_end(bs, true, NULL, false);
453 void bdrv_apply_subtree_drain(BdrvChild *child, BlockDriverState *new_parent)
455 int i;
457 for (i = 0; i < new_parent->recursive_quiesce_counter; i++) {
458 bdrv_do_drained_begin(child->bs, true, child, false, true);
462 void bdrv_unapply_subtree_drain(BdrvChild *child, BlockDriverState *old_parent)
464 int i;
466 for (i = 0; i < old_parent->recursive_quiesce_counter; i++) {
467 bdrv_do_drained_end(child->bs, true, child, false);
472 * Wait for pending requests to complete on a single BlockDriverState subtree,
473 * and suspend block driver's internal I/O until next request arrives.
475 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
476 * AioContext.
478 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
480 assert(qemu_in_coroutine());
481 bdrv_drained_begin(bs);
482 bdrv_drained_end(bs);
485 void bdrv_drain(BlockDriverState *bs)
487 bdrv_drained_begin(bs);
488 bdrv_drained_end(bs);
491 static void bdrv_drain_assert_idle(BlockDriverState *bs)
493 BdrvChild *child, *next;
495 assert(atomic_read(&bs->in_flight) == 0);
496 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
497 bdrv_drain_assert_idle(child->bs);
501 unsigned int bdrv_drain_all_count = 0;
503 static bool bdrv_drain_all_poll(void)
505 BlockDriverState *bs = NULL;
506 bool result = false;
508 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
509 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
510 while ((bs = bdrv_next_all_states(bs))) {
511 AioContext *aio_context = bdrv_get_aio_context(bs);
512 aio_context_acquire(aio_context);
513 result |= bdrv_drain_poll(bs, false, NULL, true);
514 aio_context_release(aio_context);
517 return result;
521 * Wait for pending requests to complete across all BlockDriverStates
523 * This function does not flush data to disk, use bdrv_flush_all() for that
524 * after calling this function.
526 * This pauses all block jobs and disables external clients. It must
527 * be paired with bdrv_drain_all_end().
529 * NOTE: no new block jobs or BlockDriverStates can be created between
530 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
532 void bdrv_drain_all_begin(void)
534 BlockDriverState *bs = NULL;
536 if (qemu_in_coroutine()) {
537 bdrv_co_yield_to_drain(NULL, true, false, NULL, true, true);
538 return;
541 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
542 * loop AioContext, so make sure we're in the main context. */
543 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
544 assert(bdrv_drain_all_count < INT_MAX);
545 bdrv_drain_all_count++;
547 /* Quiesce all nodes, without polling in-flight requests yet. The graph
548 * cannot change during this loop. */
549 while ((bs = bdrv_next_all_states(bs))) {
550 AioContext *aio_context = bdrv_get_aio_context(bs);
552 aio_context_acquire(aio_context);
553 bdrv_do_drained_begin(bs, false, NULL, true, false);
554 aio_context_release(aio_context);
557 /* Now poll the in-flight requests */
558 AIO_WAIT_WHILE(NULL, bdrv_drain_all_poll());
560 while ((bs = bdrv_next_all_states(bs))) {
561 bdrv_drain_assert_idle(bs);
565 void bdrv_drain_all_end(void)
567 BlockDriverState *bs = NULL;
569 while ((bs = bdrv_next_all_states(bs))) {
570 AioContext *aio_context = bdrv_get_aio_context(bs);
572 aio_context_acquire(aio_context);
573 bdrv_do_drained_end(bs, false, NULL, true);
574 aio_context_release(aio_context);
577 assert(bdrv_drain_all_count > 0);
578 bdrv_drain_all_count--;
581 void bdrv_drain_all(void)
583 bdrv_drain_all_begin();
584 bdrv_drain_all_end();
588 * Remove an active request from the tracked requests list
590 * This function should be called when a tracked request is completing.
592 static void tracked_request_end(BdrvTrackedRequest *req)
594 if (req->serialising) {
595 atomic_dec(&req->bs->serialising_in_flight);
598 qemu_co_mutex_lock(&req->bs->reqs_lock);
599 QLIST_REMOVE(req, list);
600 qemu_co_queue_restart_all(&req->wait_queue);
601 qemu_co_mutex_unlock(&req->bs->reqs_lock);
605 * Add an active request to the tracked requests list
607 static void tracked_request_begin(BdrvTrackedRequest *req,
608 BlockDriverState *bs,
609 int64_t offset,
610 uint64_t bytes,
611 enum BdrvTrackedRequestType type)
613 assert(bytes <= INT64_MAX && offset <= INT64_MAX - bytes);
615 *req = (BdrvTrackedRequest){
616 .bs = bs,
617 .offset = offset,
618 .bytes = bytes,
619 .type = type,
620 .co = qemu_coroutine_self(),
621 .serialising = false,
622 .overlap_offset = offset,
623 .overlap_bytes = bytes,
626 qemu_co_queue_init(&req->wait_queue);
628 qemu_co_mutex_lock(&bs->reqs_lock);
629 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
630 qemu_co_mutex_unlock(&bs->reqs_lock);
633 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
635 int64_t overlap_offset = req->offset & ~(align - 1);
636 uint64_t overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
637 - overlap_offset;
639 if (!req->serialising) {
640 atomic_inc(&req->bs->serialising_in_flight);
641 req->serialising = true;
644 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
645 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
648 static bool is_request_serialising_and_aligned(BdrvTrackedRequest *req)
651 * If the request is serialising, overlap_offset and overlap_bytes are set,
652 * so we can check if the request is aligned. Otherwise, don't care and
653 * return false.
656 return req->serialising && (req->offset == req->overlap_offset) &&
657 (req->bytes == req->overlap_bytes);
661 * Round a region to cluster boundaries
663 void bdrv_round_to_clusters(BlockDriverState *bs,
664 int64_t offset, int64_t bytes,
665 int64_t *cluster_offset,
666 int64_t *cluster_bytes)
668 BlockDriverInfo bdi;
670 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
671 *cluster_offset = offset;
672 *cluster_bytes = bytes;
673 } else {
674 int64_t c = bdi.cluster_size;
675 *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
676 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
680 static int bdrv_get_cluster_size(BlockDriverState *bs)
682 BlockDriverInfo bdi;
683 int ret;
685 ret = bdrv_get_info(bs, &bdi);
686 if (ret < 0 || bdi.cluster_size == 0) {
687 return bs->bl.request_alignment;
688 } else {
689 return bdi.cluster_size;
693 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
694 int64_t offset, uint64_t bytes)
696 /* aaaa bbbb */
697 if (offset >= req->overlap_offset + req->overlap_bytes) {
698 return false;
700 /* bbbb aaaa */
701 if (req->overlap_offset >= offset + bytes) {
702 return false;
704 return true;
707 void bdrv_inc_in_flight(BlockDriverState *bs)
709 atomic_inc(&bs->in_flight);
712 void bdrv_wakeup(BlockDriverState *bs)
714 aio_wait_kick();
717 void bdrv_dec_in_flight(BlockDriverState *bs)
719 atomic_dec(&bs->in_flight);
720 bdrv_wakeup(bs);
723 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
725 BlockDriverState *bs = self->bs;
726 BdrvTrackedRequest *req;
727 bool retry;
728 bool waited = false;
730 if (!atomic_read(&bs->serialising_in_flight)) {
731 return false;
734 do {
735 retry = false;
736 qemu_co_mutex_lock(&bs->reqs_lock);
737 QLIST_FOREACH(req, &bs->tracked_requests, list) {
738 if (req == self || (!req->serialising && !self->serialising)) {
739 continue;
741 if (tracked_request_overlaps(req, self->overlap_offset,
742 self->overlap_bytes))
744 /* Hitting this means there was a reentrant request, for
745 * example, a block driver issuing nested requests. This must
746 * never happen since it means deadlock.
748 assert(qemu_coroutine_self() != req->co);
750 /* If the request is already (indirectly) waiting for us, or
751 * will wait for us as soon as it wakes up, then just go on
752 * (instead of producing a deadlock in the former case). */
753 if (!req->waiting_for) {
754 self->waiting_for = req;
755 qemu_co_queue_wait(&req->wait_queue, &bs->reqs_lock);
756 self->waiting_for = NULL;
757 retry = true;
758 waited = true;
759 break;
763 qemu_co_mutex_unlock(&bs->reqs_lock);
764 } while (retry);
766 return waited;
769 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
770 size_t size)
772 if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) {
773 return -EIO;
776 if (!bdrv_is_inserted(bs)) {
777 return -ENOMEDIUM;
780 if (offset < 0) {
781 return -EIO;
784 return 0;
787 typedef struct RwCo {
788 BdrvChild *child;
789 int64_t offset;
790 QEMUIOVector *qiov;
791 bool is_write;
792 int ret;
793 BdrvRequestFlags flags;
794 } RwCo;
796 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
798 RwCo *rwco = opaque;
800 if (!rwco->is_write) {
801 rwco->ret = bdrv_co_preadv(rwco->child, rwco->offset,
802 rwco->qiov->size, rwco->qiov,
803 rwco->flags);
804 } else {
805 rwco->ret = bdrv_co_pwritev(rwco->child, rwco->offset,
806 rwco->qiov->size, rwco->qiov,
807 rwco->flags);
809 aio_wait_kick();
813 * Process a vectored synchronous request using coroutines
815 static int bdrv_prwv_co(BdrvChild *child, int64_t offset,
816 QEMUIOVector *qiov, bool is_write,
817 BdrvRequestFlags flags)
819 Coroutine *co;
820 RwCo rwco = {
821 .child = child,
822 .offset = offset,
823 .qiov = qiov,
824 .is_write = is_write,
825 .ret = NOT_DONE,
826 .flags = flags,
829 if (qemu_in_coroutine()) {
830 /* Fast-path if already in coroutine context */
831 bdrv_rw_co_entry(&rwco);
832 } else {
833 co = qemu_coroutine_create(bdrv_rw_co_entry, &rwco);
834 bdrv_coroutine_enter(child->bs, co);
835 BDRV_POLL_WHILE(child->bs, rwco.ret == NOT_DONE);
837 return rwco.ret;
841 * Process a synchronous request using coroutines
843 static int bdrv_rw_co(BdrvChild *child, int64_t sector_num, uint8_t *buf,
844 int nb_sectors, bool is_write, BdrvRequestFlags flags)
846 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf,
847 nb_sectors * BDRV_SECTOR_SIZE);
849 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
850 return -EINVAL;
853 return bdrv_prwv_co(child, sector_num << BDRV_SECTOR_BITS,
854 &qiov, is_write, flags);
857 /* return < 0 if error. See bdrv_write() for the return codes */
858 int bdrv_read(BdrvChild *child, int64_t sector_num,
859 uint8_t *buf, int nb_sectors)
861 return bdrv_rw_co(child, sector_num, buf, nb_sectors, false, 0);
864 /* Return < 0 if error. Important errors are:
865 -EIO generic I/O error (may happen for all errors)
866 -ENOMEDIUM No media inserted.
867 -EINVAL Invalid sector number or nb_sectors
868 -EACCES Trying to write a read-only device
870 int bdrv_write(BdrvChild *child, int64_t sector_num,
871 const uint8_t *buf, int nb_sectors)
873 return bdrv_rw_co(child, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
876 int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
877 int bytes, BdrvRequestFlags flags)
879 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, NULL, bytes);
881 return bdrv_prwv_co(child, offset, &qiov, true,
882 BDRV_REQ_ZERO_WRITE | flags);
886 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
887 * The operation is sped up by checking the block status and only writing
888 * zeroes to the device if they currently do not return zeroes. Optional
889 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
890 * BDRV_REQ_FUA).
892 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
894 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
896 int ret;
897 int64_t target_size, bytes, offset = 0;
898 BlockDriverState *bs = child->bs;
900 target_size = bdrv_getlength(bs);
901 if (target_size < 0) {
902 return target_size;
905 for (;;) {
906 bytes = MIN(target_size - offset, BDRV_REQUEST_MAX_BYTES);
907 if (bytes <= 0) {
908 return 0;
910 ret = bdrv_block_status(bs, offset, bytes, &bytes, NULL, NULL);
911 if (ret < 0) {
912 return ret;
914 if (ret & BDRV_BLOCK_ZERO) {
915 offset += bytes;
916 continue;
918 ret = bdrv_pwrite_zeroes(child, offset, bytes, flags);
919 if (ret < 0) {
920 return ret;
922 offset += bytes;
926 int bdrv_preadv(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
928 int ret;
930 ret = bdrv_prwv_co(child, offset, qiov, false, 0);
931 if (ret < 0) {
932 return ret;
935 return qiov->size;
938 int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int bytes)
940 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
942 if (bytes < 0) {
943 return -EINVAL;
946 return bdrv_preadv(child, offset, &qiov);
949 int bdrv_pwritev(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
951 int ret;
953 ret = bdrv_prwv_co(child, offset, qiov, true, 0);
954 if (ret < 0) {
955 return ret;
958 return qiov->size;
961 int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf, int bytes)
963 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
965 if (bytes < 0) {
966 return -EINVAL;
969 return bdrv_pwritev(child, offset, &qiov);
973 * Writes to the file and ensures that no writes are reordered across this
974 * request (acts as a barrier)
976 * Returns 0 on success, -errno in error cases.
978 int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
979 const void *buf, int count)
981 int ret;
983 ret = bdrv_pwrite(child, offset, buf, count);
984 if (ret < 0) {
985 return ret;
988 ret = bdrv_flush(child->bs);
989 if (ret < 0) {
990 return ret;
993 return 0;
996 typedef struct CoroutineIOCompletion {
997 Coroutine *coroutine;
998 int ret;
999 } CoroutineIOCompletion;
1001 static void bdrv_co_io_em_complete(void *opaque, int ret)
1003 CoroutineIOCompletion *co = opaque;
1005 co->ret = ret;
1006 aio_co_wake(co->coroutine);
1009 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
1010 uint64_t offset, uint64_t bytes,
1011 QEMUIOVector *qiov, int flags)
1013 BlockDriver *drv = bs->drv;
1014 int64_t sector_num;
1015 unsigned int nb_sectors;
1017 assert(!(flags & ~BDRV_REQ_MASK));
1019 if (!drv) {
1020 return -ENOMEDIUM;
1023 if (drv->bdrv_co_preadv) {
1024 return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
1027 if (drv->bdrv_aio_preadv) {
1028 BlockAIOCB *acb;
1029 CoroutineIOCompletion co = {
1030 .coroutine = qemu_coroutine_self(),
1033 acb = drv->bdrv_aio_preadv(bs, offset, bytes, qiov, flags,
1034 bdrv_co_io_em_complete, &co);
1035 if (acb == NULL) {
1036 return -EIO;
1037 } else {
1038 qemu_coroutine_yield();
1039 return co.ret;
1043 sector_num = offset >> BDRV_SECTOR_BITS;
1044 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1046 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1047 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1048 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
1049 assert(drv->bdrv_co_readv);
1051 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1054 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
1055 uint64_t offset, uint64_t bytes,
1056 QEMUIOVector *qiov, int flags)
1058 BlockDriver *drv = bs->drv;
1059 int64_t sector_num;
1060 unsigned int nb_sectors;
1061 int ret;
1063 assert(!(flags & ~BDRV_REQ_MASK));
1065 if (!drv) {
1066 return -ENOMEDIUM;
1069 if (drv->bdrv_co_pwritev) {
1070 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
1071 flags & bs->supported_write_flags);
1072 flags &= ~bs->supported_write_flags;
1073 goto emulate_flags;
1076 if (drv->bdrv_aio_pwritev) {
1077 BlockAIOCB *acb;
1078 CoroutineIOCompletion co = {
1079 .coroutine = qemu_coroutine_self(),
1082 acb = drv->bdrv_aio_pwritev(bs, offset, bytes, qiov,
1083 flags & bs->supported_write_flags,
1084 bdrv_co_io_em_complete, &co);
1085 flags &= ~bs->supported_write_flags;
1086 if (acb == NULL) {
1087 ret = -EIO;
1088 } else {
1089 qemu_coroutine_yield();
1090 ret = co.ret;
1092 goto emulate_flags;
1095 sector_num = offset >> BDRV_SECTOR_BITS;
1096 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1098 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1099 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1100 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
1102 assert(drv->bdrv_co_writev);
1103 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov,
1104 flags & bs->supported_write_flags);
1105 flags &= ~bs->supported_write_flags;
1107 emulate_flags:
1108 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
1109 ret = bdrv_co_flush(bs);
1112 return ret;
1115 static int coroutine_fn
1116 bdrv_driver_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1117 uint64_t bytes, QEMUIOVector *qiov)
1119 BlockDriver *drv = bs->drv;
1121 if (!drv) {
1122 return -ENOMEDIUM;
1125 if (!drv->bdrv_co_pwritev_compressed) {
1126 return -ENOTSUP;
1129 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
1132 static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
1133 int64_t offset, unsigned int bytes, QEMUIOVector *qiov)
1135 BlockDriverState *bs = child->bs;
1137 /* Perform I/O through a temporary buffer so that users who scribble over
1138 * their read buffer while the operation is in progress do not end up
1139 * modifying the image file. This is critical for zero-copy guest I/O
1140 * where anything might happen inside guest memory.
1142 void *bounce_buffer;
1144 BlockDriver *drv = bs->drv;
1145 QEMUIOVector local_qiov;
1146 int64_t cluster_offset;
1147 int64_t cluster_bytes;
1148 size_t skip_bytes;
1149 int ret;
1150 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1151 BDRV_REQUEST_MAX_BYTES);
1152 unsigned int progress = 0;
1154 if (!drv) {
1155 return -ENOMEDIUM;
1158 /* FIXME We cannot require callers to have write permissions when all they
1159 * are doing is a read request. If we did things right, write permissions
1160 * would be obtained anyway, but internally by the copy-on-read code. As
1161 * long as it is implemented here rather than in a separate filter driver,
1162 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1163 * it could request permissions. Therefore we have to bypass the permission
1164 * system for the moment. */
1165 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1167 /* Cover entire cluster so no additional backing file I/O is required when
1168 * allocating cluster in the image file. Note that this value may exceed
1169 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1170 * is one reason we loop rather than doing it all at once.
1172 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
1173 skip_bytes = offset - cluster_offset;
1175 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
1176 cluster_offset, cluster_bytes);
1178 bounce_buffer = qemu_try_blockalign(bs,
1179 MIN(MIN(max_transfer, cluster_bytes),
1180 MAX_BOUNCE_BUFFER));
1181 if (bounce_buffer == NULL) {
1182 ret = -ENOMEM;
1183 goto err;
1186 while (cluster_bytes) {
1187 int64_t pnum;
1189 ret = bdrv_is_allocated(bs, cluster_offset,
1190 MIN(cluster_bytes, max_transfer), &pnum);
1191 if (ret < 0) {
1192 /* Safe to treat errors in querying allocation as if
1193 * unallocated; we'll probably fail again soon on the
1194 * read, but at least that will set a decent errno.
1196 pnum = MIN(cluster_bytes, max_transfer);
1199 /* Stop at EOF if the image ends in the middle of the cluster */
1200 if (ret == 0 && pnum == 0) {
1201 assert(progress >= bytes);
1202 break;
1205 assert(skip_bytes < pnum);
1207 if (ret <= 0) {
1208 /* Must copy-on-read; use the bounce buffer */
1209 pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1210 qemu_iovec_init_buf(&local_qiov, bounce_buffer, pnum);
1212 ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1213 &local_qiov, 0);
1214 if (ret < 0) {
1215 goto err;
1218 bdrv_debug_event(bs, BLKDBG_COR_WRITE);
1219 if (drv->bdrv_co_pwrite_zeroes &&
1220 buffer_is_zero(bounce_buffer, pnum)) {
1221 /* FIXME: Should we (perhaps conditionally) be setting
1222 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1223 * that still correctly reads as zero? */
1224 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum,
1225 BDRV_REQ_WRITE_UNCHANGED);
1226 } else {
1227 /* This does not change the data on the disk, it is not
1228 * necessary to flush even in cache=writethrough mode.
1230 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
1231 &local_qiov,
1232 BDRV_REQ_WRITE_UNCHANGED);
1235 if (ret < 0) {
1236 /* It might be okay to ignore write errors for guest
1237 * requests. If this is a deliberate copy-on-read
1238 * then we don't want to ignore the error. Simply
1239 * report it in all cases.
1241 goto err;
1244 qemu_iovec_from_buf(qiov, progress, bounce_buffer + skip_bytes,
1245 pnum - skip_bytes);
1246 } else {
1247 /* Read directly into the destination */
1248 qemu_iovec_init(&local_qiov, qiov->niov);
1249 qemu_iovec_concat(&local_qiov, qiov, progress, pnum - skip_bytes);
1250 ret = bdrv_driver_preadv(bs, offset + progress, local_qiov.size,
1251 &local_qiov, 0);
1252 qemu_iovec_destroy(&local_qiov);
1253 if (ret < 0) {
1254 goto err;
1258 cluster_offset += pnum;
1259 cluster_bytes -= pnum;
1260 progress += pnum - skip_bytes;
1261 skip_bytes = 0;
1263 ret = 0;
1265 err:
1266 qemu_vfree(bounce_buffer);
1267 return ret;
1271 * Forwards an already correctly aligned request to the BlockDriver. This
1272 * handles copy on read, zeroing after EOF, and fragmentation of large
1273 * reads; any other features must be implemented by the caller.
1275 static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
1276 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1277 int64_t align, QEMUIOVector *qiov, int flags)
1279 BlockDriverState *bs = child->bs;
1280 int64_t total_bytes, max_bytes;
1281 int ret = 0;
1282 uint64_t bytes_remaining = bytes;
1283 int max_transfer;
1285 assert(is_power_of_2(align));
1286 assert((offset & (align - 1)) == 0);
1287 assert((bytes & (align - 1)) == 0);
1288 assert(!qiov || bytes == qiov->size);
1289 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1290 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1291 align);
1293 /* TODO: We would need a per-BDS .supported_read_flags and
1294 * potential fallback support, if we ever implement any read flags
1295 * to pass through to drivers. For now, there aren't any
1296 * passthrough flags. */
1297 assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ)));
1299 /* Handle Copy on Read and associated serialisation */
1300 if (flags & BDRV_REQ_COPY_ON_READ) {
1301 /* If we touch the same cluster it counts as an overlap. This
1302 * guarantees that allocating writes will be serialized and not race
1303 * with each other for the same cluster. For example, in copy-on-read
1304 * it ensures that the CoR read and write operations are atomic and
1305 * guest writes cannot interleave between them. */
1306 mark_request_serialising(req, bdrv_get_cluster_size(bs));
1309 /* BDRV_REQ_SERIALISING is only for write operation */
1310 assert(!(flags & BDRV_REQ_SERIALISING));
1312 if (!(flags & BDRV_REQ_NO_SERIALISING)) {
1313 wait_serialising_requests(req);
1316 if (flags & BDRV_REQ_COPY_ON_READ) {
1317 int64_t pnum;
1319 ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
1320 if (ret < 0) {
1321 goto out;
1324 if (!ret || pnum != bytes) {
1325 ret = bdrv_co_do_copy_on_readv(child, offset, bytes, qiov);
1326 goto out;
1330 /* Forward the request to the BlockDriver, possibly fragmenting it */
1331 total_bytes = bdrv_getlength(bs);
1332 if (total_bytes < 0) {
1333 ret = total_bytes;
1334 goto out;
1337 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1338 if (bytes <= max_bytes && bytes <= max_transfer) {
1339 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
1340 goto out;
1343 while (bytes_remaining) {
1344 int num;
1346 if (max_bytes) {
1347 QEMUIOVector local_qiov;
1349 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1350 assert(num);
1351 qemu_iovec_init(&local_qiov, qiov->niov);
1352 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1354 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1355 num, &local_qiov, 0);
1356 max_bytes -= num;
1357 qemu_iovec_destroy(&local_qiov);
1358 } else {
1359 num = bytes_remaining;
1360 ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0,
1361 bytes_remaining);
1363 if (ret < 0) {
1364 goto out;
1366 bytes_remaining -= num;
1369 out:
1370 return ret < 0 ? ret : 0;
1374 * Handle a read request in coroutine context
1376 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1377 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1378 BdrvRequestFlags flags)
1380 BlockDriverState *bs = child->bs;
1381 BlockDriver *drv = bs->drv;
1382 BdrvTrackedRequest req;
1384 uint64_t align = bs->bl.request_alignment;
1385 uint8_t *head_buf = NULL;
1386 uint8_t *tail_buf = NULL;
1387 QEMUIOVector local_qiov;
1388 bool use_local_qiov = false;
1389 int ret;
1391 trace_bdrv_co_preadv(child->bs, offset, bytes, flags);
1393 if (!drv) {
1394 return -ENOMEDIUM;
1397 ret = bdrv_check_byte_request(bs, offset, bytes);
1398 if (ret < 0) {
1399 return ret;
1402 bdrv_inc_in_flight(bs);
1404 /* Don't do copy-on-read if we read data before write operation */
1405 if (atomic_read(&bs->copy_on_read) && !(flags & BDRV_REQ_NO_SERIALISING)) {
1406 flags |= BDRV_REQ_COPY_ON_READ;
1409 /* Align read if necessary by padding qiov */
1410 if (offset & (align - 1)) {
1411 head_buf = qemu_blockalign(bs, align);
1412 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1413 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1414 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1415 use_local_qiov = true;
1417 bytes += offset & (align - 1);
1418 offset = offset & ~(align - 1);
1421 if ((offset + bytes) & (align - 1)) {
1422 if (!use_local_qiov) {
1423 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1424 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1425 use_local_qiov = true;
1427 tail_buf = qemu_blockalign(bs, align);
1428 qemu_iovec_add(&local_qiov, tail_buf,
1429 align - ((offset + bytes) & (align - 1)));
1431 bytes = ROUND_UP(bytes, align);
1434 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1435 ret = bdrv_aligned_preadv(child, &req, offset, bytes, align,
1436 use_local_qiov ? &local_qiov : qiov,
1437 flags);
1438 tracked_request_end(&req);
1439 bdrv_dec_in_flight(bs);
1441 if (use_local_qiov) {
1442 qemu_iovec_destroy(&local_qiov);
1443 qemu_vfree(head_buf);
1444 qemu_vfree(tail_buf);
1447 return ret;
1450 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1451 int64_t offset, int bytes, BdrvRequestFlags flags)
1453 BlockDriver *drv = bs->drv;
1454 QEMUIOVector qiov;
1455 void *buf = NULL;
1456 int ret = 0;
1457 bool need_flush = false;
1458 int head = 0;
1459 int tail = 0;
1461 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
1462 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1463 bs->bl.request_alignment);
1464 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
1466 if (!drv) {
1467 return -ENOMEDIUM;
1470 assert(alignment % bs->bl.request_alignment == 0);
1471 head = offset % alignment;
1472 tail = (offset + bytes) % alignment;
1473 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1474 assert(max_write_zeroes >= bs->bl.request_alignment);
1476 while (bytes > 0 && !ret) {
1477 int num = bytes;
1479 /* Align request. Block drivers can expect the "bulk" of the request
1480 * to be aligned, and that unaligned requests do not cross cluster
1481 * boundaries.
1483 if (head) {
1484 /* Make a small request up to the first aligned sector. For
1485 * convenience, limit this request to max_transfer even if
1486 * we don't need to fall back to writes. */
1487 num = MIN(MIN(bytes, max_transfer), alignment - head);
1488 head = (head + num) % alignment;
1489 assert(num < max_write_zeroes);
1490 } else if (tail && num > alignment) {
1491 /* Shorten the request to the last aligned sector. */
1492 num -= tail;
1495 /* limit request size */
1496 if (num > max_write_zeroes) {
1497 num = max_write_zeroes;
1500 ret = -ENOTSUP;
1501 /* First try the efficient write zeroes operation */
1502 if (drv->bdrv_co_pwrite_zeroes) {
1503 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1504 flags & bs->supported_zero_flags);
1505 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1506 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1507 need_flush = true;
1509 } else {
1510 assert(!bs->supported_zero_flags);
1513 if (ret == -ENOTSUP) {
1514 /* Fall back to bounce buffer if write zeroes is unsupported */
1515 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1517 if ((flags & BDRV_REQ_FUA) &&
1518 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1519 /* No need for bdrv_driver_pwrite() to do a fallback
1520 * flush on each chunk; use just one at the end */
1521 write_flags &= ~BDRV_REQ_FUA;
1522 need_flush = true;
1524 num = MIN(num, max_transfer);
1525 if (buf == NULL) {
1526 buf = qemu_try_blockalign0(bs, num);
1527 if (buf == NULL) {
1528 ret = -ENOMEM;
1529 goto fail;
1532 qemu_iovec_init_buf(&qiov, buf, num);
1534 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags);
1536 /* Keep bounce buffer around if it is big enough for all
1537 * all future requests.
1539 if (num < max_transfer) {
1540 qemu_vfree(buf);
1541 buf = NULL;
1545 offset += num;
1546 bytes -= num;
1549 fail:
1550 if (ret == 0 && need_flush) {
1551 ret = bdrv_co_flush(bs);
1553 qemu_vfree(buf);
1554 return ret;
1557 static inline int coroutine_fn
1558 bdrv_co_write_req_prepare(BdrvChild *child, int64_t offset, uint64_t bytes,
1559 BdrvTrackedRequest *req, int flags)
1561 BlockDriverState *bs = child->bs;
1562 bool waited;
1563 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1565 if (bs->read_only) {
1566 return -EPERM;
1569 /* BDRV_REQ_NO_SERIALISING is only for read operation */
1570 assert(!(flags & BDRV_REQ_NO_SERIALISING));
1571 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1572 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1573 assert(!(flags & ~BDRV_REQ_MASK));
1575 if (flags & BDRV_REQ_SERIALISING) {
1576 mark_request_serialising(req, bdrv_get_cluster_size(bs));
1579 waited = wait_serialising_requests(req);
1581 assert(!waited || !req->serialising ||
1582 is_request_serialising_and_aligned(req));
1583 assert(req->overlap_offset <= offset);
1584 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1585 assert(end_sector <= bs->total_sectors || child->perm & BLK_PERM_RESIZE);
1587 switch (req->type) {
1588 case BDRV_TRACKED_WRITE:
1589 case BDRV_TRACKED_DISCARD:
1590 if (flags & BDRV_REQ_WRITE_UNCHANGED) {
1591 assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1592 } else {
1593 assert(child->perm & BLK_PERM_WRITE);
1595 return notifier_with_return_list_notify(&bs->before_write_notifiers,
1596 req);
1597 case BDRV_TRACKED_TRUNCATE:
1598 assert(child->perm & BLK_PERM_RESIZE);
1599 return 0;
1600 default:
1601 abort();
1605 static inline void coroutine_fn
1606 bdrv_co_write_req_finish(BdrvChild *child, int64_t offset, uint64_t bytes,
1607 BdrvTrackedRequest *req, int ret)
1609 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1610 BlockDriverState *bs = child->bs;
1612 atomic_inc(&bs->write_gen);
1615 * Discard cannot extend the image, but in error handling cases, such as
1616 * when reverting a qcow2 cluster allocation, the discarded range can pass
1617 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1618 * here. Instead, just skip it, since semantically a discard request
1619 * beyond EOF cannot expand the image anyway.
1621 if (ret == 0 &&
1622 (req->type == BDRV_TRACKED_TRUNCATE ||
1623 end_sector > bs->total_sectors) &&
1624 req->type != BDRV_TRACKED_DISCARD) {
1625 bs->total_sectors = end_sector;
1626 bdrv_parent_cb_resize(bs);
1627 bdrv_dirty_bitmap_truncate(bs, end_sector << BDRV_SECTOR_BITS);
1629 if (req->bytes) {
1630 switch (req->type) {
1631 case BDRV_TRACKED_WRITE:
1632 stat64_max(&bs->wr_highest_offset, offset + bytes);
1633 /* fall through, to set dirty bits */
1634 case BDRV_TRACKED_DISCARD:
1635 bdrv_set_dirty(bs, offset, bytes);
1636 break;
1637 default:
1638 break;
1644 * Forwards an already correctly aligned write request to the BlockDriver,
1645 * after possibly fragmenting it.
1647 static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
1648 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1649 int64_t align, QEMUIOVector *qiov, int flags)
1651 BlockDriverState *bs = child->bs;
1652 BlockDriver *drv = bs->drv;
1653 int ret;
1655 uint64_t bytes_remaining = bytes;
1656 int max_transfer;
1658 if (!drv) {
1659 return -ENOMEDIUM;
1662 if (bdrv_has_readonly_bitmaps(bs)) {
1663 return -EPERM;
1666 assert(is_power_of_2(align));
1667 assert((offset & (align - 1)) == 0);
1668 assert((bytes & (align - 1)) == 0);
1669 assert(!qiov || bytes == qiov->size);
1670 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1671 align);
1673 ret = bdrv_co_write_req_prepare(child, offset, bytes, req, flags);
1675 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1676 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
1677 qemu_iovec_is_zero(qiov)) {
1678 flags |= BDRV_REQ_ZERO_WRITE;
1679 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1680 flags |= BDRV_REQ_MAY_UNMAP;
1684 if (ret < 0) {
1685 /* Do nothing, write notifier decided to fail this request */
1686 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1687 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1688 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
1689 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
1690 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov);
1691 } else if (bytes <= max_transfer) {
1692 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1693 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
1694 } else {
1695 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1696 while (bytes_remaining) {
1697 int num = MIN(bytes_remaining, max_transfer);
1698 QEMUIOVector local_qiov;
1699 int local_flags = flags;
1701 assert(num);
1702 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
1703 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1704 /* If FUA is going to be emulated by flush, we only
1705 * need to flush on the last iteration */
1706 local_flags &= ~BDRV_REQ_FUA;
1708 qemu_iovec_init(&local_qiov, qiov->niov);
1709 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1711 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
1712 num, &local_qiov, local_flags);
1713 qemu_iovec_destroy(&local_qiov);
1714 if (ret < 0) {
1715 break;
1717 bytes_remaining -= num;
1720 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1722 if (ret >= 0) {
1723 ret = 0;
1725 bdrv_co_write_req_finish(child, offset, bytes, req, ret);
1727 return ret;
1730 static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
1731 int64_t offset,
1732 unsigned int bytes,
1733 BdrvRequestFlags flags,
1734 BdrvTrackedRequest *req)
1736 BlockDriverState *bs = child->bs;
1737 uint8_t *buf = NULL;
1738 QEMUIOVector local_qiov;
1739 uint64_t align = bs->bl.request_alignment;
1740 unsigned int head_padding_bytes, tail_padding_bytes;
1741 int ret = 0;
1743 head_padding_bytes = offset & (align - 1);
1744 tail_padding_bytes = (align - (offset + bytes)) & (align - 1);
1747 assert(flags & BDRV_REQ_ZERO_WRITE);
1748 if (head_padding_bytes || tail_padding_bytes) {
1749 buf = qemu_blockalign(bs, align);
1750 qemu_iovec_init_buf(&local_qiov, buf, align);
1752 if (head_padding_bytes) {
1753 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1755 /* RMW the unaligned part before head. */
1756 mark_request_serialising(req, align);
1757 wait_serialising_requests(req);
1758 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1759 ret = bdrv_aligned_preadv(child, req, offset & ~(align - 1), align,
1760 align, &local_qiov, 0);
1761 if (ret < 0) {
1762 goto fail;
1764 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1766 memset(buf + head_padding_bytes, 0, zero_bytes);
1767 ret = bdrv_aligned_pwritev(child, req, offset & ~(align - 1), align,
1768 align, &local_qiov,
1769 flags & ~BDRV_REQ_ZERO_WRITE);
1770 if (ret < 0) {
1771 goto fail;
1773 offset += zero_bytes;
1774 bytes -= zero_bytes;
1777 assert(!bytes || (offset & (align - 1)) == 0);
1778 if (bytes >= align) {
1779 /* Write the aligned part in the middle. */
1780 uint64_t aligned_bytes = bytes & ~(align - 1);
1781 ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
1782 NULL, flags);
1783 if (ret < 0) {
1784 goto fail;
1786 bytes -= aligned_bytes;
1787 offset += aligned_bytes;
1790 assert(!bytes || (offset & (align - 1)) == 0);
1791 if (bytes) {
1792 assert(align == tail_padding_bytes + bytes);
1793 /* RMW the unaligned part after tail. */
1794 mark_request_serialising(req, align);
1795 wait_serialising_requests(req);
1796 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1797 ret = bdrv_aligned_preadv(child, req, offset, align,
1798 align, &local_qiov, 0);
1799 if (ret < 0) {
1800 goto fail;
1802 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1804 memset(buf, 0, bytes);
1805 ret = bdrv_aligned_pwritev(child, req, offset, align, align,
1806 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1808 fail:
1809 qemu_vfree(buf);
1810 return ret;
1815 * Handle a write request in coroutine context
1817 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
1818 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1819 BdrvRequestFlags flags)
1821 BlockDriverState *bs = child->bs;
1822 BdrvTrackedRequest req;
1823 uint64_t align = bs->bl.request_alignment;
1824 uint8_t *head_buf = NULL;
1825 uint8_t *tail_buf = NULL;
1826 QEMUIOVector local_qiov;
1827 bool use_local_qiov = false;
1828 int ret;
1830 trace_bdrv_co_pwritev(child->bs, offset, bytes, flags);
1832 if (!bs->drv) {
1833 return -ENOMEDIUM;
1836 ret = bdrv_check_byte_request(bs, offset, bytes);
1837 if (ret < 0) {
1838 return ret;
1841 bdrv_inc_in_flight(bs);
1843 * Align write if necessary by performing a read-modify-write cycle.
1844 * Pad qiov with the read parts and be sure to have a tracked request not
1845 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1847 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
1849 if (flags & BDRV_REQ_ZERO_WRITE) {
1850 ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
1851 goto out;
1854 if (offset & (align - 1)) {
1855 QEMUIOVector head_qiov;
1857 mark_request_serialising(&req, align);
1858 wait_serialising_requests(&req);
1860 head_buf = qemu_blockalign(bs, align);
1861 qemu_iovec_init_buf(&head_qiov, head_buf, align);
1863 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1864 ret = bdrv_aligned_preadv(child, &req, offset & ~(align - 1), align,
1865 align, &head_qiov, 0);
1866 if (ret < 0) {
1867 goto fail;
1869 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1871 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1872 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1873 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1874 use_local_qiov = true;
1876 bytes += offset & (align - 1);
1877 offset = offset & ~(align - 1);
1879 /* We have read the tail already if the request is smaller
1880 * than one aligned block.
1882 if (bytes < align) {
1883 qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes);
1884 bytes = align;
1888 if ((offset + bytes) & (align - 1)) {
1889 QEMUIOVector tail_qiov;
1890 size_t tail_bytes;
1891 bool waited;
1893 mark_request_serialising(&req, align);
1894 waited = wait_serialising_requests(&req);
1895 assert(!waited || !use_local_qiov);
1897 tail_buf = qemu_blockalign(bs, align);
1898 qemu_iovec_init_buf(&tail_qiov, tail_buf, align);
1900 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1901 ret = bdrv_aligned_preadv(child, &req, (offset + bytes) & ~(align - 1),
1902 align, align, &tail_qiov, 0);
1903 if (ret < 0) {
1904 goto fail;
1906 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1908 if (!use_local_qiov) {
1909 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1910 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1911 use_local_qiov = true;
1914 tail_bytes = (offset + bytes) & (align - 1);
1915 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1917 bytes = ROUND_UP(bytes, align);
1920 ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
1921 use_local_qiov ? &local_qiov : qiov,
1922 flags);
1924 fail:
1926 if (use_local_qiov) {
1927 qemu_iovec_destroy(&local_qiov);
1929 qemu_vfree(head_buf);
1930 qemu_vfree(tail_buf);
1931 out:
1932 tracked_request_end(&req);
1933 bdrv_dec_in_flight(bs);
1934 return ret;
1937 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
1938 int bytes, BdrvRequestFlags flags)
1940 trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
1942 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
1943 flags &= ~BDRV_REQ_MAY_UNMAP;
1946 return bdrv_co_pwritev(child, offset, bytes, NULL,
1947 BDRV_REQ_ZERO_WRITE | flags);
1951 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1953 int bdrv_flush_all(void)
1955 BdrvNextIterator it;
1956 BlockDriverState *bs = NULL;
1957 int result = 0;
1959 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
1960 AioContext *aio_context = bdrv_get_aio_context(bs);
1961 int ret;
1963 aio_context_acquire(aio_context);
1964 ret = bdrv_flush(bs);
1965 if (ret < 0 && !result) {
1966 result = ret;
1968 aio_context_release(aio_context);
1971 return result;
1975 typedef struct BdrvCoBlockStatusData {
1976 BlockDriverState *bs;
1977 BlockDriverState *base;
1978 bool want_zero;
1979 int64_t offset;
1980 int64_t bytes;
1981 int64_t *pnum;
1982 int64_t *map;
1983 BlockDriverState **file;
1984 int ret;
1985 bool done;
1986 } BdrvCoBlockStatusData;
1988 int coroutine_fn bdrv_co_block_status_from_file(BlockDriverState *bs,
1989 bool want_zero,
1990 int64_t offset,
1991 int64_t bytes,
1992 int64_t *pnum,
1993 int64_t *map,
1994 BlockDriverState **file)
1996 assert(bs->file && bs->file->bs);
1997 *pnum = bytes;
1998 *map = offset;
1999 *file = bs->file->bs;
2000 return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2003 int coroutine_fn bdrv_co_block_status_from_backing(BlockDriverState *bs,
2004 bool want_zero,
2005 int64_t offset,
2006 int64_t bytes,
2007 int64_t *pnum,
2008 int64_t *map,
2009 BlockDriverState **file)
2011 assert(bs->backing && bs->backing->bs);
2012 *pnum = bytes;
2013 *map = offset;
2014 *file = bs->backing->bs;
2015 return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2019 * Returns the allocation status of the specified sectors.
2020 * Drivers not implementing the functionality are assumed to not support
2021 * backing files, hence all their sectors are reported as allocated.
2023 * If 'want_zero' is true, the caller is querying for mapping
2024 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2025 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2026 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2028 * If 'offset' is beyond the end of the disk image the return value is
2029 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2031 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2032 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2033 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2035 * 'pnum' is set to the number of bytes (including and immediately
2036 * following the specified offset) that are easily known to be in the
2037 * same allocated/unallocated state. Note that a second call starting
2038 * at the original offset plus returned pnum may have the same status.
2039 * The returned value is non-zero on success except at end-of-file.
2041 * Returns negative errno on failure. Otherwise, if the
2042 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2043 * set to the host mapping and BDS corresponding to the guest offset.
2045 static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
2046 bool want_zero,
2047 int64_t offset, int64_t bytes,
2048 int64_t *pnum, int64_t *map,
2049 BlockDriverState **file)
2051 int64_t total_size;
2052 int64_t n; /* bytes */
2053 int ret;
2054 int64_t local_map = 0;
2055 BlockDriverState *local_file = NULL;
2056 int64_t aligned_offset, aligned_bytes;
2057 uint32_t align;
2059 assert(pnum);
2060 *pnum = 0;
2061 total_size = bdrv_getlength(bs);
2062 if (total_size < 0) {
2063 ret = total_size;
2064 goto early_out;
2067 if (offset >= total_size) {
2068 ret = BDRV_BLOCK_EOF;
2069 goto early_out;
2071 if (!bytes) {
2072 ret = 0;
2073 goto early_out;
2076 n = total_size - offset;
2077 if (n < bytes) {
2078 bytes = n;
2081 /* Must be non-NULL or bdrv_getlength() would have failed */
2082 assert(bs->drv);
2083 if (!bs->drv->bdrv_co_block_status) {
2084 *pnum = bytes;
2085 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2086 if (offset + bytes == total_size) {
2087 ret |= BDRV_BLOCK_EOF;
2089 if (bs->drv->protocol_name) {
2090 ret |= BDRV_BLOCK_OFFSET_VALID;
2091 local_map = offset;
2092 local_file = bs;
2094 goto early_out;
2097 bdrv_inc_in_flight(bs);
2099 /* Round out to request_alignment boundaries */
2100 align = bs->bl.request_alignment;
2101 aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2102 aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2104 ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2105 aligned_bytes, pnum, &local_map,
2106 &local_file);
2107 if (ret < 0) {
2108 *pnum = 0;
2109 goto out;
2113 * The driver's result must be a non-zero multiple of request_alignment.
2114 * Clamp pnum and adjust map to original request.
2116 assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2117 align > offset - aligned_offset);
2118 *pnum -= offset - aligned_offset;
2119 if (*pnum > bytes) {
2120 *pnum = bytes;
2122 if (ret & BDRV_BLOCK_OFFSET_VALID) {
2123 local_map += offset - aligned_offset;
2126 if (ret & BDRV_BLOCK_RAW) {
2127 assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2128 ret = bdrv_co_block_status(local_file, want_zero, local_map,
2129 *pnum, pnum, &local_map, &local_file);
2130 goto out;
2133 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2134 ret |= BDRV_BLOCK_ALLOCATED;
2135 } else if (want_zero) {
2136 if (bdrv_unallocated_blocks_are_zero(bs)) {
2137 ret |= BDRV_BLOCK_ZERO;
2138 } else if (bs->backing) {
2139 BlockDriverState *bs2 = bs->backing->bs;
2140 int64_t size2 = bdrv_getlength(bs2);
2142 if (size2 >= 0 && offset >= size2) {
2143 ret |= BDRV_BLOCK_ZERO;
2148 if (want_zero && local_file && local_file != bs &&
2149 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2150 (ret & BDRV_BLOCK_OFFSET_VALID)) {
2151 int64_t file_pnum;
2152 int ret2;
2154 ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2155 *pnum, &file_pnum, NULL, NULL);
2156 if (ret2 >= 0) {
2157 /* Ignore errors. This is just providing extra information, it
2158 * is useful but not necessary.
2160 if (ret2 & BDRV_BLOCK_EOF &&
2161 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2163 * It is valid for the format block driver to read
2164 * beyond the end of the underlying file's current
2165 * size; such areas read as zero.
2167 ret |= BDRV_BLOCK_ZERO;
2168 } else {
2169 /* Limit request to the range reported by the protocol driver */
2170 *pnum = file_pnum;
2171 ret |= (ret2 & BDRV_BLOCK_ZERO);
2176 out:
2177 bdrv_dec_in_flight(bs);
2178 if (ret >= 0 && offset + *pnum == total_size) {
2179 ret |= BDRV_BLOCK_EOF;
2181 early_out:
2182 if (file) {
2183 *file = local_file;
2185 if (map) {
2186 *map = local_map;
2188 return ret;
2191 static int coroutine_fn bdrv_co_block_status_above(BlockDriverState *bs,
2192 BlockDriverState *base,
2193 bool want_zero,
2194 int64_t offset,
2195 int64_t bytes,
2196 int64_t *pnum,
2197 int64_t *map,
2198 BlockDriverState **file)
2200 BlockDriverState *p;
2201 int ret = 0;
2202 bool first = true;
2204 assert(bs != base);
2205 for (p = bs; p != base; p = backing_bs(p)) {
2206 ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2207 file);
2208 if (ret < 0) {
2209 break;
2211 if (ret & BDRV_BLOCK_ZERO && ret & BDRV_BLOCK_EOF && !first) {
2213 * Reading beyond the end of the file continues to read
2214 * zeroes, but we can only widen the result to the
2215 * unallocated length we learned from an earlier
2216 * iteration.
2218 *pnum = bytes;
2220 if (ret & (BDRV_BLOCK_ZERO | BDRV_BLOCK_DATA)) {
2221 break;
2223 /* [offset, pnum] unallocated on this layer, which could be only
2224 * the first part of [offset, bytes]. */
2225 bytes = MIN(bytes, *pnum);
2226 first = false;
2228 return ret;
2231 /* Coroutine wrapper for bdrv_block_status_above() */
2232 static void coroutine_fn bdrv_block_status_above_co_entry(void *opaque)
2234 BdrvCoBlockStatusData *data = opaque;
2236 data->ret = bdrv_co_block_status_above(data->bs, data->base,
2237 data->want_zero,
2238 data->offset, data->bytes,
2239 data->pnum, data->map, data->file);
2240 data->done = true;
2241 aio_wait_kick();
2245 * Synchronous wrapper around bdrv_co_block_status_above().
2247 * See bdrv_co_block_status_above() for details.
2249 static int bdrv_common_block_status_above(BlockDriverState *bs,
2250 BlockDriverState *base,
2251 bool want_zero, int64_t offset,
2252 int64_t bytes, int64_t *pnum,
2253 int64_t *map,
2254 BlockDriverState **file)
2256 Coroutine *co;
2257 BdrvCoBlockStatusData data = {
2258 .bs = bs,
2259 .base = base,
2260 .want_zero = want_zero,
2261 .offset = offset,
2262 .bytes = bytes,
2263 .pnum = pnum,
2264 .map = map,
2265 .file = file,
2266 .done = false,
2269 if (qemu_in_coroutine()) {
2270 /* Fast-path if already in coroutine context */
2271 bdrv_block_status_above_co_entry(&data);
2272 } else {
2273 co = qemu_coroutine_create(bdrv_block_status_above_co_entry, &data);
2274 bdrv_coroutine_enter(bs, co);
2275 BDRV_POLL_WHILE(bs, !data.done);
2277 return data.ret;
2280 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2281 int64_t offset, int64_t bytes, int64_t *pnum,
2282 int64_t *map, BlockDriverState **file)
2284 return bdrv_common_block_status_above(bs, base, true, offset, bytes,
2285 pnum, map, file);
2288 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2289 int64_t *pnum, int64_t *map, BlockDriverState **file)
2291 return bdrv_block_status_above(bs, backing_bs(bs),
2292 offset, bytes, pnum, map, file);
2295 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
2296 int64_t bytes, int64_t *pnum)
2298 int ret;
2299 int64_t dummy;
2301 ret = bdrv_common_block_status_above(bs, backing_bs(bs), false, offset,
2302 bytes, pnum ? pnum : &dummy, NULL,
2303 NULL);
2304 if (ret < 0) {
2305 return ret;
2307 return !!(ret & BDRV_BLOCK_ALLOCATED);
2311 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2313 * Return true if (a prefix of) the given range is allocated in any image
2314 * between BASE and TOP (inclusive). BASE can be NULL to check if the given
2315 * offset is allocated in any image of the chain. Return false otherwise,
2316 * or negative errno on failure.
2318 * 'pnum' is set to the number of bytes (including and immediately
2319 * following the specified offset) that are known to be in the same
2320 * allocated/unallocated state. Note that a subsequent call starting
2321 * at 'offset + *pnum' may return the same allocation status (in other
2322 * words, the result is not necessarily the maximum possible range);
2323 * but 'pnum' will only be 0 when end of file is reached.
2326 int bdrv_is_allocated_above(BlockDriverState *top,
2327 BlockDriverState *base,
2328 int64_t offset, int64_t bytes, int64_t *pnum)
2330 BlockDriverState *intermediate;
2331 int ret;
2332 int64_t n = bytes;
2334 intermediate = top;
2335 while (intermediate && intermediate != base) {
2336 int64_t pnum_inter;
2337 int64_t size_inter;
2339 ret = bdrv_is_allocated(intermediate, offset, bytes, &pnum_inter);
2340 if (ret < 0) {
2341 return ret;
2343 if (ret) {
2344 *pnum = pnum_inter;
2345 return 1;
2348 size_inter = bdrv_getlength(intermediate);
2349 if (size_inter < 0) {
2350 return size_inter;
2352 if (n > pnum_inter &&
2353 (intermediate == top || offset + pnum_inter < size_inter)) {
2354 n = pnum_inter;
2357 intermediate = backing_bs(intermediate);
2360 *pnum = n;
2361 return 0;
2364 typedef struct BdrvVmstateCo {
2365 BlockDriverState *bs;
2366 QEMUIOVector *qiov;
2367 int64_t pos;
2368 bool is_read;
2369 int ret;
2370 } BdrvVmstateCo;
2372 static int coroutine_fn
2373 bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
2374 bool is_read)
2376 BlockDriver *drv = bs->drv;
2377 int ret = -ENOTSUP;
2379 bdrv_inc_in_flight(bs);
2381 if (!drv) {
2382 ret = -ENOMEDIUM;
2383 } else if (drv->bdrv_load_vmstate) {
2384 if (is_read) {
2385 ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2386 } else {
2387 ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2389 } else if (bs->file) {
2390 ret = bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read);
2393 bdrv_dec_in_flight(bs);
2394 return ret;
2397 static void coroutine_fn bdrv_co_rw_vmstate_entry(void *opaque)
2399 BdrvVmstateCo *co = opaque;
2400 co->ret = bdrv_co_rw_vmstate(co->bs, co->qiov, co->pos, co->is_read);
2401 aio_wait_kick();
2404 static inline int
2405 bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
2406 bool is_read)
2408 if (qemu_in_coroutine()) {
2409 return bdrv_co_rw_vmstate(bs, qiov, pos, is_read);
2410 } else {
2411 BdrvVmstateCo data = {
2412 .bs = bs,
2413 .qiov = qiov,
2414 .pos = pos,
2415 .is_read = is_read,
2416 .ret = -EINPROGRESS,
2418 Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry, &data);
2420 bdrv_coroutine_enter(bs, co);
2421 BDRV_POLL_WHILE(bs, data.ret == -EINPROGRESS);
2422 return data.ret;
2426 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2427 int64_t pos, int size)
2429 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2430 int ret;
2432 ret = bdrv_writev_vmstate(bs, &qiov, pos);
2433 if (ret < 0) {
2434 return ret;
2437 return size;
2440 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2442 return bdrv_rw_vmstate(bs, qiov, pos, false);
2445 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2446 int64_t pos, int size)
2448 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2449 int ret;
2451 ret = bdrv_readv_vmstate(bs, &qiov, pos);
2452 if (ret < 0) {
2453 return ret;
2456 return size;
2459 int bdrv_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2461 return bdrv_rw_vmstate(bs, qiov, pos, true);
2464 /**************************************************************/
2465 /* async I/Os */
2467 void bdrv_aio_cancel(BlockAIOCB *acb)
2469 qemu_aio_ref(acb);
2470 bdrv_aio_cancel_async(acb);
2471 while (acb->refcnt > 1) {
2472 if (acb->aiocb_info->get_aio_context) {
2473 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2474 } else if (acb->bs) {
2475 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2476 * assert that we're not using an I/O thread. Thread-safe
2477 * code should use bdrv_aio_cancel_async exclusively.
2479 assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2480 aio_poll(bdrv_get_aio_context(acb->bs), true);
2481 } else {
2482 abort();
2485 qemu_aio_unref(acb);
2488 /* Async version of aio cancel. The caller is not blocked if the acb implements
2489 * cancel_async, otherwise we do nothing and let the request normally complete.
2490 * In either case the completion callback must be called. */
2491 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2493 if (acb->aiocb_info->cancel_async) {
2494 acb->aiocb_info->cancel_async(acb);
2498 /**************************************************************/
2499 /* Coroutine block device emulation */
2501 typedef struct FlushCo {
2502 BlockDriverState *bs;
2503 int ret;
2504 } FlushCo;
2507 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2509 FlushCo *rwco = opaque;
2511 rwco->ret = bdrv_co_flush(rwco->bs);
2512 aio_wait_kick();
2515 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2517 int current_gen;
2518 int ret = 0;
2520 bdrv_inc_in_flight(bs);
2522 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2523 bdrv_is_sg(bs)) {
2524 goto early_exit;
2527 qemu_co_mutex_lock(&bs->reqs_lock);
2528 current_gen = atomic_read(&bs->write_gen);
2530 /* Wait until any previous flushes are completed */
2531 while (bs->active_flush_req) {
2532 qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
2535 /* Flushes reach this point in nondecreasing current_gen order. */
2536 bs->active_flush_req = true;
2537 qemu_co_mutex_unlock(&bs->reqs_lock);
2539 /* Write back all layers by calling one driver function */
2540 if (bs->drv->bdrv_co_flush) {
2541 ret = bs->drv->bdrv_co_flush(bs);
2542 goto out;
2545 /* Write back cached data to the OS even with cache=unsafe */
2546 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2547 if (bs->drv->bdrv_co_flush_to_os) {
2548 ret = bs->drv->bdrv_co_flush_to_os(bs);
2549 if (ret < 0) {
2550 goto out;
2554 /* But don't actually force it to the disk with cache=unsafe */
2555 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2556 goto flush_parent;
2559 /* Check if we really need to flush anything */
2560 if (bs->flushed_gen == current_gen) {
2561 goto flush_parent;
2564 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
2565 if (!bs->drv) {
2566 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2567 * (even in case of apparent success) */
2568 ret = -ENOMEDIUM;
2569 goto out;
2571 if (bs->drv->bdrv_co_flush_to_disk) {
2572 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2573 } else if (bs->drv->bdrv_aio_flush) {
2574 BlockAIOCB *acb;
2575 CoroutineIOCompletion co = {
2576 .coroutine = qemu_coroutine_self(),
2579 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2580 if (acb == NULL) {
2581 ret = -EIO;
2582 } else {
2583 qemu_coroutine_yield();
2584 ret = co.ret;
2586 } else {
2588 * Some block drivers always operate in either writethrough or unsafe
2589 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2590 * know how the server works (because the behaviour is hardcoded or
2591 * depends on server-side configuration), so we can't ensure that
2592 * everything is safe on disk. Returning an error doesn't work because
2593 * that would break guests even if the server operates in writethrough
2594 * mode.
2596 * Let's hope the user knows what he's doing.
2598 ret = 0;
2601 if (ret < 0) {
2602 goto out;
2605 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2606 * in the case of cache=unsafe, so there are no useless flushes.
2608 flush_parent:
2609 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2610 out:
2611 /* Notify any pending flushes that we have completed */
2612 if (ret == 0) {
2613 bs->flushed_gen = current_gen;
2616 qemu_co_mutex_lock(&bs->reqs_lock);
2617 bs->active_flush_req = false;
2618 /* Return value is ignored - it's ok if wait queue is empty */
2619 qemu_co_queue_next(&bs->flush_queue);
2620 qemu_co_mutex_unlock(&bs->reqs_lock);
2622 early_exit:
2623 bdrv_dec_in_flight(bs);
2624 return ret;
2627 int bdrv_flush(BlockDriverState *bs)
2629 Coroutine *co;
2630 FlushCo flush_co = {
2631 .bs = bs,
2632 .ret = NOT_DONE,
2635 if (qemu_in_coroutine()) {
2636 /* Fast-path if already in coroutine context */
2637 bdrv_flush_co_entry(&flush_co);
2638 } else {
2639 co = qemu_coroutine_create(bdrv_flush_co_entry, &flush_co);
2640 bdrv_coroutine_enter(bs, co);
2641 BDRV_POLL_WHILE(bs, flush_co.ret == NOT_DONE);
2644 return flush_co.ret;
2647 typedef struct DiscardCo {
2648 BdrvChild *child;
2649 int64_t offset;
2650 int bytes;
2651 int ret;
2652 } DiscardCo;
2653 static void coroutine_fn bdrv_pdiscard_co_entry(void *opaque)
2655 DiscardCo *rwco = opaque;
2657 rwco->ret = bdrv_co_pdiscard(rwco->child, rwco->offset, rwco->bytes);
2658 aio_wait_kick();
2661 int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset, int bytes)
2663 BdrvTrackedRequest req;
2664 int max_pdiscard, ret;
2665 int head, tail, align;
2666 BlockDriverState *bs = child->bs;
2668 if (!bs || !bs->drv) {
2669 return -ENOMEDIUM;
2672 if (bdrv_has_readonly_bitmaps(bs)) {
2673 return -EPERM;
2676 ret = bdrv_check_byte_request(bs, offset, bytes);
2677 if (ret < 0) {
2678 return ret;
2681 /* Do nothing if disabled. */
2682 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2683 return 0;
2686 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
2687 return 0;
2690 /* Discard is advisory, but some devices track and coalesce
2691 * unaligned requests, so we must pass everything down rather than
2692 * round here. Still, most devices will just silently ignore
2693 * unaligned requests (by returning -ENOTSUP), so we must fragment
2694 * the request accordingly. */
2695 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
2696 assert(align % bs->bl.request_alignment == 0);
2697 head = offset % align;
2698 tail = (offset + bytes) % align;
2700 bdrv_inc_in_flight(bs);
2701 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
2703 ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
2704 if (ret < 0) {
2705 goto out;
2708 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),
2709 align);
2710 assert(max_pdiscard >= bs->bl.request_alignment);
2712 while (bytes > 0) {
2713 int num = bytes;
2715 if (head) {
2716 /* Make small requests to get to alignment boundaries. */
2717 num = MIN(bytes, align - head);
2718 if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
2719 num %= bs->bl.request_alignment;
2721 head = (head + num) % align;
2722 assert(num < max_pdiscard);
2723 } else if (tail) {
2724 if (num > align) {
2725 /* Shorten the request to the last aligned cluster. */
2726 num -= tail;
2727 } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
2728 tail > bs->bl.request_alignment) {
2729 tail %= bs->bl.request_alignment;
2730 num -= tail;
2733 /* limit request size */
2734 if (num > max_pdiscard) {
2735 num = max_pdiscard;
2738 if (!bs->drv) {
2739 ret = -ENOMEDIUM;
2740 goto out;
2742 if (bs->drv->bdrv_co_pdiscard) {
2743 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
2744 } else {
2745 BlockAIOCB *acb;
2746 CoroutineIOCompletion co = {
2747 .coroutine = qemu_coroutine_self(),
2750 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
2751 bdrv_co_io_em_complete, &co);
2752 if (acb == NULL) {
2753 ret = -EIO;
2754 goto out;
2755 } else {
2756 qemu_coroutine_yield();
2757 ret = co.ret;
2760 if (ret && ret != -ENOTSUP) {
2761 goto out;
2764 offset += num;
2765 bytes -= num;
2767 ret = 0;
2768 out:
2769 bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
2770 tracked_request_end(&req);
2771 bdrv_dec_in_flight(bs);
2772 return ret;
2775 int bdrv_pdiscard(BdrvChild *child, int64_t offset, int bytes)
2777 Coroutine *co;
2778 DiscardCo rwco = {
2779 .child = child,
2780 .offset = offset,
2781 .bytes = bytes,
2782 .ret = NOT_DONE,
2785 if (qemu_in_coroutine()) {
2786 /* Fast-path if already in coroutine context */
2787 bdrv_pdiscard_co_entry(&rwco);
2788 } else {
2789 co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco);
2790 bdrv_coroutine_enter(child->bs, co);
2791 BDRV_POLL_WHILE(child->bs, rwco.ret == NOT_DONE);
2794 return rwco.ret;
2797 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
2799 BlockDriver *drv = bs->drv;
2800 CoroutineIOCompletion co = {
2801 .coroutine = qemu_coroutine_self(),
2803 BlockAIOCB *acb;
2805 bdrv_inc_in_flight(bs);
2806 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
2807 co.ret = -ENOTSUP;
2808 goto out;
2811 if (drv->bdrv_co_ioctl) {
2812 co.ret = drv->bdrv_co_ioctl(bs, req, buf);
2813 } else {
2814 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2815 if (!acb) {
2816 co.ret = -ENOTSUP;
2817 goto out;
2819 qemu_coroutine_yield();
2821 out:
2822 bdrv_dec_in_flight(bs);
2823 return co.ret;
2826 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2828 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2831 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2833 return memset(qemu_blockalign(bs, size), 0, size);
2836 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2838 size_t align = bdrv_opt_mem_align(bs);
2840 /* Ensure that NULL is never returned on success */
2841 assert(align > 0);
2842 if (size == 0) {
2843 size = align;
2846 return qemu_try_memalign(align, size);
2849 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2851 void *mem = qemu_try_blockalign(bs, size);
2853 if (mem) {
2854 memset(mem, 0, size);
2857 return mem;
2861 * Check if all memory in this vector is sector aligned.
2863 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2865 int i;
2866 size_t alignment = bdrv_min_mem_align(bs);
2868 for (i = 0; i < qiov->niov; i++) {
2869 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2870 return false;
2872 if (qiov->iov[i].iov_len % alignment) {
2873 return false;
2877 return true;
2880 void bdrv_add_before_write_notifier(BlockDriverState *bs,
2881 NotifierWithReturn *notifier)
2883 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2886 void bdrv_io_plug(BlockDriverState *bs)
2888 BdrvChild *child;
2890 QLIST_FOREACH(child, &bs->children, next) {
2891 bdrv_io_plug(child->bs);
2894 if (atomic_fetch_inc(&bs->io_plugged) == 0) {
2895 BlockDriver *drv = bs->drv;
2896 if (drv && drv->bdrv_io_plug) {
2897 drv->bdrv_io_plug(bs);
2902 void bdrv_io_unplug(BlockDriverState *bs)
2904 BdrvChild *child;
2906 assert(bs->io_plugged);
2907 if (atomic_fetch_dec(&bs->io_plugged) == 1) {
2908 BlockDriver *drv = bs->drv;
2909 if (drv && drv->bdrv_io_unplug) {
2910 drv->bdrv_io_unplug(bs);
2914 QLIST_FOREACH(child, &bs->children, next) {
2915 bdrv_io_unplug(child->bs);
2919 void bdrv_register_buf(BlockDriverState *bs, void *host, size_t size)
2921 BdrvChild *child;
2923 if (bs->drv && bs->drv->bdrv_register_buf) {
2924 bs->drv->bdrv_register_buf(bs, host, size);
2926 QLIST_FOREACH(child, &bs->children, next) {
2927 bdrv_register_buf(child->bs, host, size);
2931 void bdrv_unregister_buf(BlockDriverState *bs, void *host)
2933 BdrvChild *child;
2935 if (bs->drv && bs->drv->bdrv_unregister_buf) {
2936 bs->drv->bdrv_unregister_buf(bs, host);
2938 QLIST_FOREACH(child, &bs->children, next) {
2939 bdrv_unregister_buf(child->bs, host);
2943 static int coroutine_fn bdrv_co_copy_range_internal(
2944 BdrvChild *src, uint64_t src_offset, BdrvChild *dst,
2945 uint64_t dst_offset, uint64_t bytes,
2946 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
2947 bool recurse_src)
2949 BdrvTrackedRequest req;
2950 int ret;
2952 if (!dst || !dst->bs) {
2953 return -ENOMEDIUM;
2955 ret = bdrv_check_byte_request(dst->bs, dst_offset, bytes);
2956 if (ret) {
2957 return ret;
2959 if (write_flags & BDRV_REQ_ZERO_WRITE) {
2960 return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
2963 if (!src || !src->bs) {
2964 return -ENOMEDIUM;
2966 ret = bdrv_check_byte_request(src->bs, src_offset, bytes);
2967 if (ret) {
2968 return ret;
2971 if (!src->bs->drv->bdrv_co_copy_range_from
2972 || !dst->bs->drv->bdrv_co_copy_range_to
2973 || src->bs->encrypted || dst->bs->encrypted) {
2974 return -ENOTSUP;
2977 if (recurse_src) {
2978 bdrv_inc_in_flight(src->bs);
2979 tracked_request_begin(&req, src->bs, src_offset, bytes,
2980 BDRV_TRACKED_READ);
2982 /* BDRV_REQ_SERIALISING is only for write operation */
2983 assert(!(read_flags & BDRV_REQ_SERIALISING));
2984 if (!(read_flags & BDRV_REQ_NO_SERIALISING)) {
2985 wait_serialising_requests(&req);
2988 ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
2989 src, src_offset,
2990 dst, dst_offset,
2991 bytes,
2992 read_flags, write_flags);
2994 tracked_request_end(&req);
2995 bdrv_dec_in_flight(src->bs);
2996 } else {
2997 bdrv_inc_in_flight(dst->bs);
2998 tracked_request_begin(&req, dst->bs, dst_offset, bytes,
2999 BDRV_TRACKED_WRITE);
3000 ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3001 write_flags);
3002 if (!ret) {
3003 ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3004 src, src_offset,
3005 dst, dst_offset,
3006 bytes,
3007 read_flags, write_flags);
3009 bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
3010 tracked_request_end(&req);
3011 bdrv_dec_in_flight(dst->bs);
3014 return ret;
3017 /* Copy range from @src to @dst.
3019 * See the comment of bdrv_co_copy_range for the parameter and return value
3020 * semantics. */
3021 int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, uint64_t src_offset,
3022 BdrvChild *dst, uint64_t dst_offset,
3023 uint64_t bytes,
3024 BdrvRequestFlags read_flags,
3025 BdrvRequestFlags write_flags)
3027 trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3028 read_flags, write_flags);
3029 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3030 bytes, read_flags, write_flags, true);
3033 /* Copy range from @src to @dst.
3035 * See the comment of bdrv_co_copy_range for the parameter and return value
3036 * semantics. */
3037 int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, uint64_t src_offset,
3038 BdrvChild *dst, uint64_t dst_offset,
3039 uint64_t bytes,
3040 BdrvRequestFlags read_flags,
3041 BdrvRequestFlags write_flags)
3043 trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3044 read_flags, write_flags);
3045 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3046 bytes, read_flags, write_flags, false);
3049 int coroutine_fn bdrv_co_copy_range(BdrvChild *src, uint64_t src_offset,
3050 BdrvChild *dst, uint64_t dst_offset,
3051 uint64_t bytes, BdrvRequestFlags read_flags,
3052 BdrvRequestFlags write_flags)
3054 return bdrv_co_copy_range_from(src, src_offset,
3055 dst, dst_offset,
3056 bytes, read_flags, write_flags);
3059 static void bdrv_parent_cb_resize(BlockDriverState *bs)
3061 BdrvChild *c;
3062 QLIST_FOREACH(c, &bs->parents, next_parent) {
3063 if (c->role->resize) {
3064 c->role->resize(c);
3070 * Truncate file to 'offset' bytes (needed only for file protocols)
3072 int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset,
3073 PreallocMode prealloc, Error **errp)
3075 BlockDriverState *bs = child->bs;
3076 BlockDriver *drv = bs->drv;
3077 BdrvTrackedRequest req;
3078 int64_t old_size, new_bytes;
3079 int ret;
3082 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3083 if (!drv) {
3084 error_setg(errp, "No medium inserted");
3085 return -ENOMEDIUM;
3087 if (offset < 0) {
3088 error_setg(errp, "Image size cannot be negative");
3089 return -EINVAL;
3092 old_size = bdrv_getlength(bs);
3093 if (old_size < 0) {
3094 error_setg_errno(errp, -old_size, "Failed to get old image size");
3095 return old_size;
3098 if (offset > old_size) {
3099 new_bytes = offset - old_size;
3100 } else {
3101 new_bytes = 0;
3104 bdrv_inc_in_flight(bs);
3105 tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3106 BDRV_TRACKED_TRUNCATE);
3108 /* If we are growing the image and potentially using preallocation for the
3109 * new area, we need to make sure that no write requests are made to it
3110 * concurrently or they might be overwritten by preallocation. */
3111 if (new_bytes) {
3112 mark_request_serialising(&req, 1);
3114 if (bs->read_only) {
3115 error_setg(errp, "Image is read-only");
3116 ret = -EACCES;
3117 goto out;
3119 ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3121 if (ret < 0) {
3122 error_setg_errno(errp, -ret,
3123 "Failed to prepare request for truncation");
3124 goto out;
3127 if (!drv->bdrv_co_truncate) {
3128 if (bs->file && drv->is_filter) {
3129 ret = bdrv_co_truncate(bs->file, offset, prealloc, errp);
3130 goto out;
3132 error_setg(errp, "Image format driver does not support resize");
3133 ret = -ENOTSUP;
3134 goto out;
3137 ret = drv->bdrv_co_truncate(bs, offset, prealloc, errp);
3138 if (ret < 0) {
3139 goto out;
3141 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3142 if (ret < 0) {
3143 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3144 } else {
3145 offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3147 /* It's possible that truncation succeeded but refresh_total_sectors
3148 * failed, but the latter doesn't affect how we should finish the request.
3149 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3150 bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3152 out:
3153 tracked_request_end(&req);
3154 bdrv_dec_in_flight(bs);
3156 return ret;
3159 typedef struct TruncateCo {
3160 BdrvChild *child;
3161 int64_t offset;
3162 PreallocMode prealloc;
3163 Error **errp;
3164 int ret;
3165 } TruncateCo;
3167 static void coroutine_fn bdrv_truncate_co_entry(void *opaque)
3169 TruncateCo *tco = opaque;
3170 tco->ret = bdrv_co_truncate(tco->child, tco->offset, tco->prealloc,
3171 tco->errp);
3172 aio_wait_kick();
3175 int bdrv_truncate(BdrvChild *child, int64_t offset, PreallocMode prealloc,
3176 Error **errp)
3178 Coroutine *co;
3179 TruncateCo tco = {
3180 .child = child,
3181 .offset = offset,
3182 .prealloc = prealloc,
3183 .errp = errp,
3184 .ret = NOT_DONE,
3187 if (qemu_in_coroutine()) {
3188 /* Fast-path if already in coroutine context */
3189 bdrv_truncate_co_entry(&tco);
3190 } else {
3191 co = qemu_coroutine_create(bdrv_truncate_co_entry, &tco);
3192 bdrv_coroutine_enter(child->bs, co);
3193 BDRV_POLL_WHILE(child->bs, tco.ret == NOT_DONE);
3196 return tco.ret;