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