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