xref: /qemu/block/io.c (revision 083fe9a1)
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         assert(!(flags & BDRV_REQ_NO_WAIT));
2207         bdrv_make_request_serialising(req, align);
2208 
2209         bdrv_padding_rmw_read(child, req, &pad, true);
2210 
2211         if (pad.head || pad.merge_reads) {
2212             int64_t aligned_offset = offset & ~(align - 1);
2213             int64_t write_bytes = pad.merge_reads ? pad.buf_len : align;
2214 
2215             qemu_iovec_init_buf(&local_qiov, pad.buf, write_bytes);
2216             ret = bdrv_aligned_pwritev(child, req, aligned_offset, write_bytes,
2217                                        align, &local_qiov, 0,
2218                                        flags & ~BDRV_REQ_ZERO_WRITE);
2219             if (ret < 0 || pad.merge_reads) {
2220                 /* Error or all work is done */
2221                 goto out;
2222             }
2223             offset += write_bytes - pad.head;
2224             bytes -= write_bytes - pad.head;
2225         }
2226     }
2227 
2228     assert(!bytes || (offset & (align - 1)) == 0);
2229     if (bytes >= align) {
2230         /* Write the aligned part in the middle. */
2231         int64_t aligned_bytes = bytes & ~(align - 1);
2232         ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
2233                                    NULL, 0, flags);
2234         if (ret < 0) {
2235             goto out;
2236         }
2237         bytes -= aligned_bytes;
2238         offset += aligned_bytes;
2239     }
2240 
2241     assert(!bytes || (offset & (align - 1)) == 0);
2242     if (bytes) {
2243         assert(align == pad.tail + bytes);
2244 
2245         qemu_iovec_init_buf(&local_qiov, pad.tail_buf, align);
2246         ret = bdrv_aligned_pwritev(child, req, offset, align, align,
2247                                    &local_qiov, 0,
2248                                    flags & ~BDRV_REQ_ZERO_WRITE);
2249     }
2250 
2251 out:
2252     bdrv_padding_destroy(&pad);
2253 
2254     return ret;
2255 }
2256 
2257 /*
2258  * Handle a write request in coroutine context
2259  */
2260 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
2261     int64_t offset, int64_t bytes, QEMUIOVector *qiov,
2262     BdrvRequestFlags flags)
2263 {
2264     IO_CODE();
2265     return bdrv_co_pwritev_part(child, offset, bytes, qiov, 0, flags);
2266 }
2267 
2268 int coroutine_fn bdrv_co_pwritev_part(BdrvChild *child,
2269     int64_t offset, int64_t bytes, QEMUIOVector *qiov, size_t qiov_offset,
2270     BdrvRequestFlags flags)
2271 {
2272     BlockDriverState *bs = child->bs;
2273     BdrvTrackedRequest req;
2274     uint64_t align = bs->bl.request_alignment;
2275     BdrvRequestPadding pad;
2276     int ret;
2277     bool padded = false;
2278     IO_CODE();
2279 
2280     trace_bdrv_co_pwritev_part(child->bs, offset, bytes, flags);
2281 
2282     if (!bdrv_is_inserted(bs)) {
2283         return -ENOMEDIUM;
2284     }
2285 
2286     if (flags & BDRV_REQ_ZERO_WRITE) {
2287         ret = bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, NULL);
2288     } else {
2289         ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
2290     }
2291     if (ret < 0) {
2292         return ret;
2293     }
2294 
2295     /* If the request is misaligned then we can't make it efficient */
2296     if ((flags & BDRV_REQ_NO_FALLBACK) &&
2297         !QEMU_IS_ALIGNED(offset | bytes, align))
2298     {
2299         return -ENOTSUP;
2300     }
2301 
2302     if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
2303         /*
2304          * Aligning zero request is nonsense. Even if driver has special meaning
2305          * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2306          * it to driver due to request_alignment.
2307          *
2308          * Still, no reason to return an error if someone do unaligned
2309          * zero-length write occasionally.
2310          */
2311         return 0;
2312     }
2313 
2314     if (!(flags & BDRV_REQ_ZERO_WRITE)) {
2315         /*
2316          * Pad request for following read-modify-write cycle.
2317          * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2318          * alignment only if there is no ZERO flag.
2319          */
2320         ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
2321                                &padded);
2322         if (ret < 0) {
2323             return ret;
2324         }
2325     }
2326 
2327     bdrv_inc_in_flight(bs);
2328     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
2329 
2330     if (flags & BDRV_REQ_ZERO_WRITE) {
2331         assert(!padded);
2332         ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
2333         goto out;
2334     }
2335 
2336     if (padded) {
2337         /*
2338          * Request was unaligned to request_alignment and therefore
2339          * padded.  We are going to do read-modify-write, and must
2340          * serialize the request to prevent interactions of the
2341          * widened region with other transactions.
2342          */
2343         assert(!(flags & BDRV_REQ_NO_WAIT));
2344         bdrv_make_request_serialising(&req, align);
2345         bdrv_padding_rmw_read(child, &req, &pad, false);
2346     }
2347 
2348     ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
2349                                qiov, qiov_offset, flags);
2350 
2351     bdrv_padding_destroy(&pad);
2352 
2353 out:
2354     tracked_request_end(&req);
2355     bdrv_dec_in_flight(bs);
2356 
2357     return ret;
2358 }
2359 
2360 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
2361                                        int64_t bytes, BdrvRequestFlags flags)
2362 {
2363     IO_CODE();
2364     trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
2365 
2366     if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
2367         flags &= ~BDRV_REQ_MAY_UNMAP;
2368     }
2369 
2370     return bdrv_co_pwritev(child, offset, bytes, NULL,
2371                            BDRV_REQ_ZERO_WRITE | flags);
2372 }
2373 
2374 /*
2375  * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2376  */
2377 int bdrv_flush_all(void)
2378 {
2379     BdrvNextIterator it;
2380     BlockDriverState *bs = NULL;
2381     int result = 0;
2382 
2383     GLOBAL_STATE_CODE();
2384 
2385     /*
2386      * bdrv queue is managed by record/replay,
2387      * creating new flush request for stopping
2388      * the VM may break the determinism
2389      */
2390     if (replay_events_enabled()) {
2391         return result;
2392     }
2393 
2394     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
2395         AioContext *aio_context = bdrv_get_aio_context(bs);
2396         int ret;
2397 
2398         aio_context_acquire(aio_context);
2399         ret = bdrv_flush(bs);
2400         if (ret < 0 && !result) {
2401             result = ret;
2402         }
2403         aio_context_release(aio_context);
2404     }
2405 
2406     return result;
2407 }
2408 
2409 /*
2410  * Returns the allocation status of the specified sectors.
2411  * Drivers not implementing the functionality are assumed to not support
2412  * backing files, hence all their sectors are reported as allocated.
2413  *
2414  * If 'want_zero' is true, the caller is querying for mapping
2415  * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2416  * _ZERO where possible; otherwise, the result favors larger 'pnum',
2417  * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2418  *
2419  * If 'offset' is beyond the end of the disk image the return value is
2420  * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2421  *
2422  * 'bytes' is the max value 'pnum' should be set to.  If bytes goes
2423  * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2424  * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2425  *
2426  * 'pnum' is set to the number of bytes (including and immediately
2427  * following the specified offset) that are easily known to be in the
2428  * same allocated/unallocated state.  Note that a second call starting
2429  * at the original offset plus returned pnum may have the same status.
2430  * The returned value is non-zero on success except at end-of-file.
2431  *
2432  * Returns negative errno on failure.  Otherwise, if the
2433  * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2434  * set to the host mapping and BDS corresponding to the guest offset.
2435  */
2436 static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
2437                                              bool want_zero,
2438                                              int64_t offset, int64_t bytes,
2439                                              int64_t *pnum, int64_t *map,
2440                                              BlockDriverState **file)
2441 {
2442     int64_t total_size;
2443     int64_t n; /* bytes */
2444     int ret;
2445     int64_t local_map = 0;
2446     BlockDriverState *local_file = NULL;
2447     int64_t aligned_offset, aligned_bytes;
2448     uint32_t align;
2449     bool has_filtered_child;
2450 
2451     assert(pnum);
2452     *pnum = 0;
2453     total_size = bdrv_getlength(bs);
2454     if (total_size < 0) {
2455         ret = total_size;
2456         goto early_out;
2457     }
2458 
2459     if (offset >= total_size) {
2460         ret = BDRV_BLOCK_EOF;
2461         goto early_out;
2462     }
2463     if (!bytes) {
2464         ret = 0;
2465         goto early_out;
2466     }
2467 
2468     n = total_size - offset;
2469     if (n < bytes) {
2470         bytes = n;
2471     }
2472 
2473     /* Must be non-NULL or bdrv_getlength() would have failed */
2474     assert(bs->drv);
2475     has_filtered_child = bdrv_filter_child(bs);
2476     if (!bs->drv->bdrv_co_block_status && !has_filtered_child) {
2477         *pnum = bytes;
2478         ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2479         if (offset + bytes == total_size) {
2480             ret |= BDRV_BLOCK_EOF;
2481         }
2482         if (bs->drv->protocol_name) {
2483             ret |= BDRV_BLOCK_OFFSET_VALID;
2484             local_map = offset;
2485             local_file = bs;
2486         }
2487         goto early_out;
2488     }
2489 
2490     bdrv_inc_in_flight(bs);
2491 
2492     /* Round out to request_alignment boundaries */
2493     align = bs->bl.request_alignment;
2494     aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2495     aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2496 
2497     if (bs->drv->bdrv_co_block_status) {
2498         /*
2499          * Use the block-status cache only for protocol nodes: Format
2500          * drivers are generally quick to inquire the status, but protocol
2501          * drivers often need to get information from outside of qemu, so
2502          * we do not have control over the actual implementation.  There
2503          * have been cases where inquiring the status took an unreasonably
2504          * long time, and we can do nothing in qemu to fix it.
2505          * This is especially problematic for images with large data areas,
2506          * because finding the few holes in them and giving them special
2507          * treatment does not gain much performance.  Therefore, we try to
2508          * cache the last-identified data region.
2509          *
2510          * Second, limiting ourselves to protocol nodes allows us to assume
2511          * the block status for data regions to be DATA | OFFSET_VALID, and
2512          * that the host offset is the same as the guest offset.
2513          *
2514          * Note that it is possible that external writers zero parts of
2515          * the cached regions without the cache being invalidated, and so
2516          * we may report zeroes as data.  This is not catastrophic,
2517          * however, because reporting zeroes as data is fine.
2518          */
2519         if (QLIST_EMPTY(&bs->children) &&
2520             bdrv_bsc_is_data(bs, aligned_offset, pnum))
2521         {
2522             ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2523             local_file = bs;
2524             local_map = aligned_offset;
2525         } else {
2526             ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2527                                                 aligned_bytes, pnum, &local_map,
2528                                                 &local_file);
2529 
2530             /*
2531              * Note that checking QLIST_EMPTY(&bs->children) is also done when
2532              * the cache is queried above.  Technically, we do not need to check
2533              * it here; the worst that can happen is that we fill the cache for
2534              * non-protocol nodes, and then it is never used.  However, filling
2535              * the cache requires an RCU update, so double check here to avoid
2536              * such an update if possible.
2537              *
2538              * Check want_zero, because we only want to update the cache when we
2539              * have accurate information about what is zero and what is data.
2540              */
2541             if (want_zero &&
2542                 ret == (BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID) &&
2543                 QLIST_EMPTY(&bs->children))
2544             {
2545                 /*
2546                  * When a protocol driver reports BLOCK_OFFSET_VALID, the
2547                  * returned local_map value must be the same as the offset we
2548                  * have passed (aligned_offset), and local_bs must be the node
2549                  * itself.
2550                  * Assert this, because we follow this rule when reading from
2551                  * the cache (see the `local_file = bs` and
2552                  * `local_map = aligned_offset` assignments above), and the
2553                  * result the cache delivers must be the same as the driver
2554                  * would deliver.
2555                  */
2556                 assert(local_file == bs);
2557                 assert(local_map == aligned_offset);
2558                 bdrv_bsc_fill(bs, aligned_offset, *pnum);
2559             }
2560         }
2561     } else {
2562         /* Default code for filters */
2563 
2564         local_file = bdrv_filter_bs(bs);
2565         assert(local_file);
2566 
2567         *pnum = aligned_bytes;
2568         local_map = aligned_offset;
2569         ret = BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2570     }
2571     if (ret < 0) {
2572         *pnum = 0;
2573         goto out;
2574     }
2575 
2576     /*
2577      * The driver's result must be a non-zero multiple of request_alignment.
2578      * Clamp pnum and adjust map to original request.
2579      */
2580     assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2581            align > offset - aligned_offset);
2582     if (ret & BDRV_BLOCK_RECURSE) {
2583         assert(ret & BDRV_BLOCK_DATA);
2584         assert(ret & BDRV_BLOCK_OFFSET_VALID);
2585         assert(!(ret & BDRV_BLOCK_ZERO));
2586     }
2587 
2588     *pnum -= offset - aligned_offset;
2589     if (*pnum > bytes) {
2590         *pnum = bytes;
2591     }
2592     if (ret & BDRV_BLOCK_OFFSET_VALID) {
2593         local_map += offset - aligned_offset;
2594     }
2595 
2596     if (ret & BDRV_BLOCK_RAW) {
2597         assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2598         ret = bdrv_co_block_status(local_file, want_zero, local_map,
2599                                    *pnum, pnum, &local_map, &local_file);
2600         goto out;
2601     }
2602 
2603     if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2604         ret |= BDRV_BLOCK_ALLOCATED;
2605     } else if (bs->drv->supports_backing) {
2606         BlockDriverState *cow_bs = bdrv_cow_bs(bs);
2607 
2608         if (!cow_bs) {
2609             ret |= BDRV_BLOCK_ZERO;
2610         } else if (want_zero) {
2611             int64_t size2 = bdrv_getlength(cow_bs);
2612 
2613             if (size2 >= 0 && offset >= size2) {
2614                 ret |= BDRV_BLOCK_ZERO;
2615             }
2616         }
2617     }
2618 
2619     if (want_zero && ret & BDRV_BLOCK_RECURSE &&
2620         local_file && local_file != bs &&
2621         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2622         (ret & BDRV_BLOCK_OFFSET_VALID)) {
2623         int64_t file_pnum;
2624         int ret2;
2625 
2626         ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2627                                     *pnum, &file_pnum, NULL, NULL);
2628         if (ret2 >= 0) {
2629             /* Ignore errors.  This is just providing extra information, it
2630              * is useful but not necessary.
2631              */
2632             if (ret2 & BDRV_BLOCK_EOF &&
2633                 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2634                 /*
2635                  * It is valid for the format block driver to read
2636                  * beyond the end of the underlying file's current
2637                  * size; such areas read as zero.
2638                  */
2639                 ret |= BDRV_BLOCK_ZERO;
2640             } else {
2641                 /* Limit request to the range reported by the protocol driver */
2642                 *pnum = file_pnum;
2643                 ret |= (ret2 & BDRV_BLOCK_ZERO);
2644             }
2645         }
2646     }
2647 
2648 out:
2649     bdrv_dec_in_flight(bs);
2650     if (ret >= 0 && offset + *pnum == total_size) {
2651         ret |= BDRV_BLOCK_EOF;
2652     }
2653 early_out:
2654     if (file) {
2655         *file = local_file;
2656     }
2657     if (map) {
2658         *map = local_map;
2659     }
2660     return ret;
2661 }
2662 
2663 int coroutine_fn
2664 bdrv_co_common_block_status_above(BlockDriverState *bs,
2665                                   BlockDriverState *base,
2666                                   bool include_base,
2667                                   bool want_zero,
2668                                   int64_t offset,
2669                                   int64_t bytes,
2670                                   int64_t *pnum,
2671                                   int64_t *map,
2672                                   BlockDriverState **file,
2673                                   int *depth)
2674 {
2675     int ret;
2676     BlockDriverState *p;
2677     int64_t eof = 0;
2678     int dummy;
2679     IO_CODE();
2680 
2681     assert(!include_base || base); /* Can't include NULL base */
2682 
2683     if (!depth) {
2684         depth = &dummy;
2685     }
2686     *depth = 0;
2687 
2688     if (!include_base && bs == base) {
2689         *pnum = bytes;
2690         return 0;
2691     }
2692 
2693     ret = bdrv_co_block_status(bs, want_zero, offset, bytes, pnum, map, file);
2694     ++*depth;
2695     if (ret < 0 || *pnum == 0 || ret & BDRV_BLOCK_ALLOCATED || bs == base) {
2696         return ret;
2697     }
2698 
2699     if (ret & BDRV_BLOCK_EOF) {
2700         eof = offset + *pnum;
2701     }
2702 
2703     assert(*pnum <= bytes);
2704     bytes = *pnum;
2705 
2706     for (p = bdrv_filter_or_cow_bs(bs); include_base || p != base;
2707          p = bdrv_filter_or_cow_bs(p))
2708     {
2709         ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2710                                    file);
2711         ++*depth;
2712         if (ret < 0) {
2713             return ret;
2714         }
2715         if (*pnum == 0) {
2716             /*
2717              * The top layer deferred to this layer, and because this layer is
2718              * short, any zeroes that we synthesize beyond EOF behave as if they
2719              * were allocated at this layer.
2720              *
2721              * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2722              * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2723              * below.
2724              */
2725             assert(ret & BDRV_BLOCK_EOF);
2726             *pnum = bytes;
2727             if (file) {
2728                 *file = p;
2729             }
2730             ret = BDRV_BLOCK_ZERO | BDRV_BLOCK_ALLOCATED;
2731             break;
2732         }
2733         if (ret & BDRV_BLOCK_ALLOCATED) {
2734             /*
2735              * We've found the node and the status, we must break.
2736              *
2737              * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2738              * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2739              * below.
2740              */
2741             ret &= ~BDRV_BLOCK_EOF;
2742             break;
2743         }
2744 
2745         if (p == base) {
2746             assert(include_base);
2747             break;
2748         }
2749 
2750         /*
2751          * OK, [offset, offset + *pnum) region is unallocated on this layer,
2752          * let's continue the diving.
2753          */
2754         assert(*pnum <= bytes);
2755         bytes = *pnum;
2756     }
2757 
2758     if (offset + *pnum == eof) {
2759         ret |= BDRV_BLOCK_EOF;
2760     }
2761 
2762     return ret;
2763 }
2764 
2765 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2766                             int64_t offset, int64_t bytes, int64_t *pnum,
2767                             int64_t *map, BlockDriverState **file)
2768 {
2769     IO_CODE();
2770     return bdrv_common_block_status_above(bs, base, false, true, offset, bytes,
2771                                           pnum, map, file, NULL);
2772 }
2773 
2774 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2775                       int64_t *pnum, int64_t *map, BlockDriverState **file)
2776 {
2777     IO_CODE();
2778     return bdrv_block_status_above(bs, bdrv_filter_or_cow_bs(bs),
2779                                    offset, bytes, pnum, map, file);
2780 }
2781 
2782 /*
2783  * Check @bs (and its backing chain) to see if the range defined
2784  * by @offset and @bytes is known to read as zeroes.
2785  * Return 1 if that is the case, 0 otherwise and -errno on error.
2786  * This test is meant to be fast rather than accurate so returning 0
2787  * does not guarantee non-zero data.
2788  */
2789 int coroutine_fn bdrv_co_is_zero_fast(BlockDriverState *bs, int64_t offset,
2790                                       int64_t bytes)
2791 {
2792     int ret;
2793     int64_t pnum = bytes;
2794     IO_CODE();
2795 
2796     if (!bytes) {
2797         return 1;
2798     }
2799 
2800     ret = bdrv_common_block_status_above(bs, NULL, false, false, offset,
2801                                          bytes, &pnum, NULL, NULL, NULL);
2802 
2803     if (ret < 0) {
2804         return ret;
2805     }
2806 
2807     return (pnum == bytes) && (ret & BDRV_BLOCK_ZERO);
2808 }
2809 
2810 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
2811                                    int64_t bytes, int64_t *pnum)
2812 {
2813     int ret;
2814     int64_t dummy;
2815     IO_CODE();
2816 
2817     ret = bdrv_common_block_status_above(bs, bs, true, false, offset,
2818                                          bytes, pnum ? pnum : &dummy, NULL,
2819                                          NULL, NULL);
2820     if (ret < 0) {
2821         return ret;
2822     }
2823     return !!(ret & BDRV_BLOCK_ALLOCATED);
2824 }
2825 
2826 /*
2827  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2828  *
2829  * Return a positive depth if (a prefix of) the given range is allocated
2830  * in any image between BASE and TOP (BASE is only included if include_base
2831  * is set).  Depth 1 is TOP, 2 is the first backing layer, and so forth.
2832  * BASE can be NULL to check if the given offset is allocated in any
2833  * image of the chain.  Return 0 otherwise, or negative errno on
2834  * failure.
2835  *
2836  * 'pnum' is set to the number of bytes (including and immediately
2837  * following the specified offset) that are known to be in the same
2838  * allocated/unallocated state.  Note that a subsequent call starting
2839  * at 'offset + *pnum' may return the same allocation status (in other
2840  * words, the result is not necessarily the maximum possible range);
2841  * but 'pnum' will only be 0 when end of file is reached.
2842  */
2843 int bdrv_is_allocated_above(BlockDriverState *top,
2844                             BlockDriverState *base,
2845                             bool include_base, int64_t offset,
2846                             int64_t bytes, int64_t *pnum)
2847 {
2848     int depth;
2849     int ret = bdrv_common_block_status_above(top, base, include_base, false,
2850                                              offset, bytes, pnum, NULL, NULL,
2851                                              &depth);
2852     IO_CODE();
2853     if (ret < 0) {
2854         return ret;
2855     }
2856 
2857     if (ret & BDRV_BLOCK_ALLOCATED) {
2858         return depth;
2859     }
2860     return 0;
2861 }
2862 
2863 int coroutine_fn
2864 bdrv_co_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2865 {
2866     BlockDriver *drv = bs->drv;
2867     BlockDriverState *child_bs = bdrv_primary_bs(bs);
2868     int ret;
2869     IO_CODE();
2870 
2871     ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2872     if (ret < 0) {
2873         return ret;
2874     }
2875 
2876     if (!drv) {
2877         return -ENOMEDIUM;
2878     }
2879 
2880     bdrv_inc_in_flight(bs);
2881 
2882     if (drv->bdrv_load_vmstate) {
2883         ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2884     } else if (child_bs) {
2885         ret = bdrv_co_readv_vmstate(child_bs, qiov, pos);
2886     } else {
2887         ret = -ENOTSUP;
2888     }
2889 
2890     bdrv_dec_in_flight(bs);
2891 
2892     return ret;
2893 }
2894 
2895 int coroutine_fn
2896 bdrv_co_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2897 {
2898     BlockDriver *drv = bs->drv;
2899     BlockDriverState *child_bs = bdrv_primary_bs(bs);
2900     int ret;
2901     IO_CODE();
2902 
2903     ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2904     if (ret < 0) {
2905         return ret;
2906     }
2907 
2908     if (!drv) {
2909         return -ENOMEDIUM;
2910     }
2911 
2912     bdrv_inc_in_flight(bs);
2913 
2914     if (drv->bdrv_save_vmstate) {
2915         ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2916     } else if (child_bs) {
2917         ret = bdrv_co_writev_vmstate(child_bs, qiov, pos);
2918     } else {
2919         ret = -ENOTSUP;
2920     }
2921 
2922     bdrv_dec_in_flight(bs);
2923 
2924     return ret;
2925 }
2926 
2927 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2928                       int64_t pos, int size)
2929 {
2930     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2931     int ret = bdrv_writev_vmstate(bs, &qiov, pos);
2932     IO_CODE();
2933 
2934     return ret < 0 ? ret : size;
2935 }
2936 
2937 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2938                       int64_t pos, int size)
2939 {
2940     QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2941     int ret = bdrv_readv_vmstate(bs, &qiov, pos);
2942     IO_CODE();
2943 
2944     return ret < 0 ? ret : size;
2945 }
2946 
2947 /**************************************************************/
2948 /* async I/Os */
2949 
2950 void bdrv_aio_cancel(BlockAIOCB *acb)
2951 {
2952     IO_CODE();
2953     qemu_aio_ref(acb);
2954     bdrv_aio_cancel_async(acb);
2955     while (acb->refcnt > 1) {
2956         if (acb->aiocb_info->get_aio_context) {
2957             aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2958         } else if (acb->bs) {
2959             /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2960              * assert that we're not using an I/O thread.  Thread-safe
2961              * code should use bdrv_aio_cancel_async exclusively.
2962              */
2963             assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2964             aio_poll(bdrv_get_aio_context(acb->bs), true);
2965         } else {
2966             abort();
2967         }
2968     }
2969     qemu_aio_unref(acb);
2970 }
2971 
2972 /* Async version of aio cancel. The caller is not blocked if the acb implements
2973  * cancel_async, otherwise we do nothing and let the request normally complete.
2974  * In either case the completion callback must be called. */
2975 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2976 {
2977     IO_CODE();
2978     if (acb->aiocb_info->cancel_async) {
2979         acb->aiocb_info->cancel_async(acb);
2980     }
2981 }
2982 
2983 /**************************************************************/
2984 /* Coroutine block device emulation */
2985 
2986 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2987 {
2988     BdrvChild *primary_child = bdrv_primary_child(bs);
2989     BdrvChild *child;
2990     int current_gen;
2991     int ret = 0;
2992     IO_CODE();
2993 
2994     bdrv_inc_in_flight(bs);
2995 
2996     if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
2997         bdrv_is_sg(bs)) {
2998         goto early_exit;
2999     }
3000 
3001     qemu_co_mutex_lock(&bs->reqs_lock);
3002     current_gen = qatomic_read(&bs->write_gen);
3003 
3004     /* Wait until any previous flushes are completed */
3005     while (bs->active_flush_req) {
3006         qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
3007     }
3008 
3009     /* Flushes reach this point in nondecreasing current_gen order.  */
3010     bs->active_flush_req = true;
3011     qemu_co_mutex_unlock(&bs->reqs_lock);
3012 
3013     /* Write back all layers by calling one driver function */
3014     if (bs->drv->bdrv_co_flush) {
3015         ret = bs->drv->bdrv_co_flush(bs);
3016         goto out;
3017     }
3018 
3019     /* Write back cached data to the OS even with cache=unsafe */
3020     BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_OS);
3021     if (bs->drv->bdrv_co_flush_to_os) {
3022         ret = bs->drv->bdrv_co_flush_to_os(bs);
3023         if (ret < 0) {
3024             goto out;
3025         }
3026     }
3027 
3028     /* But don't actually force it to the disk with cache=unsafe */
3029     if (bs->open_flags & BDRV_O_NO_FLUSH) {
3030         goto flush_children;
3031     }
3032 
3033     /* Check if we really need to flush anything */
3034     if (bs->flushed_gen == current_gen) {
3035         goto flush_children;
3036     }
3037 
3038     BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_DISK);
3039     if (!bs->drv) {
3040         /* bs->drv->bdrv_co_flush() might have ejected the BDS
3041          * (even in case of apparent success) */
3042         ret = -ENOMEDIUM;
3043         goto out;
3044     }
3045     if (bs->drv->bdrv_co_flush_to_disk) {
3046         ret = bs->drv->bdrv_co_flush_to_disk(bs);
3047     } else if (bs->drv->bdrv_aio_flush) {
3048         BlockAIOCB *acb;
3049         CoroutineIOCompletion co = {
3050             .coroutine = qemu_coroutine_self(),
3051         };
3052 
3053         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3054         if (acb == NULL) {
3055             ret = -EIO;
3056         } else {
3057             qemu_coroutine_yield();
3058             ret = co.ret;
3059         }
3060     } else {
3061         /*
3062          * Some block drivers always operate in either writethrough or unsafe
3063          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
3064          * know how the server works (because the behaviour is hardcoded or
3065          * depends on server-side configuration), so we can't ensure that
3066          * everything is safe on disk. Returning an error doesn't work because
3067          * that would break guests even if the server operates in writethrough
3068          * mode.
3069          *
3070          * Let's hope the user knows what he's doing.
3071          */
3072         ret = 0;
3073     }
3074 
3075     if (ret < 0) {
3076         goto out;
3077     }
3078 
3079     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
3080      * in the case of cache=unsafe, so there are no useless flushes.
3081      */
3082 flush_children:
3083     ret = 0;
3084     QLIST_FOREACH(child, &bs->children, next) {
3085         if (child->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
3086             int this_child_ret = bdrv_co_flush(child->bs);
3087             if (!ret) {
3088                 ret = this_child_ret;
3089             }
3090         }
3091     }
3092 
3093 out:
3094     /* Notify any pending flushes that we have completed */
3095     if (ret == 0) {
3096         bs->flushed_gen = current_gen;
3097     }
3098 
3099     qemu_co_mutex_lock(&bs->reqs_lock);
3100     bs->active_flush_req = false;
3101     /* Return value is ignored - it's ok if wait queue is empty */
3102     qemu_co_queue_next(&bs->flush_queue);
3103     qemu_co_mutex_unlock(&bs->reqs_lock);
3104 
3105 early_exit:
3106     bdrv_dec_in_flight(bs);
3107     return ret;
3108 }
3109 
3110 int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset,
3111                                   int64_t bytes)
3112 {
3113     BdrvTrackedRequest req;
3114     int ret;
3115     int64_t max_pdiscard;
3116     int head, tail, align;
3117     BlockDriverState *bs = child->bs;
3118     IO_CODE();
3119 
3120     if (!bs || !bs->drv || !bdrv_is_inserted(bs)) {
3121         return -ENOMEDIUM;
3122     }
3123 
3124     if (bdrv_has_readonly_bitmaps(bs)) {
3125         return -EPERM;
3126     }
3127 
3128     ret = bdrv_check_request(offset, bytes, NULL);
3129     if (ret < 0) {
3130         return ret;
3131     }
3132 
3133     /* Do nothing if disabled.  */
3134     if (!(bs->open_flags & BDRV_O_UNMAP)) {
3135         return 0;
3136     }
3137 
3138     if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
3139         return 0;
3140     }
3141 
3142     /* Invalidate the cached block-status data range if this discard overlaps */
3143     bdrv_bsc_invalidate_range(bs, offset, bytes);
3144 
3145     /* Discard is advisory, but some devices track and coalesce
3146      * unaligned requests, so we must pass everything down rather than
3147      * round here.  Still, most devices will just silently ignore
3148      * unaligned requests (by returning -ENOTSUP), so we must fragment
3149      * the request accordingly.  */
3150     align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
3151     assert(align % bs->bl.request_alignment == 0);
3152     head = offset % align;
3153     tail = (offset + bytes) % align;
3154 
3155     bdrv_inc_in_flight(bs);
3156     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
3157 
3158     ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
3159     if (ret < 0) {
3160         goto out;
3161     }
3162 
3163     max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT64_MAX),
3164                                    align);
3165     assert(max_pdiscard >= bs->bl.request_alignment);
3166 
3167     while (bytes > 0) {
3168         int64_t num = bytes;
3169 
3170         if (head) {
3171             /* Make small requests to get to alignment boundaries. */
3172             num = MIN(bytes, align - head);
3173             if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
3174                 num %= bs->bl.request_alignment;
3175             }
3176             head = (head + num) % align;
3177             assert(num < max_pdiscard);
3178         } else if (tail) {
3179             if (num > align) {
3180                 /* Shorten the request to the last aligned cluster.  */
3181                 num -= tail;
3182             } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
3183                        tail > bs->bl.request_alignment) {
3184                 tail %= bs->bl.request_alignment;
3185                 num -= tail;
3186             }
3187         }
3188         /* limit request size */
3189         if (num > max_pdiscard) {
3190             num = max_pdiscard;
3191         }
3192 
3193         if (!bs->drv) {
3194             ret = -ENOMEDIUM;
3195             goto out;
3196         }
3197         if (bs->drv->bdrv_co_pdiscard) {
3198             ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
3199         } else {
3200             BlockAIOCB *acb;
3201             CoroutineIOCompletion co = {
3202                 .coroutine = qemu_coroutine_self(),
3203             };
3204 
3205             acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
3206                                              bdrv_co_io_em_complete, &co);
3207             if (acb == NULL) {
3208                 ret = -EIO;
3209                 goto out;
3210             } else {
3211                 qemu_coroutine_yield();
3212                 ret = co.ret;
3213             }
3214         }
3215         if (ret && ret != -ENOTSUP) {
3216             goto out;
3217         }
3218 
3219         offset += num;
3220         bytes -= num;
3221     }
3222     ret = 0;
3223 out:
3224     bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
3225     tracked_request_end(&req);
3226     bdrv_dec_in_flight(bs);
3227     return ret;
3228 }
3229 
3230 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
3231 {
3232     BlockDriver *drv = bs->drv;
3233     CoroutineIOCompletion co = {
3234         .coroutine = qemu_coroutine_self(),
3235     };
3236     BlockAIOCB *acb;
3237     IO_CODE();
3238 
3239     bdrv_inc_in_flight(bs);
3240     if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
3241         co.ret = -ENOTSUP;
3242         goto out;
3243     }
3244 
3245     if (drv->bdrv_co_ioctl) {
3246         co.ret = drv->bdrv_co_ioctl(bs, req, buf);
3247     } else {
3248         acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
3249         if (!acb) {
3250             co.ret = -ENOTSUP;
3251             goto out;
3252         }
3253         qemu_coroutine_yield();
3254     }
3255 out:
3256     bdrv_dec_in_flight(bs);
3257     return co.ret;
3258 }
3259 
3260 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3261 {
3262     IO_CODE();
3263     return qemu_memalign(bdrv_opt_mem_align(bs), size);
3264 }
3265 
3266 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
3267 {
3268     IO_CODE();
3269     return memset(qemu_blockalign(bs, size), 0, size);
3270 }
3271 
3272 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
3273 {
3274     size_t align = bdrv_opt_mem_align(bs);
3275     IO_CODE();
3276 
3277     /* Ensure that NULL is never returned on success */
3278     assert(align > 0);
3279     if (size == 0) {
3280         size = align;
3281     }
3282 
3283     return qemu_try_memalign(align, size);
3284 }
3285 
3286 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
3287 {
3288     void *mem = qemu_try_blockalign(bs, size);
3289     IO_CODE();
3290 
3291     if (mem) {
3292         memset(mem, 0, size);
3293     }
3294 
3295     return mem;
3296 }
3297 
3298 /*
3299  * Check if all memory in this vector is sector aligned.
3300  */
3301 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
3302 {
3303     int i;
3304     size_t alignment = bdrv_min_mem_align(bs);
3305     IO_CODE();
3306 
3307     for (i = 0; i < qiov->niov; i++) {
3308         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
3309             return false;
3310         }
3311         if (qiov->iov[i].iov_len % alignment) {
3312             return false;
3313         }
3314     }
3315 
3316     return true;
3317 }
3318 
3319 void bdrv_io_plug(BlockDriverState *bs)
3320 {
3321     BdrvChild *child;
3322     IO_CODE();
3323 
3324     QLIST_FOREACH(child, &bs->children, next) {
3325         bdrv_io_plug(child->bs);
3326     }
3327 
3328     if (qatomic_fetch_inc(&bs->io_plugged) == 0) {
3329         BlockDriver *drv = bs->drv;
3330         if (drv && drv->bdrv_io_plug) {
3331             drv->bdrv_io_plug(bs);
3332         }
3333     }
3334 }
3335 
3336 void bdrv_io_unplug(BlockDriverState *bs)
3337 {
3338     BdrvChild *child;
3339     IO_CODE();
3340 
3341     assert(bs->io_plugged);
3342     if (qatomic_fetch_dec(&bs->io_plugged) == 1) {
3343         BlockDriver *drv = bs->drv;
3344         if (drv && drv->bdrv_io_unplug) {
3345             drv->bdrv_io_unplug(bs);
3346         }
3347     }
3348 
3349     QLIST_FOREACH(child, &bs->children, next) {
3350         bdrv_io_unplug(child->bs);
3351     }
3352 }
3353 
3354 void bdrv_register_buf(BlockDriverState *bs, void *host, size_t size)
3355 {
3356     BdrvChild *child;
3357 
3358     GLOBAL_STATE_CODE();
3359     if (bs->drv && bs->drv->bdrv_register_buf) {
3360         bs->drv->bdrv_register_buf(bs, host, size);
3361     }
3362     QLIST_FOREACH(child, &bs->children, next) {
3363         bdrv_register_buf(child->bs, host, size);
3364     }
3365 }
3366 
3367 void bdrv_unregister_buf(BlockDriverState *bs, void *host)
3368 {
3369     BdrvChild *child;
3370 
3371     GLOBAL_STATE_CODE();
3372     if (bs->drv && bs->drv->bdrv_unregister_buf) {
3373         bs->drv->bdrv_unregister_buf(bs, host);
3374     }
3375     QLIST_FOREACH(child, &bs->children, next) {
3376         bdrv_unregister_buf(child->bs, host);
3377     }
3378 }
3379 
3380 static int coroutine_fn bdrv_co_copy_range_internal(
3381         BdrvChild *src, int64_t src_offset, BdrvChild *dst,
3382         int64_t dst_offset, int64_t bytes,
3383         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
3384         bool recurse_src)
3385 {
3386     BdrvTrackedRequest req;
3387     int ret;
3388 
3389     /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3390     assert(!(read_flags & BDRV_REQ_NO_FALLBACK));
3391     assert(!(write_flags & BDRV_REQ_NO_FALLBACK));
3392     assert(!(read_flags & BDRV_REQ_NO_WAIT));
3393     assert(!(write_flags & BDRV_REQ_NO_WAIT));
3394 
3395     if (!dst || !dst->bs || !bdrv_is_inserted(dst->bs)) {
3396         return -ENOMEDIUM;
3397     }
3398     ret = bdrv_check_request32(dst_offset, bytes, NULL, 0);
3399     if (ret) {
3400         return ret;
3401     }
3402     if (write_flags & BDRV_REQ_ZERO_WRITE) {
3403         return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
3404     }
3405 
3406     if (!src || !src->bs || !bdrv_is_inserted(src->bs)) {
3407         return -ENOMEDIUM;
3408     }
3409     ret = bdrv_check_request32(src_offset, bytes, NULL, 0);
3410     if (ret) {
3411         return ret;
3412     }
3413 
3414     if (!src->bs->drv->bdrv_co_copy_range_from
3415         || !dst->bs->drv->bdrv_co_copy_range_to
3416         || src->bs->encrypted || dst->bs->encrypted) {
3417         return -ENOTSUP;
3418     }
3419 
3420     if (recurse_src) {
3421         bdrv_inc_in_flight(src->bs);
3422         tracked_request_begin(&req, src->bs, src_offset, bytes,
3423                               BDRV_TRACKED_READ);
3424 
3425         /* BDRV_REQ_SERIALISING is only for write operation */
3426         assert(!(read_flags & BDRV_REQ_SERIALISING));
3427         bdrv_wait_serialising_requests(&req);
3428 
3429         ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
3430                                                     src, src_offset,
3431                                                     dst, dst_offset,
3432                                                     bytes,
3433                                                     read_flags, write_flags);
3434 
3435         tracked_request_end(&req);
3436         bdrv_dec_in_flight(src->bs);
3437     } else {
3438         bdrv_inc_in_flight(dst->bs);
3439         tracked_request_begin(&req, dst->bs, dst_offset, bytes,
3440                               BDRV_TRACKED_WRITE);
3441         ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3442                                         write_flags);
3443         if (!ret) {
3444             ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3445                                                       src, src_offset,
3446                                                       dst, dst_offset,
3447                                                       bytes,
3448                                                       read_flags, write_flags);
3449         }
3450         bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
3451         tracked_request_end(&req);
3452         bdrv_dec_in_flight(dst->bs);
3453     }
3454 
3455     return ret;
3456 }
3457 
3458 /* Copy range from @src to @dst.
3459  *
3460  * See the comment of bdrv_co_copy_range for the parameter and return value
3461  * semantics. */
3462 int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
3463                                          BdrvChild *dst, int64_t dst_offset,
3464                                          int64_t bytes,
3465                                          BdrvRequestFlags read_flags,
3466                                          BdrvRequestFlags write_flags)
3467 {
3468     IO_CODE();
3469     trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3470                                   read_flags, write_flags);
3471     return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3472                                        bytes, read_flags, write_flags, true);
3473 }
3474 
3475 /* Copy range from @src to @dst.
3476  *
3477  * See the comment of bdrv_co_copy_range for the parameter and return value
3478  * semantics. */
3479 int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
3480                                        BdrvChild *dst, int64_t dst_offset,
3481                                        int64_t bytes,
3482                                        BdrvRequestFlags read_flags,
3483                                        BdrvRequestFlags write_flags)
3484 {
3485     IO_CODE();
3486     trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3487                                 read_flags, write_flags);
3488     return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3489                                        bytes, read_flags, write_flags, false);
3490 }
3491 
3492 int coroutine_fn bdrv_co_copy_range(BdrvChild *src, int64_t src_offset,
3493                                     BdrvChild *dst, int64_t dst_offset,
3494                                     int64_t bytes, BdrvRequestFlags read_flags,
3495                                     BdrvRequestFlags write_flags)
3496 {
3497     IO_CODE();
3498     return bdrv_co_copy_range_from(src, src_offset,
3499                                    dst, dst_offset,
3500                                    bytes, read_flags, write_flags);
3501 }
3502 
3503 static void bdrv_parent_cb_resize(BlockDriverState *bs)
3504 {
3505     BdrvChild *c;
3506     QLIST_FOREACH(c, &bs->parents, next_parent) {
3507         if (c->klass->resize) {
3508             c->klass->resize(c);
3509         }
3510     }
3511 }
3512 
3513 /**
3514  * Truncate file to 'offset' bytes (needed only for file protocols)
3515  *
3516  * If 'exact' is true, the file must be resized to exactly the given
3517  * 'offset'.  Otherwise, it is sufficient for the node to be at least
3518  * 'offset' bytes in length.
3519  */
3520 int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset, bool exact,
3521                                   PreallocMode prealloc, BdrvRequestFlags flags,
3522                                   Error **errp)
3523 {
3524     BlockDriverState *bs = child->bs;
3525     BdrvChild *filtered, *backing;
3526     BlockDriver *drv = bs->drv;
3527     BdrvTrackedRequest req;
3528     int64_t old_size, new_bytes;
3529     int ret;
3530     IO_CODE();
3531 
3532     /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3533     if (!drv) {
3534         error_setg(errp, "No medium inserted");
3535         return -ENOMEDIUM;
3536     }
3537     if (offset < 0) {
3538         error_setg(errp, "Image size cannot be negative");
3539         return -EINVAL;
3540     }
3541 
3542     ret = bdrv_check_request(offset, 0, errp);
3543     if (ret < 0) {
3544         return ret;
3545     }
3546 
3547     old_size = bdrv_getlength(bs);
3548     if (old_size < 0) {
3549         error_setg_errno(errp, -old_size, "Failed to get old image size");
3550         return old_size;
3551     }
3552 
3553     if (bdrv_is_read_only(bs)) {
3554         error_setg(errp, "Image is read-only");
3555         return -EACCES;
3556     }
3557 
3558     if (offset > old_size) {
3559         new_bytes = offset - old_size;
3560     } else {
3561         new_bytes = 0;
3562     }
3563 
3564     bdrv_inc_in_flight(bs);
3565     tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3566                           BDRV_TRACKED_TRUNCATE);
3567 
3568     /* If we are growing the image and potentially using preallocation for the
3569      * new area, we need to make sure that no write requests are made to it
3570      * concurrently or they might be overwritten by preallocation. */
3571     if (new_bytes) {
3572         bdrv_make_request_serialising(&req, 1);
3573     }
3574     ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3575                                     0);
3576     if (ret < 0) {
3577         error_setg_errno(errp, -ret,
3578                          "Failed to prepare request for truncation");
3579         goto out;
3580     }
3581 
3582     filtered = bdrv_filter_child(bs);
3583     backing = bdrv_cow_child(bs);
3584 
3585     /*
3586      * If the image has a backing file that is large enough that it would
3587      * provide data for the new area, we cannot leave it unallocated because
3588      * then the backing file content would become visible. Instead, zero-fill
3589      * the new area.
3590      *
3591      * Note that if the image has a backing file, but was opened without the
3592      * backing file, taking care of keeping things consistent with that backing
3593      * file is the user's responsibility.
3594      */
3595     if (new_bytes && backing) {
3596         int64_t backing_len;
3597 
3598         backing_len = bdrv_getlength(backing->bs);
3599         if (backing_len < 0) {
3600             ret = backing_len;
3601             error_setg_errno(errp, -ret, "Could not get backing file size");
3602             goto out;
3603         }
3604 
3605         if (backing_len > old_size) {
3606             flags |= BDRV_REQ_ZERO_WRITE;
3607         }
3608     }
3609 
3610     if (drv->bdrv_co_truncate) {
3611         if (flags & ~bs->supported_truncate_flags) {
3612             error_setg(errp, "Block driver does not support requested flags");
3613             ret = -ENOTSUP;
3614             goto out;
3615         }
3616         ret = drv->bdrv_co_truncate(bs, offset, exact, prealloc, flags, errp);
3617     } else if (filtered) {
3618         ret = bdrv_co_truncate(filtered, offset, exact, prealloc, flags, errp);
3619     } else {
3620         error_setg(errp, "Image format driver does not support resize");
3621         ret = -ENOTSUP;
3622         goto out;
3623     }
3624     if (ret < 0) {
3625         goto out;
3626     }
3627 
3628     ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3629     if (ret < 0) {
3630         error_setg_errno(errp, -ret, "Could not refresh total sector count");
3631     } else {
3632         offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3633     }
3634     /* It's possible that truncation succeeded but refresh_total_sectors
3635      * failed, but the latter doesn't affect how we should finish the request.
3636      * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3637     bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3638 
3639 out:
3640     tracked_request_end(&req);
3641     bdrv_dec_in_flight(bs);
3642 
3643     return ret;
3644 }
3645 
3646 void bdrv_cancel_in_flight(BlockDriverState *bs)
3647 {
3648     GLOBAL_STATE_CODE();
3649     if (!bs || !bs->drv) {
3650         return;
3651     }
3652 
3653     if (bs->drv->bdrv_cancel_in_flight) {
3654         bs->drv->bdrv_cancel_in_flight(bs);
3655     }
3656 }
3657 
3658 int coroutine_fn
3659 bdrv_co_preadv_snapshot(BdrvChild *child, int64_t offset, int64_t bytes,
3660                         QEMUIOVector *qiov, size_t qiov_offset)
3661 {
3662     BlockDriverState *bs = child->bs;
3663     BlockDriver *drv = bs->drv;
3664     int ret;
3665     IO_CODE();
3666 
3667     if (!drv) {
3668         return -ENOMEDIUM;
3669     }
3670 
3671     if (!drv->bdrv_co_preadv_snapshot) {
3672         return -ENOTSUP;
3673     }
3674 
3675     bdrv_inc_in_flight(bs);
3676     ret = drv->bdrv_co_preadv_snapshot(bs, offset, bytes, qiov, qiov_offset);
3677     bdrv_dec_in_flight(bs);
3678 
3679     return ret;
3680 }
3681 
3682 int coroutine_fn
3683 bdrv_co_snapshot_block_status(BlockDriverState *bs,
3684                               bool want_zero, int64_t offset, int64_t bytes,
3685                               int64_t *pnum, int64_t *map,
3686                               BlockDriverState **file)
3687 {
3688     BlockDriver *drv = bs->drv;
3689     int ret;
3690     IO_CODE();
3691 
3692     if (!drv) {
3693         return -ENOMEDIUM;
3694     }
3695 
3696     if (!drv->bdrv_co_snapshot_block_status) {
3697         return -ENOTSUP;
3698     }
3699 
3700     bdrv_inc_in_flight(bs);
3701     ret = drv->bdrv_co_snapshot_block_status(bs, want_zero, offset, bytes,
3702                                              pnum, map, file);
3703     bdrv_dec_in_flight(bs);
3704 
3705     return ret;
3706 }
3707 
3708 int coroutine_fn
3709 bdrv_co_pdiscard_snapshot(BlockDriverState *bs, int64_t offset, int64_t bytes)
3710 {
3711     BlockDriver *drv = bs->drv;
3712     int ret;
3713     IO_CODE();
3714 
3715     if (!drv) {
3716         return -ENOMEDIUM;
3717     }
3718 
3719     if (!drv->bdrv_co_pdiscard_snapshot) {
3720         return -ENOTSUP;
3721     }
3722 
3723     bdrv_inc_in_flight(bs);
3724     ret = drv->bdrv_co_pdiscard_snapshot(bs, offset, bytes);
3725     bdrv_dec_in_flight(bs);
3726 
3727     return ret;
3728 }
3729