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