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