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