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