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