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