xref: /openbmc/qemu/block/io.c (revision 7b52a921c12c01be3b2ce331081dd9accea99948)
1 /*
2  * Block layer I/O functions
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "trace.h"
27 #include "sysemu/block-backend.h"
28 #include "block/aio-wait.h"
29 #include "block/blockjob.h"
30 #include "block/blockjob_int.h"
31 #include "block/block_int.h"
32 #include "block/coroutines.h"
33 #include "block/write-threshold.h"
34 #include "qemu/cutils.h"
35 #include "qemu/memalign.h"
36 #include "qapi/error.h"
37 #include "qemu/error-report.h"
38 #include "qemu/main-loop.h"
39 #include "sysemu/replay.h"
40 
41 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
42 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
43 
44 static void bdrv_parent_cb_resize(BlockDriverState *bs);
45 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
46     int64_t offset, int64_t bytes, BdrvRequestFlags flags);
47 
48 static void bdrv_parent_drained_begin(BlockDriverState *bs, BdrvChild *ignore)
49 {
50     BdrvChild *c, *next;
51 
52     QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
53         if (c == ignore) {
54             continue;
55         }
56         bdrv_parent_drained_begin_single(c);
57     }
58 }
59 
60 void bdrv_parent_drained_end_single(BdrvChild *c)
61 {
62     IO_OR_GS_CODE();
63 
64     assert(c->quiesced_parent);
65     c->quiesced_parent = false;
66 
67     if (c->klass->drained_end) {
68         c->klass->drained_end(c);
69     }
70 }
71 
72 static void bdrv_parent_drained_end(BlockDriverState *bs, BdrvChild *ignore)
73 {
74     BdrvChild *c;
75 
76     QLIST_FOREACH(c, &bs->parents, next_parent) {
77         if (c == ignore) {
78             continue;
79         }
80         bdrv_parent_drained_end_single(c);
81     }
82 }
83 
84 bool bdrv_parent_drained_poll_single(BdrvChild *c)
85 {
86     if (c->klass->drained_poll) {
87         return c->klass->drained_poll(c);
88     }
89     return false;
90 }
91 
92 static bool bdrv_parent_drained_poll(BlockDriverState *bs, BdrvChild *ignore,
93                                      bool ignore_bds_parents)
94 {
95     BdrvChild *c, *next;
96     bool busy = false;
97 
98     QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
99         if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
100             continue;
101         }
102         busy |= bdrv_parent_drained_poll_single(c);
103     }
104 
105     return busy;
106 }
107 
108 void bdrv_parent_drained_begin_single(BdrvChild *c)
109 {
110     IO_OR_GS_CODE();
111 
112     assert(!c->quiesced_parent);
113     c->quiesced_parent = true;
114 
115     if (c->klass->drained_begin) {
116         c->klass->drained_begin(c);
117     }
118 }
119 
120 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
121 {
122     dst->pdiscard_alignment = MAX(dst->pdiscard_alignment,
123                                   src->pdiscard_alignment);
124     dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
125     dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer);
126     dst->max_hw_transfer = MIN_NON_ZERO(dst->max_hw_transfer,
127                                         src->max_hw_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);
133     dst->max_hw_iov = MIN_NON_ZERO(dst->max_hw_iov, src->max_hw_iov);
134 }
135 
136 typedef struct BdrvRefreshLimitsState {
137     BlockDriverState *bs;
138     BlockLimits old_bl;
139 } BdrvRefreshLimitsState;
140 
141 static void bdrv_refresh_limits_abort(void *opaque)
142 {
143     BdrvRefreshLimitsState *s = opaque;
144 
145     s->bs->bl = s->old_bl;
146 }
147 
148 static TransactionActionDrv bdrv_refresh_limits_drv = {
149     .abort = bdrv_refresh_limits_abort,
150     .clean = g_free,
151 };
152 
153 /* @tran is allowed to be NULL, in this case no rollback is possible. */
154 void bdrv_refresh_limits(BlockDriverState *bs, Transaction *tran, Error **errp)
155 {
156     ERRP_GUARD();
157     BlockDriver *drv = bs->drv;
158     BdrvChild *c;
159     bool have_limits;
160 
161     GLOBAL_STATE_CODE();
162 
163     if (tran) {
164         BdrvRefreshLimitsState *s = g_new(BdrvRefreshLimitsState, 1);
165         *s = (BdrvRefreshLimitsState) {
166             .bs = bs,
167             .old_bl = bs->bl,
168         };
169         tran_add(tran, &bdrv_refresh_limits_drv, s);
170     }
171 
172     memset(&bs->bl, 0, sizeof(bs->bl));
173 
174     if (!drv) {
175         return;
176     }
177 
178     /* Default alignment based on whether driver has byte interface */
179     bs->bl.request_alignment = (drv->bdrv_co_preadv ||
180                                 drv->bdrv_aio_preadv ||
181                                 drv->bdrv_co_preadv_part) ? 1 : 512;
182 
183     /* Take some limits from the children as a default */
184     have_limits = false;
185     QLIST_FOREACH(c, &bs->children, next) {
186         if (c->role & (BDRV_CHILD_DATA | BDRV_CHILD_FILTERED | BDRV_CHILD_COW))
187         {
188             bdrv_merge_limits(&bs->bl, &c->bs->bl);
189             have_limits = true;
190         }
191     }
192 
193     if (!have_limits) {
194         bs->bl.min_mem_alignment = 512;
195         bs->bl.opt_mem_alignment = qemu_real_host_page_size();
196 
197         /* Safe default since most protocols use readv()/writev()/etc */
198         bs->bl.max_iov = IOV_MAX;
199     }
200 
201     /* Then let the driver override it */
202     if (drv->bdrv_refresh_limits) {
203         drv->bdrv_refresh_limits(bs, errp);
204         if (*errp) {
205             return;
206         }
207     }
208 
209     if (bs->bl.request_alignment > BDRV_MAX_ALIGNMENT) {
210         error_setg(errp, "Driver requires too large request alignment");
211     }
212 }
213 
214 /**
215  * The copy-on-read flag is actually a reference count so multiple users may
216  * use the feature without worrying about clobbering its previous state.
217  * Copy-on-read stays enabled until all users have called to disable it.
218  */
219 void bdrv_enable_copy_on_read(BlockDriverState *bs)
220 {
221     IO_CODE();
222     qatomic_inc(&bs->copy_on_read);
223 }
224 
225 void bdrv_disable_copy_on_read(BlockDriverState *bs)
226 {
227     int old = qatomic_fetch_dec(&bs->copy_on_read);
228     IO_CODE();
229     assert(old >= 1);
230 }
231 
232 typedef struct {
233     Coroutine *co;
234     BlockDriverState *bs;
235     bool done;
236     bool begin;
237     bool poll;
238     BdrvChild *parent;
239 } BdrvCoDrainData;
240 
241 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
242 bool bdrv_drain_poll(BlockDriverState *bs, BdrvChild *ignore_parent,
243                      bool ignore_bds_parents)
244 {
245     IO_OR_GS_CODE();
246 
247     if (bdrv_parent_drained_poll(bs, ignore_parent, ignore_bds_parents)) {
248         return true;
249     }
250 
251     if (qatomic_read(&bs->in_flight)) {
252         return true;
253     }
254 
255     return false;
256 }
257 
258 static bool bdrv_drain_poll_top_level(BlockDriverState *bs,
259                                       BdrvChild *ignore_parent)
260 {
261     return bdrv_drain_poll(bs, ignore_parent, false);
262 }
263 
264 static void bdrv_do_drained_begin(BlockDriverState *bs, BdrvChild *parent,
265                                   bool poll);
266 static void bdrv_do_drained_end(BlockDriverState *bs, BdrvChild *parent);
267 
268 static void bdrv_co_drain_bh_cb(void *opaque)
269 {
270     BdrvCoDrainData *data = opaque;
271     Coroutine *co = data->co;
272     BlockDriverState *bs = data->bs;
273 
274     if (bs) {
275         AioContext *ctx = bdrv_get_aio_context(bs);
276         aio_context_acquire(ctx);
277         bdrv_dec_in_flight(bs);
278         if (data->begin) {
279             bdrv_do_drained_begin(bs, data->parent, data->poll);
280         } else {
281             assert(!data->poll);
282             bdrv_do_drained_end(bs, data->parent);
283         }
284         aio_context_release(ctx);
285     } else {
286         assert(data->begin);
287         bdrv_drain_all_begin();
288     }
289 
290     data->done = true;
291     aio_co_wake(co);
292 }
293 
294 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs,
295                                                 bool begin,
296                                                 BdrvChild *parent,
297                                                 bool poll)
298 {
299     BdrvCoDrainData data;
300     Coroutine *self = qemu_coroutine_self();
301     AioContext *ctx = bdrv_get_aio_context(bs);
302     AioContext *co_ctx = qemu_coroutine_get_aio_context(self);
303 
304     /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
305      * other coroutines run if they were queued by aio_co_enter(). */
306 
307     assert(qemu_in_coroutine());
308     data = (BdrvCoDrainData) {
309         .co = self,
310         .bs = bs,
311         .done = false,
312         .begin = begin,
313         .parent = parent,
314         .poll = poll,
315     };
316 
317     if (bs) {
318         bdrv_inc_in_flight(bs);
319     }
320 
321     /*
322      * Temporarily drop the lock across yield or we would get deadlocks.
323      * bdrv_co_drain_bh_cb() reaquires the lock as needed.
324      *
325      * When we yield below, the lock for the current context will be
326      * released, so if this is actually the lock that protects bs, don't drop
327      * it a second time.
328      */
329     if (ctx != co_ctx) {
330         aio_context_release(ctx);
331     }
332     replay_bh_schedule_oneshot_event(ctx, bdrv_co_drain_bh_cb, &data);
333 
334     qemu_coroutine_yield();
335     /* If we are resumed from some other event (such as an aio completion or a
336      * timer callback), it is a bug in the caller that should be fixed. */
337     assert(data.done);
338 
339     /* Reaquire the AioContext of bs if we dropped it */
340     if (ctx != co_ctx) {
341         aio_context_acquire(ctx);
342     }
343 }
344 
345 static void bdrv_do_drained_begin(BlockDriverState *bs, BdrvChild *parent,
346                                   bool poll)
347 {
348     IO_OR_GS_CODE();
349 
350     if (qemu_in_coroutine()) {
351         bdrv_co_yield_to_drain(bs, true, parent, poll);
352         return;
353     }
354 
355     /* Stop things in parent-to-child order */
356     if (qatomic_fetch_inc(&bs->quiesce_counter) == 0) {
357         aio_disable_external(bdrv_get_aio_context(bs));
358         bdrv_parent_drained_begin(bs, parent);
359         if (bs->drv && bs->drv->bdrv_drain_begin) {
360             bs->drv->bdrv_drain_begin(bs);
361         }
362     }
363 
364     /*
365      * Wait for drained requests to finish.
366      *
367      * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
368      * call is needed so things in this AioContext can make progress even
369      * though we don't return to the main AioContext loop - this automatically
370      * includes other nodes in the same AioContext and therefore all child
371      * nodes.
372      */
373     if (poll) {
374         BDRV_POLL_WHILE(bs, bdrv_drain_poll_top_level(bs, parent));
375     }
376 }
377 
378 void bdrv_do_drained_begin_quiesce(BlockDriverState *bs, BdrvChild *parent)
379 {
380     bdrv_do_drained_begin(bs, parent, false);
381 }
382 
383 void bdrv_drained_begin(BlockDriverState *bs)
384 {
385     IO_OR_GS_CODE();
386     bdrv_do_drained_begin(bs, NULL, true);
387 }
388 
389 /**
390  * This function does not poll, nor must any of its recursively called
391  * functions.
392  */
393 static void bdrv_do_drained_end(BlockDriverState *bs, BdrvChild *parent)
394 {
395     int old_quiesce_counter;
396 
397     if (qemu_in_coroutine()) {
398         bdrv_co_yield_to_drain(bs, false, parent, false);
399         return;
400     }
401     assert(bs->quiesce_counter > 0);
402 
403     /* Re-enable things in child-to-parent order */
404     old_quiesce_counter = qatomic_fetch_dec(&bs->quiesce_counter);
405     if (old_quiesce_counter == 1) {
406         if (bs->drv && bs->drv->bdrv_drain_end) {
407             bs->drv->bdrv_drain_end(bs);
408         }
409         bdrv_parent_drained_end(bs, parent);
410         aio_enable_external(bdrv_get_aio_context(bs));
411     }
412 }
413 
414 void bdrv_drained_end(BlockDriverState *bs)
415 {
416     IO_OR_GS_CODE();
417     bdrv_do_drained_end(bs, NULL);
418 }
419 
420 void bdrv_drain(BlockDriverState *bs)
421 {
422     IO_OR_GS_CODE();
423     bdrv_drained_begin(bs);
424     bdrv_drained_end(bs);
425 }
426 
427 static void bdrv_drain_assert_idle(BlockDriverState *bs)
428 {
429     BdrvChild *child, *next;
430 
431     assert(qatomic_read(&bs->in_flight) == 0);
432     QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
433         bdrv_drain_assert_idle(child->bs);
434     }
435 }
436 
437 unsigned int bdrv_drain_all_count = 0;
438 
439 static bool bdrv_drain_all_poll(void)
440 {
441     BlockDriverState *bs = NULL;
442     bool result = false;
443     GLOBAL_STATE_CODE();
444 
445     /* bdrv_drain_poll() can't make changes to the graph and we are holding the
446      * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
447     while ((bs = bdrv_next_all_states(bs))) {
448         AioContext *aio_context = bdrv_get_aio_context(bs);
449         aio_context_acquire(aio_context);
450         result |= bdrv_drain_poll(bs, NULL, true);
451         aio_context_release(aio_context);
452     }
453 
454     return result;
455 }
456 
457 /*
458  * Wait for pending requests to complete across all BlockDriverStates
459  *
460  * This function does not flush data to disk, use bdrv_flush_all() for that
461  * after calling this function.
462  *
463  * This pauses all block jobs and disables external clients. It must
464  * be paired with bdrv_drain_all_end().
465  *
466  * NOTE: no new block jobs or BlockDriverStates can be created between
467  * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
468  */
469 void bdrv_drain_all_begin(void)
470 {
471     BlockDriverState *bs = NULL;
472     GLOBAL_STATE_CODE();
473 
474     if (qemu_in_coroutine()) {
475         bdrv_co_yield_to_drain(NULL, true, NULL, true);
476         return;
477     }
478 
479     /*
480      * bdrv queue is managed by record/replay,
481      * waiting for finishing the I/O requests may
482      * be infinite
483      */
484     if (replay_events_enabled()) {
485         return;
486     }
487 
488     /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
489      * loop AioContext, so make sure we're in the main context. */
490     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
491     assert(bdrv_drain_all_count < INT_MAX);
492     bdrv_drain_all_count++;
493 
494     /* Quiesce all nodes, without polling in-flight requests yet. The graph
495      * cannot change during this loop. */
496     while ((bs = bdrv_next_all_states(bs))) {
497         AioContext *aio_context = bdrv_get_aio_context(bs);
498 
499         aio_context_acquire(aio_context);
500         bdrv_do_drained_begin(bs, NULL, false);
501         aio_context_release(aio_context);
502     }
503 
504     /* Now poll the in-flight requests */
505     AIO_WAIT_WHILE(NULL, bdrv_drain_all_poll());
506 
507     while ((bs = bdrv_next_all_states(bs))) {
508         bdrv_drain_assert_idle(bs);
509     }
510 }
511 
512 void bdrv_drain_all_end_quiesce(BlockDriverState *bs)
513 {
514     GLOBAL_STATE_CODE();
515 
516     g_assert(bs->quiesce_counter > 0);
517     g_assert(!bs->refcnt);
518 
519     while (bs->quiesce_counter) {
520         bdrv_do_drained_end(bs, NULL);
521     }
522 }
523 
524 void bdrv_drain_all_end(void)
525 {
526     BlockDriverState *bs = NULL;
527     GLOBAL_STATE_CODE();
528 
529     /*
530      * bdrv queue is managed by record/replay,
531      * waiting for finishing the I/O requests may
532      * be endless
533      */
534     if (replay_events_enabled()) {
535         return;
536     }
537 
538     while ((bs = bdrv_next_all_states(bs))) {
539         AioContext *aio_context = bdrv_get_aio_context(bs);
540 
541         aio_context_acquire(aio_context);
542         bdrv_do_drained_end(bs, NULL);
543         aio_context_release(aio_context);
544     }
545 
546     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
547     assert(bdrv_drain_all_count > 0);
548     bdrv_drain_all_count--;
549 }
550 
551 void bdrv_drain_all(void)
552 {
553     GLOBAL_STATE_CODE();
554     bdrv_drain_all_begin();
555     bdrv_drain_all_end();
556 }
557 
558 /**
559  * Remove an active request from the tracked requests list
560  *
561  * This function should be called when a tracked request is completing.
562  */
563 static void coroutine_fn tracked_request_end(BdrvTrackedRequest *req)
564 {
565     if (req->serialising) {
566         qatomic_dec(&req->bs->serialising_in_flight);
567     }
568 
569     qemu_co_mutex_lock(&req->bs->reqs_lock);
570     QLIST_REMOVE(req, list);
571     qemu_co_queue_restart_all(&req->wait_queue);
572     qemu_co_mutex_unlock(&req->bs->reqs_lock);
573 }
574 
575 /**
576  * Add an active request to the tracked requests list
577  */
578 static void coroutine_fn tracked_request_begin(BdrvTrackedRequest *req,
579                                                BlockDriverState *bs,
580                                                int64_t offset,
581                                                int64_t bytes,
582                                                enum BdrvTrackedRequestType type)
583 {
584     bdrv_check_request(offset, bytes, &error_abort);
585 
586     *req = (BdrvTrackedRequest){
587         .bs = bs,
588         .offset         = offset,
589         .bytes          = bytes,
590         .type           = type,
591         .co             = qemu_coroutine_self(),
592         .serialising    = false,
593         .overlap_offset = offset,
594         .overlap_bytes  = bytes,
595     };
596 
597     qemu_co_queue_init(&req->wait_queue);
598 
599     qemu_co_mutex_lock(&bs->reqs_lock);
600     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
601     qemu_co_mutex_unlock(&bs->reqs_lock);
602 }
603 
604 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
605                                      int64_t offset, int64_t bytes)
606 {
607     bdrv_check_request(offset, bytes, &error_abort);
608 
609     /*        aaaa   bbbb */
610     if (offset >= req->overlap_offset + req->overlap_bytes) {
611         return false;
612     }
613     /* bbbb   aaaa        */
614     if (req->overlap_offset >= offset + bytes) {
615         return false;
616     }
617     return true;
618 }
619 
620 /* Called with self->bs->reqs_lock held */
621 static coroutine_fn BdrvTrackedRequest *
622 bdrv_find_conflicting_request(BdrvTrackedRequest *self)
623 {
624     BdrvTrackedRequest *req;
625 
626     QLIST_FOREACH(req, &self->bs->tracked_requests, list) {
627         if (req == self || (!req->serialising && !self->serialising)) {
628             continue;
629         }
630         if (tracked_request_overlaps(req, self->overlap_offset,
631                                      self->overlap_bytes))
632         {
633             /*
634              * Hitting this means there was a reentrant request, for
635              * example, a block driver issuing nested requests.  This must
636              * never happen since it means deadlock.
637              */
638             assert(qemu_coroutine_self() != req->co);
639 
640             /*
641              * If the request is already (indirectly) waiting for us, or
642              * will wait for us as soon as it wakes up, then just go on
643              * (instead of producing a deadlock in the former case).
644              */
645             if (!req->waiting_for) {
646                 return req;
647             }
648         }
649     }
650 
651     return NULL;
652 }
653 
654 /* Called with self->bs->reqs_lock held */
655 static void coroutine_fn
656 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest *self)
657 {
658     BdrvTrackedRequest *req;
659 
660     while ((req = bdrv_find_conflicting_request(self))) {
661         self->waiting_for = req;
662         qemu_co_queue_wait(&req->wait_queue, &self->bs->reqs_lock);
663         self->waiting_for = NULL;
664     }
665 }
666 
667 /* Called with req->bs->reqs_lock held */
668 static void tracked_request_set_serialising(BdrvTrackedRequest *req,
669                                             uint64_t align)
670 {
671     int64_t overlap_offset = req->offset & ~(align - 1);
672     int64_t overlap_bytes =
673         ROUND_UP(req->offset + req->bytes, align) - overlap_offset;
674 
675     bdrv_check_request(req->offset, req->bytes, &error_abort);
676 
677     if (!req->serialising) {
678         qatomic_inc(&req->bs->serialising_in_flight);
679         req->serialising = true;
680     }
681 
682     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
683     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
684 }
685 
686 /**
687  * Return the tracked request on @bs for the current coroutine, or
688  * NULL if there is none.
689  */
690 BdrvTrackedRequest *coroutine_fn bdrv_co_get_self_request(BlockDriverState *bs)
691 {
692     BdrvTrackedRequest *req;
693     Coroutine *self = qemu_coroutine_self();
694     IO_CODE();
695 
696     QLIST_FOREACH(req, &bs->tracked_requests, list) {
697         if (req->co == self) {
698             return req;
699         }
700     }
701 
702     return NULL;
703 }
704 
705 /**
706  * Round a region to cluster boundaries
707  */
708 void bdrv_round_to_clusters(BlockDriverState *bs,
709                             int64_t offset, int64_t bytes,
710                             int64_t *cluster_offset,
711                             int64_t *cluster_bytes)
712 {
713     BlockDriverInfo bdi;
714     IO_CODE();
715     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
716         *cluster_offset = offset;
717         *cluster_bytes = bytes;
718     } else {
719         int64_t c = bdi.cluster_size;
720         *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
721         *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
722     }
723 }
724 
725 static int bdrv_get_cluster_size(BlockDriverState *bs)
726 {
727     BlockDriverInfo bdi;
728     int ret;
729 
730     ret = bdrv_get_info(bs, &bdi);
731     if (ret < 0 || bdi.cluster_size == 0) {
732         return bs->bl.request_alignment;
733     } else {
734         return bdi.cluster_size;
735     }
736 }
737 
738 void bdrv_inc_in_flight(BlockDriverState *bs)
739 {
740     IO_CODE();
741     qatomic_inc(&bs->in_flight);
742 }
743 
744 void bdrv_wakeup(BlockDriverState *bs)
745 {
746     IO_CODE();
747     aio_wait_kick();
748 }
749 
750 void bdrv_dec_in_flight(BlockDriverState *bs)
751 {
752     IO_CODE();
753     qatomic_dec(&bs->in_flight);
754     bdrv_wakeup(bs);
755 }
756 
757 static void coroutine_fn
758 bdrv_wait_serialising_requests(BdrvTrackedRequest *self)
759 {
760     BlockDriverState *bs = self->bs;
761 
762     if (!qatomic_read(&bs->serialising_in_flight)) {
763         return;
764     }
765 
766     qemu_co_mutex_lock(&bs->reqs_lock);
767     bdrv_wait_serialising_requests_locked(self);
768     qemu_co_mutex_unlock(&bs->reqs_lock);
769 }
770 
771 void coroutine_fn bdrv_make_request_serialising(BdrvTrackedRequest *req,
772                                                 uint64_t align)
773 {
774     IO_CODE();
775 
776     qemu_co_mutex_lock(&req->bs->reqs_lock);
777 
778     tracked_request_set_serialising(req, align);
779     bdrv_wait_serialising_requests_locked(req);
780 
781     qemu_co_mutex_unlock(&req->bs->reqs_lock);
782 }
783 
784 int bdrv_check_qiov_request(int64_t offset, int64_t bytes,
785                             QEMUIOVector *qiov, size_t qiov_offset,
786                             Error **errp)
787 {
788     /*
789      * Check generic offset/bytes correctness
790      */
791 
792     if (offset < 0) {
793         error_setg(errp, "offset is negative: %" PRIi64, offset);
794         return -EIO;
795     }
796 
797     if (bytes < 0) {
798         error_setg(errp, "bytes is negative: %" PRIi64, bytes);
799         return -EIO;
800     }
801 
802     if (bytes > BDRV_MAX_LENGTH) {
803         error_setg(errp, "bytes(%" PRIi64 ") exceeds maximum(%" PRIi64 ")",
804                    bytes, BDRV_MAX_LENGTH);
805         return -EIO;
806     }
807 
808     if (offset > BDRV_MAX_LENGTH) {
809         error_setg(errp, "offset(%" PRIi64 ") exceeds maximum(%" PRIi64 ")",
810                    offset, BDRV_MAX_LENGTH);
811         return -EIO;
812     }
813 
814     if (offset > BDRV_MAX_LENGTH - bytes) {
815         error_setg(errp, "sum of offset(%" PRIi64 ") and bytes(%" PRIi64 ") "
816                    "exceeds maximum(%" PRIi64 ")", offset, bytes,
817                    BDRV_MAX_LENGTH);
818         return -EIO;
819     }
820 
821     if (!qiov) {
822         return 0;
823     }
824 
825     /*
826      * Check qiov and qiov_offset
827      */
828 
829     if (qiov_offset > qiov->size) {
830         error_setg(errp, "qiov_offset(%zu) overflow io vector size(%zu)",
831                    qiov_offset, qiov->size);
832         return -EIO;
833     }
834 
835     if (bytes > qiov->size - qiov_offset) {
836         error_setg(errp, "bytes(%" PRIi64 ") + qiov_offset(%zu) overflow io "
837                    "vector size(%zu)", bytes, qiov_offset, qiov->size);
838         return -EIO;
839     }
840 
841     return 0;
842 }
843 
844 int bdrv_check_request(int64_t offset, int64_t bytes, Error **errp)
845 {
846     return bdrv_check_qiov_request(offset, bytes, NULL, 0, errp);
847 }
848 
849 static int bdrv_check_request32(int64_t offset, int64_t bytes,
850                                 QEMUIOVector *qiov, size_t qiov_offset)
851 {
852     int ret = bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, NULL);
853     if (ret < 0) {
854         return ret;
855     }
856 
857     if (bytes > BDRV_REQUEST_MAX_BYTES) {
858         return -EIO;
859     }
860 
861     return 0;
862 }
863 
864 /*
865  * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
866  * The operation is sped up by checking the block status and only writing
867  * zeroes to the device if they currently do not return zeroes. Optional
868  * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
869  * BDRV_REQ_FUA).
870  *
871  * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
872  */
873 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
874 {
875     int ret;
876     int64_t target_size, bytes, offset = 0;
877     BlockDriverState *bs = child->bs;
878     IO_CODE();
879 
880     target_size = bdrv_getlength(bs);
881     if (target_size < 0) {
882         return target_size;
883     }
884 
885     for (;;) {
886         bytes = MIN(target_size - offset, BDRV_REQUEST_MAX_BYTES);
887         if (bytes <= 0) {
888             return 0;
889         }
890         ret = bdrv_block_status(bs, offset, bytes, &bytes, NULL, NULL);
891         if (ret < 0) {
892             return ret;
893         }
894         if (ret & BDRV_BLOCK_ZERO) {
895             offset += bytes;
896             continue;
897         }
898         ret = bdrv_pwrite_zeroes(child, offset, bytes, flags);
899         if (ret < 0) {
900             return ret;
901         }
902         offset += bytes;
903     }
904 }
905 
906 /*
907  * Writes to the file and ensures that no writes are reordered across this
908  * request (acts as a barrier)
909  *
910  * Returns 0 on success, -errno in error cases.
911  */
912 int coroutine_fn bdrv_co_pwrite_sync(BdrvChild *child, int64_t offset,
913                                      int64_t bytes, const void *buf,
914                                      BdrvRequestFlags flags)
915 {
916     int ret;
917     IO_CODE();
918 
919     ret = bdrv_co_pwrite(child, offset, bytes, buf, flags);
920     if (ret < 0) {
921         return ret;
922     }
923 
924     ret = bdrv_co_flush(child->bs);
925     if (ret < 0) {
926         return ret;
927     }
928 
929     return 0;
930 }
931 
932 typedef struct CoroutineIOCompletion {
933     Coroutine *coroutine;
934     int ret;
935 } CoroutineIOCompletion;
936 
937 static void bdrv_co_io_em_complete(void *opaque, int ret)
938 {
939     CoroutineIOCompletion *co = opaque;
940 
941     co->ret = ret;
942     aio_co_wake(co->coroutine);
943 }
944 
945 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
946                                            int64_t offset, int64_t bytes,
947                                            QEMUIOVector *qiov,
948                                            size_t qiov_offset, int flags)
949 {
950     BlockDriver *drv = bs->drv;
951     int64_t sector_num;
952     unsigned int nb_sectors;
953     QEMUIOVector local_qiov;
954     int ret;
955 
956     bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
957     assert(!(flags & ~bs->supported_read_flags));
958 
959     if (!drv) {
960         return -ENOMEDIUM;
961     }
962 
963     if (drv->bdrv_co_preadv_part) {
964         return drv->bdrv_co_preadv_part(bs, offset, bytes, qiov, qiov_offset,
965                                         flags);
966     }
967 
968     if (qiov_offset > 0 || bytes != qiov->size) {
969         qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
970         qiov = &local_qiov;
971     }
972 
973     if (drv->bdrv_co_preadv) {
974         ret = drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
975         goto out;
976     }
977 
978     if (drv->bdrv_aio_preadv) {
979         BlockAIOCB *acb;
980         CoroutineIOCompletion co = {
981             .coroutine = qemu_coroutine_self(),
982         };
983 
984         acb = drv->bdrv_aio_preadv(bs, offset, bytes, qiov, flags,
985                                    bdrv_co_io_em_complete, &co);
986         if (acb == NULL) {
987             ret = -EIO;
988             goto out;
989         } else {
990             qemu_coroutine_yield();
991             ret = co.ret;
992             goto out;
993         }
994     }
995 
996     sector_num = offset >> BDRV_SECTOR_BITS;
997     nb_sectors = bytes >> BDRV_SECTOR_BITS;
998 
999     assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1000     assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1001     assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1002     assert(drv->bdrv_co_readv);
1003 
1004     ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1005 
1006 out:
1007     if (qiov == &local_qiov) {
1008         qemu_iovec_destroy(&local_qiov);
1009     }
1010 
1011     return ret;
1012 }
1013 
1014 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
1015                                             int64_t offset, int64_t bytes,
1016                                             QEMUIOVector *qiov,
1017                                             size_t qiov_offset,
1018                                             BdrvRequestFlags flags)
1019 {
1020     BlockDriver *drv = bs->drv;
1021     bool emulate_fua = false;
1022     int64_t sector_num;
1023     unsigned int nb_sectors;
1024     QEMUIOVector local_qiov;
1025     int ret;
1026 
1027     bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1028 
1029     if (!drv) {
1030         return -ENOMEDIUM;
1031     }
1032 
1033     if ((flags & BDRV_REQ_FUA) &&
1034         (~bs->supported_write_flags & BDRV_REQ_FUA)) {
1035         flags &= ~BDRV_REQ_FUA;
1036         emulate_fua = true;
1037     }
1038 
1039     flags &= bs->supported_write_flags;
1040 
1041     if (drv->bdrv_co_pwritev_part) {
1042         ret = drv->bdrv_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset,
1043                                         flags);
1044         goto emulate_flags;
1045     }
1046 
1047     if (qiov_offset > 0 || bytes != qiov->size) {
1048         qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1049         qiov = &local_qiov;
1050     }
1051 
1052     if (drv->bdrv_co_pwritev) {
1053         ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov, flags);
1054         goto emulate_flags;
1055     }
1056 
1057     if (drv->bdrv_aio_pwritev) {
1058         BlockAIOCB *acb;
1059         CoroutineIOCompletion co = {
1060             .coroutine = qemu_coroutine_self(),
1061         };
1062 
1063         acb = drv->bdrv_aio_pwritev(bs, offset, bytes, qiov, flags,
1064                                     bdrv_co_io_em_complete, &co);
1065         if (acb == NULL) {
1066             ret = -EIO;
1067         } else {
1068             qemu_coroutine_yield();
1069             ret = co.ret;
1070         }
1071         goto emulate_flags;
1072     }
1073 
1074     sector_num = offset >> BDRV_SECTOR_BITS;
1075     nb_sectors = bytes >> BDRV_SECTOR_BITS;
1076 
1077     assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1078     assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1079     assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1080 
1081     assert(drv->bdrv_co_writev);
1082     ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov, flags);
1083 
1084 emulate_flags:
1085     if (ret == 0 && emulate_fua) {
1086         ret = bdrv_co_flush(bs);
1087     }
1088 
1089     if (qiov == &local_qiov) {
1090         qemu_iovec_destroy(&local_qiov);
1091     }
1092 
1093     return ret;
1094 }
1095 
1096 static int coroutine_fn
1097 bdrv_driver_pwritev_compressed(BlockDriverState *bs, int64_t offset,
1098                                int64_t bytes, QEMUIOVector *qiov,
1099                                size_t qiov_offset)
1100 {
1101     BlockDriver *drv = bs->drv;
1102     QEMUIOVector local_qiov;
1103     int ret;
1104 
1105     bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1106 
1107     if (!drv) {
1108         return -ENOMEDIUM;
1109     }
1110 
1111     if (!block_driver_can_compress(drv)) {
1112         return -ENOTSUP;
1113     }
1114 
1115     if (drv->bdrv_co_pwritev_compressed_part) {
1116         return drv->bdrv_co_pwritev_compressed_part(bs, offset, bytes,
1117                                                     qiov, qiov_offset);
1118     }
1119 
1120     if (qiov_offset == 0) {
1121         return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
1122     }
1123 
1124     qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1125     ret = drv->bdrv_co_pwritev_compressed(bs, offset, bytes, &local_qiov);
1126     qemu_iovec_destroy(&local_qiov);
1127 
1128     return ret;
1129 }
1130 
1131 static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
1132         int64_t offset, int64_t bytes, QEMUIOVector *qiov,
1133         size_t qiov_offset, int flags)
1134 {
1135     BlockDriverState *bs = child->bs;
1136 
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.
1141      */
1142     void *bounce_buffer = NULL;
1143 
1144     BlockDriver *drv = bs->drv;
1145     int64_t cluster_offset;
1146     int64_t cluster_bytes;
1147     int64_t skip_bytes;
1148     int ret;
1149     int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1150                                     BDRV_REQUEST_MAX_BYTES);
1151     int64_t progress = 0;
1152     bool skip_write;
1153 
1154     bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1155 
1156     if (!drv) {
1157         return -ENOMEDIUM;
1158     }
1159 
1160     /*
1161      * Do not write anything when the BDS is inactive.  That is not
1162      * allowed, and it would not help.
1163      */
1164     skip_write = (bs->open_flags & BDRV_O_INACTIVE);
1165 
1166     /* FIXME We cannot require callers to have write permissions when all they
1167      * are doing is a read request. If we did things right, write permissions
1168      * would be obtained anyway, but internally by the copy-on-read code. As
1169      * long as it is implemented here rather than in a separate filter driver,
1170      * the copy-on-read code doesn't have its own BdrvChild, however, for which
1171      * it could request permissions. Therefore we have to bypass the permission
1172      * system for the moment. */
1173     // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1174 
1175     /* Cover entire cluster so no additional backing file I/O is required when
1176      * allocating cluster in the image file.  Note that this value may exceed
1177      * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1178      * is one reason we loop rather than doing it all at once.
1179      */
1180     bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
1181     skip_bytes = offset - cluster_offset;
1182 
1183     trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
1184                                    cluster_offset, cluster_bytes);
1185 
1186     while (cluster_bytes) {
1187         int64_t pnum;
1188 
1189         if (skip_write) {
1190             ret = 1; /* "already allocated", so nothing will be copied */
1191             pnum = MIN(cluster_bytes, max_transfer);
1192         } else {
1193             ret = bdrv_is_allocated(bs, cluster_offset,
1194                                     MIN(cluster_bytes, max_transfer), &pnum);
1195             if (ret < 0) {
1196                 /*
1197                  * Safe to treat errors in querying allocation as if
1198                  * unallocated; we'll probably fail again soon on the
1199                  * read, but at least that will set a decent errno.
1200                  */
1201                 pnum = MIN(cluster_bytes, max_transfer);
1202             }
1203 
1204             /* Stop at EOF if the image ends in the middle of the cluster */
1205             if (ret == 0 && pnum == 0) {
1206                 assert(progress >= bytes);
1207                 break;
1208             }
1209 
1210             assert(skip_bytes < pnum);
1211         }
1212 
1213         if (ret <= 0) {
1214             QEMUIOVector local_qiov;
1215 
1216             /* Must copy-on-read; use the bounce buffer */
1217             pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1218             if (!bounce_buffer) {
1219                 int64_t max_we_need = MAX(pnum, cluster_bytes - pnum);
1220                 int64_t max_allowed = MIN(max_transfer, MAX_BOUNCE_BUFFER);
1221                 int64_t bounce_buffer_len = MIN(max_we_need, max_allowed);
1222 
1223                 bounce_buffer = qemu_try_blockalign(bs, bounce_buffer_len);
1224                 if (!bounce_buffer) {
1225                     ret = -ENOMEM;
1226                     goto err;
1227                 }
1228             }
1229             qemu_iovec_init_buf(&local_qiov, bounce_buffer, pnum);
1230 
1231             ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1232                                      &local_qiov, 0, 0);
1233             if (ret < 0) {
1234                 goto err;
1235             }
1236 
1237             bdrv_debug_event(bs, BLKDBG_COR_WRITE);
1238             if (drv->bdrv_co_pwrite_zeroes &&
1239                 buffer_is_zero(bounce_buffer, pnum)) {
1240                 /* FIXME: Should we (perhaps conditionally) be setting
1241                  * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1242                  * that still correctly reads as zero? */
1243                 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum,
1244                                                BDRV_REQ_WRITE_UNCHANGED);
1245             } else {
1246                 /* This does not change the data on the disk, it is not
1247                  * necessary to flush even in cache=writethrough mode.
1248                  */
1249                 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
1250                                           &local_qiov, 0,
1251                                           BDRV_REQ_WRITE_UNCHANGED);
1252             }
1253 
1254             if (ret < 0) {
1255                 /* It might be okay to ignore write errors for guest
1256                  * requests.  If this is a deliberate copy-on-read
1257                  * then we don't want to ignore the error.  Simply
1258                  * report it in all cases.
1259                  */
1260                 goto err;
1261             }
1262 
1263             if (!(flags & BDRV_REQ_PREFETCH)) {
1264                 qemu_iovec_from_buf(qiov, qiov_offset + progress,
1265                                     bounce_buffer + skip_bytes,
1266                                     MIN(pnum - skip_bytes, bytes - progress));
1267             }
1268         } else if (!(flags & BDRV_REQ_PREFETCH)) {
1269             /* Read directly into the destination */
1270             ret = bdrv_driver_preadv(bs, offset + progress,
1271                                      MIN(pnum - skip_bytes, bytes - progress),
1272                                      qiov, qiov_offset + progress, 0);
1273             if (ret < 0) {
1274                 goto err;
1275             }
1276         }
1277 
1278         cluster_offset += pnum;
1279         cluster_bytes -= pnum;
1280         progress += pnum - skip_bytes;
1281         skip_bytes = 0;
1282     }
1283     ret = 0;
1284 
1285 err:
1286     qemu_vfree(bounce_buffer);
1287     return ret;
1288 }
1289 
1290 /*
1291  * Forwards an already correctly aligned request to the BlockDriver. This
1292  * handles copy on read, zeroing after EOF, and fragmentation of large
1293  * reads; any other features must be implemented by the caller.
1294  */
1295 static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
1296     BdrvTrackedRequest *req, int64_t offset, int64_t bytes,
1297     int64_t align, QEMUIOVector *qiov, size_t qiov_offset, int flags)
1298 {
1299     BlockDriverState *bs = child->bs;
1300     int64_t total_bytes, max_bytes;
1301     int ret = 0;
1302     int64_t bytes_remaining = bytes;
1303     int max_transfer;
1304 
1305     bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1306     assert(is_power_of_2(align));
1307     assert((offset & (align - 1)) == 0);
1308     assert((bytes & (align - 1)) == 0);
1309     assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1310     max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1311                                    align);
1312 
1313     /*
1314      * TODO: We would need a per-BDS .supported_read_flags and
1315      * potential fallback support, if we ever implement any read flags
1316      * to pass through to drivers.  For now, there aren't any
1317      * passthrough flags except the BDRV_REQ_REGISTERED_BUF optimization hint.
1318      */
1319     assert(!(flags & ~(BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH |
1320                        BDRV_REQ_REGISTERED_BUF)));
1321 
1322     /* Handle Copy on Read and associated serialisation */
1323     if (flags & BDRV_REQ_COPY_ON_READ) {
1324         /* If we touch the same cluster it counts as an overlap.  This
1325          * guarantees that allocating writes will be serialized and not race
1326          * with each other for the same cluster.  For example, in copy-on-read
1327          * it ensures that the CoR read and write operations are atomic and
1328          * guest writes cannot interleave between them. */
1329         bdrv_make_request_serialising(req, bdrv_get_cluster_size(bs));
1330     } else {
1331         bdrv_wait_serialising_requests(req);
1332     }
1333 
1334     if (flags & BDRV_REQ_COPY_ON_READ) {
1335         int64_t pnum;
1336 
1337         /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1338         flags &= ~BDRV_REQ_COPY_ON_READ;
1339 
1340         ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
1341         if (ret < 0) {
1342             goto out;
1343         }
1344 
1345         if (!ret || pnum != bytes) {
1346             ret = bdrv_co_do_copy_on_readv(child, offset, bytes,
1347                                            qiov, qiov_offset, flags);
1348             goto out;
1349         } else if (flags & BDRV_REQ_PREFETCH) {
1350             goto out;
1351         }
1352     }
1353 
1354     /* Forward the request to the BlockDriver, possibly fragmenting it */
1355     total_bytes = bdrv_getlength(bs);
1356     if (total_bytes < 0) {
1357         ret = total_bytes;
1358         goto out;
1359     }
1360 
1361     assert(!(flags & ~(bs->supported_read_flags | BDRV_REQ_REGISTERED_BUF)));
1362 
1363     max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1364     if (bytes <= max_bytes && bytes <= max_transfer) {
1365         ret = bdrv_driver_preadv(bs, offset, bytes, qiov, qiov_offset, flags);
1366         goto out;
1367     }
1368 
1369     while (bytes_remaining) {
1370         int64_t num;
1371 
1372         if (max_bytes) {
1373             num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1374             assert(num);
1375 
1376             ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1377                                      num, qiov,
1378                                      qiov_offset + bytes - bytes_remaining,
1379                                      flags);
1380             max_bytes -= num;
1381         } else {
1382             num = bytes_remaining;
1383             ret = qemu_iovec_memset(qiov, qiov_offset + bytes - bytes_remaining,
1384                                     0, bytes_remaining);
1385         }
1386         if (ret < 0) {
1387             goto out;
1388         }
1389         bytes_remaining -= num;
1390     }
1391 
1392 out:
1393     return ret < 0 ? ret : 0;
1394 }
1395 
1396 /*
1397  * Request padding
1398  *
1399  *  |<---- align ----->|                     |<----- align ---->|
1400  *  |<- head ->|<------------- bytes ------------->|<-- tail -->|
1401  *  |          |       |                     |     |            |
1402  * -*----------$-------*-------- ... --------*-----$------------*---
1403  *  |          |       |                     |     |            |
1404  *  |          offset  |                     |     end          |
1405  *  ALIGN_DOWN(offset) ALIGN_UP(offset)      ALIGN_DOWN(end)   ALIGN_UP(end)
1406  *  [buf   ... )                             [tail_buf          )
1407  *
1408  * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1409  * is placed at the beginning of @buf and @tail at the @end.
1410  *
1411  * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1412  * around tail, if tail exists.
1413  *
1414  * @merge_reads is true for small requests,
1415  * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1416  * head and tail exist but @buf_len == align and @tail_buf == @buf.
1417  */
1418 typedef struct BdrvRequestPadding {
1419     uint8_t *buf;
1420     size_t buf_len;
1421     uint8_t *tail_buf;
1422     size_t head;
1423     size_t tail;
1424     bool merge_reads;
1425     QEMUIOVector local_qiov;
1426 } BdrvRequestPadding;
1427 
1428 static bool bdrv_init_padding(BlockDriverState *bs,
1429                               int64_t offset, int64_t bytes,
1430                               BdrvRequestPadding *pad)
1431 {
1432     int64_t align = bs->bl.request_alignment;
1433     int64_t sum;
1434 
1435     bdrv_check_request(offset, bytes, &error_abort);
1436     assert(align <= INT_MAX); /* documented in block/block_int.h */
1437     assert(align <= SIZE_MAX / 2); /* so we can allocate the buffer */
1438 
1439     memset(pad, 0, sizeof(*pad));
1440 
1441     pad->head = offset & (align - 1);
1442     pad->tail = ((offset + bytes) & (align - 1));
1443     if (pad->tail) {
1444         pad->tail = align - pad->tail;
1445     }
1446 
1447     if (!pad->head && !pad->tail) {
1448         return false;
1449     }
1450 
1451     assert(bytes); /* Nothing good in aligning zero-length requests */
1452 
1453     sum = pad->head + bytes + pad->tail;
1454     pad->buf_len = (sum > align && pad->head && pad->tail) ? 2 * align : align;
1455     pad->buf = qemu_blockalign(bs, pad->buf_len);
1456     pad->merge_reads = sum == pad->buf_len;
1457     if (pad->tail) {
1458         pad->tail_buf = pad->buf + pad->buf_len - align;
1459     }
1460 
1461     return true;
1462 }
1463 
1464 static coroutine_fn int bdrv_padding_rmw_read(BdrvChild *child,
1465                                               BdrvTrackedRequest *req,
1466                                               BdrvRequestPadding *pad,
1467                                               bool zero_middle)
1468 {
1469     QEMUIOVector local_qiov;
1470     BlockDriverState *bs = child->bs;
1471     uint64_t align = bs->bl.request_alignment;
1472     int ret;
1473 
1474     assert(req->serialising && pad->buf);
1475 
1476     if (pad->head || pad->merge_reads) {
1477         int64_t bytes = pad->merge_reads ? pad->buf_len : align;
1478 
1479         qemu_iovec_init_buf(&local_qiov, pad->buf, bytes);
1480 
1481         if (pad->head) {
1482             bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1483         }
1484         if (pad->merge_reads && pad->tail) {
1485             bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1486         }
1487         ret = bdrv_aligned_preadv(child, req, req->overlap_offset, bytes,
1488                                   align, &local_qiov, 0, 0);
1489         if (ret < 0) {
1490             return ret;
1491         }
1492         if (pad->head) {
1493             bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1494         }
1495         if (pad->merge_reads && pad->tail) {
1496             bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1497         }
1498 
1499         if (pad->merge_reads) {
1500             goto zero_mem;
1501         }
1502     }
1503 
1504     if (pad->tail) {
1505         qemu_iovec_init_buf(&local_qiov, pad->tail_buf, align);
1506 
1507         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1508         ret = bdrv_aligned_preadv(
1509                 child, req,
1510                 req->overlap_offset + req->overlap_bytes - align,
1511                 align, align, &local_qiov, 0, 0);
1512         if (ret < 0) {
1513             return ret;
1514         }
1515         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1516     }
1517 
1518 zero_mem:
1519     if (zero_middle) {
1520         memset(pad->buf + pad->head, 0, pad->buf_len - pad->head - pad->tail);
1521     }
1522 
1523     return 0;
1524 }
1525 
1526 static void bdrv_padding_destroy(BdrvRequestPadding *pad)
1527 {
1528     if (pad->buf) {
1529         qemu_vfree(pad->buf);
1530         qemu_iovec_destroy(&pad->local_qiov);
1531     }
1532     memset(pad, 0, sizeof(*pad));
1533 }
1534 
1535 /*
1536  * bdrv_pad_request
1537  *
1538  * Exchange request parameters with padded request if needed. Don't include RMW
1539  * read of padding, bdrv_padding_rmw_read() should be called separately if
1540  * needed.
1541  *
1542  * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1543  *  - on function start they represent original request
1544  *  - on failure or when padding is not needed they are unchanged
1545  *  - on success when padding is needed they represent padded request
1546  */
1547 static int bdrv_pad_request(BlockDriverState *bs,
1548                             QEMUIOVector **qiov, size_t *qiov_offset,
1549                             int64_t *offset, int64_t *bytes,
1550                             BdrvRequestPadding *pad, bool *padded,
1551                             BdrvRequestFlags *flags)
1552 {
1553     int ret;
1554 
1555     bdrv_check_qiov_request(*offset, *bytes, *qiov, *qiov_offset, &error_abort);
1556 
1557     if (!bdrv_init_padding(bs, *offset, *bytes, pad)) {
1558         if (padded) {
1559             *padded = false;
1560         }
1561         return 0;
1562     }
1563 
1564     ret = qemu_iovec_init_extended(&pad->local_qiov, pad->buf, pad->head,
1565                                    *qiov, *qiov_offset, *bytes,
1566                                    pad->buf + pad->buf_len - pad->tail,
1567                                    pad->tail);
1568     if (ret < 0) {
1569         bdrv_padding_destroy(pad);
1570         return ret;
1571     }
1572     *bytes += pad->head + pad->tail;
1573     *offset -= pad->head;
1574     *qiov = &pad->local_qiov;
1575     *qiov_offset = 0;
1576     if (padded) {
1577         *padded = true;
1578     }
1579     if (flags) {
1580         /* Can't use optimization hint with bounce buffer */
1581         *flags &= ~BDRV_REQ_REGISTERED_BUF;
1582     }
1583 
1584     return 0;
1585 }
1586 
1587 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1588     int64_t offset, int64_t bytes, QEMUIOVector *qiov,
1589     BdrvRequestFlags flags)
1590 {
1591     IO_CODE();
1592     return bdrv_co_preadv_part(child, offset, bytes, qiov, 0, flags);
1593 }
1594 
1595 int coroutine_fn bdrv_co_preadv_part(BdrvChild *child,
1596     int64_t offset, int64_t bytes,
1597     QEMUIOVector *qiov, size_t qiov_offset,
1598     BdrvRequestFlags flags)
1599 {
1600     BlockDriverState *bs = child->bs;
1601     BdrvTrackedRequest req;
1602     BdrvRequestPadding pad;
1603     int ret;
1604     IO_CODE();
1605 
1606     trace_bdrv_co_preadv_part(bs, offset, bytes, flags);
1607 
1608     if (!bdrv_is_inserted(bs)) {
1609         return -ENOMEDIUM;
1610     }
1611 
1612     ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
1613     if (ret < 0) {
1614         return ret;
1615     }
1616 
1617     if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
1618         /*
1619          * Aligning zero request is nonsense. Even if driver has special meaning
1620          * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1621          * it to driver due to request_alignment.
1622          *
1623          * Still, no reason to return an error if someone do unaligned
1624          * zero-length read occasionally.
1625          */
1626         return 0;
1627     }
1628 
1629     bdrv_inc_in_flight(bs);
1630 
1631     /* Don't do copy-on-read if we read data before write operation */
1632     if (qatomic_read(&bs->copy_on_read)) {
1633         flags |= BDRV_REQ_COPY_ON_READ;
1634     }
1635 
1636     ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
1637                            NULL, &flags);
1638     if (ret < 0) {
1639         goto fail;
1640     }
1641 
1642     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1643     ret = bdrv_aligned_preadv(child, &req, offset, bytes,
1644                               bs->bl.request_alignment,
1645                               qiov, qiov_offset, flags);
1646     tracked_request_end(&req);
1647     bdrv_padding_destroy(&pad);
1648 
1649 fail:
1650     bdrv_dec_in_flight(bs);
1651 
1652     return ret;
1653 }
1654 
1655 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1656     int64_t offset, int64_t bytes, BdrvRequestFlags flags)
1657 {
1658     BlockDriver *drv = bs->drv;
1659     QEMUIOVector qiov;
1660     void *buf = NULL;
1661     int ret = 0;
1662     bool need_flush = false;
1663     int head = 0;
1664     int tail = 0;
1665 
1666     int64_t max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes,
1667                                             INT64_MAX);
1668     int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1669                         bs->bl.request_alignment);
1670     int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
1671 
1672     bdrv_check_request(offset, bytes, &error_abort);
1673 
1674     if (!drv) {
1675         return -ENOMEDIUM;
1676     }
1677 
1678     if ((flags & ~bs->supported_zero_flags) & BDRV_REQ_NO_FALLBACK) {
1679         return -ENOTSUP;
1680     }
1681 
1682     /* By definition there is no user buffer so this flag doesn't make sense */
1683     if (flags & BDRV_REQ_REGISTERED_BUF) {
1684         return -EINVAL;
1685     }
1686 
1687     /* Invalidate the cached block-status data range if this write overlaps */
1688     bdrv_bsc_invalidate_range(bs, offset, bytes);
1689 
1690     assert(alignment % bs->bl.request_alignment == 0);
1691     head = offset % alignment;
1692     tail = (offset + bytes) % alignment;
1693     max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1694     assert(max_write_zeroes >= bs->bl.request_alignment);
1695 
1696     while (bytes > 0 && !ret) {
1697         int64_t num = bytes;
1698 
1699         /* Align request.  Block drivers can expect the "bulk" of the request
1700          * to be aligned, and that unaligned requests do not cross cluster
1701          * boundaries.
1702          */
1703         if (head) {
1704             /* Make a small request up to the first aligned sector. For
1705              * convenience, limit this request to max_transfer even if
1706              * we don't need to fall back to writes.  */
1707             num = MIN(MIN(bytes, max_transfer), alignment - head);
1708             head = (head + num) % alignment;
1709             assert(num < max_write_zeroes);
1710         } else if (tail && num > alignment) {
1711             /* Shorten the request to the last aligned sector.  */
1712             num -= tail;
1713         }
1714 
1715         /* limit request size */
1716         if (num > max_write_zeroes) {
1717             num = max_write_zeroes;
1718         }
1719 
1720         ret = -ENOTSUP;
1721         /* First try the efficient write zeroes operation */
1722         if (drv->bdrv_co_pwrite_zeroes) {
1723             ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1724                                              flags & bs->supported_zero_flags);
1725             if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1726                 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1727                 need_flush = true;
1728             }
1729         } else {
1730             assert(!bs->supported_zero_flags);
1731         }
1732 
1733         if (ret == -ENOTSUP && !(flags & BDRV_REQ_NO_FALLBACK)) {
1734             /* Fall back to bounce buffer if write zeroes is unsupported */
1735             BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1736 
1737             if ((flags & BDRV_REQ_FUA) &&
1738                 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1739                 /* No need for bdrv_driver_pwrite() to do a fallback
1740                  * flush on each chunk; use just one at the end */
1741                 write_flags &= ~BDRV_REQ_FUA;
1742                 need_flush = true;
1743             }
1744             num = MIN(num, max_transfer);
1745             if (buf == NULL) {
1746                 buf = qemu_try_blockalign0(bs, num);
1747                 if (buf == NULL) {
1748                     ret = -ENOMEM;
1749                     goto fail;
1750                 }
1751             }
1752             qemu_iovec_init_buf(&qiov, buf, num);
1753 
1754             ret = bdrv_driver_pwritev(bs, offset, num, &qiov, 0, write_flags);
1755 
1756             /* Keep bounce buffer around if it is big enough for all
1757              * all future requests.
1758              */
1759             if (num < max_transfer) {
1760                 qemu_vfree(buf);
1761                 buf = NULL;
1762             }
1763         }
1764 
1765         offset += num;
1766         bytes -= num;
1767     }
1768 
1769 fail:
1770     if (ret == 0 && need_flush) {
1771         ret = bdrv_co_flush(bs);
1772     }
1773     qemu_vfree(buf);
1774     return ret;
1775 }
1776 
1777 static inline int coroutine_fn
1778 bdrv_co_write_req_prepare(BdrvChild *child, int64_t offset, int64_t bytes,
1779                           BdrvTrackedRequest *req, int flags)
1780 {
1781     BlockDriverState *bs = child->bs;
1782 
1783     bdrv_check_request(offset, bytes, &error_abort);
1784 
1785     if (bdrv_is_read_only(bs)) {
1786         return -EPERM;
1787     }
1788 
1789     assert(!(bs->open_flags & BDRV_O_INACTIVE));
1790     assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1791     assert(!(flags & ~BDRV_REQ_MASK));
1792     assert(!((flags & BDRV_REQ_NO_WAIT) && !(flags & BDRV_REQ_SERIALISING)));
1793 
1794     if (flags & BDRV_REQ_SERIALISING) {
1795         QEMU_LOCK_GUARD(&bs->reqs_lock);
1796 
1797         tracked_request_set_serialising(req, bdrv_get_cluster_size(bs));
1798 
1799         if ((flags & BDRV_REQ_NO_WAIT) && bdrv_find_conflicting_request(req)) {
1800             return -EBUSY;
1801         }
1802 
1803         bdrv_wait_serialising_requests_locked(req);
1804     } else {
1805         bdrv_wait_serialising_requests(req);
1806     }
1807 
1808     assert(req->overlap_offset <= offset);
1809     assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1810     assert(offset + bytes <= bs->total_sectors * BDRV_SECTOR_SIZE ||
1811            child->perm & BLK_PERM_RESIZE);
1812 
1813     switch (req->type) {
1814     case BDRV_TRACKED_WRITE:
1815     case BDRV_TRACKED_DISCARD:
1816         if (flags & BDRV_REQ_WRITE_UNCHANGED) {
1817             assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1818         } else {
1819             assert(child->perm & BLK_PERM_WRITE);
1820         }
1821         bdrv_write_threshold_check_write(bs, offset, bytes);
1822         return 0;
1823     case BDRV_TRACKED_TRUNCATE:
1824         assert(child->perm & BLK_PERM_RESIZE);
1825         return 0;
1826     default:
1827         abort();
1828     }
1829 }
1830 
1831 static inline void coroutine_fn
1832 bdrv_co_write_req_finish(BdrvChild *child, int64_t offset, int64_t bytes,
1833                          BdrvTrackedRequest *req, int ret)
1834 {
1835     int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1836     BlockDriverState *bs = child->bs;
1837 
1838     bdrv_check_request(offset, bytes, &error_abort);
1839 
1840     qatomic_inc(&bs->write_gen);
1841 
1842     /*
1843      * Discard cannot extend the image, but in error handling cases, such as
1844      * when reverting a qcow2 cluster allocation, the discarded range can pass
1845      * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1846      * here. Instead, just skip it, since semantically a discard request
1847      * beyond EOF cannot expand the image anyway.
1848      */
1849     if (ret == 0 &&
1850         (req->type == BDRV_TRACKED_TRUNCATE ||
1851          end_sector > bs->total_sectors) &&
1852         req->type != BDRV_TRACKED_DISCARD) {
1853         bs->total_sectors = end_sector;
1854         bdrv_parent_cb_resize(bs);
1855         bdrv_dirty_bitmap_truncate(bs, end_sector << BDRV_SECTOR_BITS);
1856     }
1857     if (req->bytes) {
1858         switch (req->type) {
1859         case BDRV_TRACKED_WRITE:
1860             stat64_max(&bs->wr_highest_offset, offset + bytes);
1861             /* fall through, to set dirty bits */
1862         case BDRV_TRACKED_DISCARD:
1863             bdrv_set_dirty(bs, offset, bytes);
1864             break;
1865         default:
1866             break;
1867         }
1868     }
1869 }
1870 
1871 /*
1872  * Forwards an already correctly aligned write request to the BlockDriver,
1873  * after possibly fragmenting it.
1874  */
1875 static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
1876     BdrvTrackedRequest *req, int64_t offset, int64_t bytes,
1877     int64_t align, QEMUIOVector *qiov, size_t qiov_offset,
1878     BdrvRequestFlags flags)
1879 {
1880     BlockDriverState *bs = child->bs;
1881     BlockDriver *drv = bs->drv;
1882     int ret;
1883 
1884     int64_t bytes_remaining = bytes;
1885     int max_transfer;
1886 
1887     bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1888 
1889     if (!drv) {
1890         return -ENOMEDIUM;
1891     }
1892 
1893     if (bdrv_has_readonly_bitmaps(bs)) {
1894         return -EPERM;
1895     }
1896 
1897     assert(is_power_of_2(align));
1898     assert((offset & (align - 1)) == 0);
1899     assert((bytes & (align - 1)) == 0);
1900     max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1901                                    align);
1902 
1903     ret = bdrv_co_write_req_prepare(child, offset, bytes, req, flags);
1904 
1905     if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1906         !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
1907         qemu_iovec_is_zero(qiov, qiov_offset, bytes)) {
1908         flags |= BDRV_REQ_ZERO_WRITE;
1909         if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1910             flags |= BDRV_REQ_MAY_UNMAP;
1911         }
1912     }
1913 
1914     if (ret < 0) {
1915         /* Do nothing, write notifier decided to fail this request */
1916     } else if (flags & BDRV_REQ_ZERO_WRITE) {
1917         bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
1918         ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
1919     } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
1920         ret = bdrv_driver_pwritev_compressed(bs, offset, bytes,
1921                                              qiov, qiov_offset);
1922     } else if (bytes <= max_transfer) {
1923         bdrv_debug_event(bs, BLKDBG_PWRITEV);
1924         ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, qiov_offset, flags);
1925     } else {
1926         bdrv_debug_event(bs, BLKDBG_PWRITEV);
1927         while (bytes_remaining) {
1928             int num = MIN(bytes_remaining, max_transfer);
1929             int local_flags = flags;
1930 
1931             assert(num);
1932             if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
1933                 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1934                 /* If FUA is going to be emulated by flush, we only
1935                  * need to flush on the last iteration */
1936                 local_flags &= ~BDRV_REQ_FUA;
1937             }
1938 
1939             ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
1940                                       num, qiov,
1941                                       qiov_offset + bytes - bytes_remaining,
1942                                       local_flags);
1943             if (ret < 0) {
1944                 break;
1945             }
1946             bytes_remaining -= num;
1947         }
1948     }
1949     bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
1950 
1951     if (ret >= 0) {
1952         ret = 0;
1953     }
1954     bdrv_co_write_req_finish(child, offset, bytes, req, ret);
1955 
1956     return ret;
1957 }
1958 
1959 static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
1960                                                 int64_t offset,
1961                                                 int64_t bytes,
1962                                                 BdrvRequestFlags flags,
1963                                                 BdrvTrackedRequest *req)
1964 {
1965     BlockDriverState *bs = child->bs;
1966     QEMUIOVector local_qiov;
1967     uint64_t align = bs->bl.request_alignment;
1968     int ret = 0;
1969     bool padding;
1970     BdrvRequestPadding pad;
1971 
1972     /* This flag doesn't make sense for padding or zero writes */
1973     flags &= ~BDRV_REQ_REGISTERED_BUF;
1974 
1975     padding = bdrv_init_padding(bs, offset, bytes, &pad);
1976     if (padding) {
1977         assert(!(flags & BDRV_REQ_NO_WAIT));
1978         bdrv_make_request_serialising(req, align);
1979 
1980         bdrv_padding_rmw_read(child, req, &pad, true);
1981 
1982         if (pad.head || pad.merge_reads) {
1983             int64_t aligned_offset = offset & ~(align - 1);
1984             int64_t write_bytes = pad.merge_reads ? pad.buf_len : align;
1985 
1986             qemu_iovec_init_buf(&local_qiov, pad.buf, write_bytes);
1987             ret = bdrv_aligned_pwritev(child, req, aligned_offset, write_bytes,
1988                                        align, &local_qiov, 0,
1989                                        flags & ~BDRV_REQ_ZERO_WRITE);
1990             if (ret < 0 || pad.merge_reads) {
1991                 /* Error or all work is done */
1992                 goto out;
1993             }
1994             offset += write_bytes - pad.head;
1995             bytes -= write_bytes - pad.head;
1996         }
1997     }
1998 
1999     assert(!bytes || (offset & (align - 1)) == 0);
2000     if (bytes >= align) {
2001         /* Write the aligned part in the middle. */
2002         int64_t aligned_bytes = bytes & ~(align - 1);
2003         ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
2004                                    NULL, 0, flags);
2005         if (ret < 0) {
2006             goto out;
2007         }
2008         bytes -= aligned_bytes;
2009         offset += aligned_bytes;
2010     }
2011 
2012     assert(!bytes || (offset & (align - 1)) == 0);
2013     if (bytes) {
2014         assert(align == pad.tail + bytes);
2015 
2016         qemu_iovec_init_buf(&local_qiov, pad.tail_buf, align);
2017         ret = bdrv_aligned_pwritev(child, req, offset, align, align,
2018                                    &local_qiov, 0,
2019                                    flags & ~BDRV_REQ_ZERO_WRITE);
2020     }
2021 
2022 out:
2023     bdrv_padding_destroy(&pad);
2024 
2025     return ret;
2026 }
2027 
2028 /*
2029  * Handle a write request in coroutine context
2030  */
2031 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
2032     int64_t offset, int64_t bytes, QEMUIOVector *qiov,
2033     BdrvRequestFlags flags)
2034 {
2035     IO_CODE();
2036     return bdrv_co_pwritev_part(child, offset, bytes, qiov, 0, flags);
2037 }
2038 
2039 int coroutine_fn bdrv_co_pwritev_part(BdrvChild *child,
2040     int64_t offset, int64_t bytes, QEMUIOVector *qiov, size_t qiov_offset,
2041     BdrvRequestFlags flags)
2042 {
2043     BlockDriverState *bs = child->bs;
2044     BdrvTrackedRequest req;
2045     uint64_t align = bs->bl.request_alignment;
2046     BdrvRequestPadding pad;
2047     int ret;
2048     bool padded = false;
2049     IO_CODE();
2050 
2051     trace_bdrv_co_pwritev_part(child->bs, offset, bytes, flags);
2052 
2053     if (!bdrv_is_inserted(bs)) {
2054         return -ENOMEDIUM;
2055     }
2056 
2057     if (flags & BDRV_REQ_ZERO_WRITE) {
2058         ret = bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, NULL);
2059     } else {
2060         ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
2061     }
2062     if (ret < 0) {
2063         return ret;
2064     }
2065 
2066     /* If the request is misaligned then we can't make it efficient */
2067     if ((flags & BDRV_REQ_NO_FALLBACK) &&
2068         !QEMU_IS_ALIGNED(offset | bytes, align))
2069     {
2070         return -ENOTSUP;
2071     }
2072 
2073     if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
2074         /*
2075          * Aligning zero request is nonsense. Even if driver has special meaning
2076          * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2077          * it to driver due to request_alignment.
2078          *
2079          * Still, no reason to return an error if someone do unaligned
2080          * zero-length write occasionally.
2081          */
2082         return 0;
2083     }
2084 
2085     if (!(flags & BDRV_REQ_ZERO_WRITE)) {
2086         /*
2087          * Pad request for following read-modify-write cycle.
2088          * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2089          * alignment only if there is no ZERO flag.
2090          */
2091         ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
2092                                &padded, &flags);
2093         if (ret < 0) {
2094             return ret;
2095         }
2096     }
2097 
2098     bdrv_inc_in_flight(bs);
2099     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
2100 
2101     if (flags & BDRV_REQ_ZERO_WRITE) {
2102         assert(!padded);
2103         ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
2104         goto out;
2105     }
2106 
2107     if (padded) {
2108         /*
2109          * Request was unaligned to request_alignment and therefore
2110          * padded.  We are going to do read-modify-write, and must
2111          * serialize the request to prevent interactions of the
2112          * widened region with other transactions.
2113          */
2114         assert(!(flags & BDRV_REQ_NO_WAIT));
2115         bdrv_make_request_serialising(&req, align);
2116         bdrv_padding_rmw_read(child, &req, &pad, false);
2117     }
2118 
2119     ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
2120                                qiov, qiov_offset, flags);
2121 
2122     bdrv_padding_destroy(&pad);
2123 
2124 out:
2125     tracked_request_end(&req);
2126     bdrv_dec_in_flight(bs);
2127 
2128     return ret;
2129 }
2130 
2131 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
2132                                        int64_t bytes, BdrvRequestFlags flags)
2133 {
2134     IO_CODE();
2135     trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
2136 
2137     if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
2138         flags &= ~BDRV_REQ_MAY_UNMAP;
2139     }
2140 
2141     return bdrv_co_pwritev(child, offset, bytes, NULL,
2142                            BDRV_REQ_ZERO_WRITE | flags);
2143 }
2144 
2145 /*
2146  * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2147  */
2148 int bdrv_flush_all(void)
2149 {
2150     BdrvNextIterator it;
2151     BlockDriverState *bs = NULL;
2152     int result = 0;
2153 
2154     GLOBAL_STATE_CODE();
2155 
2156     /*
2157      * bdrv queue is managed by record/replay,
2158      * creating new flush request for stopping
2159      * the VM may break the determinism
2160      */
2161     if (replay_events_enabled()) {
2162         return result;
2163     }
2164 
2165     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
2166         AioContext *aio_context = bdrv_get_aio_context(bs);
2167         int ret;
2168 
2169         aio_context_acquire(aio_context);
2170         ret = bdrv_flush(bs);
2171         if (ret < 0 && !result) {
2172             result = ret;
2173         }
2174         aio_context_release(aio_context);
2175     }
2176 
2177     return result;
2178 }
2179 
2180 /*
2181  * Returns the allocation status of the specified sectors.
2182  * Drivers not implementing the functionality are assumed to not support
2183  * backing files, hence all their sectors are reported as allocated.
2184  *
2185  * If 'want_zero' is true, the caller is querying for mapping
2186  * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2187  * _ZERO where possible; otherwise, the result favors larger 'pnum',
2188  * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2189  *
2190  * If 'offset' is beyond the end of the disk image the return value is
2191  * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2192  *
2193  * 'bytes' is the max value 'pnum' should be set to.  If bytes goes
2194  * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2195  * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2196  *
2197  * 'pnum' is set to the number of bytes (including and immediately
2198  * following the specified offset) that are easily known to be in the
2199  * same allocated/unallocated state.  Note that a second call starting
2200  * at the original offset plus returned pnum may have the same status.
2201  * The returned value is non-zero on success except at end-of-file.
2202  *
2203  * Returns negative errno on failure.  Otherwise, if the
2204  * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2205  * set to the host mapping and BDS corresponding to the guest offset.
2206  */
2207 static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
2208                                              bool want_zero,
2209                                              int64_t offset, int64_t bytes,
2210                                              int64_t *pnum, int64_t *map,
2211                                              BlockDriverState **file)
2212 {
2213     int64_t total_size;
2214     int64_t n; /* bytes */
2215     int ret;
2216     int64_t local_map = 0;
2217     BlockDriverState *local_file = NULL;
2218     int64_t aligned_offset, aligned_bytes;
2219     uint32_t align;
2220     bool has_filtered_child;
2221 
2222     assert(pnum);
2223     *pnum = 0;
2224     total_size = bdrv_getlength(bs);
2225     if (total_size < 0) {
2226         ret = total_size;
2227         goto early_out;
2228     }
2229 
2230     if (offset >= total_size) {
2231         ret = BDRV_BLOCK_EOF;
2232         goto early_out;
2233     }
2234     if (!bytes) {
2235         ret = 0;
2236         goto early_out;
2237     }
2238 
2239     n = total_size - offset;
2240     if (n < bytes) {
2241         bytes = n;
2242     }
2243 
2244     /* Must be non-NULL or bdrv_getlength() would have failed */
2245     assert(bs->drv);
2246     has_filtered_child = bdrv_filter_child(bs);
2247     if (!bs->drv->bdrv_co_block_status && !has_filtered_child) {
2248         *pnum = bytes;
2249         ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2250         if (offset + bytes == total_size) {
2251             ret |= BDRV_BLOCK_EOF;
2252         }
2253         if (bs->drv->protocol_name) {
2254             ret |= BDRV_BLOCK_OFFSET_VALID;
2255             local_map = offset;
2256             local_file = bs;
2257         }
2258         goto early_out;
2259     }
2260 
2261     bdrv_inc_in_flight(bs);
2262 
2263     /* Round out to request_alignment boundaries */
2264     align = bs->bl.request_alignment;
2265     aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2266     aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2267 
2268     if (bs->drv->bdrv_co_block_status) {
2269         /*
2270          * Use the block-status cache only for protocol nodes: Format
2271          * drivers are generally quick to inquire the status, but protocol
2272          * drivers often need to get information from outside of qemu, so
2273          * we do not have control over the actual implementation.  There
2274          * have been cases where inquiring the status took an unreasonably
2275          * long time, and we can do nothing in qemu to fix it.
2276          * This is especially problematic for images with large data areas,
2277          * because finding the few holes in them and giving them special
2278          * treatment does not gain much performance.  Therefore, we try to
2279          * cache the last-identified data region.
2280          *
2281          * Second, limiting ourselves to protocol nodes allows us to assume
2282          * the block status for data regions to be DATA | OFFSET_VALID, and
2283          * that the host offset is the same as the guest offset.
2284          *
2285          * Note that it is possible that external writers zero parts of
2286          * the cached regions without the cache being invalidated, and so
2287          * we may report zeroes as data.  This is not catastrophic,
2288          * however, because reporting zeroes as data is fine.
2289          */
2290         if (QLIST_EMPTY(&bs->children) &&
2291             bdrv_bsc_is_data(bs, aligned_offset, pnum))
2292         {
2293             ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2294             local_file = bs;
2295             local_map = aligned_offset;
2296         } else {
2297             ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2298                                                 aligned_bytes, pnum, &local_map,
2299                                                 &local_file);
2300 
2301             /*
2302              * Note that checking QLIST_EMPTY(&bs->children) is also done when
2303              * the cache is queried above.  Technically, we do not need to check
2304              * it here; the worst that can happen is that we fill the cache for
2305              * non-protocol nodes, and then it is never used.  However, filling
2306              * the cache requires an RCU update, so double check here to avoid
2307              * such an update if possible.
2308              *
2309              * Check want_zero, because we only want to update the cache when we
2310              * have accurate information about what is zero and what is data.
2311              */
2312             if (want_zero &&
2313                 ret == (BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID) &&
2314                 QLIST_EMPTY(&bs->children))
2315             {
2316                 /*
2317                  * When a protocol driver reports BLOCK_OFFSET_VALID, the
2318                  * returned local_map value must be the same as the offset we
2319                  * have passed (aligned_offset), and local_bs must be the node
2320                  * itself.
2321                  * Assert this, because we follow this rule when reading from
2322                  * the cache (see the `local_file = bs` and
2323                  * `local_map = aligned_offset` assignments above), and the
2324                  * result the cache delivers must be the same as the driver
2325                  * would deliver.
2326                  */
2327                 assert(local_file == bs);
2328                 assert(local_map == aligned_offset);
2329                 bdrv_bsc_fill(bs, aligned_offset, *pnum);
2330             }
2331         }
2332     } else {
2333         /* Default code for filters */
2334 
2335         local_file = bdrv_filter_bs(bs);
2336         assert(local_file);
2337 
2338         *pnum = aligned_bytes;
2339         local_map = aligned_offset;
2340         ret = BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2341     }
2342     if (ret < 0) {
2343         *pnum = 0;
2344         goto out;
2345     }
2346 
2347     /*
2348      * The driver's result must be a non-zero multiple of request_alignment.
2349      * Clamp pnum and adjust map to original request.
2350      */
2351     assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2352            align > offset - aligned_offset);
2353     if (ret & BDRV_BLOCK_RECURSE) {
2354         assert(ret & BDRV_BLOCK_DATA);
2355         assert(ret & BDRV_BLOCK_OFFSET_VALID);
2356         assert(!(ret & BDRV_BLOCK_ZERO));
2357     }
2358 
2359     *pnum -= offset - aligned_offset;
2360     if (*pnum > bytes) {
2361         *pnum = bytes;
2362     }
2363     if (ret & BDRV_BLOCK_OFFSET_VALID) {
2364         local_map += offset - aligned_offset;
2365     }
2366 
2367     if (ret & BDRV_BLOCK_RAW) {
2368         assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2369         ret = bdrv_co_block_status(local_file, want_zero, local_map,
2370                                    *pnum, pnum, &local_map, &local_file);
2371         goto out;
2372     }
2373 
2374     if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2375         ret |= BDRV_BLOCK_ALLOCATED;
2376     } else if (bs->drv->supports_backing) {
2377         BlockDriverState *cow_bs = bdrv_cow_bs(bs);
2378 
2379         if (!cow_bs) {
2380             ret |= BDRV_BLOCK_ZERO;
2381         } else if (want_zero) {
2382             int64_t size2 = bdrv_getlength(cow_bs);
2383 
2384             if (size2 >= 0 && offset >= size2) {
2385                 ret |= BDRV_BLOCK_ZERO;
2386             }
2387         }
2388     }
2389 
2390     if (want_zero && ret & BDRV_BLOCK_RECURSE &&
2391         local_file && local_file != bs &&
2392         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2393         (ret & BDRV_BLOCK_OFFSET_VALID)) {
2394         int64_t file_pnum;
2395         int ret2;
2396 
2397         ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2398                                     *pnum, &file_pnum, NULL, NULL);
2399         if (ret2 >= 0) {
2400             /* Ignore errors.  This is just providing extra information, it
2401              * is useful but not necessary.
2402              */
2403             if (ret2 & BDRV_BLOCK_EOF &&
2404                 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2405                 /*
2406                  * It is valid for the format block driver to read
2407                  * beyond the end of the underlying file's current
2408                  * size; such areas read as zero.
2409                  */
2410                 ret |= BDRV_BLOCK_ZERO;
2411             } else {
2412                 /* Limit request to the range reported by the protocol driver */
2413                 *pnum = file_pnum;
2414                 ret |= (ret2 & BDRV_BLOCK_ZERO);
2415             }
2416         }
2417     }
2418 
2419 out:
2420     bdrv_dec_in_flight(bs);
2421     if (ret >= 0 && offset + *pnum == total_size) {
2422         ret |= BDRV_BLOCK_EOF;
2423     }
2424 early_out:
2425     if (file) {
2426         *file = local_file;
2427     }
2428     if (map) {
2429         *map = local_map;
2430     }
2431     return ret;
2432 }
2433 
2434 int coroutine_fn
2435 bdrv_co_common_block_status_above(BlockDriverState *bs,
2436                                   BlockDriverState *base,
2437                                   bool include_base,
2438                                   bool want_zero,
2439                                   int64_t offset,
2440                                   int64_t bytes,
2441                                   int64_t *pnum,
2442                                   int64_t *map,
2443                                   BlockDriverState **file,
2444                                   int *depth)
2445 {
2446     int ret;
2447     BlockDriverState *p;
2448     int64_t eof = 0;
2449     int dummy;
2450     IO_CODE();
2451 
2452     assert(!include_base || base); /* Can't include NULL base */
2453 
2454     if (!depth) {
2455         depth = &dummy;
2456     }
2457     *depth = 0;
2458 
2459     if (!include_base && bs == base) {
2460         *pnum = bytes;
2461         return 0;
2462     }
2463 
2464     ret = bdrv_co_block_status(bs, want_zero, offset, bytes, pnum, map, file);
2465     ++*depth;
2466     if (ret < 0 || *pnum == 0 || ret & BDRV_BLOCK_ALLOCATED || bs == base) {
2467         return ret;
2468     }
2469 
2470     if (ret & BDRV_BLOCK_EOF) {
2471         eof = offset + *pnum;
2472     }
2473 
2474     assert(*pnum <= bytes);
2475     bytes = *pnum;
2476 
2477     for (p = bdrv_filter_or_cow_bs(bs); include_base || p != base;
2478          p = bdrv_filter_or_cow_bs(p))
2479     {
2480         ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2481                                    file);
2482         ++*depth;
2483         if (ret < 0) {
2484             return ret;
2485         }
2486         if (*pnum == 0) {
2487             /*
2488              * The top layer deferred to this layer, and because this layer is
2489              * short, any zeroes that we synthesize beyond EOF behave as if they
2490              * were allocated at this layer.
2491              *
2492              * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2493              * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2494              * below.
2495              */
2496             assert(ret & BDRV_BLOCK_EOF);
2497             *pnum = bytes;
2498             if (file) {
2499                 *file = p;
2500             }
2501             ret = BDRV_BLOCK_ZERO | BDRV_BLOCK_ALLOCATED;
2502             break;
2503         }
2504         if (ret & BDRV_BLOCK_ALLOCATED) {
2505             /*
2506              * We've found the node and the status, we must break.
2507              *
2508              * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2509              * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2510              * below.
2511              */
2512             ret &= ~BDRV_BLOCK_EOF;
2513             break;
2514         }
2515 
2516         if (p == base) {
2517             assert(include_base);
2518             break;
2519         }
2520 
2521         /*
2522          * OK, [offset, offset + *pnum) region is unallocated on this layer,
2523          * let's continue the diving.
2524          */
2525         assert(*pnum <= bytes);
2526         bytes = *pnum;
2527     }
2528 
2529     if (offset + *pnum == eof) {
2530         ret |= BDRV_BLOCK_EOF;
2531     }
2532 
2533     return ret;
2534 }
2535 
2536 int coroutine_fn bdrv_co_block_status_above(BlockDriverState *bs,
2537                                             BlockDriverState *base,
2538                                             int64_t offset, int64_t bytes,
2539                                             int64_t *pnum, int64_t *map,
2540                                             BlockDriverState **file)
2541 {
2542     IO_CODE();
2543     return bdrv_co_common_block_status_above(bs, base, false, true, offset,
2544                                              bytes, pnum, map, file, NULL);
2545 }
2546 
2547 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2548                             int64_t offset, int64_t bytes, int64_t *pnum,
2549                             int64_t *map, BlockDriverState **file)
2550 {
2551     IO_CODE();
2552     return bdrv_common_block_status_above(bs, base, false, true, offset, bytes,
2553                                           pnum, map, file, NULL);
2554 }
2555 
2556 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2557                       int64_t *pnum, int64_t *map, BlockDriverState **file)
2558 {
2559     IO_CODE();
2560     return bdrv_block_status_above(bs, bdrv_filter_or_cow_bs(bs),
2561                                    offset, bytes, pnum, map, file);
2562 }
2563 
2564 /*
2565  * Check @bs (and its backing chain) to see if the range defined
2566  * by @offset and @bytes is known to read as zeroes.
2567  * Return 1 if that is the case, 0 otherwise and -errno on error.
2568  * This test is meant to be fast rather than accurate so returning 0
2569  * does not guarantee non-zero data.
2570  */
2571 int coroutine_fn bdrv_co_is_zero_fast(BlockDriverState *bs, int64_t offset,
2572                                       int64_t bytes)
2573 {
2574     int ret;
2575     int64_t pnum = bytes;
2576     IO_CODE();
2577 
2578     if (!bytes) {
2579         return 1;
2580     }
2581 
2582     ret = bdrv_co_common_block_status_above(bs, NULL, false, false, offset,
2583                                             bytes, &pnum, NULL, NULL, NULL);
2584 
2585     if (ret < 0) {
2586         return ret;
2587     }
2588 
2589     return (pnum == bytes) && (ret & BDRV_BLOCK_ZERO);
2590 }
2591 
2592 int coroutine_fn bdrv_co_is_allocated(BlockDriverState *bs, int64_t offset,
2593                                       int64_t bytes, int64_t *pnum)
2594 {
2595     int ret;
2596     int64_t dummy;
2597     IO_CODE();
2598 
2599     ret = bdrv_co_common_block_status_above(bs, bs, true, false, offset,
2600                                             bytes, pnum ? pnum : &dummy, NULL,
2601                                             NULL, NULL);
2602     if (ret < 0) {
2603         return ret;
2604     }
2605     return !!(ret & BDRV_BLOCK_ALLOCATED);
2606 }
2607 
2608 int bdrv_is_allocated(BlockDriverState *bs, int64_t offset, int64_t bytes,
2609                       int64_t *pnum)
2610 {
2611     int ret;
2612     int64_t dummy;
2613     IO_CODE();
2614 
2615     ret = bdrv_common_block_status_above(bs, bs, true, false, offset,
2616                                          bytes, pnum ? pnum : &dummy, NULL,
2617                                          NULL, NULL);
2618     if (ret < 0) {
2619         return ret;
2620     }
2621     return !!(ret & BDRV_BLOCK_ALLOCATED);
2622 }
2623 
2624 /* See bdrv_is_allocated_above for documentation */
2625 int coroutine_fn bdrv_co_is_allocated_above(BlockDriverState *top,
2626                                             BlockDriverState *base,
2627                                             bool include_base, int64_t offset,
2628                                             int64_t bytes, int64_t *pnum)
2629 {
2630     int depth;
2631     int ret;
2632     IO_CODE();
2633 
2634     ret = bdrv_co_common_block_status_above(top, base, include_base, false,
2635                                             offset, bytes, pnum, NULL, NULL,
2636                                             &depth);
2637     if (ret < 0) {
2638         return ret;
2639     }
2640 
2641     if (ret & BDRV_BLOCK_ALLOCATED) {
2642         return depth;
2643     }
2644     return 0;
2645 }
2646 
2647 /*
2648  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2649  *
2650  * Return a positive depth if (a prefix of) the given range is allocated
2651  * in any image between BASE and TOP (BASE is only included if include_base
2652  * is set).  Depth 1 is TOP, 2 is the first backing layer, and so forth.
2653  * BASE can be NULL to check if the given offset is allocated in any
2654  * image of the chain.  Return 0 otherwise, or negative errno on
2655  * failure.
2656  *
2657  * 'pnum' is set to the number of bytes (including and immediately
2658  * following the specified offset) that are known to be in the same
2659  * allocated/unallocated state.  Note that a subsequent call starting
2660  * at 'offset + *pnum' may return the same allocation status (in other
2661  * words, the result is not necessarily the maximum possible range);
2662  * but 'pnum' will only be 0 when end of file is reached.
2663  */
2664 int bdrv_is_allocated_above(BlockDriverState *top,
2665                             BlockDriverState *base,
2666                             bool include_base, int64_t offset,
2667                             int64_t bytes, int64_t *pnum)
2668 {
2669     int depth;
2670     int ret;
2671     IO_CODE();
2672 
2673     ret = bdrv_common_block_status_above(top, base, include_base, false,
2674                                          offset, bytes, pnum, NULL, NULL,
2675                                          &depth);
2676     if (ret < 0) {
2677         return ret;
2678     }
2679 
2680     if (ret & BDRV_BLOCK_ALLOCATED) {
2681         return depth;
2682     }
2683     return 0;
2684 }
2685 
2686 int coroutine_fn
2687 bdrv_co_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2688 {
2689     BlockDriver *drv = bs->drv;
2690     BlockDriverState *child_bs = bdrv_primary_bs(bs);
2691     int ret;
2692     IO_CODE();
2693 
2694     ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2695     if (ret < 0) {
2696         return ret;
2697     }
2698 
2699     if (!drv) {
2700         return -ENOMEDIUM;
2701     }
2702 
2703     bdrv_inc_in_flight(bs);
2704 
2705     if (drv->bdrv_load_vmstate) {
2706         ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2707     } else if (child_bs) {
2708         ret = bdrv_co_readv_vmstate(child_bs, qiov, pos);
2709     } else {
2710         ret = -ENOTSUP;
2711     }
2712 
2713     bdrv_dec_in_flight(bs);
2714 
2715     return ret;
2716 }
2717 
2718 int coroutine_fn
2719 bdrv_co_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2720 {
2721     BlockDriver *drv = bs->drv;
2722     BlockDriverState *child_bs = bdrv_primary_bs(bs);
2723     int ret;
2724     IO_CODE();
2725 
2726     ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2727     if (ret < 0) {
2728         return ret;
2729     }
2730 
2731     if (!drv) {
2732         return -ENOMEDIUM;
2733     }
2734 
2735     bdrv_inc_in_flight(bs);
2736 
2737     if (drv->bdrv_save_vmstate) {
2738         ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2739     } else if (child_bs) {
2740         ret = bdrv_co_writev_vmstate(child_bs, qiov, pos);
2741     } else {
2742         ret = -ENOTSUP;
2743     }
2744 
2745     bdrv_dec_in_flight(bs);
2746 
2747     return ret;
2748 }
2749 
2750 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2751                       int64_t pos, int size)
2752 {
2753     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2754     int ret = bdrv_writev_vmstate(bs, &qiov, pos);
2755     IO_CODE();
2756 
2757     return ret < 0 ? ret : size;
2758 }
2759 
2760 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2761                       int64_t pos, int size)
2762 {
2763     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2764     int ret = bdrv_readv_vmstate(bs, &qiov, pos);
2765     IO_CODE();
2766 
2767     return ret < 0 ? ret : size;
2768 }
2769 
2770 /**************************************************************/
2771 /* async I/Os */
2772 
2773 void bdrv_aio_cancel(BlockAIOCB *acb)
2774 {
2775     IO_CODE();
2776     qemu_aio_ref(acb);
2777     bdrv_aio_cancel_async(acb);
2778     while (acb->refcnt > 1) {
2779         if (acb->aiocb_info->get_aio_context) {
2780             aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2781         } else if (acb->bs) {
2782             /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2783              * assert that we're not using an I/O thread.  Thread-safe
2784              * code should use bdrv_aio_cancel_async exclusively.
2785              */
2786             assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2787             aio_poll(bdrv_get_aio_context(acb->bs), true);
2788         } else {
2789             abort();
2790         }
2791     }
2792     qemu_aio_unref(acb);
2793 }
2794 
2795 /* Async version of aio cancel. The caller is not blocked if the acb implements
2796  * cancel_async, otherwise we do nothing and let the request normally complete.
2797  * In either case the completion callback must be called. */
2798 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2799 {
2800     IO_CODE();
2801     if (acb->aiocb_info->cancel_async) {
2802         acb->aiocb_info->cancel_async(acb);
2803     }
2804 }
2805 
2806 /**************************************************************/
2807 /* Coroutine block device emulation */
2808 
2809 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2810 {
2811     BdrvChild *primary_child = bdrv_primary_child(bs);
2812     BdrvChild *child;
2813     int current_gen;
2814     int ret = 0;
2815     IO_CODE();
2816 
2817     bdrv_inc_in_flight(bs);
2818 
2819     if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2820         bdrv_is_sg(bs)) {
2821         goto early_exit;
2822     }
2823 
2824     qemu_co_mutex_lock(&bs->reqs_lock);
2825     current_gen = qatomic_read(&bs->write_gen);
2826 
2827     /* Wait until any previous flushes are completed */
2828     while (bs->active_flush_req) {
2829         qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
2830     }
2831 
2832     /* Flushes reach this point in nondecreasing current_gen order.  */
2833     bs->active_flush_req = true;
2834     qemu_co_mutex_unlock(&bs->reqs_lock);
2835 
2836     /* Write back all layers by calling one driver function */
2837     if (bs->drv->bdrv_co_flush) {
2838         ret = bs->drv->bdrv_co_flush(bs);
2839         goto out;
2840     }
2841 
2842     /* Write back cached data to the OS even with cache=unsafe */
2843     BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_OS);
2844     if (bs->drv->bdrv_co_flush_to_os) {
2845         ret = bs->drv->bdrv_co_flush_to_os(bs);
2846         if (ret < 0) {
2847             goto out;
2848         }
2849     }
2850 
2851     /* But don't actually force it to the disk with cache=unsafe */
2852     if (bs->open_flags & BDRV_O_NO_FLUSH) {
2853         goto flush_children;
2854     }
2855 
2856     /* Check if we really need to flush anything */
2857     if (bs->flushed_gen == current_gen) {
2858         goto flush_children;
2859     }
2860 
2861     BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_DISK);
2862     if (!bs->drv) {
2863         /* bs->drv->bdrv_co_flush() might have ejected the BDS
2864          * (even in case of apparent success) */
2865         ret = -ENOMEDIUM;
2866         goto out;
2867     }
2868     if (bs->drv->bdrv_co_flush_to_disk) {
2869         ret = bs->drv->bdrv_co_flush_to_disk(bs);
2870     } else if (bs->drv->bdrv_aio_flush) {
2871         BlockAIOCB *acb;
2872         CoroutineIOCompletion co = {
2873             .coroutine = qemu_coroutine_self(),
2874         };
2875 
2876         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2877         if (acb == NULL) {
2878             ret = -EIO;
2879         } else {
2880             qemu_coroutine_yield();
2881             ret = co.ret;
2882         }
2883     } else {
2884         /*
2885          * Some block drivers always operate in either writethrough or unsafe
2886          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2887          * know how the server works (because the behaviour is hardcoded or
2888          * depends on server-side configuration), so we can't ensure that
2889          * everything is safe on disk. Returning an error doesn't work because
2890          * that would break guests even if the server operates in writethrough
2891          * mode.
2892          *
2893          * Let's hope the user knows what he's doing.
2894          */
2895         ret = 0;
2896     }
2897 
2898     if (ret < 0) {
2899         goto out;
2900     }
2901 
2902     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
2903      * in the case of cache=unsafe, so there are no useless flushes.
2904      */
2905 flush_children:
2906     ret = 0;
2907     QLIST_FOREACH(child, &bs->children, next) {
2908         if (child->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2909             int this_child_ret = bdrv_co_flush(child->bs);
2910             if (!ret) {
2911                 ret = this_child_ret;
2912             }
2913         }
2914     }
2915 
2916 out:
2917     /* Notify any pending flushes that we have completed */
2918     if (ret == 0) {
2919         bs->flushed_gen = current_gen;
2920     }
2921 
2922     qemu_co_mutex_lock(&bs->reqs_lock);
2923     bs->active_flush_req = false;
2924     /* Return value is ignored - it's ok if wait queue is empty */
2925     qemu_co_queue_next(&bs->flush_queue);
2926     qemu_co_mutex_unlock(&bs->reqs_lock);
2927 
2928 early_exit:
2929     bdrv_dec_in_flight(bs);
2930     return ret;
2931 }
2932 
2933 int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset,
2934                                   int64_t bytes)
2935 {
2936     BdrvTrackedRequest req;
2937     int ret;
2938     int64_t max_pdiscard;
2939     int head, tail, align;
2940     BlockDriverState *bs = child->bs;
2941     IO_CODE();
2942 
2943     if (!bs || !bs->drv || !bdrv_is_inserted(bs)) {
2944         return -ENOMEDIUM;
2945     }
2946 
2947     if (bdrv_has_readonly_bitmaps(bs)) {
2948         return -EPERM;
2949     }
2950 
2951     ret = bdrv_check_request(offset, bytes, NULL);
2952     if (ret < 0) {
2953         return ret;
2954     }
2955 
2956     /* Do nothing if disabled.  */
2957     if (!(bs->open_flags & BDRV_O_UNMAP)) {
2958         return 0;
2959     }
2960 
2961     if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
2962         return 0;
2963     }
2964 
2965     /* Invalidate the cached block-status data range if this discard overlaps */
2966     bdrv_bsc_invalidate_range(bs, offset, bytes);
2967 
2968     /* Discard is advisory, but some devices track and coalesce
2969      * unaligned requests, so we must pass everything down rather than
2970      * round here.  Still, most devices will just silently ignore
2971      * unaligned requests (by returning -ENOTSUP), so we must fragment
2972      * the request accordingly.  */
2973     align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
2974     assert(align % bs->bl.request_alignment == 0);
2975     head = offset % align;
2976     tail = (offset + bytes) % align;
2977 
2978     bdrv_inc_in_flight(bs);
2979     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
2980 
2981     ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
2982     if (ret < 0) {
2983         goto out;
2984     }
2985 
2986     max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT64_MAX),
2987                                    align);
2988     assert(max_pdiscard >= bs->bl.request_alignment);
2989 
2990     while (bytes > 0) {
2991         int64_t num = bytes;
2992 
2993         if (head) {
2994             /* Make small requests to get to alignment boundaries. */
2995             num = MIN(bytes, align - head);
2996             if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
2997                 num %= bs->bl.request_alignment;
2998             }
2999             head = (head + num) % align;
3000             assert(num < max_pdiscard);
3001         } else if (tail) {
3002             if (num > align) {
3003                 /* Shorten the request to the last aligned cluster.  */
3004                 num -= tail;
3005             } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
3006                        tail > bs->bl.request_alignment) {
3007                 tail %= bs->bl.request_alignment;
3008                 num -= tail;
3009             }
3010         }
3011         /* limit request size */
3012         if (num > max_pdiscard) {
3013             num = max_pdiscard;
3014         }
3015 
3016         if (!bs->drv) {
3017             ret = -ENOMEDIUM;
3018             goto out;
3019         }
3020         if (bs->drv->bdrv_co_pdiscard) {
3021             ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
3022         } else {
3023             BlockAIOCB *acb;
3024             CoroutineIOCompletion co = {
3025                 .coroutine = qemu_coroutine_self(),
3026             };
3027 
3028             acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
3029                                              bdrv_co_io_em_complete, &co);
3030             if (acb == NULL) {
3031                 ret = -EIO;
3032                 goto out;
3033             } else {
3034                 qemu_coroutine_yield();
3035                 ret = co.ret;
3036             }
3037         }
3038         if (ret && ret != -ENOTSUP) {
3039             goto out;
3040         }
3041 
3042         offset += num;
3043         bytes -= num;
3044     }
3045     ret = 0;
3046 out:
3047     bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
3048     tracked_request_end(&req);
3049     bdrv_dec_in_flight(bs);
3050     return ret;
3051 }
3052 
3053 int coroutine_fn bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
3054 {
3055     BlockDriver *drv = bs->drv;
3056     CoroutineIOCompletion co = {
3057         .coroutine = qemu_coroutine_self(),
3058     };
3059     BlockAIOCB *acb;
3060     IO_CODE();
3061 
3062     bdrv_inc_in_flight(bs);
3063     if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
3064         co.ret = -ENOTSUP;
3065         goto out;
3066     }
3067 
3068     if (drv->bdrv_co_ioctl) {
3069         co.ret = drv->bdrv_co_ioctl(bs, req, buf);
3070     } else {
3071         acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
3072         if (!acb) {
3073             co.ret = -ENOTSUP;
3074             goto out;
3075         }
3076         qemu_coroutine_yield();
3077     }
3078 out:
3079     bdrv_dec_in_flight(bs);
3080     return co.ret;
3081 }
3082 
3083 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3084 {
3085     IO_CODE();
3086     return qemu_memalign(bdrv_opt_mem_align(bs), size);
3087 }
3088 
3089 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
3090 {
3091     IO_CODE();
3092     return memset(qemu_blockalign(bs, size), 0, size);
3093 }
3094 
3095 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
3096 {
3097     size_t align = bdrv_opt_mem_align(bs);
3098     IO_CODE();
3099 
3100     /* Ensure that NULL is never returned on success */
3101     assert(align > 0);
3102     if (size == 0) {
3103         size = align;
3104     }
3105 
3106     return qemu_try_memalign(align, size);
3107 }
3108 
3109 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
3110 {
3111     void *mem = qemu_try_blockalign(bs, size);
3112     IO_CODE();
3113 
3114     if (mem) {
3115         memset(mem, 0, size);
3116     }
3117 
3118     return mem;
3119 }
3120 
3121 void bdrv_io_plug(BlockDriverState *bs)
3122 {
3123     BdrvChild *child;
3124     IO_CODE();
3125 
3126     QLIST_FOREACH(child, &bs->children, next) {
3127         bdrv_io_plug(child->bs);
3128     }
3129 
3130     if (qatomic_fetch_inc(&bs->io_plugged) == 0) {
3131         BlockDriver *drv = bs->drv;
3132         if (drv && drv->bdrv_io_plug) {
3133             drv->bdrv_io_plug(bs);
3134         }
3135     }
3136 }
3137 
3138 void bdrv_io_unplug(BlockDriverState *bs)
3139 {
3140     BdrvChild *child;
3141     IO_CODE();
3142 
3143     assert(bs->io_plugged);
3144     if (qatomic_fetch_dec(&bs->io_plugged) == 1) {
3145         BlockDriver *drv = bs->drv;
3146         if (drv && drv->bdrv_io_unplug) {
3147             drv->bdrv_io_unplug(bs);
3148         }
3149     }
3150 
3151     QLIST_FOREACH(child, &bs->children, next) {
3152         bdrv_io_unplug(child->bs);
3153     }
3154 }
3155 
3156 /* Helper that undoes bdrv_register_buf() when it fails partway through */
3157 static void bdrv_register_buf_rollback(BlockDriverState *bs,
3158                                        void *host,
3159                                        size_t size,
3160                                        BdrvChild *final_child)
3161 {
3162     BdrvChild *child;
3163 
3164     QLIST_FOREACH(child, &bs->children, next) {
3165         if (child == final_child) {
3166             break;
3167         }
3168 
3169         bdrv_unregister_buf(child->bs, host, size);
3170     }
3171 
3172     if (bs->drv && bs->drv->bdrv_unregister_buf) {
3173         bs->drv->bdrv_unregister_buf(bs, host, size);
3174     }
3175 }
3176 
3177 bool bdrv_register_buf(BlockDriverState *bs, void *host, size_t size,
3178                        Error **errp)
3179 {
3180     BdrvChild *child;
3181 
3182     GLOBAL_STATE_CODE();
3183     if (bs->drv && bs->drv->bdrv_register_buf) {
3184         if (!bs->drv->bdrv_register_buf(bs, host, size, errp)) {
3185             return false;
3186         }
3187     }
3188     QLIST_FOREACH(child, &bs->children, next) {
3189         if (!bdrv_register_buf(child->bs, host, size, errp)) {
3190             bdrv_register_buf_rollback(bs, host, size, child);
3191             return false;
3192         }
3193     }
3194     return true;
3195 }
3196 
3197 void bdrv_unregister_buf(BlockDriverState *bs, void *host, size_t size)
3198 {
3199     BdrvChild *child;
3200 
3201     GLOBAL_STATE_CODE();
3202     if (bs->drv && bs->drv->bdrv_unregister_buf) {
3203         bs->drv->bdrv_unregister_buf(bs, host, size);
3204     }
3205     QLIST_FOREACH(child, &bs->children, next) {
3206         bdrv_unregister_buf(child->bs, host, size);
3207     }
3208 }
3209 
3210 static int coroutine_fn bdrv_co_copy_range_internal(
3211         BdrvChild *src, int64_t src_offset, BdrvChild *dst,
3212         int64_t dst_offset, int64_t bytes,
3213         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
3214         bool recurse_src)
3215 {
3216     BdrvTrackedRequest req;
3217     int ret;
3218 
3219     /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3220     assert(!(read_flags & BDRV_REQ_NO_FALLBACK));
3221     assert(!(write_flags & BDRV_REQ_NO_FALLBACK));
3222     assert(!(read_flags & BDRV_REQ_NO_WAIT));
3223     assert(!(write_flags & BDRV_REQ_NO_WAIT));
3224 
3225     if (!dst || !dst->bs || !bdrv_is_inserted(dst->bs)) {
3226         return -ENOMEDIUM;
3227     }
3228     ret = bdrv_check_request32(dst_offset, bytes, NULL, 0);
3229     if (ret) {
3230         return ret;
3231     }
3232     if (write_flags & BDRV_REQ_ZERO_WRITE) {
3233         return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
3234     }
3235 
3236     if (!src || !src->bs || !bdrv_is_inserted(src->bs)) {
3237         return -ENOMEDIUM;
3238     }
3239     ret = bdrv_check_request32(src_offset, bytes, NULL, 0);
3240     if (ret) {
3241         return ret;
3242     }
3243 
3244     if (!src->bs->drv->bdrv_co_copy_range_from
3245         || !dst->bs->drv->bdrv_co_copy_range_to
3246         || src->bs->encrypted || dst->bs->encrypted) {
3247         return -ENOTSUP;
3248     }
3249 
3250     if (recurse_src) {
3251         bdrv_inc_in_flight(src->bs);
3252         tracked_request_begin(&req, src->bs, src_offset, bytes,
3253                               BDRV_TRACKED_READ);
3254 
3255         /* BDRV_REQ_SERIALISING is only for write operation */
3256         assert(!(read_flags & BDRV_REQ_SERIALISING));
3257         bdrv_wait_serialising_requests(&req);
3258 
3259         ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
3260                                                     src, src_offset,
3261                                                     dst, dst_offset,
3262                                                     bytes,
3263                                                     read_flags, write_flags);
3264 
3265         tracked_request_end(&req);
3266         bdrv_dec_in_flight(src->bs);
3267     } else {
3268         bdrv_inc_in_flight(dst->bs);
3269         tracked_request_begin(&req, dst->bs, dst_offset, bytes,
3270                               BDRV_TRACKED_WRITE);
3271         ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3272                                         write_flags);
3273         if (!ret) {
3274             ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3275                                                       src, src_offset,
3276                                                       dst, dst_offset,
3277                                                       bytes,
3278                                                       read_flags, write_flags);
3279         }
3280         bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
3281         tracked_request_end(&req);
3282         bdrv_dec_in_flight(dst->bs);
3283     }
3284 
3285     return ret;
3286 }
3287 
3288 /* Copy range from @src to @dst.
3289  *
3290  * See the comment of bdrv_co_copy_range for the parameter and return value
3291  * semantics. */
3292 int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
3293                                          BdrvChild *dst, int64_t dst_offset,
3294                                          int64_t bytes,
3295                                          BdrvRequestFlags read_flags,
3296                                          BdrvRequestFlags write_flags)
3297 {
3298     IO_CODE();
3299     trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3300                                   read_flags, write_flags);
3301     return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3302                                        bytes, read_flags, write_flags, true);
3303 }
3304 
3305 /* Copy range from @src to @dst.
3306  *
3307  * See the comment of bdrv_co_copy_range for the parameter and return value
3308  * semantics. */
3309 int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
3310                                        BdrvChild *dst, int64_t dst_offset,
3311                                        int64_t bytes,
3312                                        BdrvRequestFlags read_flags,
3313                                        BdrvRequestFlags write_flags)
3314 {
3315     IO_CODE();
3316     trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3317                                 read_flags, write_flags);
3318     return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3319                                        bytes, read_flags, write_flags, false);
3320 }
3321 
3322 int coroutine_fn bdrv_co_copy_range(BdrvChild *src, int64_t src_offset,
3323                                     BdrvChild *dst, int64_t dst_offset,
3324                                     int64_t bytes, BdrvRequestFlags read_flags,
3325                                     BdrvRequestFlags write_flags)
3326 {
3327     IO_CODE();
3328     return bdrv_co_copy_range_from(src, src_offset,
3329                                    dst, dst_offset,
3330                                    bytes, read_flags, write_flags);
3331 }
3332 
3333 static void bdrv_parent_cb_resize(BlockDriverState *bs)
3334 {
3335     BdrvChild *c;
3336     QLIST_FOREACH(c, &bs->parents, next_parent) {
3337         if (c->klass->resize) {
3338             c->klass->resize(c);
3339         }
3340     }
3341 }
3342 
3343 /**
3344  * Truncate file to 'offset' bytes (needed only for file protocols)
3345  *
3346  * If 'exact' is true, the file must be resized to exactly the given
3347  * 'offset'.  Otherwise, it is sufficient for the node to be at least
3348  * 'offset' bytes in length.
3349  */
3350 int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset, bool exact,
3351                                   PreallocMode prealloc, BdrvRequestFlags flags,
3352                                   Error **errp)
3353 {
3354     BlockDriverState *bs = child->bs;
3355     BdrvChild *filtered, *backing;
3356     BlockDriver *drv = bs->drv;
3357     BdrvTrackedRequest req;
3358     int64_t old_size, new_bytes;
3359     int ret;
3360     IO_CODE();
3361 
3362     /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3363     if (!drv) {
3364         error_setg(errp, "No medium inserted");
3365         return -ENOMEDIUM;
3366     }
3367     if (offset < 0) {
3368         error_setg(errp, "Image size cannot be negative");
3369         return -EINVAL;
3370     }
3371 
3372     ret = bdrv_check_request(offset, 0, errp);
3373     if (ret < 0) {
3374         return ret;
3375     }
3376 
3377     old_size = bdrv_getlength(bs);
3378     if (old_size < 0) {
3379         error_setg_errno(errp, -old_size, "Failed to get old image size");
3380         return old_size;
3381     }
3382 
3383     if (bdrv_is_read_only(bs)) {
3384         error_setg(errp, "Image is read-only");
3385         return -EACCES;
3386     }
3387 
3388     if (offset > old_size) {
3389         new_bytes = offset - old_size;
3390     } else {
3391         new_bytes = 0;
3392     }
3393 
3394     bdrv_inc_in_flight(bs);
3395     tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3396                           BDRV_TRACKED_TRUNCATE);
3397 
3398     /* If we are growing the image and potentially using preallocation for the
3399      * new area, we need to make sure that no write requests are made to it
3400      * concurrently or they might be overwritten by preallocation. */
3401     if (new_bytes) {
3402         bdrv_make_request_serialising(&req, 1);
3403     }
3404     ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3405                                     0);
3406     if (ret < 0) {
3407         error_setg_errno(errp, -ret,
3408                          "Failed to prepare request for truncation");
3409         goto out;
3410     }
3411 
3412     filtered = bdrv_filter_child(bs);
3413     backing = bdrv_cow_child(bs);
3414 
3415     /*
3416      * If the image has a backing file that is large enough that it would
3417      * provide data for the new area, we cannot leave it unallocated because
3418      * then the backing file content would become visible. Instead, zero-fill
3419      * the new area.
3420      *
3421      * Note that if the image has a backing file, but was opened without the
3422      * backing file, taking care of keeping things consistent with that backing
3423      * file is the user's responsibility.
3424      */
3425     if (new_bytes && backing) {
3426         int64_t backing_len;
3427 
3428         backing_len = bdrv_getlength(backing->bs);
3429         if (backing_len < 0) {
3430             ret = backing_len;
3431             error_setg_errno(errp, -ret, "Could not get backing file size");
3432             goto out;
3433         }
3434 
3435         if (backing_len > old_size) {
3436             flags |= BDRV_REQ_ZERO_WRITE;
3437         }
3438     }
3439 
3440     if (drv->bdrv_co_truncate) {
3441         if (flags & ~bs->supported_truncate_flags) {
3442             error_setg(errp, "Block driver does not support requested flags");
3443             ret = -ENOTSUP;
3444             goto out;
3445         }
3446         ret = drv->bdrv_co_truncate(bs, offset, exact, prealloc, flags, errp);
3447     } else if (filtered) {
3448         ret = bdrv_co_truncate(filtered, offset, exact, prealloc, flags, errp);
3449     } else {
3450         error_setg(errp, "Image format driver does not support resize");
3451         ret = -ENOTSUP;
3452         goto out;
3453     }
3454     if (ret < 0) {
3455         goto out;
3456     }
3457 
3458     ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3459     if (ret < 0) {
3460         error_setg_errno(errp, -ret, "Could not refresh total sector count");
3461     } else {
3462         offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3463     }
3464     /* It's possible that truncation succeeded but refresh_total_sectors
3465      * failed, but the latter doesn't affect how we should finish the request.
3466      * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3467     bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3468 
3469 out:
3470     tracked_request_end(&req);
3471     bdrv_dec_in_flight(bs);
3472 
3473     return ret;
3474 }
3475 
3476 void bdrv_cancel_in_flight(BlockDriverState *bs)
3477 {
3478     GLOBAL_STATE_CODE();
3479     if (!bs || !bs->drv) {
3480         return;
3481     }
3482 
3483     if (bs->drv->bdrv_cancel_in_flight) {
3484         bs->drv->bdrv_cancel_in_flight(bs);
3485     }
3486 }
3487 
3488 int coroutine_fn
3489 bdrv_co_preadv_snapshot(BdrvChild *child, int64_t offset, int64_t bytes,
3490                         QEMUIOVector *qiov, size_t qiov_offset)
3491 {
3492     BlockDriverState *bs = child->bs;
3493     BlockDriver *drv = bs->drv;
3494     int ret;
3495     IO_CODE();
3496 
3497     if (!drv) {
3498         return -ENOMEDIUM;
3499     }
3500 
3501     if (!drv->bdrv_co_preadv_snapshot) {
3502         return -ENOTSUP;
3503     }
3504 
3505     bdrv_inc_in_flight(bs);
3506     ret = drv->bdrv_co_preadv_snapshot(bs, offset, bytes, qiov, qiov_offset);
3507     bdrv_dec_in_flight(bs);
3508 
3509     return ret;
3510 }
3511 
3512 int coroutine_fn
3513 bdrv_co_snapshot_block_status(BlockDriverState *bs,
3514                               bool want_zero, int64_t offset, int64_t bytes,
3515                               int64_t *pnum, int64_t *map,
3516                               BlockDriverState **file)
3517 {
3518     BlockDriver *drv = bs->drv;
3519     int ret;
3520     IO_CODE();
3521 
3522     if (!drv) {
3523         return -ENOMEDIUM;
3524     }
3525 
3526     if (!drv->bdrv_co_snapshot_block_status) {
3527         return -ENOTSUP;
3528     }
3529 
3530     bdrv_inc_in_flight(bs);
3531     ret = drv->bdrv_co_snapshot_block_status(bs, want_zero, offset, bytes,
3532                                              pnum, map, file);
3533     bdrv_dec_in_flight(bs);
3534 
3535     return ret;
3536 }
3537 
3538 int coroutine_fn
3539 bdrv_co_pdiscard_snapshot(BlockDriverState *bs, int64_t offset, int64_t bytes)
3540 {
3541     BlockDriver *drv = bs->drv;
3542     int ret;
3543     IO_CODE();
3544 
3545     if (!drv) {
3546         return -ENOMEDIUM;
3547     }
3548 
3549     if (!drv->bdrv_co_pdiscard_snapshot) {
3550         return -ENOTSUP;
3551     }
3552 
3553     bdrv_inc_in_flight(bs);
3554     ret = drv->bdrv_co_pdiscard_snapshot(bs, offset, bytes);
3555     bdrv_dec_in_flight(bs);
3556 
3557     return ret;
3558 }
3559