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