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