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