block: Loop unsafely in bdrv*drained_end()
[qemu/ar7.git] / block / io.c
blobb89e155d2139e68436e41a8cd1d6992a5e42e446
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 static 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 static void bdrv_parent_drained_end_single_no_poll(BdrvChild *c,
59 int *drained_end_counter)
61 assert(c->parent_quiesce_counter > 0);
62 c->parent_quiesce_counter--;
63 if (c->role->drained_end) {
64 c->role->drained_end(c, drained_end_counter);
68 void bdrv_parent_drained_end_single(BdrvChild *c)
70 int drained_end_counter = 0;
71 bdrv_parent_drained_end_single_no_poll(c, &drained_end_counter);
72 BDRV_POLL_WHILE(c->bs, atomic_read(&drained_end_counter) > 0);
75 static void bdrv_parent_drained_end(BlockDriverState *bs, BdrvChild *ignore,
76 bool ignore_bds_parents,
77 int *drained_end_counter)
79 BdrvChild *c;
81 QLIST_FOREACH(c, &bs->parents, next_parent) {
82 if (c == ignore || (ignore_bds_parents && c->role->parent_is_bds)) {
83 continue;
85 bdrv_parent_drained_end_single_no_poll(c, drained_end_counter);
89 static bool bdrv_parent_drained_poll_single(BdrvChild *c)
91 if (c->role->drained_poll) {
92 return c->role->drained_poll(c);
94 return false;
97 static bool bdrv_parent_drained_poll(BlockDriverState *bs, BdrvChild *ignore,
98 bool ignore_bds_parents)
100 BdrvChild *c, *next;
101 bool busy = false;
103 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
104 if (c == ignore || (ignore_bds_parents && c->role->parent_is_bds)) {
105 continue;
107 busy |= bdrv_parent_drained_poll_single(c);
110 return busy;
113 void bdrv_parent_drained_begin_single(BdrvChild *c, bool poll)
115 c->parent_quiesce_counter++;
116 if (c->role->drained_begin) {
117 c->role->drained_begin(c);
119 if (poll) {
120 BDRV_POLL_WHILE(c->bs, bdrv_parent_drained_poll_single(c));
124 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
126 dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
127 dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer);
128 dst->opt_mem_alignment = MAX(dst->opt_mem_alignment,
129 src->opt_mem_alignment);
130 dst->min_mem_alignment = MAX(dst->min_mem_alignment,
131 src->min_mem_alignment);
132 dst->max_iov = MIN_NON_ZERO(dst->max_iov, src->max_iov);
135 void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
137 BlockDriver *drv = bs->drv;
138 Error *local_err = NULL;
140 memset(&bs->bl, 0, sizeof(bs->bl));
142 if (!drv) {
143 return;
146 /* Default alignment based on whether driver has byte interface */
147 bs->bl.request_alignment = (drv->bdrv_co_preadv ||
148 drv->bdrv_aio_preadv) ? 1 : 512;
150 /* Take some limits from the children as a default */
151 if (bs->file) {
152 bdrv_refresh_limits(bs->file->bs, &local_err);
153 if (local_err) {
154 error_propagate(errp, local_err);
155 return;
157 bdrv_merge_limits(&bs->bl, &bs->file->bs->bl);
158 } else {
159 bs->bl.min_mem_alignment = 512;
160 bs->bl.opt_mem_alignment = getpagesize();
162 /* Safe default since most protocols use readv()/writev()/etc */
163 bs->bl.max_iov = IOV_MAX;
166 if (bs->backing) {
167 bdrv_refresh_limits(bs->backing->bs, &local_err);
168 if (local_err) {
169 error_propagate(errp, local_err);
170 return;
172 bdrv_merge_limits(&bs->bl, &bs->backing->bs->bl);
175 /* Then let the driver override it */
176 if (drv->bdrv_refresh_limits) {
177 drv->bdrv_refresh_limits(bs, errp);
182 * The copy-on-read flag is actually a reference count so multiple users may
183 * use the feature without worrying about clobbering its previous state.
184 * Copy-on-read stays enabled until all users have called to disable it.
186 void bdrv_enable_copy_on_read(BlockDriverState *bs)
188 atomic_inc(&bs->copy_on_read);
191 void bdrv_disable_copy_on_read(BlockDriverState *bs)
193 int old = atomic_fetch_dec(&bs->copy_on_read);
194 assert(old >= 1);
197 typedef struct {
198 Coroutine *co;
199 BlockDriverState *bs;
200 bool done;
201 bool begin;
202 bool recursive;
203 bool poll;
204 BdrvChild *parent;
205 bool ignore_bds_parents;
206 int *drained_end_counter;
207 } BdrvCoDrainData;
209 static void coroutine_fn bdrv_drain_invoke_entry(void *opaque)
211 BdrvCoDrainData *data = opaque;
212 BlockDriverState *bs = data->bs;
214 if (data->begin) {
215 bs->drv->bdrv_co_drain_begin(bs);
216 } else {
217 bs->drv->bdrv_co_drain_end(bs);
220 /* Set data->done before reading bs->wakeup. */
221 atomic_mb_set(&data->done, true);
222 bdrv_dec_in_flight(bs);
224 if (!data->begin) {
225 atomic_dec(data->drained_end_counter);
228 g_free(data);
231 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
232 static void bdrv_drain_invoke(BlockDriverState *bs, bool begin,
233 int *drained_end_counter)
235 BdrvCoDrainData *data;
237 if (!bs->drv || (begin && !bs->drv->bdrv_co_drain_begin) ||
238 (!begin && !bs->drv->bdrv_co_drain_end)) {
239 return;
242 data = g_new(BdrvCoDrainData, 1);
243 *data = (BdrvCoDrainData) {
244 .bs = bs,
245 .done = false,
246 .begin = begin,
247 .drained_end_counter = drained_end_counter,
250 if (!begin) {
251 atomic_inc(drained_end_counter);
254 /* Make sure the driver callback completes during the polling phase for
255 * drain_begin. */
256 bdrv_inc_in_flight(bs);
257 data->co = qemu_coroutine_create(bdrv_drain_invoke_entry, data);
258 aio_co_schedule(bdrv_get_aio_context(bs), data->co);
261 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
262 bool bdrv_drain_poll(BlockDriverState *bs, bool recursive,
263 BdrvChild *ignore_parent, bool ignore_bds_parents)
265 BdrvChild *child, *next;
267 if (bdrv_parent_drained_poll(bs, ignore_parent, ignore_bds_parents)) {
268 return true;
271 if (atomic_read(&bs->in_flight)) {
272 return true;
275 if (recursive) {
276 assert(!ignore_bds_parents);
277 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
278 if (bdrv_drain_poll(child->bs, recursive, child, false)) {
279 return true;
284 return false;
287 static bool bdrv_drain_poll_top_level(BlockDriverState *bs, bool recursive,
288 BdrvChild *ignore_parent)
290 return bdrv_drain_poll(bs, recursive, ignore_parent, false);
293 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
294 BdrvChild *parent, bool ignore_bds_parents,
295 bool poll);
296 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
297 BdrvChild *parent, bool ignore_bds_parents,
298 int *drained_end_counter);
300 static void bdrv_co_drain_bh_cb(void *opaque)
302 BdrvCoDrainData *data = opaque;
303 Coroutine *co = data->co;
304 BlockDriverState *bs = data->bs;
306 if (bs) {
307 AioContext *ctx = bdrv_get_aio_context(bs);
308 AioContext *co_ctx = qemu_coroutine_get_aio_context(co);
311 * When the coroutine yielded, the lock for its home context was
312 * released, so we need to re-acquire it here. If it explicitly
313 * acquired a different context, the lock is still held and we don't
314 * want to lock it a second time (or AIO_WAIT_WHILE() would hang).
316 if (ctx == co_ctx) {
317 aio_context_acquire(ctx);
319 bdrv_dec_in_flight(bs);
320 if (data->begin) {
321 assert(!data->drained_end_counter);
322 bdrv_do_drained_begin(bs, data->recursive, data->parent,
323 data->ignore_bds_parents, data->poll);
324 } else {
325 assert(!data->poll);
326 bdrv_do_drained_end(bs, data->recursive, data->parent,
327 data->ignore_bds_parents,
328 data->drained_end_counter);
330 if (ctx == co_ctx) {
331 aio_context_release(ctx);
333 } else {
334 assert(data->begin);
335 bdrv_drain_all_begin();
338 data->done = true;
339 aio_co_wake(co);
342 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs,
343 bool begin, bool recursive,
344 BdrvChild *parent,
345 bool ignore_bds_parents,
346 bool poll,
347 int *drained_end_counter)
349 BdrvCoDrainData data;
351 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
352 * other coroutines run if they were queued by aio_co_enter(). */
354 assert(qemu_in_coroutine());
355 data = (BdrvCoDrainData) {
356 .co = qemu_coroutine_self(),
357 .bs = bs,
358 .done = false,
359 .begin = begin,
360 .recursive = recursive,
361 .parent = parent,
362 .ignore_bds_parents = ignore_bds_parents,
363 .poll = poll,
364 .drained_end_counter = drained_end_counter,
367 if (bs) {
368 bdrv_inc_in_flight(bs);
370 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs),
371 bdrv_co_drain_bh_cb, &data);
373 qemu_coroutine_yield();
374 /* If we are resumed from some other event (such as an aio completion or a
375 * timer callback), it is a bug in the caller that should be fixed. */
376 assert(data.done);
379 void bdrv_do_drained_begin_quiesce(BlockDriverState *bs,
380 BdrvChild *parent, bool ignore_bds_parents)
382 assert(!qemu_in_coroutine());
384 /* Stop things in parent-to-child order */
385 if (atomic_fetch_inc(&bs->quiesce_counter) == 0) {
386 aio_disable_external(bdrv_get_aio_context(bs));
389 bdrv_parent_drained_begin(bs, parent, ignore_bds_parents);
390 bdrv_drain_invoke(bs, true, NULL);
393 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
394 BdrvChild *parent, bool ignore_bds_parents,
395 bool poll)
397 BdrvChild *child, *next;
399 if (qemu_in_coroutine()) {
400 bdrv_co_yield_to_drain(bs, true, recursive, parent, ignore_bds_parents,
401 poll, NULL);
402 return;
405 bdrv_do_drained_begin_quiesce(bs, parent, ignore_bds_parents);
407 if (recursive) {
408 assert(!ignore_bds_parents);
409 bs->recursive_quiesce_counter++;
410 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
411 bdrv_do_drained_begin(child->bs, true, child, ignore_bds_parents,
412 false);
417 * Wait for drained requests to finish.
419 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
420 * call is needed so things in this AioContext can make progress even
421 * though we don't return to the main AioContext loop - this automatically
422 * includes other nodes in the same AioContext and therefore all child
423 * nodes.
425 if (poll) {
426 assert(!ignore_bds_parents);
427 BDRV_POLL_WHILE(bs, bdrv_drain_poll_top_level(bs, recursive, parent));
431 void bdrv_drained_begin(BlockDriverState *bs)
433 bdrv_do_drained_begin(bs, false, NULL, false, true);
436 void bdrv_subtree_drained_begin(BlockDriverState *bs)
438 bdrv_do_drained_begin(bs, true, NULL, false, true);
442 * This function does not poll, nor must any of its recursively called
443 * functions. The *drained_end_counter pointee will be incremented
444 * once for every background operation scheduled, and decremented once
445 * the operation settles. Therefore, the pointer must remain valid
446 * until the pointee reaches 0. That implies that whoever sets up the
447 * pointee has to poll until it is 0.
449 * We use atomic operations to access *drained_end_counter, because
450 * (1) when called from bdrv_set_aio_context_ignore(), the subgraph of
451 * @bs may contain nodes in different AioContexts,
452 * (2) bdrv_drain_all_end() uses the same counter for all nodes,
453 * regardless of which AioContext they are in.
455 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
456 BdrvChild *parent, bool ignore_bds_parents,
457 int *drained_end_counter)
459 BdrvChild *child;
460 int old_quiesce_counter;
462 assert(drained_end_counter != NULL);
464 if (qemu_in_coroutine()) {
465 bdrv_co_yield_to_drain(bs, false, recursive, parent, ignore_bds_parents,
466 false, drained_end_counter);
467 return;
469 assert(bs->quiesce_counter > 0);
471 /* Re-enable things in child-to-parent order */
472 bdrv_drain_invoke(bs, false, drained_end_counter);
473 bdrv_parent_drained_end(bs, parent, ignore_bds_parents,
474 drained_end_counter);
476 old_quiesce_counter = atomic_fetch_dec(&bs->quiesce_counter);
477 if (old_quiesce_counter == 1) {
478 aio_enable_external(bdrv_get_aio_context(bs));
481 if (recursive) {
482 assert(!ignore_bds_parents);
483 bs->recursive_quiesce_counter--;
484 QLIST_FOREACH(child, &bs->children, next) {
485 bdrv_do_drained_end(child->bs, true, child, ignore_bds_parents,
486 drained_end_counter);
491 void bdrv_drained_end(BlockDriverState *bs)
493 int drained_end_counter = 0;
494 bdrv_do_drained_end(bs, false, NULL, false, &drained_end_counter);
495 BDRV_POLL_WHILE(bs, atomic_read(&drained_end_counter) > 0);
498 void bdrv_drained_end_no_poll(BlockDriverState *bs, int *drained_end_counter)
500 bdrv_do_drained_end(bs, false, NULL, false, drained_end_counter);
503 void bdrv_subtree_drained_end(BlockDriverState *bs)
505 int drained_end_counter = 0;
506 bdrv_do_drained_end(bs, true, NULL, false, &drained_end_counter);
507 BDRV_POLL_WHILE(bs, atomic_read(&drained_end_counter) > 0);
510 void bdrv_apply_subtree_drain(BdrvChild *child, BlockDriverState *new_parent)
512 int i;
514 for (i = 0; i < new_parent->recursive_quiesce_counter; i++) {
515 bdrv_do_drained_begin(child->bs, true, child, false, true);
519 void bdrv_unapply_subtree_drain(BdrvChild *child, BlockDriverState *old_parent)
521 int drained_end_counter = 0;
522 int i;
524 for (i = 0; i < old_parent->recursive_quiesce_counter; i++) {
525 bdrv_do_drained_end(child->bs, true, child, false,
526 &drained_end_counter);
529 BDRV_POLL_WHILE(child->bs, atomic_read(&drained_end_counter) > 0);
533 * Wait for pending requests to complete on a single BlockDriverState subtree,
534 * and suspend block driver's internal I/O until next request arrives.
536 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
537 * AioContext.
539 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
541 assert(qemu_in_coroutine());
542 bdrv_drained_begin(bs);
543 bdrv_drained_end(bs);
546 void bdrv_drain(BlockDriverState *bs)
548 bdrv_drained_begin(bs);
549 bdrv_drained_end(bs);
552 static void bdrv_drain_assert_idle(BlockDriverState *bs)
554 BdrvChild *child, *next;
556 assert(atomic_read(&bs->in_flight) == 0);
557 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
558 bdrv_drain_assert_idle(child->bs);
562 unsigned int bdrv_drain_all_count = 0;
564 static bool bdrv_drain_all_poll(void)
566 BlockDriverState *bs = NULL;
567 bool result = false;
569 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
570 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
571 while ((bs = bdrv_next_all_states(bs))) {
572 AioContext *aio_context = bdrv_get_aio_context(bs);
573 aio_context_acquire(aio_context);
574 result |= bdrv_drain_poll(bs, false, NULL, true);
575 aio_context_release(aio_context);
578 return result;
582 * Wait for pending requests to complete across all BlockDriverStates
584 * This function does not flush data to disk, use bdrv_flush_all() for that
585 * after calling this function.
587 * This pauses all block jobs and disables external clients. It must
588 * be paired with bdrv_drain_all_end().
590 * NOTE: no new block jobs or BlockDriverStates can be created between
591 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
593 void bdrv_drain_all_begin(void)
595 BlockDriverState *bs = NULL;
597 if (qemu_in_coroutine()) {
598 bdrv_co_yield_to_drain(NULL, true, false, NULL, true, true, NULL);
599 return;
602 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
603 * loop AioContext, so make sure we're in the main context. */
604 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
605 assert(bdrv_drain_all_count < INT_MAX);
606 bdrv_drain_all_count++;
608 /* Quiesce all nodes, without polling in-flight requests yet. The graph
609 * cannot change during this loop. */
610 while ((bs = bdrv_next_all_states(bs))) {
611 AioContext *aio_context = bdrv_get_aio_context(bs);
613 aio_context_acquire(aio_context);
614 bdrv_do_drained_begin(bs, false, NULL, true, false);
615 aio_context_release(aio_context);
618 /* Now poll the in-flight requests */
619 AIO_WAIT_WHILE(NULL, bdrv_drain_all_poll());
621 while ((bs = bdrv_next_all_states(bs))) {
622 bdrv_drain_assert_idle(bs);
626 void bdrv_drain_all_end(void)
628 BlockDriverState *bs = NULL;
629 int drained_end_counter = 0;
631 while ((bs = bdrv_next_all_states(bs))) {
632 AioContext *aio_context = bdrv_get_aio_context(bs);
634 aio_context_acquire(aio_context);
635 bdrv_do_drained_end(bs, false, NULL, true, &drained_end_counter);
636 aio_context_release(aio_context);
639 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
640 AIO_WAIT_WHILE(NULL, atomic_read(&drained_end_counter) > 0);
642 assert(bdrv_drain_all_count > 0);
643 bdrv_drain_all_count--;
646 void bdrv_drain_all(void)
648 bdrv_drain_all_begin();
649 bdrv_drain_all_end();
653 * Remove an active request from the tracked requests list
655 * This function should be called when a tracked request is completing.
657 static void tracked_request_end(BdrvTrackedRequest *req)
659 if (req->serialising) {
660 atomic_dec(&req->bs->serialising_in_flight);
663 qemu_co_mutex_lock(&req->bs->reqs_lock);
664 QLIST_REMOVE(req, list);
665 qemu_co_queue_restart_all(&req->wait_queue);
666 qemu_co_mutex_unlock(&req->bs->reqs_lock);
670 * Add an active request to the tracked requests list
672 static void tracked_request_begin(BdrvTrackedRequest *req,
673 BlockDriverState *bs,
674 int64_t offset,
675 uint64_t bytes,
676 enum BdrvTrackedRequestType type)
678 assert(bytes <= INT64_MAX && offset <= INT64_MAX - bytes);
680 *req = (BdrvTrackedRequest){
681 .bs = bs,
682 .offset = offset,
683 .bytes = bytes,
684 .type = type,
685 .co = qemu_coroutine_self(),
686 .serialising = false,
687 .overlap_offset = offset,
688 .overlap_bytes = bytes,
691 qemu_co_queue_init(&req->wait_queue);
693 qemu_co_mutex_lock(&bs->reqs_lock);
694 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
695 qemu_co_mutex_unlock(&bs->reqs_lock);
698 static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
700 int64_t overlap_offset = req->offset & ~(align - 1);
701 uint64_t overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
702 - overlap_offset;
704 if (!req->serialising) {
705 atomic_inc(&req->bs->serialising_in_flight);
706 req->serialising = true;
709 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
710 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
713 static bool is_request_serialising_and_aligned(BdrvTrackedRequest *req)
716 * If the request is serialising, overlap_offset and overlap_bytes are set,
717 * so we can check if the request is aligned. Otherwise, don't care and
718 * return false.
721 return req->serialising && (req->offset == req->overlap_offset) &&
722 (req->bytes == req->overlap_bytes);
726 * Round a region to cluster boundaries
728 void bdrv_round_to_clusters(BlockDriverState *bs,
729 int64_t offset, int64_t bytes,
730 int64_t *cluster_offset,
731 int64_t *cluster_bytes)
733 BlockDriverInfo bdi;
735 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
736 *cluster_offset = offset;
737 *cluster_bytes = bytes;
738 } else {
739 int64_t c = bdi.cluster_size;
740 *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
741 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
745 static int bdrv_get_cluster_size(BlockDriverState *bs)
747 BlockDriverInfo bdi;
748 int ret;
750 ret = bdrv_get_info(bs, &bdi);
751 if (ret < 0 || bdi.cluster_size == 0) {
752 return bs->bl.request_alignment;
753 } else {
754 return bdi.cluster_size;
758 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
759 int64_t offset, uint64_t bytes)
761 /* aaaa bbbb */
762 if (offset >= req->overlap_offset + req->overlap_bytes) {
763 return false;
765 /* bbbb aaaa */
766 if (req->overlap_offset >= offset + bytes) {
767 return false;
769 return true;
772 void bdrv_inc_in_flight(BlockDriverState *bs)
774 atomic_inc(&bs->in_flight);
777 void bdrv_wakeup(BlockDriverState *bs)
779 aio_wait_kick();
782 void bdrv_dec_in_flight(BlockDriverState *bs)
784 atomic_dec(&bs->in_flight);
785 bdrv_wakeup(bs);
788 static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
790 BlockDriverState *bs = self->bs;
791 BdrvTrackedRequest *req;
792 bool retry;
793 bool waited = false;
795 if (!atomic_read(&bs->serialising_in_flight)) {
796 return false;
799 do {
800 retry = false;
801 qemu_co_mutex_lock(&bs->reqs_lock);
802 QLIST_FOREACH(req, &bs->tracked_requests, list) {
803 if (req == self || (!req->serialising && !self->serialising)) {
804 continue;
806 if (tracked_request_overlaps(req, self->overlap_offset,
807 self->overlap_bytes))
809 /* Hitting this means there was a reentrant request, for
810 * example, a block driver issuing nested requests. This must
811 * never happen since it means deadlock.
813 assert(qemu_coroutine_self() != req->co);
815 /* If the request is already (indirectly) waiting for us, or
816 * will wait for us as soon as it wakes up, then just go on
817 * (instead of producing a deadlock in the former case). */
818 if (!req->waiting_for) {
819 self->waiting_for = req;
820 qemu_co_queue_wait(&req->wait_queue, &bs->reqs_lock);
821 self->waiting_for = NULL;
822 retry = true;
823 waited = true;
824 break;
828 qemu_co_mutex_unlock(&bs->reqs_lock);
829 } while (retry);
831 return waited;
834 static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
835 size_t size)
837 if (size > BDRV_REQUEST_MAX_BYTES) {
838 return -EIO;
841 if (!bdrv_is_inserted(bs)) {
842 return -ENOMEDIUM;
845 if (offset < 0) {
846 return -EIO;
849 return 0;
852 typedef struct RwCo {
853 BdrvChild *child;
854 int64_t offset;
855 QEMUIOVector *qiov;
856 bool is_write;
857 int ret;
858 BdrvRequestFlags flags;
859 } RwCo;
861 static void coroutine_fn bdrv_rw_co_entry(void *opaque)
863 RwCo *rwco = opaque;
865 if (!rwco->is_write) {
866 rwco->ret = bdrv_co_preadv(rwco->child, rwco->offset,
867 rwco->qiov->size, rwco->qiov,
868 rwco->flags);
869 } else {
870 rwco->ret = bdrv_co_pwritev(rwco->child, rwco->offset,
871 rwco->qiov->size, rwco->qiov,
872 rwco->flags);
874 aio_wait_kick();
878 * Process a vectored synchronous request using coroutines
880 static int bdrv_prwv_co(BdrvChild *child, int64_t offset,
881 QEMUIOVector *qiov, bool is_write,
882 BdrvRequestFlags flags)
884 Coroutine *co;
885 RwCo rwco = {
886 .child = child,
887 .offset = offset,
888 .qiov = qiov,
889 .is_write = is_write,
890 .ret = NOT_DONE,
891 .flags = flags,
894 if (qemu_in_coroutine()) {
895 /* Fast-path if already in coroutine context */
896 bdrv_rw_co_entry(&rwco);
897 } else {
898 co = qemu_coroutine_create(bdrv_rw_co_entry, &rwco);
899 bdrv_coroutine_enter(child->bs, co);
900 BDRV_POLL_WHILE(child->bs, rwco.ret == NOT_DONE);
902 return rwco.ret;
905 int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
906 int bytes, BdrvRequestFlags flags)
908 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, NULL, bytes);
910 return bdrv_prwv_co(child, offset, &qiov, true,
911 BDRV_REQ_ZERO_WRITE | flags);
915 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
916 * The operation is sped up by checking the block status and only writing
917 * zeroes to the device if they currently do not return zeroes. Optional
918 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
919 * BDRV_REQ_FUA).
921 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
923 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
925 int ret;
926 int64_t target_size, bytes, offset = 0;
927 BlockDriverState *bs = child->bs;
929 target_size = bdrv_getlength(bs);
930 if (target_size < 0) {
931 return target_size;
934 for (;;) {
935 bytes = MIN(target_size - offset, BDRV_REQUEST_MAX_BYTES);
936 if (bytes <= 0) {
937 return 0;
939 ret = bdrv_block_status(bs, offset, bytes, &bytes, NULL, NULL);
940 if (ret < 0) {
941 return ret;
943 if (ret & BDRV_BLOCK_ZERO) {
944 offset += bytes;
945 continue;
947 ret = bdrv_pwrite_zeroes(child, offset, bytes, flags);
948 if (ret < 0) {
949 return ret;
951 offset += bytes;
955 int bdrv_preadv(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
957 int ret;
959 ret = bdrv_prwv_co(child, offset, qiov, false, 0);
960 if (ret < 0) {
961 return ret;
964 return qiov->size;
967 /* See bdrv_pwrite() for the return codes */
968 int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int bytes)
970 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
972 if (bytes < 0) {
973 return -EINVAL;
976 return bdrv_preadv(child, offset, &qiov);
979 int bdrv_pwritev(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
981 int ret;
983 ret = bdrv_prwv_co(child, offset, qiov, true, 0);
984 if (ret < 0) {
985 return ret;
988 return qiov->size;
991 /* Return no. of bytes on success or < 0 on error. Important errors are:
992 -EIO generic I/O error (may happen for all errors)
993 -ENOMEDIUM No media inserted.
994 -EINVAL Invalid offset or number of bytes
995 -EACCES Trying to write a read-only device
997 int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf, int bytes)
999 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
1001 if (bytes < 0) {
1002 return -EINVAL;
1005 return bdrv_pwritev(child, offset, &qiov);
1009 * Writes to the file and ensures that no writes are reordered across this
1010 * request (acts as a barrier)
1012 * Returns 0 on success, -errno in error cases.
1014 int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
1015 const void *buf, int count)
1017 int ret;
1019 ret = bdrv_pwrite(child, offset, buf, count);
1020 if (ret < 0) {
1021 return ret;
1024 ret = bdrv_flush(child->bs);
1025 if (ret < 0) {
1026 return ret;
1029 return 0;
1032 typedef struct CoroutineIOCompletion {
1033 Coroutine *coroutine;
1034 int ret;
1035 } CoroutineIOCompletion;
1037 static void bdrv_co_io_em_complete(void *opaque, int ret)
1039 CoroutineIOCompletion *co = opaque;
1041 co->ret = ret;
1042 aio_co_wake(co->coroutine);
1045 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
1046 uint64_t offset, uint64_t bytes,
1047 QEMUIOVector *qiov, int flags)
1049 BlockDriver *drv = bs->drv;
1050 int64_t sector_num;
1051 unsigned int nb_sectors;
1053 assert(!(flags & ~BDRV_REQ_MASK));
1054 assert(!(flags & BDRV_REQ_NO_FALLBACK));
1056 if (!drv) {
1057 return -ENOMEDIUM;
1060 if (drv->bdrv_co_preadv) {
1061 return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
1064 if (drv->bdrv_aio_preadv) {
1065 BlockAIOCB *acb;
1066 CoroutineIOCompletion co = {
1067 .coroutine = qemu_coroutine_self(),
1070 acb = drv->bdrv_aio_preadv(bs, offset, bytes, qiov, flags,
1071 bdrv_co_io_em_complete, &co);
1072 if (acb == NULL) {
1073 return -EIO;
1074 } else {
1075 qemu_coroutine_yield();
1076 return co.ret;
1080 sector_num = offset >> BDRV_SECTOR_BITS;
1081 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1083 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1084 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1085 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1086 assert(drv->bdrv_co_readv);
1088 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1091 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
1092 uint64_t offset, uint64_t bytes,
1093 QEMUIOVector *qiov, int flags)
1095 BlockDriver *drv = bs->drv;
1096 int64_t sector_num;
1097 unsigned int nb_sectors;
1098 int ret;
1100 assert(!(flags & ~BDRV_REQ_MASK));
1101 assert(!(flags & BDRV_REQ_NO_FALLBACK));
1103 if (!drv) {
1104 return -ENOMEDIUM;
1107 if (drv->bdrv_co_pwritev) {
1108 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
1109 flags & bs->supported_write_flags);
1110 flags &= ~bs->supported_write_flags;
1111 goto emulate_flags;
1114 if (drv->bdrv_aio_pwritev) {
1115 BlockAIOCB *acb;
1116 CoroutineIOCompletion co = {
1117 .coroutine = qemu_coroutine_self(),
1120 acb = drv->bdrv_aio_pwritev(bs, offset, bytes, qiov,
1121 flags & bs->supported_write_flags,
1122 bdrv_co_io_em_complete, &co);
1123 flags &= ~bs->supported_write_flags;
1124 if (acb == NULL) {
1125 ret = -EIO;
1126 } else {
1127 qemu_coroutine_yield();
1128 ret = co.ret;
1130 goto emulate_flags;
1133 sector_num = offset >> BDRV_SECTOR_BITS;
1134 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1136 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1137 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1138 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1140 assert(drv->bdrv_co_writev);
1141 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov,
1142 flags & bs->supported_write_flags);
1143 flags &= ~bs->supported_write_flags;
1145 emulate_flags:
1146 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
1147 ret = bdrv_co_flush(bs);
1150 return ret;
1153 static int coroutine_fn
1154 bdrv_driver_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1155 uint64_t bytes, QEMUIOVector *qiov)
1157 BlockDriver *drv = bs->drv;
1159 if (!drv) {
1160 return -ENOMEDIUM;
1163 if (!drv->bdrv_co_pwritev_compressed) {
1164 return -ENOTSUP;
1167 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
1170 static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
1171 int64_t offset, unsigned int bytes, QEMUIOVector *qiov)
1173 BlockDriverState *bs = child->bs;
1175 /* Perform I/O through a temporary buffer so that users who scribble over
1176 * their read buffer while the operation is in progress do not end up
1177 * modifying the image file. This is critical for zero-copy guest I/O
1178 * where anything might happen inside guest memory.
1180 void *bounce_buffer;
1182 BlockDriver *drv = bs->drv;
1183 QEMUIOVector local_qiov;
1184 int64_t cluster_offset;
1185 int64_t cluster_bytes;
1186 size_t skip_bytes;
1187 int ret;
1188 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1189 BDRV_REQUEST_MAX_BYTES);
1190 unsigned int progress = 0;
1192 if (!drv) {
1193 return -ENOMEDIUM;
1196 /* FIXME We cannot require callers to have write permissions when all they
1197 * are doing is a read request. If we did things right, write permissions
1198 * would be obtained anyway, but internally by the copy-on-read code. As
1199 * long as it is implemented here rather than in a separate filter driver,
1200 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1201 * it could request permissions. Therefore we have to bypass the permission
1202 * system for the moment. */
1203 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1205 /* Cover entire cluster so no additional backing file I/O is required when
1206 * allocating cluster in the image file. Note that this value may exceed
1207 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1208 * is one reason we loop rather than doing it all at once.
1210 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
1211 skip_bytes = offset - cluster_offset;
1213 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
1214 cluster_offset, cluster_bytes);
1216 bounce_buffer = qemu_try_blockalign(bs,
1217 MIN(MIN(max_transfer, cluster_bytes),
1218 MAX_BOUNCE_BUFFER));
1219 if (bounce_buffer == NULL) {
1220 ret = -ENOMEM;
1221 goto err;
1224 while (cluster_bytes) {
1225 int64_t pnum;
1227 ret = bdrv_is_allocated(bs, cluster_offset,
1228 MIN(cluster_bytes, max_transfer), &pnum);
1229 if (ret < 0) {
1230 /* Safe to treat errors in querying allocation as if
1231 * unallocated; we'll probably fail again soon on the
1232 * read, but at least that will set a decent errno.
1234 pnum = MIN(cluster_bytes, max_transfer);
1237 /* Stop at EOF if the image ends in the middle of the cluster */
1238 if (ret == 0 && pnum == 0) {
1239 assert(progress >= bytes);
1240 break;
1243 assert(skip_bytes < pnum);
1245 if (ret <= 0) {
1246 /* Must copy-on-read; use the bounce buffer */
1247 pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1248 qemu_iovec_init_buf(&local_qiov, bounce_buffer, pnum);
1250 ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1251 &local_qiov, 0);
1252 if (ret < 0) {
1253 goto err;
1256 bdrv_debug_event(bs, BLKDBG_COR_WRITE);
1257 if (drv->bdrv_co_pwrite_zeroes &&
1258 buffer_is_zero(bounce_buffer, pnum)) {
1259 /* FIXME: Should we (perhaps conditionally) be setting
1260 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1261 * that still correctly reads as zero? */
1262 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum,
1263 BDRV_REQ_WRITE_UNCHANGED);
1264 } else {
1265 /* This does not change the data on the disk, it is not
1266 * necessary to flush even in cache=writethrough mode.
1268 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
1269 &local_qiov,
1270 BDRV_REQ_WRITE_UNCHANGED);
1273 if (ret < 0) {
1274 /* It might be okay to ignore write errors for guest
1275 * requests. If this is a deliberate copy-on-read
1276 * then we don't want to ignore the error. Simply
1277 * report it in all cases.
1279 goto err;
1282 qemu_iovec_from_buf(qiov, progress, bounce_buffer + skip_bytes,
1283 pnum - skip_bytes);
1284 } else {
1285 /* Read directly into the destination */
1286 qemu_iovec_init(&local_qiov, qiov->niov);
1287 qemu_iovec_concat(&local_qiov, qiov, progress, pnum - skip_bytes);
1288 ret = bdrv_driver_preadv(bs, offset + progress, local_qiov.size,
1289 &local_qiov, 0);
1290 qemu_iovec_destroy(&local_qiov);
1291 if (ret < 0) {
1292 goto err;
1296 cluster_offset += pnum;
1297 cluster_bytes -= pnum;
1298 progress += pnum - skip_bytes;
1299 skip_bytes = 0;
1301 ret = 0;
1303 err:
1304 qemu_vfree(bounce_buffer);
1305 return ret;
1309 * Forwards an already correctly aligned request to the BlockDriver. This
1310 * handles copy on read, zeroing after EOF, and fragmentation of large
1311 * reads; any other features must be implemented by the caller.
1313 static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
1314 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1315 int64_t align, QEMUIOVector *qiov, int flags)
1317 BlockDriverState *bs = child->bs;
1318 int64_t total_bytes, max_bytes;
1319 int ret = 0;
1320 uint64_t bytes_remaining = bytes;
1321 int max_transfer;
1323 assert(is_power_of_2(align));
1324 assert((offset & (align - 1)) == 0);
1325 assert((bytes & (align - 1)) == 0);
1326 assert(!qiov || bytes == qiov->size);
1327 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1328 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1329 align);
1331 /* TODO: We would need a per-BDS .supported_read_flags and
1332 * potential fallback support, if we ever implement any read flags
1333 * to pass through to drivers. For now, there aren't any
1334 * passthrough flags. */
1335 assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ)));
1337 /* Handle Copy on Read and associated serialisation */
1338 if (flags & BDRV_REQ_COPY_ON_READ) {
1339 /* If we touch the same cluster it counts as an overlap. This
1340 * guarantees that allocating writes will be serialized and not race
1341 * with each other for the same cluster. For example, in copy-on-read
1342 * it ensures that the CoR read and write operations are atomic and
1343 * guest writes cannot interleave between them. */
1344 mark_request_serialising(req, bdrv_get_cluster_size(bs));
1347 /* BDRV_REQ_SERIALISING is only for write operation */
1348 assert(!(flags & BDRV_REQ_SERIALISING));
1350 if (!(flags & BDRV_REQ_NO_SERIALISING)) {
1351 wait_serialising_requests(req);
1354 if (flags & BDRV_REQ_COPY_ON_READ) {
1355 int64_t pnum;
1357 ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
1358 if (ret < 0) {
1359 goto out;
1362 if (!ret || pnum != bytes) {
1363 ret = bdrv_co_do_copy_on_readv(child, offset, bytes, qiov);
1364 goto out;
1368 /* Forward the request to the BlockDriver, possibly fragmenting it */
1369 total_bytes = bdrv_getlength(bs);
1370 if (total_bytes < 0) {
1371 ret = total_bytes;
1372 goto out;
1375 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1376 if (bytes <= max_bytes && bytes <= max_transfer) {
1377 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
1378 goto out;
1381 while (bytes_remaining) {
1382 int num;
1384 if (max_bytes) {
1385 QEMUIOVector local_qiov;
1387 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1388 assert(num);
1389 qemu_iovec_init(&local_qiov, qiov->niov);
1390 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1392 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1393 num, &local_qiov, 0);
1394 max_bytes -= num;
1395 qemu_iovec_destroy(&local_qiov);
1396 } else {
1397 num = bytes_remaining;
1398 ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0,
1399 bytes_remaining);
1401 if (ret < 0) {
1402 goto out;
1404 bytes_remaining -= num;
1407 out:
1408 return ret < 0 ? ret : 0;
1412 * Handle a read request in coroutine context
1414 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1415 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1416 BdrvRequestFlags flags)
1418 BlockDriverState *bs = child->bs;
1419 BlockDriver *drv = bs->drv;
1420 BdrvTrackedRequest req;
1422 uint64_t align = bs->bl.request_alignment;
1423 uint8_t *head_buf = NULL;
1424 uint8_t *tail_buf = NULL;
1425 QEMUIOVector local_qiov;
1426 bool use_local_qiov = false;
1427 int ret;
1429 trace_bdrv_co_preadv(child->bs, offset, bytes, flags);
1431 if (!drv) {
1432 return -ENOMEDIUM;
1435 ret = bdrv_check_byte_request(bs, offset, bytes);
1436 if (ret < 0) {
1437 return ret;
1440 bdrv_inc_in_flight(bs);
1442 /* Don't do copy-on-read if we read data before write operation */
1443 if (atomic_read(&bs->copy_on_read) && !(flags & BDRV_REQ_NO_SERIALISING)) {
1444 flags |= BDRV_REQ_COPY_ON_READ;
1447 /* Align read if necessary by padding qiov */
1448 if (offset & (align - 1)) {
1449 head_buf = qemu_blockalign(bs, align);
1450 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1451 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1452 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1453 use_local_qiov = true;
1455 bytes += offset & (align - 1);
1456 offset = offset & ~(align - 1);
1459 if ((offset + bytes) & (align - 1)) {
1460 if (!use_local_qiov) {
1461 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1462 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1463 use_local_qiov = true;
1465 tail_buf = qemu_blockalign(bs, align);
1466 qemu_iovec_add(&local_qiov, tail_buf,
1467 align - ((offset + bytes) & (align - 1)));
1469 bytes = ROUND_UP(bytes, align);
1472 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1473 ret = bdrv_aligned_preadv(child, &req, offset, bytes, align,
1474 use_local_qiov ? &local_qiov : qiov,
1475 flags);
1476 tracked_request_end(&req);
1477 bdrv_dec_in_flight(bs);
1479 if (use_local_qiov) {
1480 qemu_iovec_destroy(&local_qiov);
1481 qemu_vfree(head_buf);
1482 qemu_vfree(tail_buf);
1485 return ret;
1488 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1489 int64_t offset, int bytes, BdrvRequestFlags flags)
1491 BlockDriver *drv = bs->drv;
1492 QEMUIOVector qiov;
1493 void *buf = NULL;
1494 int ret = 0;
1495 bool need_flush = false;
1496 int head = 0;
1497 int tail = 0;
1499 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
1500 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1501 bs->bl.request_alignment);
1502 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
1504 if (!drv) {
1505 return -ENOMEDIUM;
1508 if ((flags & ~bs->supported_zero_flags) & BDRV_REQ_NO_FALLBACK) {
1509 return -ENOTSUP;
1512 assert(alignment % bs->bl.request_alignment == 0);
1513 head = offset % alignment;
1514 tail = (offset + bytes) % alignment;
1515 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1516 assert(max_write_zeroes >= bs->bl.request_alignment);
1518 while (bytes > 0 && !ret) {
1519 int num = bytes;
1521 /* Align request. Block drivers can expect the "bulk" of the request
1522 * to be aligned, and that unaligned requests do not cross cluster
1523 * boundaries.
1525 if (head) {
1526 /* Make a small request up to the first aligned sector. For
1527 * convenience, limit this request to max_transfer even if
1528 * we don't need to fall back to writes. */
1529 num = MIN(MIN(bytes, max_transfer), alignment - head);
1530 head = (head + num) % alignment;
1531 assert(num < max_write_zeroes);
1532 } else if (tail && num > alignment) {
1533 /* Shorten the request to the last aligned sector. */
1534 num -= tail;
1537 /* limit request size */
1538 if (num > max_write_zeroes) {
1539 num = max_write_zeroes;
1542 ret = -ENOTSUP;
1543 /* First try the efficient write zeroes operation */
1544 if (drv->bdrv_co_pwrite_zeroes) {
1545 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1546 flags & bs->supported_zero_flags);
1547 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1548 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1549 need_flush = true;
1551 } else {
1552 assert(!bs->supported_zero_flags);
1555 if (ret < 0 && !(flags & BDRV_REQ_NO_FALLBACK)) {
1556 /* Fall back to bounce buffer if write zeroes is unsupported */
1557 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1559 if ((flags & BDRV_REQ_FUA) &&
1560 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1561 /* No need for bdrv_driver_pwrite() to do a fallback
1562 * flush on each chunk; use just one at the end */
1563 write_flags &= ~BDRV_REQ_FUA;
1564 need_flush = true;
1566 num = MIN(num, max_transfer);
1567 if (buf == NULL) {
1568 buf = qemu_try_blockalign0(bs, num);
1569 if (buf == NULL) {
1570 ret = -ENOMEM;
1571 goto fail;
1574 qemu_iovec_init_buf(&qiov, buf, num);
1576 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags);
1578 /* Keep bounce buffer around if it is big enough for all
1579 * all future requests.
1581 if (num < max_transfer) {
1582 qemu_vfree(buf);
1583 buf = NULL;
1587 offset += num;
1588 bytes -= num;
1591 fail:
1592 if (ret == 0 && need_flush) {
1593 ret = bdrv_co_flush(bs);
1595 qemu_vfree(buf);
1596 return ret;
1599 static inline int coroutine_fn
1600 bdrv_co_write_req_prepare(BdrvChild *child, int64_t offset, uint64_t bytes,
1601 BdrvTrackedRequest *req, int flags)
1603 BlockDriverState *bs = child->bs;
1604 bool waited;
1605 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1607 if (bs->read_only) {
1608 return -EPERM;
1611 /* BDRV_REQ_NO_SERIALISING is only for read operation */
1612 assert(!(flags & BDRV_REQ_NO_SERIALISING));
1613 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1614 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1615 assert(!(flags & ~BDRV_REQ_MASK));
1617 if (flags & BDRV_REQ_SERIALISING) {
1618 mark_request_serialising(req, bdrv_get_cluster_size(bs));
1621 waited = wait_serialising_requests(req);
1623 assert(!waited || !req->serialising ||
1624 is_request_serialising_and_aligned(req));
1625 assert(req->overlap_offset <= offset);
1626 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1627 assert(end_sector <= bs->total_sectors || child->perm & BLK_PERM_RESIZE);
1629 switch (req->type) {
1630 case BDRV_TRACKED_WRITE:
1631 case BDRV_TRACKED_DISCARD:
1632 if (flags & BDRV_REQ_WRITE_UNCHANGED) {
1633 assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1634 } else {
1635 assert(child->perm & BLK_PERM_WRITE);
1637 return notifier_with_return_list_notify(&bs->before_write_notifiers,
1638 req);
1639 case BDRV_TRACKED_TRUNCATE:
1640 assert(child->perm & BLK_PERM_RESIZE);
1641 return 0;
1642 default:
1643 abort();
1647 static inline void coroutine_fn
1648 bdrv_co_write_req_finish(BdrvChild *child, int64_t offset, uint64_t bytes,
1649 BdrvTrackedRequest *req, int ret)
1651 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1652 BlockDriverState *bs = child->bs;
1654 atomic_inc(&bs->write_gen);
1657 * Discard cannot extend the image, but in error handling cases, such as
1658 * when reverting a qcow2 cluster allocation, the discarded range can pass
1659 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1660 * here. Instead, just skip it, since semantically a discard request
1661 * beyond EOF cannot expand the image anyway.
1663 if (ret == 0 &&
1664 (req->type == BDRV_TRACKED_TRUNCATE ||
1665 end_sector > bs->total_sectors) &&
1666 req->type != BDRV_TRACKED_DISCARD) {
1667 bs->total_sectors = end_sector;
1668 bdrv_parent_cb_resize(bs);
1669 bdrv_dirty_bitmap_truncate(bs, end_sector << BDRV_SECTOR_BITS);
1671 if (req->bytes) {
1672 switch (req->type) {
1673 case BDRV_TRACKED_WRITE:
1674 stat64_max(&bs->wr_highest_offset, offset + bytes);
1675 /* fall through, to set dirty bits */
1676 case BDRV_TRACKED_DISCARD:
1677 bdrv_set_dirty(bs, offset, bytes);
1678 break;
1679 default:
1680 break;
1686 * Forwards an already correctly aligned write request to the BlockDriver,
1687 * after possibly fragmenting it.
1689 static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
1690 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1691 int64_t align, QEMUIOVector *qiov, int flags)
1693 BlockDriverState *bs = child->bs;
1694 BlockDriver *drv = bs->drv;
1695 int ret;
1697 uint64_t bytes_remaining = bytes;
1698 int max_transfer;
1700 if (!drv) {
1701 return -ENOMEDIUM;
1704 if (bdrv_has_readonly_bitmaps(bs)) {
1705 return -EPERM;
1708 assert(is_power_of_2(align));
1709 assert((offset & (align - 1)) == 0);
1710 assert((bytes & (align - 1)) == 0);
1711 assert(!qiov || bytes == qiov->size);
1712 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1713 align);
1715 ret = bdrv_co_write_req_prepare(child, offset, bytes, req, flags);
1717 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1718 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
1719 qemu_iovec_is_zero(qiov)) {
1720 flags |= BDRV_REQ_ZERO_WRITE;
1721 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1722 flags |= BDRV_REQ_MAY_UNMAP;
1726 if (ret < 0) {
1727 /* Do nothing, write notifier decided to fail this request */
1728 } else if (flags & BDRV_REQ_ZERO_WRITE) {
1729 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1730 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
1731 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
1732 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov);
1733 } else if (bytes <= max_transfer) {
1734 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1735 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
1736 } else {
1737 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1738 while (bytes_remaining) {
1739 int num = MIN(bytes_remaining, max_transfer);
1740 QEMUIOVector local_qiov;
1741 int local_flags = flags;
1743 assert(num);
1744 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
1745 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1746 /* If FUA is going to be emulated by flush, we only
1747 * need to flush on the last iteration */
1748 local_flags &= ~BDRV_REQ_FUA;
1750 qemu_iovec_init(&local_qiov, qiov->niov);
1751 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1753 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
1754 num, &local_qiov, local_flags);
1755 qemu_iovec_destroy(&local_qiov);
1756 if (ret < 0) {
1757 break;
1759 bytes_remaining -= num;
1762 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1764 if (ret >= 0) {
1765 ret = 0;
1767 bdrv_co_write_req_finish(child, offset, bytes, req, ret);
1769 return ret;
1772 static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
1773 int64_t offset,
1774 unsigned int bytes,
1775 BdrvRequestFlags flags,
1776 BdrvTrackedRequest *req)
1778 BlockDriverState *bs = child->bs;
1779 uint8_t *buf = NULL;
1780 QEMUIOVector local_qiov;
1781 uint64_t align = bs->bl.request_alignment;
1782 unsigned int head_padding_bytes, tail_padding_bytes;
1783 int ret = 0;
1785 head_padding_bytes = offset & (align - 1);
1786 tail_padding_bytes = (align - (offset + bytes)) & (align - 1);
1789 assert(flags & BDRV_REQ_ZERO_WRITE);
1790 if (head_padding_bytes || tail_padding_bytes) {
1791 buf = qemu_blockalign(bs, align);
1792 qemu_iovec_init_buf(&local_qiov, buf, align);
1794 if (head_padding_bytes) {
1795 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1797 /* RMW the unaligned part before head. */
1798 mark_request_serialising(req, align);
1799 wait_serialising_requests(req);
1800 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1801 ret = bdrv_aligned_preadv(child, req, offset & ~(align - 1), align,
1802 align, &local_qiov, 0);
1803 if (ret < 0) {
1804 goto fail;
1806 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1808 memset(buf + head_padding_bytes, 0, zero_bytes);
1809 ret = bdrv_aligned_pwritev(child, req, offset & ~(align - 1), align,
1810 align, &local_qiov,
1811 flags & ~BDRV_REQ_ZERO_WRITE);
1812 if (ret < 0) {
1813 goto fail;
1815 offset += zero_bytes;
1816 bytes -= zero_bytes;
1819 assert(!bytes || (offset & (align - 1)) == 0);
1820 if (bytes >= align) {
1821 /* Write the aligned part in the middle. */
1822 uint64_t aligned_bytes = bytes & ~(align - 1);
1823 ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
1824 NULL, flags);
1825 if (ret < 0) {
1826 goto fail;
1828 bytes -= aligned_bytes;
1829 offset += aligned_bytes;
1832 assert(!bytes || (offset & (align - 1)) == 0);
1833 if (bytes) {
1834 assert(align == tail_padding_bytes + bytes);
1835 /* RMW the unaligned part after tail. */
1836 mark_request_serialising(req, align);
1837 wait_serialising_requests(req);
1838 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1839 ret = bdrv_aligned_preadv(child, req, offset, align,
1840 align, &local_qiov, 0);
1841 if (ret < 0) {
1842 goto fail;
1844 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1846 memset(buf, 0, bytes);
1847 ret = bdrv_aligned_pwritev(child, req, offset, align, align,
1848 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1850 fail:
1851 qemu_vfree(buf);
1852 return ret;
1857 * Handle a write request in coroutine context
1859 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
1860 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1861 BdrvRequestFlags flags)
1863 BlockDriverState *bs = child->bs;
1864 BdrvTrackedRequest req;
1865 uint64_t align = bs->bl.request_alignment;
1866 uint8_t *head_buf = NULL;
1867 uint8_t *tail_buf = NULL;
1868 QEMUIOVector local_qiov;
1869 bool use_local_qiov = false;
1870 int ret;
1872 trace_bdrv_co_pwritev(child->bs, offset, bytes, flags);
1874 if (!bs->drv) {
1875 return -ENOMEDIUM;
1878 ret = bdrv_check_byte_request(bs, offset, bytes);
1879 if (ret < 0) {
1880 return ret;
1883 bdrv_inc_in_flight(bs);
1885 * Align write if necessary by performing a read-modify-write cycle.
1886 * Pad qiov with the read parts and be sure to have a tracked request not
1887 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1889 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
1891 if (flags & BDRV_REQ_ZERO_WRITE) {
1892 ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
1893 goto out;
1896 if (offset & (align - 1)) {
1897 QEMUIOVector head_qiov;
1899 mark_request_serialising(&req, align);
1900 wait_serialising_requests(&req);
1902 head_buf = qemu_blockalign(bs, align);
1903 qemu_iovec_init_buf(&head_qiov, head_buf, align);
1905 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1906 ret = bdrv_aligned_preadv(child, &req, offset & ~(align - 1), align,
1907 align, &head_qiov, 0);
1908 if (ret < 0) {
1909 goto fail;
1911 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1913 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1914 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1915 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1916 use_local_qiov = true;
1918 bytes += offset & (align - 1);
1919 offset = offset & ~(align - 1);
1921 /* We have read the tail already if the request is smaller
1922 * than one aligned block.
1924 if (bytes < align) {
1925 qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes);
1926 bytes = align;
1930 if ((offset + bytes) & (align - 1)) {
1931 QEMUIOVector tail_qiov;
1932 size_t tail_bytes;
1933 bool waited;
1935 mark_request_serialising(&req, align);
1936 waited = wait_serialising_requests(&req);
1937 assert(!waited || !use_local_qiov);
1939 tail_buf = qemu_blockalign(bs, align);
1940 qemu_iovec_init_buf(&tail_qiov, tail_buf, align);
1942 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1943 ret = bdrv_aligned_preadv(child, &req, (offset + bytes) & ~(align - 1),
1944 align, align, &tail_qiov, 0);
1945 if (ret < 0) {
1946 goto fail;
1948 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1950 if (!use_local_qiov) {
1951 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1952 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1953 use_local_qiov = true;
1956 tail_bytes = (offset + bytes) & (align - 1);
1957 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1959 bytes = ROUND_UP(bytes, align);
1962 ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
1963 use_local_qiov ? &local_qiov : qiov,
1964 flags);
1966 fail:
1968 if (use_local_qiov) {
1969 qemu_iovec_destroy(&local_qiov);
1971 qemu_vfree(head_buf);
1972 qemu_vfree(tail_buf);
1973 out:
1974 tracked_request_end(&req);
1975 bdrv_dec_in_flight(bs);
1976 return ret;
1979 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
1980 int bytes, BdrvRequestFlags flags)
1982 trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
1984 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
1985 flags &= ~BDRV_REQ_MAY_UNMAP;
1988 return bdrv_co_pwritev(child, offset, bytes, NULL,
1989 BDRV_REQ_ZERO_WRITE | flags);
1993 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1995 int bdrv_flush_all(void)
1997 BdrvNextIterator it;
1998 BlockDriverState *bs = NULL;
1999 int result = 0;
2001 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
2002 AioContext *aio_context = bdrv_get_aio_context(bs);
2003 int ret;
2005 aio_context_acquire(aio_context);
2006 ret = bdrv_flush(bs);
2007 if (ret < 0 && !result) {
2008 result = ret;
2010 aio_context_release(aio_context);
2013 return result;
2017 typedef struct BdrvCoBlockStatusData {
2018 BlockDriverState *bs;
2019 BlockDriverState *base;
2020 bool want_zero;
2021 int64_t offset;
2022 int64_t bytes;
2023 int64_t *pnum;
2024 int64_t *map;
2025 BlockDriverState **file;
2026 int ret;
2027 bool done;
2028 } BdrvCoBlockStatusData;
2030 int coroutine_fn bdrv_co_block_status_from_file(BlockDriverState *bs,
2031 bool want_zero,
2032 int64_t offset,
2033 int64_t bytes,
2034 int64_t *pnum,
2035 int64_t *map,
2036 BlockDriverState **file)
2038 assert(bs->file && bs->file->bs);
2039 *pnum = bytes;
2040 *map = offset;
2041 *file = bs->file->bs;
2042 return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2045 int coroutine_fn bdrv_co_block_status_from_backing(BlockDriverState *bs,
2046 bool want_zero,
2047 int64_t offset,
2048 int64_t bytes,
2049 int64_t *pnum,
2050 int64_t *map,
2051 BlockDriverState **file)
2053 assert(bs->backing && bs->backing->bs);
2054 *pnum = bytes;
2055 *map = offset;
2056 *file = bs->backing->bs;
2057 return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2061 * Returns the allocation status of the specified sectors.
2062 * Drivers not implementing the functionality are assumed to not support
2063 * backing files, hence all their sectors are reported as allocated.
2065 * If 'want_zero' is true, the caller is querying for mapping
2066 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2067 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2068 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2070 * If 'offset' is beyond the end of the disk image the return value is
2071 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2073 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2074 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2075 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2077 * 'pnum' is set to the number of bytes (including and immediately
2078 * following the specified offset) that are easily known to be in the
2079 * same allocated/unallocated state. Note that a second call starting
2080 * at the original offset plus returned pnum may have the same status.
2081 * The returned value is non-zero on success except at end-of-file.
2083 * Returns negative errno on failure. Otherwise, if the
2084 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2085 * set to the host mapping and BDS corresponding to the guest offset.
2087 static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
2088 bool want_zero,
2089 int64_t offset, int64_t bytes,
2090 int64_t *pnum, int64_t *map,
2091 BlockDriverState **file)
2093 int64_t total_size;
2094 int64_t n; /* bytes */
2095 int ret;
2096 int64_t local_map = 0;
2097 BlockDriverState *local_file = NULL;
2098 int64_t aligned_offset, aligned_bytes;
2099 uint32_t align;
2101 assert(pnum);
2102 *pnum = 0;
2103 total_size = bdrv_getlength(bs);
2104 if (total_size < 0) {
2105 ret = total_size;
2106 goto early_out;
2109 if (offset >= total_size) {
2110 ret = BDRV_BLOCK_EOF;
2111 goto early_out;
2113 if (!bytes) {
2114 ret = 0;
2115 goto early_out;
2118 n = total_size - offset;
2119 if (n < bytes) {
2120 bytes = n;
2123 /* Must be non-NULL or bdrv_getlength() would have failed */
2124 assert(bs->drv);
2125 if (!bs->drv->bdrv_co_block_status) {
2126 *pnum = bytes;
2127 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2128 if (offset + bytes == total_size) {
2129 ret |= BDRV_BLOCK_EOF;
2131 if (bs->drv->protocol_name) {
2132 ret |= BDRV_BLOCK_OFFSET_VALID;
2133 local_map = offset;
2134 local_file = bs;
2136 goto early_out;
2139 bdrv_inc_in_flight(bs);
2141 /* Round out to request_alignment boundaries */
2142 align = bs->bl.request_alignment;
2143 aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2144 aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2146 ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2147 aligned_bytes, pnum, &local_map,
2148 &local_file);
2149 if (ret < 0) {
2150 *pnum = 0;
2151 goto out;
2155 * The driver's result must be a non-zero multiple of request_alignment.
2156 * Clamp pnum and adjust map to original request.
2158 assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2159 align > offset - aligned_offset);
2160 if (ret & BDRV_BLOCK_RECURSE) {
2161 assert(ret & BDRV_BLOCK_DATA);
2162 assert(ret & BDRV_BLOCK_OFFSET_VALID);
2163 assert(!(ret & BDRV_BLOCK_ZERO));
2166 *pnum -= offset - aligned_offset;
2167 if (*pnum > bytes) {
2168 *pnum = bytes;
2170 if (ret & BDRV_BLOCK_OFFSET_VALID) {
2171 local_map += offset - aligned_offset;
2174 if (ret & BDRV_BLOCK_RAW) {
2175 assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2176 ret = bdrv_co_block_status(local_file, want_zero, local_map,
2177 *pnum, pnum, &local_map, &local_file);
2178 goto out;
2181 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2182 ret |= BDRV_BLOCK_ALLOCATED;
2183 } else if (want_zero) {
2184 if (bdrv_unallocated_blocks_are_zero(bs)) {
2185 ret |= BDRV_BLOCK_ZERO;
2186 } else if (bs->backing) {
2187 BlockDriverState *bs2 = bs->backing->bs;
2188 int64_t size2 = bdrv_getlength(bs2);
2190 if (size2 >= 0 && offset >= size2) {
2191 ret |= BDRV_BLOCK_ZERO;
2196 if (want_zero && ret & BDRV_BLOCK_RECURSE &&
2197 local_file && local_file != bs &&
2198 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2199 (ret & BDRV_BLOCK_OFFSET_VALID)) {
2200 int64_t file_pnum;
2201 int ret2;
2203 ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2204 *pnum, &file_pnum, NULL, NULL);
2205 if (ret2 >= 0) {
2206 /* Ignore errors. This is just providing extra information, it
2207 * is useful but not necessary.
2209 if (ret2 & BDRV_BLOCK_EOF &&
2210 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2212 * It is valid for the format block driver to read
2213 * beyond the end of the underlying file's current
2214 * size; such areas read as zero.
2216 ret |= BDRV_BLOCK_ZERO;
2217 } else {
2218 /* Limit request to the range reported by the protocol driver */
2219 *pnum = file_pnum;
2220 ret |= (ret2 & BDRV_BLOCK_ZERO);
2225 out:
2226 bdrv_dec_in_flight(bs);
2227 if (ret >= 0 && offset + *pnum == total_size) {
2228 ret |= BDRV_BLOCK_EOF;
2230 early_out:
2231 if (file) {
2232 *file = local_file;
2234 if (map) {
2235 *map = local_map;
2237 return ret;
2240 static int coroutine_fn bdrv_co_block_status_above(BlockDriverState *bs,
2241 BlockDriverState *base,
2242 bool want_zero,
2243 int64_t offset,
2244 int64_t bytes,
2245 int64_t *pnum,
2246 int64_t *map,
2247 BlockDriverState **file)
2249 BlockDriverState *p;
2250 int ret = 0;
2251 bool first = true;
2253 assert(bs != base);
2254 for (p = bs; p != base; p = backing_bs(p)) {
2255 ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2256 file);
2257 if (ret < 0) {
2258 break;
2260 if (ret & BDRV_BLOCK_ZERO && ret & BDRV_BLOCK_EOF && !first) {
2262 * Reading beyond the end of the file continues to read
2263 * zeroes, but we can only widen the result to the
2264 * unallocated length we learned from an earlier
2265 * iteration.
2267 *pnum = bytes;
2269 if (ret & (BDRV_BLOCK_ZERO | BDRV_BLOCK_DATA)) {
2270 break;
2272 /* [offset, pnum] unallocated on this layer, which could be only
2273 * the first part of [offset, bytes]. */
2274 bytes = MIN(bytes, *pnum);
2275 first = false;
2277 return ret;
2280 /* Coroutine wrapper for bdrv_block_status_above() */
2281 static void coroutine_fn bdrv_block_status_above_co_entry(void *opaque)
2283 BdrvCoBlockStatusData *data = opaque;
2285 data->ret = bdrv_co_block_status_above(data->bs, data->base,
2286 data->want_zero,
2287 data->offset, data->bytes,
2288 data->pnum, data->map, data->file);
2289 data->done = true;
2290 aio_wait_kick();
2294 * Synchronous wrapper around bdrv_co_block_status_above().
2296 * See bdrv_co_block_status_above() for details.
2298 static int bdrv_common_block_status_above(BlockDriverState *bs,
2299 BlockDriverState *base,
2300 bool want_zero, int64_t offset,
2301 int64_t bytes, int64_t *pnum,
2302 int64_t *map,
2303 BlockDriverState **file)
2305 Coroutine *co;
2306 BdrvCoBlockStatusData data = {
2307 .bs = bs,
2308 .base = base,
2309 .want_zero = want_zero,
2310 .offset = offset,
2311 .bytes = bytes,
2312 .pnum = pnum,
2313 .map = map,
2314 .file = file,
2315 .done = false,
2318 if (qemu_in_coroutine()) {
2319 /* Fast-path if already in coroutine context */
2320 bdrv_block_status_above_co_entry(&data);
2321 } else {
2322 co = qemu_coroutine_create(bdrv_block_status_above_co_entry, &data);
2323 bdrv_coroutine_enter(bs, co);
2324 BDRV_POLL_WHILE(bs, !data.done);
2326 return data.ret;
2329 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2330 int64_t offset, int64_t bytes, int64_t *pnum,
2331 int64_t *map, BlockDriverState **file)
2333 return bdrv_common_block_status_above(bs, base, true, offset, bytes,
2334 pnum, map, file);
2337 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2338 int64_t *pnum, int64_t *map, BlockDriverState **file)
2340 return bdrv_block_status_above(bs, backing_bs(bs),
2341 offset, bytes, pnum, map, file);
2344 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
2345 int64_t bytes, int64_t *pnum)
2347 int ret;
2348 int64_t dummy;
2350 ret = bdrv_common_block_status_above(bs, backing_bs(bs), false, offset,
2351 bytes, pnum ? pnum : &dummy, NULL,
2352 NULL);
2353 if (ret < 0) {
2354 return ret;
2356 return !!(ret & BDRV_BLOCK_ALLOCATED);
2360 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2362 * Return 1 if (a prefix of) the given range is allocated in any image
2363 * between BASE and TOP (BASE is only included if include_base is set).
2364 * BASE can be NULL to check if the given offset is allocated in any
2365 * image of the chain. Return 0 otherwise, or negative errno on
2366 * failure.
2368 * 'pnum' is set to the number of bytes (including and immediately
2369 * following the specified offset) that are known to be in the same
2370 * allocated/unallocated state. Note that a subsequent call starting
2371 * at 'offset + *pnum' may return the same allocation status (in other
2372 * words, the result is not necessarily the maximum possible range);
2373 * but 'pnum' will only be 0 when end of file is reached.
2376 int bdrv_is_allocated_above(BlockDriverState *top,
2377 BlockDriverState *base,
2378 bool include_base, int64_t offset,
2379 int64_t bytes, int64_t *pnum)
2381 BlockDriverState *intermediate;
2382 int ret;
2383 int64_t n = bytes;
2385 assert(base || !include_base);
2387 intermediate = top;
2388 while (include_base || intermediate != base) {
2389 int64_t pnum_inter;
2390 int64_t size_inter;
2392 assert(intermediate);
2393 ret = bdrv_is_allocated(intermediate, offset, bytes, &pnum_inter);
2394 if (ret < 0) {
2395 return ret;
2397 if (ret) {
2398 *pnum = pnum_inter;
2399 return 1;
2402 size_inter = bdrv_getlength(intermediate);
2403 if (size_inter < 0) {
2404 return size_inter;
2406 if (n > pnum_inter &&
2407 (intermediate == top || offset + pnum_inter < size_inter)) {
2408 n = pnum_inter;
2411 if (intermediate == base) {
2412 break;
2415 intermediate = backing_bs(intermediate);
2418 *pnum = n;
2419 return 0;
2422 typedef struct BdrvVmstateCo {
2423 BlockDriverState *bs;
2424 QEMUIOVector *qiov;
2425 int64_t pos;
2426 bool is_read;
2427 int ret;
2428 } BdrvVmstateCo;
2430 static int coroutine_fn
2431 bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
2432 bool is_read)
2434 BlockDriver *drv = bs->drv;
2435 int ret = -ENOTSUP;
2437 bdrv_inc_in_flight(bs);
2439 if (!drv) {
2440 ret = -ENOMEDIUM;
2441 } else if (drv->bdrv_load_vmstate) {
2442 if (is_read) {
2443 ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2444 } else {
2445 ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2447 } else if (bs->file) {
2448 ret = bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read);
2451 bdrv_dec_in_flight(bs);
2452 return ret;
2455 static void coroutine_fn bdrv_co_rw_vmstate_entry(void *opaque)
2457 BdrvVmstateCo *co = opaque;
2458 co->ret = bdrv_co_rw_vmstate(co->bs, co->qiov, co->pos, co->is_read);
2459 aio_wait_kick();
2462 static inline int
2463 bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
2464 bool is_read)
2466 if (qemu_in_coroutine()) {
2467 return bdrv_co_rw_vmstate(bs, qiov, pos, is_read);
2468 } else {
2469 BdrvVmstateCo data = {
2470 .bs = bs,
2471 .qiov = qiov,
2472 .pos = pos,
2473 .is_read = is_read,
2474 .ret = -EINPROGRESS,
2476 Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry, &data);
2478 bdrv_coroutine_enter(bs, co);
2479 BDRV_POLL_WHILE(bs, data.ret == -EINPROGRESS);
2480 return data.ret;
2484 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2485 int64_t pos, int size)
2487 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2488 int ret;
2490 ret = bdrv_writev_vmstate(bs, &qiov, pos);
2491 if (ret < 0) {
2492 return ret;
2495 return size;
2498 int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2500 return bdrv_rw_vmstate(bs, qiov, pos, false);
2503 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2504 int64_t pos, int size)
2506 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2507 int ret;
2509 ret = bdrv_readv_vmstate(bs, &qiov, pos);
2510 if (ret < 0) {
2511 return ret;
2514 return size;
2517 int bdrv_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2519 return bdrv_rw_vmstate(bs, qiov, pos, true);
2522 /**************************************************************/
2523 /* async I/Os */
2525 void bdrv_aio_cancel(BlockAIOCB *acb)
2527 qemu_aio_ref(acb);
2528 bdrv_aio_cancel_async(acb);
2529 while (acb->refcnt > 1) {
2530 if (acb->aiocb_info->get_aio_context) {
2531 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2532 } else if (acb->bs) {
2533 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2534 * assert that we're not using an I/O thread. Thread-safe
2535 * code should use bdrv_aio_cancel_async exclusively.
2537 assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2538 aio_poll(bdrv_get_aio_context(acb->bs), true);
2539 } else {
2540 abort();
2543 qemu_aio_unref(acb);
2546 /* Async version of aio cancel. The caller is not blocked if the acb implements
2547 * cancel_async, otherwise we do nothing and let the request normally complete.
2548 * In either case the completion callback must be called. */
2549 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2551 if (acb->aiocb_info->cancel_async) {
2552 acb->aiocb_info->cancel_async(acb);
2556 /**************************************************************/
2557 /* Coroutine block device emulation */
2559 typedef struct FlushCo {
2560 BlockDriverState *bs;
2561 int ret;
2562 } FlushCo;
2565 static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2567 FlushCo *rwco = opaque;
2569 rwco->ret = bdrv_co_flush(rwco->bs);
2570 aio_wait_kick();
2573 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2575 int current_gen;
2576 int ret = 0;
2578 bdrv_inc_in_flight(bs);
2580 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2581 bdrv_is_sg(bs)) {
2582 goto early_exit;
2585 qemu_co_mutex_lock(&bs->reqs_lock);
2586 current_gen = atomic_read(&bs->write_gen);
2588 /* Wait until any previous flushes are completed */
2589 while (bs->active_flush_req) {
2590 qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
2593 /* Flushes reach this point in nondecreasing current_gen order. */
2594 bs->active_flush_req = true;
2595 qemu_co_mutex_unlock(&bs->reqs_lock);
2597 /* Write back all layers by calling one driver function */
2598 if (bs->drv->bdrv_co_flush) {
2599 ret = bs->drv->bdrv_co_flush(bs);
2600 goto out;
2603 /* Write back cached data to the OS even with cache=unsafe */
2604 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2605 if (bs->drv->bdrv_co_flush_to_os) {
2606 ret = bs->drv->bdrv_co_flush_to_os(bs);
2607 if (ret < 0) {
2608 goto out;
2612 /* But don't actually force it to the disk with cache=unsafe */
2613 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2614 goto flush_parent;
2617 /* Check if we really need to flush anything */
2618 if (bs->flushed_gen == current_gen) {
2619 goto flush_parent;
2622 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
2623 if (!bs->drv) {
2624 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2625 * (even in case of apparent success) */
2626 ret = -ENOMEDIUM;
2627 goto out;
2629 if (bs->drv->bdrv_co_flush_to_disk) {
2630 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2631 } else if (bs->drv->bdrv_aio_flush) {
2632 BlockAIOCB *acb;
2633 CoroutineIOCompletion co = {
2634 .coroutine = qemu_coroutine_self(),
2637 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2638 if (acb == NULL) {
2639 ret = -EIO;
2640 } else {
2641 qemu_coroutine_yield();
2642 ret = co.ret;
2644 } else {
2646 * Some block drivers always operate in either writethrough or unsafe
2647 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2648 * know how the server works (because the behaviour is hardcoded or
2649 * depends on server-side configuration), so we can't ensure that
2650 * everything is safe on disk. Returning an error doesn't work because
2651 * that would break guests even if the server operates in writethrough
2652 * mode.
2654 * Let's hope the user knows what he's doing.
2656 ret = 0;
2659 if (ret < 0) {
2660 goto out;
2663 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2664 * in the case of cache=unsafe, so there are no useless flushes.
2666 flush_parent:
2667 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2668 out:
2669 /* Notify any pending flushes that we have completed */
2670 if (ret == 0) {
2671 bs->flushed_gen = current_gen;
2674 qemu_co_mutex_lock(&bs->reqs_lock);
2675 bs->active_flush_req = false;
2676 /* Return value is ignored - it's ok if wait queue is empty */
2677 qemu_co_queue_next(&bs->flush_queue);
2678 qemu_co_mutex_unlock(&bs->reqs_lock);
2680 early_exit:
2681 bdrv_dec_in_flight(bs);
2682 return ret;
2685 int bdrv_flush(BlockDriverState *bs)
2687 Coroutine *co;
2688 FlushCo flush_co = {
2689 .bs = bs,
2690 .ret = NOT_DONE,
2693 if (qemu_in_coroutine()) {
2694 /* Fast-path if already in coroutine context */
2695 bdrv_flush_co_entry(&flush_co);
2696 } else {
2697 co = qemu_coroutine_create(bdrv_flush_co_entry, &flush_co);
2698 bdrv_coroutine_enter(bs, co);
2699 BDRV_POLL_WHILE(bs, flush_co.ret == NOT_DONE);
2702 return flush_co.ret;
2705 typedef struct DiscardCo {
2706 BdrvChild *child;
2707 int64_t offset;
2708 int64_t bytes;
2709 int ret;
2710 } DiscardCo;
2711 static void coroutine_fn bdrv_pdiscard_co_entry(void *opaque)
2713 DiscardCo *rwco = opaque;
2715 rwco->ret = bdrv_co_pdiscard(rwco->child, rwco->offset, rwco->bytes);
2716 aio_wait_kick();
2719 int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset,
2720 int64_t bytes)
2722 BdrvTrackedRequest req;
2723 int max_pdiscard, ret;
2724 int head, tail, align;
2725 BlockDriverState *bs = child->bs;
2727 if (!bs || !bs->drv || !bdrv_is_inserted(bs)) {
2728 return -ENOMEDIUM;
2731 if (bdrv_has_readonly_bitmaps(bs)) {
2732 return -EPERM;
2735 if (offset < 0 || bytes < 0 || bytes > INT64_MAX - offset) {
2736 return -EIO;
2739 /* Do nothing if disabled. */
2740 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2741 return 0;
2744 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
2745 return 0;
2748 /* Discard is advisory, but some devices track and coalesce
2749 * unaligned requests, so we must pass everything down rather than
2750 * round here. Still, most devices will just silently ignore
2751 * unaligned requests (by returning -ENOTSUP), so we must fragment
2752 * the request accordingly. */
2753 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
2754 assert(align % bs->bl.request_alignment == 0);
2755 head = offset % align;
2756 tail = (offset + bytes) % align;
2758 bdrv_inc_in_flight(bs);
2759 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
2761 ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
2762 if (ret < 0) {
2763 goto out;
2766 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),
2767 align);
2768 assert(max_pdiscard >= bs->bl.request_alignment);
2770 while (bytes > 0) {
2771 int64_t num = bytes;
2773 if (head) {
2774 /* Make small requests to get to alignment boundaries. */
2775 num = MIN(bytes, align - head);
2776 if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
2777 num %= bs->bl.request_alignment;
2779 head = (head + num) % align;
2780 assert(num < max_pdiscard);
2781 } else if (tail) {
2782 if (num > align) {
2783 /* Shorten the request to the last aligned cluster. */
2784 num -= tail;
2785 } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
2786 tail > bs->bl.request_alignment) {
2787 tail %= bs->bl.request_alignment;
2788 num -= tail;
2791 /* limit request size */
2792 if (num > max_pdiscard) {
2793 num = max_pdiscard;
2796 if (!bs->drv) {
2797 ret = -ENOMEDIUM;
2798 goto out;
2800 if (bs->drv->bdrv_co_pdiscard) {
2801 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
2802 } else {
2803 BlockAIOCB *acb;
2804 CoroutineIOCompletion co = {
2805 .coroutine = qemu_coroutine_self(),
2808 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
2809 bdrv_co_io_em_complete, &co);
2810 if (acb == NULL) {
2811 ret = -EIO;
2812 goto out;
2813 } else {
2814 qemu_coroutine_yield();
2815 ret = co.ret;
2818 if (ret && ret != -ENOTSUP) {
2819 goto out;
2822 offset += num;
2823 bytes -= num;
2825 ret = 0;
2826 out:
2827 bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
2828 tracked_request_end(&req);
2829 bdrv_dec_in_flight(bs);
2830 return ret;
2833 int bdrv_pdiscard(BdrvChild *child, int64_t offset, int64_t bytes)
2835 Coroutine *co;
2836 DiscardCo rwco = {
2837 .child = child,
2838 .offset = offset,
2839 .bytes = bytes,
2840 .ret = NOT_DONE,
2843 if (qemu_in_coroutine()) {
2844 /* Fast-path if already in coroutine context */
2845 bdrv_pdiscard_co_entry(&rwco);
2846 } else {
2847 co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco);
2848 bdrv_coroutine_enter(child->bs, co);
2849 BDRV_POLL_WHILE(child->bs, rwco.ret == NOT_DONE);
2852 return rwco.ret;
2855 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
2857 BlockDriver *drv = bs->drv;
2858 CoroutineIOCompletion co = {
2859 .coroutine = qemu_coroutine_self(),
2861 BlockAIOCB *acb;
2863 bdrv_inc_in_flight(bs);
2864 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
2865 co.ret = -ENOTSUP;
2866 goto out;
2869 if (drv->bdrv_co_ioctl) {
2870 co.ret = drv->bdrv_co_ioctl(bs, req, buf);
2871 } else {
2872 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2873 if (!acb) {
2874 co.ret = -ENOTSUP;
2875 goto out;
2877 qemu_coroutine_yield();
2879 out:
2880 bdrv_dec_in_flight(bs);
2881 return co.ret;
2884 void *qemu_blockalign(BlockDriverState *bs, size_t size)
2886 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2889 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2891 return memset(qemu_blockalign(bs, size), 0, size);
2894 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2896 size_t align = bdrv_opt_mem_align(bs);
2898 /* Ensure that NULL is never returned on success */
2899 assert(align > 0);
2900 if (size == 0) {
2901 size = align;
2904 return qemu_try_memalign(align, size);
2907 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2909 void *mem = qemu_try_blockalign(bs, size);
2911 if (mem) {
2912 memset(mem, 0, size);
2915 return mem;
2919 * Check if all memory in this vector is sector aligned.
2921 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2923 int i;
2924 size_t alignment = bdrv_min_mem_align(bs);
2926 for (i = 0; i < qiov->niov; i++) {
2927 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2928 return false;
2930 if (qiov->iov[i].iov_len % alignment) {
2931 return false;
2935 return true;
2938 void bdrv_add_before_write_notifier(BlockDriverState *bs,
2939 NotifierWithReturn *notifier)
2941 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2944 void bdrv_io_plug(BlockDriverState *bs)
2946 BdrvChild *child;
2948 QLIST_FOREACH(child, &bs->children, next) {
2949 bdrv_io_plug(child->bs);
2952 if (atomic_fetch_inc(&bs->io_plugged) == 0) {
2953 BlockDriver *drv = bs->drv;
2954 if (drv && drv->bdrv_io_plug) {
2955 drv->bdrv_io_plug(bs);
2960 void bdrv_io_unplug(BlockDriverState *bs)
2962 BdrvChild *child;
2964 assert(bs->io_plugged);
2965 if (atomic_fetch_dec(&bs->io_plugged) == 1) {
2966 BlockDriver *drv = bs->drv;
2967 if (drv && drv->bdrv_io_unplug) {
2968 drv->bdrv_io_unplug(bs);
2972 QLIST_FOREACH(child, &bs->children, next) {
2973 bdrv_io_unplug(child->bs);
2977 void bdrv_register_buf(BlockDriverState *bs, void *host, size_t size)
2979 BdrvChild *child;
2981 if (bs->drv && bs->drv->bdrv_register_buf) {
2982 bs->drv->bdrv_register_buf(bs, host, size);
2984 QLIST_FOREACH(child, &bs->children, next) {
2985 bdrv_register_buf(child->bs, host, size);
2989 void bdrv_unregister_buf(BlockDriverState *bs, void *host)
2991 BdrvChild *child;
2993 if (bs->drv && bs->drv->bdrv_unregister_buf) {
2994 bs->drv->bdrv_unregister_buf(bs, host);
2996 QLIST_FOREACH(child, &bs->children, next) {
2997 bdrv_unregister_buf(child->bs, host);
3001 static int coroutine_fn bdrv_co_copy_range_internal(
3002 BdrvChild *src, uint64_t src_offset, BdrvChild *dst,
3003 uint64_t dst_offset, uint64_t bytes,
3004 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
3005 bool recurse_src)
3007 BdrvTrackedRequest req;
3008 int ret;
3010 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3011 assert(!(read_flags & BDRV_REQ_NO_FALLBACK));
3012 assert(!(write_flags & BDRV_REQ_NO_FALLBACK));
3014 if (!dst || !dst->bs) {
3015 return -ENOMEDIUM;
3017 ret = bdrv_check_byte_request(dst->bs, dst_offset, bytes);
3018 if (ret) {
3019 return ret;
3021 if (write_flags & BDRV_REQ_ZERO_WRITE) {
3022 return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
3025 if (!src || !src->bs) {
3026 return -ENOMEDIUM;
3028 ret = bdrv_check_byte_request(src->bs, src_offset, bytes);
3029 if (ret) {
3030 return ret;
3033 if (!src->bs->drv->bdrv_co_copy_range_from
3034 || !dst->bs->drv->bdrv_co_copy_range_to
3035 || src->bs->encrypted || dst->bs->encrypted) {
3036 return -ENOTSUP;
3039 if (recurse_src) {
3040 bdrv_inc_in_flight(src->bs);
3041 tracked_request_begin(&req, src->bs, src_offset, bytes,
3042 BDRV_TRACKED_READ);
3044 /* BDRV_REQ_SERIALISING is only for write operation */
3045 assert(!(read_flags & BDRV_REQ_SERIALISING));
3046 if (!(read_flags & BDRV_REQ_NO_SERIALISING)) {
3047 wait_serialising_requests(&req);
3050 ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
3051 src, src_offset,
3052 dst, dst_offset,
3053 bytes,
3054 read_flags, write_flags);
3056 tracked_request_end(&req);
3057 bdrv_dec_in_flight(src->bs);
3058 } else {
3059 bdrv_inc_in_flight(dst->bs);
3060 tracked_request_begin(&req, dst->bs, dst_offset, bytes,
3061 BDRV_TRACKED_WRITE);
3062 ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3063 write_flags);
3064 if (!ret) {
3065 ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3066 src, src_offset,
3067 dst, dst_offset,
3068 bytes,
3069 read_flags, write_flags);
3071 bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
3072 tracked_request_end(&req);
3073 bdrv_dec_in_flight(dst->bs);
3076 return ret;
3079 /* Copy range from @src to @dst.
3081 * See the comment of bdrv_co_copy_range for the parameter and return value
3082 * semantics. */
3083 int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, uint64_t src_offset,
3084 BdrvChild *dst, uint64_t dst_offset,
3085 uint64_t bytes,
3086 BdrvRequestFlags read_flags,
3087 BdrvRequestFlags write_flags)
3089 trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3090 read_flags, write_flags);
3091 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3092 bytes, read_flags, write_flags, true);
3095 /* Copy range from @src to @dst.
3097 * See the comment of bdrv_co_copy_range for the parameter and return value
3098 * semantics. */
3099 int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, uint64_t src_offset,
3100 BdrvChild *dst, uint64_t dst_offset,
3101 uint64_t bytes,
3102 BdrvRequestFlags read_flags,
3103 BdrvRequestFlags write_flags)
3105 trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3106 read_flags, write_flags);
3107 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3108 bytes, read_flags, write_flags, false);
3111 int coroutine_fn bdrv_co_copy_range(BdrvChild *src, uint64_t src_offset,
3112 BdrvChild *dst, uint64_t dst_offset,
3113 uint64_t bytes, BdrvRequestFlags read_flags,
3114 BdrvRequestFlags write_flags)
3116 return bdrv_co_copy_range_from(src, src_offset,
3117 dst, dst_offset,
3118 bytes, read_flags, write_flags);
3121 static void bdrv_parent_cb_resize(BlockDriverState *bs)
3123 BdrvChild *c;
3124 QLIST_FOREACH(c, &bs->parents, next_parent) {
3125 if (c->role->resize) {
3126 c->role->resize(c);
3132 * Truncate file to 'offset' bytes (needed only for file protocols)
3134 int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset,
3135 PreallocMode prealloc, Error **errp)
3137 BlockDriverState *bs = child->bs;
3138 BlockDriver *drv = bs->drv;
3139 BdrvTrackedRequest req;
3140 int64_t old_size, new_bytes;
3141 int ret;
3144 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3145 if (!drv) {
3146 error_setg(errp, "No medium inserted");
3147 return -ENOMEDIUM;
3149 if (offset < 0) {
3150 error_setg(errp, "Image size cannot be negative");
3151 return -EINVAL;
3154 old_size = bdrv_getlength(bs);
3155 if (old_size < 0) {
3156 error_setg_errno(errp, -old_size, "Failed to get old image size");
3157 return old_size;
3160 if (offset > old_size) {
3161 new_bytes = offset - old_size;
3162 } else {
3163 new_bytes = 0;
3166 bdrv_inc_in_flight(bs);
3167 tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3168 BDRV_TRACKED_TRUNCATE);
3170 /* If we are growing the image and potentially using preallocation for the
3171 * new area, we need to make sure that no write requests are made to it
3172 * concurrently or they might be overwritten by preallocation. */
3173 if (new_bytes) {
3174 mark_request_serialising(&req, 1);
3176 if (bs->read_only) {
3177 error_setg(errp, "Image is read-only");
3178 ret = -EACCES;
3179 goto out;
3181 ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3183 if (ret < 0) {
3184 error_setg_errno(errp, -ret,
3185 "Failed to prepare request for truncation");
3186 goto out;
3189 if (!drv->bdrv_co_truncate) {
3190 if (bs->file && drv->is_filter) {
3191 ret = bdrv_co_truncate(bs->file, offset, prealloc, errp);
3192 goto out;
3194 error_setg(errp, "Image format driver does not support resize");
3195 ret = -ENOTSUP;
3196 goto out;
3199 ret = drv->bdrv_co_truncate(bs, offset, prealloc, errp);
3200 if (ret < 0) {
3201 goto out;
3203 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3204 if (ret < 0) {
3205 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3206 } else {
3207 offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3209 /* It's possible that truncation succeeded but refresh_total_sectors
3210 * failed, but the latter doesn't affect how we should finish the request.
3211 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3212 bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3214 out:
3215 tracked_request_end(&req);
3216 bdrv_dec_in_flight(bs);
3218 return ret;
3221 typedef struct TruncateCo {
3222 BdrvChild *child;
3223 int64_t offset;
3224 PreallocMode prealloc;
3225 Error **errp;
3226 int ret;
3227 } TruncateCo;
3229 static void coroutine_fn bdrv_truncate_co_entry(void *opaque)
3231 TruncateCo *tco = opaque;
3232 tco->ret = bdrv_co_truncate(tco->child, tco->offset, tco->prealloc,
3233 tco->errp);
3234 aio_wait_kick();
3237 int bdrv_truncate(BdrvChild *child, int64_t offset, PreallocMode prealloc,
3238 Error **errp)
3240 Coroutine *co;
3241 TruncateCo tco = {
3242 .child = child,
3243 .offset = offset,
3244 .prealloc = prealloc,
3245 .errp = errp,
3246 .ret = NOT_DONE,
3249 if (qemu_in_coroutine()) {
3250 /* Fast-path if already in coroutine context */
3251 bdrv_truncate_co_entry(&tco);
3252 } else {
3253 co = qemu_coroutine_create(bdrv_truncate_co_entry, &tco);
3254 bdrv_coroutine_enter(child->bs, co);
3255 BDRV_POLL_WHILE(child->bs, tco.ret == NOT_DONE);
3258 return tco.ret;