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