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