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