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