]> git.proxmox.com Git - mirror_qemu.git/blame - block/io.c
gluster: Handle changed glfs_ftruncate signature
[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{
0d93ed08
VSO
846 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf,
847 nb_sectors * BDRV_SECTOR_SIZE);
61007b31
SH
848
849 if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
850 return -EINVAL;
851 }
852
e293b7a3 853 return bdrv_prwv_co(child, sector_num << BDRV_SECTOR_BITS,
61007b31
SH
854 &qiov, is_write, flags);
855}
856
857/* return < 0 if error. See bdrv_write() for the return codes */
fbcbbf4e 858int bdrv_read(BdrvChild *child, int64_t sector_num,
61007b31
SH
859 uint8_t *buf, int nb_sectors)
860{
e293b7a3 861 return bdrv_rw_co(child, sector_num, buf, nb_sectors, false, 0);
61007b31
SH
862}
863
61007b31
SH
864/* Return < 0 if error. Important errors are:
865 -EIO generic I/O error (may happen for all errors)
866 -ENOMEDIUM No media inserted.
867 -EINVAL Invalid sector number or nb_sectors
868 -EACCES Trying to write a read-only device
869*/
18d51c4b 870int bdrv_write(BdrvChild *child, int64_t sector_num,
61007b31
SH
871 const uint8_t *buf, int nb_sectors)
872{
e293b7a3 873 return bdrv_rw_co(child, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
61007b31
SH
874}
875
720ff280 876int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
f5a5ca79 877 int bytes, BdrvRequestFlags flags)
61007b31 878{
0d93ed08 879 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, NULL, bytes);
74021bc4 880
e293b7a3 881 return bdrv_prwv_co(child, offset, &qiov, true,
74021bc4 882 BDRV_REQ_ZERO_WRITE | flags);
61007b31
SH
883}
884
885/*
74021bc4 886 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
61007b31
SH
887 * The operation is sped up by checking the block status and only writing
888 * zeroes to the device if they currently do not return zeroes. Optional
74021bc4 889 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
465fe887 890 * BDRV_REQ_FUA).
61007b31
SH
891 *
892 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
893 */
720ff280 894int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
61007b31 895{
237d78f8
EB
896 int ret;
897 int64_t target_size, bytes, offset = 0;
720ff280 898 BlockDriverState *bs = child->bs;
61007b31 899
7286d610
EB
900 target_size = bdrv_getlength(bs);
901 if (target_size < 0) {
902 return target_size;
61007b31
SH
903 }
904
905 for (;;) {
7286d610
EB
906 bytes = MIN(target_size - offset, BDRV_REQUEST_MAX_BYTES);
907 if (bytes <= 0) {
61007b31
SH
908 return 0;
909 }
237d78f8 910 ret = bdrv_block_status(bs, offset, bytes, &bytes, NULL, NULL);
61007b31 911 if (ret < 0) {
7286d610
EB
912 error_report("error getting block status at offset %" PRId64 ": %s",
913 offset, strerror(-ret));
61007b31
SH
914 return ret;
915 }
916 if (ret & BDRV_BLOCK_ZERO) {
237d78f8 917 offset += bytes;
61007b31
SH
918 continue;
919 }
237d78f8 920 ret = bdrv_pwrite_zeroes(child, offset, bytes, flags);
61007b31 921 if (ret < 0) {
7286d610
EB
922 error_report("error writing zeroes at offset %" PRId64 ": %s",
923 offset, strerror(-ret));
61007b31
SH
924 return ret;
925 }
237d78f8 926 offset += bytes;
61007b31
SH
927 }
928}
929
cf2ab8fc 930int bdrv_preadv(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
f1e84741
KW
931{
932 int ret;
933
e293b7a3 934 ret = bdrv_prwv_co(child, offset, qiov, false, 0);
f1e84741
KW
935 if (ret < 0) {
936 return ret;
937 }
938
939 return qiov->size;
940}
941
cf2ab8fc 942int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int bytes)
61007b31 943{
0d93ed08 944 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
61007b31
SH
945
946 if (bytes < 0) {
947 return -EINVAL;
948 }
949
cf2ab8fc 950 return bdrv_preadv(child, offset, &qiov);
61007b31
SH
951}
952
d9ca2ea2 953int bdrv_pwritev(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
61007b31
SH
954{
955 int ret;
956
e293b7a3 957 ret = bdrv_prwv_co(child, offset, qiov, true, 0);
61007b31
SH
958 if (ret < 0) {
959 return ret;
960 }
961
962 return qiov->size;
963}
964
d9ca2ea2 965int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf, int bytes)
61007b31 966{
0d93ed08 967 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
61007b31
SH
968
969 if (bytes < 0) {
970 return -EINVAL;
971 }
972
d9ca2ea2 973 return bdrv_pwritev(child, offset, &qiov);
61007b31
SH
974}
975
976/*
977 * Writes to the file and ensures that no writes are reordered across this
978 * request (acts as a barrier)
979 *
980 * Returns 0 on success, -errno in error cases.
981 */
d9ca2ea2
KW
982int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
983 const void *buf, int count)
61007b31
SH
984{
985 int ret;
986
d9ca2ea2 987 ret = bdrv_pwrite(child, offset, buf, count);
61007b31
SH
988 if (ret < 0) {
989 return ret;
990 }
991
d9ca2ea2 992 ret = bdrv_flush(child->bs);
855a6a93
KW
993 if (ret < 0) {
994 return ret;
61007b31
SH
995 }
996
997 return 0;
998}
999
08844473
KW
1000typedef struct CoroutineIOCompletion {
1001 Coroutine *coroutine;
1002 int ret;
1003} CoroutineIOCompletion;
1004
1005static void bdrv_co_io_em_complete(void *opaque, int ret)
1006{
1007 CoroutineIOCompletion *co = opaque;
1008
1009 co->ret = ret;
b9e413dd 1010 aio_co_wake(co->coroutine);
08844473
KW
1011}
1012
166fe960
KW
1013static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
1014 uint64_t offset, uint64_t bytes,
1015 QEMUIOVector *qiov, int flags)
1016{
1017 BlockDriver *drv = bs->drv;
3fb06697
KW
1018 int64_t sector_num;
1019 unsigned int nb_sectors;
1020
fa166538
EB
1021 assert(!(flags & ~BDRV_REQ_MASK));
1022
d470ad42
HR
1023 if (!drv) {
1024 return -ENOMEDIUM;
1025 }
1026
3fb06697
KW
1027 if (drv->bdrv_co_preadv) {
1028 return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
1029 }
1030
edfab6a0 1031 if (drv->bdrv_aio_preadv) {
08844473
KW
1032 BlockAIOCB *acb;
1033 CoroutineIOCompletion co = {
1034 .coroutine = qemu_coroutine_self(),
1035 };
1036
edfab6a0
EB
1037 acb = drv->bdrv_aio_preadv(bs, offset, bytes, qiov, flags,
1038 bdrv_co_io_em_complete, &co);
08844473
KW
1039 if (acb == NULL) {
1040 return -EIO;
1041 } else {
1042 qemu_coroutine_yield();
1043 return co.ret;
1044 }
1045 }
edfab6a0
EB
1046
1047 sector_num = offset >> BDRV_SECTOR_BITS;
1048 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1049
1050 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1051 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1052 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
1053 assert(drv->bdrv_co_readv);
1054
1055 return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
166fe960
KW
1056}
1057
78a07294
KW
1058static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
1059 uint64_t offset, uint64_t bytes,
1060 QEMUIOVector *qiov, int flags)
1061{
1062 BlockDriver *drv = bs->drv;
3fb06697
KW
1063 int64_t sector_num;
1064 unsigned int nb_sectors;
78a07294
KW
1065 int ret;
1066
fa166538
EB
1067 assert(!(flags & ~BDRV_REQ_MASK));
1068
d470ad42
HR
1069 if (!drv) {
1070 return -ENOMEDIUM;
1071 }
1072
3fb06697 1073 if (drv->bdrv_co_pwritev) {
515c2f43
KW
1074 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
1075 flags & bs->supported_write_flags);
1076 flags &= ~bs->supported_write_flags;
3fb06697
KW
1077 goto emulate_flags;
1078 }
1079
edfab6a0 1080 if (drv->bdrv_aio_pwritev) {
08844473
KW
1081 BlockAIOCB *acb;
1082 CoroutineIOCompletion co = {
1083 .coroutine = qemu_coroutine_self(),
1084 };
1085
edfab6a0
EB
1086 acb = drv->bdrv_aio_pwritev(bs, offset, bytes, qiov,
1087 flags & bs->supported_write_flags,
1088 bdrv_co_io_em_complete, &co);
1089 flags &= ~bs->supported_write_flags;
08844473 1090 if (acb == NULL) {
3fb06697 1091 ret = -EIO;
08844473
KW
1092 } else {
1093 qemu_coroutine_yield();
3fb06697 1094 ret = co.ret;
08844473 1095 }
edfab6a0
EB
1096 goto emulate_flags;
1097 }
1098
1099 sector_num = offset >> BDRV_SECTOR_BITS;
1100 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1101
1102 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1103 assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1104 assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
1105
e18a58b4
EB
1106 assert(drv->bdrv_co_writev);
1107 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov,
1108 flags & bs->supported_write_flags);
1109 flags &= ~bs->supported_write_flags;
78a07294 1110
3fb06697 1111emulate_flags:
4df863f3 1112 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
78a07294
KW
1113 ret = bdrv_co_flush(bs);
1114 }
1115
1116 return ret;
1117}
1118
29a298af
PB
1119static int coroutine_fn
1120bdrv_driver_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1121 uint64_t bytes, QEMUIOVector *qiov)
1122{
1123 BlockDriver *drv = bs->drv;
1124
d470ad42
HR
1125 if (!drv) {
1126 return -ENOMEDIUM;
1127 }
1128
29a298af
PB
1129 if (!drv->bdrv_co_pwritev_compressed) {
1130 return -ENOTSUP;
1131 }
1132
29a298af
PB
1133 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
1134}
1135
85c97ca7 1136static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
244483e6 1137 int64_t offset, unsigned int bytes, QEMUIOVector *qiov)
61007b31 1138{
85c97ca7
KW
1139 BlockDriverState *bs = child->bs;
1140
61007b31
SH
1141 /* Perform I/O through a temporary buffer so that users who scribble over
1142 * their read buffer while the operation is in progress do not end up
1143 * modifying the image file. This is critical for zero-copy guest I/O
1144 * where anything might happen inside guest memory.
1145 */
1146 void *bounce_buffer;
1147
1148 BlockDriver *drv = bs->drv;
cb2e2878 1149 QEMUIOVector local_qiov;
244483e6 1150 int64_t cluster_offset;
7cfd5275 1151 int64_t cluster_bytes;
61007b31
SH
1152 size_t skip_bytes;
1153 int ret;
cb2e2878
EB
1154 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1155 BDRV_REQUEST_MAX_BYTES);
1156 unsigned int progress = 0;
61007b31 1157
d470ad42
HR
1158 if (!drv) {
1159 return -ENOMEDIUM;
1160 }
1161
1bf03e66
KW
1162 /* FIXME We cannot require callers to have write permissions when all they
1163 * are doing is a read request. If we did things right, write permissions
1164 * would be obtained anyway, but internally by the copy-on-read code. As
765d9df9 1165 * long as it is implemented here rather than in a separate filter driver,
1bf03e66
KW
1166 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1167 * it could request permissions. Therefore we have to bypass the permission
1168 * system for the moment. */
1169 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
afa4b293 1170
61007b31 1171 /* Cover entire cluster so no additional backing file I/O is required when
cb2e2878
EB
1172 * allocating cluster in the image file. Note that this value may exceed
1173 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1174 * is one reason we loop rather than doing it all at once.
61007b31 1175 */
244483e6 1176 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
cb2e2878 1177 skip_bytes = offset - cluster_offset;
61007b31 1178
244483e6
KW
1179 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
1180 cluster_offset, cluster_bytes);
61007b31 1181
cb2e2878
EB
1182 bounce_buffer = qemu_try_blockalign(bs,
1183 MIN(MIN(max_transfer, cluster_bytes),
1184 MAX_BOUNCE_BUFFER));
61007b31
SH
1185 if (bounce_buffer == NULL) {
1186 ret = -ENOMEM;
1187 goto err;
1188 }
1189
cb2e2878
EB
1190 while (cluster_bytes) {
1191 int64_t pnum;
61007b31 1192
cb2e2878
EB
1193 ret = bdrv_is_allocated(bs, cluster_offset,
1194 MIN(cluster_bytes, max_transfer), &pnum);
1195 if (ret < 0) {
1196 /* Safe to treat errors in querying allocation as if
1197 * unallocated; we'll probably fail again soon on the
1198 * read, but at least that will set a decent errno.
1199 */
1200 pnum = MIN(cluster_bytes, max_transfer);
1201 }
61007b31 1202
b0ddcbbb
KW
1203 /* Stop at EOF if the image ends in the middle of the cluster */
1204 if (ret == 0 && pnum == 0) {
1205 assert(progress >= bytes);
1206 break;
1207 }
1208
cb2e2878 1209 assert(skip_bytes < pnum);
61007b31 1210
cb2e2878
EB
1211 if (ret <= 0) {
1212 /* Must copy-on-read; use the bounce buffer */
0d93ed08
VSO
1213 pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1214 qemu_iovec_init_buf(&local_qiov, bounce_buffer, pnum);
61007b31 1215
cb2e2878
EB
1216 ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1217 &local_qiov, 0);
1218 if (ret < 0) {
1219 goto err;
1220 }
1221
1222 bdrv_debug_event(bs, BLKDBG_COR_WRITE);
1223 if (drv->bdrv_co_pwrite_zeroes &&
1224 buffer_is_zero(bounce_buffer, pnum)) {
1225 /* FIXME: Should we (perhaps conditionally) be setting
1226 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1227 * that still correctly reads as zero? */
7adcf59f
HR
1228 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum,
1229 BDRV_REQ_WRITE_UNCHANGED);
cb2e2878
EB
1230 } else {
1231 /* This does not change the data on the disk, it is not
1232 * necessary to flush even in cache=writethrough mode.
1233 */
1234 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
7adcf59f
HR
1235 &local_qiov,
1236 BDRV_REQ_WRITE_UNCHANGED);
cb2e2878
EB
1237 }
1238
1239 if (ret < 0) {
1240 /* It might be okay to ignore write errors for guest
1241 * requests. If this is a deliberate copy-on-read
1242 * then we don't want to ignore the error. Simply
1243 * report it in all cases.
1244 */
1245 goto err;
1246 }
1247
1248 qemu_iovec_from_buf(qiov, progress, bounce_buffer + skip_bytes,
1249 pnum - skip_bytes);
1250 } else {
1251 /* Read directly into the destination */
1252 qemu_iovec_init(&local_qiov, qiov->niov);
1253 qemu_iovec_concat(&local_qiov, qiov, progress, pnum - skip_bytes);
1254 ret = bdrv_driver_preadv(bs, offset + progress, local_qiov.size,
1255 &local_qiov, 0);
1256 qemu_iovec_destroy(&local_qiov);
1257 if (ret < 0) {
1258 goto err;
1259 }
1260 }
1261
1262 cluster_offset += pnum;
1263 cluster_bytes -= pnum;
1264 progress += pnum - skip_bytes;
1265 skip_bytes = 0;
1266 }
1267 ret = 0;
61007b31
SH
1268
1269err:
1270 qemu_vfree(bounce_buffer);
1271 return ret;
1272}
1273
1274/*
1275 * Forwards an already correctly aligned request to the BlockDriver. This
1a62d0ac
EB
1276 * handles copy on read, zeroing after EOF, and fragmentation of large
1277 * reads; any other features must be implemented by the caller.
61007b31 1278 */
85c97ca7 1279static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
61007b31
SH
1280 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1281 int64_t align, QEMUIOVector *qiov, int flags)
1282{
85c97ca7 1283 BlockDriverState *bs = child->bs;
c9d20029 1284 int64_t total_bytes, max_bytes;
1a62d0ac
EB
1285 int ret = 0;
1286 uint64_t bytes_remaining = bytes;
1287 int max_transfer;
61007b31 1288
49c07526
KW
1289 assert(is_power_of_2(align));
1290 assert((offset & (align - 1)) == 0);
1291 assert((bytes & (align - 1)) == 0);
61007b31 1292 assert(!qiov || bytes == qiov->size);
abb06c5a 1293 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1a62d0ac
EB
1294 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1295 align);
a604fa2b
EB
1296
1297 /* TODO: We would need a per-BDS .supported_read_flags and
1298 * potential fallback support, if we ever implement any read flags
1299 * to pass through to drivers. For now, there aren't any
1300 * passthrough flags. */
1301 assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ)));
61007b31
SH
1302
1303 /* Handle Copy on Read and associated serialisation */
1304 if (flags & BDRV_REQ_COPY_ON_READ) {
1305 /* If we touch the same cluster it counts as an overlap. This
1306 * guarantees that allocating writes will be serialized and not race
1307 * with each other for the same cluster. For example, in copy-on-read
1308 * it ensures that the CoR read and write operations are atomic and
1309 * guest writes cannot interleave between them. */
1310 mark_request_serialising(req, bdrv_get_cluster_size(bs));
1311 }
1312
09d2f948
VSO
1313 /* BDRV_REQ_SERIALISING is only for write operation */
1314 assert(!(flags & BDRV_REQ_SERIALISING));
1315
61408b25
FZ
1316 if (!(flags & BDRV_REQ_NO_SERIALISING)) {
1317 wait_serialising_requests(req);
1318 }
61007b31
SH
1319
1320 if (flags & BDRV_REQ_COPY_ON_READ) {
d6a644bb 1321 int64_t pnum;
61007b31 1322
88e63df2 1323 ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
61007b31
SH
1324 if (ret < 0) {
1325 goto out;
1326 }
1327
88e63df2 1328 if (!ret || pnum != bytes) {
85c97ca7 1329 ret = bdrv_co_do_copy_on_readv(child, offset, bytes, qiov);
61007b31
SH
1330 goto out;
1331 }
1332 }
1333
1a62d0ac 1334 /* Forward the request to the BlockDriver, possibly fragmenting it */
c9d20029
KW
1335 total_bytes = bdrv_getlength(bs);
1336 if (total_bytes < 0) {
1337 ret = total_bytes;
1338 goto out;
1339 }
61007b31 1340
c9d20029 1341 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1a62d0ac 1342 if (bytes <= max_bytes && bytes <= max_transfer) {
c9d20029 1343 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
1a62d0ac
EB
1344 goto out;
1345 }
61007b31 1346
1a62d0ac
EB
1347 while (bytes_remaining) {
1348 int num;
61007b31 1349
1a62d0ac
EB
1350 if (max_bytes) {
1351 QEMUIOVector local_qiov;
61007b31 1352
1a62d0ac
EB
1353 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1354 assert(num);
1355 qemu_iovec_init(&local_qiov, qiov->niov);
1356 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
61007b31 1357
1a62d0ac
EB
1358 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1359 num, &local_qiov, 0);
1360 max_bytes -= num;
1361 qemu_iovec_destroy(&local_qiov);
1362 } else {
1363 num = bytes_remaining;
1364 ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0,
1365 bytes_remaining);
1366 }
1367 if (ret < 0) {
1368 goto out;
1369 }
1370 bytes_remaining -= num;
61007b31
SH
1371 }
1372
1373out:
1a62d0ac 1374 return ret < 0 ? ret : 0;
61007b31
SH
1375}
1376
61007b31
SH
1377/*
1378 * Handle a read request in coroutine context
1379 */
a03ef88f 1380int coroutine_fn bdrv_co_preadv(BdrvChild *child,
61007b31
SH
1381 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1382 BdrvRequestFlags flags)
1383{
a03ef88f 1384 BlockDriverState *bs = child->bs;
61007b31
SH
1385 BlockDriver *drv = bs->drv;
1386 BdrvTrackedRequest req;
1387
a5b8dd2c 1388 uint64_t align = bs->bl.request_alignment;
61007b31
SH
1389 uint8_t *head_buf = NULL;
1390 uint8_t *tail_buf = NULL;
1391 QEMUIOVector local_qiov;
1392 bool use_local_qiov = false;
1393 int ret;
1394
f42cf447
DB
1395 trace_bdrv_co_preadv(child->bs, offset, bytes, flags);
1396
61007b31
SH
1397 if (!drv) {
1398 return -ENOMEDIUM;
1399 }
1400
1401 ret = bdrv_check_byte_request(bs, offset, bytes);
1402 if (ret < 0) {
1403 return ret;
1404 }
1405
99723548
PB
1406 bdrv_inc_in_flight(bs);
1407
9568b511 1408 /* Don't do copy-on-read if we read data before write operation */
d3faa13e 1409 if (atomic_read(&bs->copy_on_read) && !(flags & BDRV_REQ_NO_SERIALISING)) {
61007b31
SH
1410 flags |= BDRV_REQ_COPY_ON_READ;
1411 }
1412
61007b31
SH
1413 /* Align read if necessary by padding qiov */
1414 if (offset & (align - 1)) {
1415 head_buf = qemu_blockalign(bs, align);
1416 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1417 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1418 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1419 use_local_qiov = true;
1420
1421 bytes += offset & (align - 1);
1422 offset = offset & ~(align - 1);
1423 }
1424
1425 if ((offset + bytes) & (align - 1)) {
1426 if (!use_local_qiov) {
1427 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1428 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1429 use_local_qiov = true;
1430 }
1431 tail_buf = qemu_blockalign(bs, align);
1432 qemu_iovec_add(&local_qiov, tail_buf,
1433 align - ((offset + bytes) & (align - 1)));
1434
1435 bytes = ROUND_UP(bytes, align);
1436 }
1437
ebde595c 1438 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
85c97ca7 1439 ret = bdrv_aligned_preadv(child, &req, offset, bytes, align,
61007b31
SH
1440 use_local_qiov ? &local_qiov : qiov,
1441 flags);
1442 tracked_request_end(&req);
99723548 1443 bdrv_dec_in_flight(bs);
61007b31
SH
1444
1445 if (use_local_qiov) {
1446 qemu_iovec_destroy(&local_qiov);
1447 qemu_vfree(head_buf);
1448 qemu_vfree(tail_buf);
1449 }
1450
1451 return ret;
1452}
1453
d05aa8bb 1454static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
f5a5ca79 1455 int64_t offset, int bytes, BdrvRequestFlags flags)
61007b31
SH
1456{
1457 BlockDriver *drv = bs->drv;
1458 QEMUIOVector qiov;
0d93ed08 1459 void *buf = NULL;
61007b31 1460 int ret = 0;
465fe887 1461 bool need_flush = false;
443668ca
DL
1462 int head = 0;
1463 int tail = 0;
61007b31 1464
cf081fca 1465 int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
a5b8dd2c
EB
1466 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1467 bs->bl.request_alignment);
cb2e2878 1468 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
d05aa8bb 1469
d470ad42
HR
1470 if (!drv) {
1471 return -ENOMEDIUM;
1472 }
1473
b8d0a980
EB
1474 assert(alignment % bs->bl.request_alignment == 0);
1475 head = offset % alignment;
f5a5ca79 1476 tail = (offset + bytes) % alignment;
b8d0a980
EB
1477 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1478 assert(max_write_zeroes >= bs->bl.request_alignment);
61007b31 1479
f5a5ca79
MP
1480 while (bytes > 0 && !ret) {
1481 int num = bytes;
61007b31
SH
1482
1483 /* Align request. Block drivers can expect the "bulk" of the request
443668ca
DL
1484 * to be aligned, and that unaligned requests do not cross cluster
1485 * boundaries.
61007b31 1486 */
443668ca 1487 if (head) {
b2f95fee
EB
1488 /* Make a small request up to the first aligned sector. For
1489 * convenience, limit this request to max_transfer even if
1490 * we don't need to fall back to writes. */
f5a5ca79 1491 num = MIN(MIN(bytes, max_transfer), alignment - head);
b2f95fee
EB
1492 head = (head + num) % alignment;
1493 assert(num < max_write_zeroes);
d05aa8bb 1494 } else if (tail && num > alignment) {
443668ca
DL
1495 /* Shorten the request to the last aligned sector. */
1496 num -= tail;
61007b31
SH
1497 }
1498
1499 /* limit request size */
1500 if (num > max_write_zeroes) {
1501 num = max_write_zeroes;
1502 }
1503
1504 ret = -ENOTSUP;
1505 /* First try the efficient write zeroes operation */
d05aa8bb
EB
1506 if (drv->bdrv_co_pwrite_zeroes) {
1507 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1508 flags & bs->supported_zero_flags);
1509 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1510 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1511 need_flush = true;
1512 }
465fe887
EB
1513 } else {
1514 assert(!bs->supported_zero_flags);
61007b31
SH
1515 }
1516
1517 if (ret == -ENOTSUP) {
1518 /* Fall back to bounce buffer if write zeroes is unsupported */
465fe887
EB
1519 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1520
1521 if ((flags & BDRV_REQ_FUA) &&
1522 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1523 /* No need for bdrv_driver_pwrite() to do a fallback
1524 * flush on each chunk; use just one at the end */
1525 write_flags &= ~BDRV_REQ_FUA;
1526 need_flush = true;
1527 }
5def6b80 1528 num = MIN(num, max_transfer);
0d93ed08
VSO
1529 if (buf == NULL) {
1530 buf = qemu_try_blockalign0(bs, num);
1531 if (buf == NULL) {
61007b31
SH
1532 ret = -ENOMEM;
1533 goto fail;
1534 }
61007b31 1535 }
0d93ed08 1536 qemu_iovec_init_buf(&qiov, buf, num);
61007b31 1537
d05aa8bb 1538 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags);
61007b31
SH
1539
1540 /* Keep bounce buffer around if it is big enough for all
1541 * all future requests.
1542 */
5def6b80 1543 if (num < max_transfer) {
0d93ed08
VSO
1544 qemu_vfree(buf);
1545 buf = NULL;
61007b31
SH
1546 }
1547 }
1548
d05aa8bb 1549 offset += num;
f5a5ca79 1550 bytes -= num;
61007b31
SH
1551 }
1552
1553fail:
465fe887
EB
1554 if (ret == 0 && need_flush) {
1555 ret = bdrv_co_flush(bs);
1556 }
0d93ed08 1557 qemu_vfree(buf);
61007b31
SH
1558 return ret;
1559}
1560
85fe2479
FZ
1561static inline int coroutine_fn
1562bdrv_co_write_req_prepare(BdrvChild *child, int64_t offset, uint64_t bytes,
1563 BdrvTrackedRequest *req, int flags)
1564{
1565 BlockDriverState *bs = child->bs;
1566 bool waited;
1567 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1568
1569 if (bs->read_only) {
1570 return -EPERM;
1571 }
1572
1573 /* BDRV_REQ_NO_SERIALISING is only for read operation */
1574 assert(!(flags & BDRV_REQ_NO_SERIALISING));
1575 assert(!(bs->open_flags & BDRV_O_INACTIVE));
1576 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1577 assert(!(flags & ~BDRV_REQ_MASK));
1578
1579 if (flags & BDRV_REQ_SERIALISING) {
1580 mark_request_serialising(req, bdrv_get_cluster_size(bs));
1581 }
1582
1583 waited = wait_serialising_requests(req);
1584
1585 assert(!waited || !req->serialising ||
1586 is_request_serialising_and_aligned(req));
1587 assert(req->overlap_offset <= offset);
1588 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
cd47d792 1589 assert(end_sector <= bs->total_sectors || child->perm & BLK_PERM_RESIZE);
85fe2479 1590
cd47d792
FZ
1591 switch (req->type) {
1592 case BDRV_TRACKED_WRITE:
1593 case BDRV_TRACKED_DISCARD:
1594 if (flags & BDRV_REQ_WRITE_UNCHANGED) {
1595 assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1596 } else {
1597 assert(child->perm & BLK_PERM_WRITE);
1598 }
1599 return notifier_with_return_list_notify(&bs->before_write_notifiers,
1600 req);
1601 case BDRV_TRACKED_TRUNCATE:
1602 assert(child->perm & BLK_PERM_RESIZE);
1603 return 0;
1604 default:
1605 abort();
85fe2479 1606 }
85fe2479
FZ
1607}
1608
1609static inline void coroutine_fn
1610bdrv_co_write_req_finish(BdrvChild *child, int64_t offset, uint64_t bytes,
1611 BdrvTrackedRequest *req, int ret)
1612{
1613 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
1614 BlockDriverState *bs = child->bs;
1615
1616 atomic_inc(&bs->write_gen);
85fe2479 1617
00695c27
FZ
1618 /*
1619 * Discard cannot extend the image, but in error handling cases, such as
1620 * when reverting a qcow2 cluster allocation, the discarded range can pass
1621 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1622 * here. Instead, just skip it, since semantically a discard request
1623 * beyond EOF cannot expand the image anyway.
1624 */
7f8f03ef 1625 if (ret == 0 &&
cd47d792
FZ
1626 (req->type == BDRV_TRACKED_TRUNCATE ||
1627 end_sector > bs->total_sectors) &&
1628 req->type != BDRV_TRACKED_DISCARD) {
7f8f03ef
FZ
1629 bs->total_sectors = end_sector;
1630 bdrv_parent_cb_resize(bs);
1631 bdrv_dirty_bitmap_truncate(bs, end_sector << BDRV_SECTOR_BITS);
85fe2479 1632 }
00695c27
FZ
1633 if (req->bytes) {
1634 switch (req->type) {
1635 case BDRV_TRACKED_WRITE:
1636 stat64_max(&bs->wr_highest_offset, offset + bytes);
1637 /* fall through, to set dirty bits */
1638 case BDRV_TRACKED_DISCARD:
1639 bdrv_set_dirty(bs, offset, bytes);
1640 break;
1641 default:
1642 break;
1643 }
1644 }
85fe2479
FZ
1645}
1646
61007b31 1647/*
04ed95f4
EB
1648 * Forwards an already correctly aligned write request to the BlockDriver,
1649 * after possibly fragmenting it.
61007b31 1650 */
85c97ca7 1651static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
61007b31 1652 BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
cff86b38 1653 int64_t align, QEMUIOVector *qiov, int flags)
61007b31 1654{
85c97ca7 1655 BlockDriverState *bs = child->bs;
61007b31 1656 BlockDriver *drv = bs->drv;
61007b31
SH
1657 int ret;
1658
04ed95f4
EB
1659 uint64_t bytes_remaining = bytes;
1660 int max_transfer;
61007b31 1661
d470ad42
HR
1662 if (!drv) {
1663 return -ENOMEDIUM;
1664 }
1665
d6883bc9
VSO
1666 if (bdrv_has_readonly_bitmaps(bs)) {
1667 return -EPERM;
1668 }
1669
cff86b38
EB
1670 assert(is_power_of_2(align));
1671 assert((offset & (align - 1)) == 0);
1672 assert((bytes & (align - 1)) == 0);
61007b31 1673 assert(!qiov || bytes == qiov->size);
04ed95f4
EB
1674 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1675 align);
61007b31 1676
85fe2479 1677 ret = bdrv_co_write_req_prepare(child, offset, bytes, req, flags);
61007b31
SH
1678
1679 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
c1499a5e 1680 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
61007b31
SH
1681 qemu_iovec_is_zero(qiov)) {
1682 flags |= BDRV_REQ_ZERO_WRITE;
1683 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
1684 flags |= BDRV_REQ_MAY_UNMAP;
1685 }
1686 }
1687
1688 if (ret < 0) {
1689 /* Do nothing, write notifier decided to fail this request */
1690 } else if (flags & BDRV_REQ_ZERO_WRITE) {
9a4f4c31 1691 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
9896c876 1692 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
3ea1a091
PB
1693 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
1694 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov);
04ed95f4 1695 } else if (bytes <= max_transfer) {
9a4f4c31 1696 bdrv_debug_event(bs, BLKDBG_PWRITEV);
78a07294 1697 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
04ed95f4
EB
1698 } else {
1699 bdrv_debug_event(bs, BLKDBG_PWRITEV);
1700 while (bytes_remaining) {
1701 int num = MIN(bytes_remaining, max_transfer);
1702 QEMUIOVector local_qiov;
1703 int local_flags = flags;
1704
1705 assert(num);
1706 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
1707 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1708 /* If FUA is going to be emulated by flush, we only
1709 * need to flush on the last iteration */
1710 local_flags &= ~BDRV_REQ_FUA;
1711 }
1712 qemu_iovec_init(&local_qiov, qiov->niov);
1713 qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
1714
1715 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
1716 num, &local_qiov, local_flags);
1717 qemu_iovec_destroy(&local_qiov);
1718 if (ret < 0) {
1719 break;
1720 }
1721 bytes_remaining -= num;
1722 }
61007b31 1723 }
9a4f4c31 1724 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
61007b31 1725
61007b31 1726 if (ret >= 0) {
04ed95f4 1727 ret = 0;
61007b31 1728 }
85fe2479 1729 bdrv_co_write_req_finish(child, offset, bytes, req, ret);
61007b31
SH
1730
1731 return ret;
1732}
1733
85c97ca7 1734static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
9eeb6dd1
FZ
1735 int64_t offset,
1736 unsigned int bytes,
1737 BdrvRequestFlags flags,
1738 BdrvTrackedRequest *req)
1739{
85c97ca7 1740 BlockDriverState *bs = child->bs;
9eeb6dd1
FZ
1741 uint8_t *buf = NULL;
1742 QEMUIOVector local_qiov;
a5b8dd2c 1743 uint64_t align = bs->bl.request_alignment;
9eeb6dd1
FZ
1744 unsigned int head_padding_bytes, tail_padding_bytes;
1745 int ret = 0;
1746
1747 head_padding_bytes = offset & (align - 1);
f13ce1be 1748 tail_padding_bytes = (align - (offset + bytes)) & (align - 1);
9eeb6dd1
FZ
1749
1750
1751 assert(flags & BDRV_REQ_ZERO_WRITE);
1752 if (head_padding_bytes || tail_padding_bytes) {
1753 buf = qemu_blockalign(bs, align);
0d93ed08 1754 qemu_iovec_init_buf(&local_qiov, buf, align);
9eeb6dd1
FZ
1755 }
1756 if (head_padding_bytes) {
1757 uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
1758
1759 /* RMW the unaligned part before head. */
1760 mark_request_serialising(req, align);
1761 wait_serialising_requests(req);
9a4f4c31 1762 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
85c97ca7 1763 ret = bdrv_aligned_preadv(child, req, offset & ~(align - 1), align,
9eeb6dd1
FZ
1764 align, &local_qiov, 0);
1765 if (ret < 0) {
1766 goto fail;
1767 }
9a4f4c31 1768 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
9eeb6dd1
FZ
1769
1770 memset(buf + head_padding_bytes, 0, zero_bytes);
85c97ca7 1771 ret = bdrv_aligned_pwritev(child, req, offset & ~(align - 1), align,
cff86b38 1772 align, &local_qiov,
9eeb6dd1
FZ
1773 flags & ~BDRV_REQ_ZERO_WRITE);
1774 if (ret < 0) {
1775 goto fail;
1776 }
1777 offset += zero_bytes;
1778 bytes -= zero_bytes;
1779 }
1780
1781 assert(!bytes || (offset & (align - 1)) == 0);
1782 if (bytes >= align) {
1783 /* Write the aligned part in the middle. */
1784 uint64_t aligned_bytes = bytes & ~(align - 1);
85c97ca7 1785 ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
9eeb6dd1
FZ
1786 NULL, flags);
1787 if (ret < 0) {
1788 goto fail;
1789 }
1790 bytes -= aligned_bytes;
1791 offset += aligned_bytes;
1792 }
1793
1794 assert(!bytes || (offset & (align - 1)) == 0);
1795 if (bytes) {
1796 assert(align == tail_padding_bytes + bytes);
1797 /* RMW the unaligned part after tail. */
1798 mark_request_serialising(req, align);
1799 wait_serialising_requests(req);
9a4f4c31 1800 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
85c97ca7 1801 ret = bdrv_aligned_preadv(child, req, offset, align,
9eeb6dd1
FZ
1802 align, &local_qiov, 0);
1803 if (ret < 0) {
1804 goto fail;
1805 }
9a4f4c31 1806 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
9eeb6dd1
FZ
1807
1808 memset(buf, 0, bytes);
85c97ca7 1809 ret = bdrv_aligned_pwritev(child, req, offset, align, align,
9eeb6dd1
FZ
1810 &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
1811 }
1812fail:
1813 qemu_vfree(buf);
1814 return ret;
1815
1816}
1817
61007b31
SH
1818/*
1819 * Handle a write request in coroutine context
1820 */
a03ef88f 1821int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
61007b31
SH
1822 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
1823 BdrvRequestFlags flags)
1824{
a03ef88f 1825 BlockDriverState *bs = child->bs;
61007b31 1826 BdrvTrackedRequest req;
a5b8dd2c 1827 uint64_t align = bs->bl.request_alignment;
61007b31
SH
1828 uint8_t *head_buf = NULL;
1829 uint8_t *tail_buf = NULL;
1830 QEMUIOVector local_qiov;
1831 bool use_local_qiov = false;
1832 int ret;
1833
f42cf447
DB
1834 trace_bdrv_co_pwritev(child->bs, offset, bytes, flags);
1835
61007b31
SH
1836 if (!bs->drv) {
1837 return -ENOMEDIUM;
1838 }
61007b31
SH
1839
1840 ret = bdrv_check_byte_request(bs, offset, bytes);
1841 if (ret < 0) {
1842 return ret;
1843 }
1844
99723548 1845 bdrv_inc_in_flight(bs);
61007b31
SH
1846 /*
1847 * Align write if necessary by performing a read-modify-write cycle.
1848 * Pad qiov with the read parts and be sure to have a tracked request not
1849 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1850 */
ebde595c 1851 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
61007b31 1852
18a59f03 1853 if (flags & BDRV_REQ_ZERO_WRITE) {
85c97ca7 1854 ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
9eeb6dd1
FZ
1855 goto out;
1856 }
1857
61007b31
SH
1858 if (offset & (align - 1)) {
1859 QEMUIOVector head_qiov;
61007b31
SH
1860
1861 mark_request_serialising(&req, align);
1862 wait_serialising_requests(&req);
1863
1864 head_buf = qemu_blockalign(bs, align);
0d93ed08 1865 qemu_iovec_init_buf(&head_qiov, head_buf, align);
61007b31 1866
9a4f4c31 1867 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
85c97ca7 1868 ret = bdrv_aligned_preadv(child, &req, offset & ~(align - 1), align,
61007b31
SH
1869 align, &head_qiov, 0);
1870 if (ret < 0) {
1871 goto fail;
1872 }
9a4f4c31 1873 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
61007b31
SH
1874
1875 qemu_iovec_init(&local_qiov, qiov->niov + 2);
1876 qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
1877 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1878 use_local_qiov = true;
1879
1880 bytes += offset & (align - 1);
1881 offset = offset & ~(align - 1);
117bc3fa
PL
1882
1883 /* We have read the tail already if the request is smaller
1884 * than one aligned block.
1885 */
1886 if (bytes < align) {
1887 qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes);
1888 bytes = align;
1889 }
61007b31
SH
1890 }
1891
1892 if ((offset + bytes) & (align - 1)) {
1893 QEMUIOVector tail_qiov;
61007b31
SH
1894 size_t tail_bytes;
1895 bool waited;
1896
1897 mark_request_serialising(&req, align);
1898 waited = wait_serialising_requests(&req);
1899 assert(!waited || !use_local_qiov);
1900
1901 tail_buf = qemu_blockalign(bs, align);
0d93ed08 1902 qemu_iovec_init_buf(&tail_qiov, tail_buf, align);
61007b31 1903
9a4f4c31 1904 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
85c97ca7
KW
1905 ret = bdrv_aligned_preadv(child, &req, (offset + bytes) & ~(align - 1),
1906 align, align, &tail_qiov, 0);
61007b31
SH
1907 if (ret < 0) {
1908 goto fail;
1909 }
9a4f4c31 1910 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
61007b31
SH
1911
1912 if (!use_local_qiov) {
1913 qemu_iovec_init(&local_qiov, qiov->niov + 1);
1914 qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
1915 use_local_qiov = true;
1916 }
1917
1918 tail_bytes = (offset + bytes) & (align - 1);
1919 qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
1920
1921 bytes = ROUND_UP(bytes, align);
1922 }
1923
85c97ca7 1924 ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
3ea1a091
PB
1925 use_local_qiov ? &local_qiov : qiov,
1926 flags);
61007b31
SH
1927
1928fail:
61007b31
SH
1929
1930 if (use_local_qiov) {
1931 qemu_iovec_destroy(&local_qiov);
1932 }
1933 qemu_vfree(head_buf);
1934 qemu_vfree(tail_buf);
9eeb6dd1
FZ
1935out:
1936 tracked_request_end(&req);
99723548 1937 bdrv_dec_in_flight(bs);
61007b31
SH
1938 return ret;
1939}
1940
a03ef88f 1941int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
f5a5ca79 1942 int bytes, BdrvRequestFlags flags)
61007b31 1943{
f5a5ca79 1944 trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
61007b31 1945
a03ef88f 1946 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
61007b31
SH
1947 flags &= ~BDRV_REQ_MAY_UNMAP;
1948 }
61007b31 1949
f5a5ca79 1950 return bdrv_co_pwritev(child, offset, bytes, NULL,
74021bc4 1951 BDRV_REQ_ZERO_WRITE | flags);
61007b31
SH
1952}
1953
4085f5c7
JS
1954/*
1955 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
1956 */
1957int bdrv_flush_all(void)
1958{
1959 BdrvNextIterator it;
1960 BlockDriverState *bs = NULL;
1961 int result = 0;
1962
1963 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
1964 AioContext *aio_context = bdrv_get_aio_context(bs);
1965 int ret;
1966
1967 aio_context_acquire(aio_context);
1968 ret = bdrv_flush(bs);
1969 if (ret < 0 && !result) {
1970 result = ret;
1971 }
1972 aio_context_release(aio_context);
1973 }
1974
1975 return result;
1976}
1977
1978
4bcd936e 1979typedef struct BdrvCoBlockStatusData {
61007b31
SH
1980 BlockDriverState *bs;
1981 BlockDriverState *base;
c9ce8c4d 1982 bool want_zero;
4bcd936e
EB
1983 int64_t offset;
1984 int64_t bytes;
1985 int64_t *pnum;
1986 int64_t *map;
c9ce8c4d 1987 BlockDriverState **file;
4bcd936e 1988 int ret;
61007b31 1989 bool done;
4bcd936e 1990} BdrvCoBlockStatusData;
61007b31 1991
3e4d0e72
EB
1992int coroutine_fn bdrv_co_block_status_from_file(BlockDriverState *bs,
1993 bool want_zero,
1994 int64_t offset,
1995 int64_t bytes,
1996 int64_t *pnum,
1997 int64_t *map,
1998 BlockDriverState **file)
f7cc69b3
MP
1999{
2000 assert(bs->file && bs->file->bs);
3e4d0e72
EB
2001 *pnum = bytes;
2002 *map = offset;
f7cc69b3 2003 *file = bs->file->bs;
3e4d0e72 2004 return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
f7cc69b3
MP
2005}
2006
3e4d0e72
EB
2007int coroutine_fn bdrv_co_block_status_from_backing(BlockDriverState *bs,
2008 bool want_zero,
2009 int64_t offset,
2010 int64_t bytes,
2011 int64_t *pnum,
2012 int64_t *map,
2013 BlockDriverState **file)
f7cc69b3
MP
2014{
2015 assert(bs->backing && bs->backing->bs);
3e4d0e72
EB
2016 *pnum = bytes;
2017 *map = offset;
f7cc69b3 2018 *file = bs->backing->bs;
3e4d0e72 2019 return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
f7cc69b3
MP
2020}
2021
61007b31
SH
2022/*
2023 * Returns the allocation status of the specified sectors.
2024 * Drivers not implementing the functionality are assumed to not support
2025 * backing files, hence all their sectors are reported as allocated.
2026 *
86a3d5c6
EB
2027 * If 'want_zero' is true, the caller is querying for mapping
2028 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2029 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2030 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
c9ce8c4d 2031 *
2e8bc787 2032 * If 'offset' is beyond the end of the disk image the return value is
fb0d8654 2033 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
61007b31 2034 *
2e8bc787 2035 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
fb0d8654
EB
2036 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2037 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
67a0fd2a 2038 *
2e8bc787
EB
2039 * 'pnum' is set to the number of bytes (including and immediately
2040 * following the specified offset) that are easily known to be in the
2041 * same allocated/unallocated state. Note that a second call starting
2042 * at the original offset plus returned pnum may have the same status.
2043 * The returned value is non-zero on success except at end-of-file.
2044 *
2045 * Returns negative errno on failure. Otherwise, if the
2046 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2047 * set to the host mapping and BDS corresponding to the guest offset.
61007b31 2048 */
2e8bc787
EB
2049static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
2050 bool want_zero,
2051 int64_t offset, int64_t bytes,
2052 int64_t *pnum, int64_t *map,
2053 BlockDriverState **file)
2054{
2055 int64_t total_size;
2056 int64_t n; /* bytes */
efa6e2ed 2057 int ret;
2e8bc787 2058 int64_t local_map = 0;
298a1665 2059 BlockDriverState *local_file = NULL;
efa6e2ed
EB
2060 int64_t aligned_offset, aligned_bytes;
2061 uint32_t align;
61007b31 2062
298a1665
EB
2063 assert(pnum);
2064 *pnum = 0;
2e8bc787
EB
2065 total_size = bdrv_getlength(bs);
2066 if (total_size < 0) {
2067 ret = total_size;
298a1665 2068 goto early_out;
61007b31
SH
2069 }
2070
2e8bc787 2071 if (offset >= total_size) {
298a1665
EB
2072 ret = BDRV_BLOCK_EOF;
2073 goto early_out;
61007b31 2074 }
2e8bc787 2075 if (!bytes) {
298a1665
EB
2076 ret = 0;
2077 goto early_out;
9cdcfd9f 2078 }
61007b31 2079
2e8bc787
EB
2080 n = total_size - offset;
2081 if (n < bytes) {
2082 bytes = n;
61007b31
SH
2083 }
2084
d470ad42
HR
2085 /* Must be non-NULL or bdrv_getlength() would have failed */
2086 assert(bs->drv);
636cb512 2087 if (!bs->drv->bdrv_co_block_status) {
2e8bc787 2088 *pnum = bytes;
61007b31 2089 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2e8bc787 2090 if (offset + bytes == total_size) {
fb0d8654
EB
2091 ret |= BDRV_BLOCK_EOF;
2092 }
61007b31 2093 if (bs->drv->protocol_name) {
2e8bc787
EB
2094 ret |= BDRV_BLOCK_OFFSET_VALID;
2095 local_map = offset;
298a1665 2096 local_file = bs;
61007b31 2097 }
298a1665 2098 goto early_out;
61007b31
SH
2099 }
2100
99723548 2101 bdrv_inc_in_flight(bs);
efa6e2ed
EB
2102
2103 /* Round out to request_alignment boundaries */
86a3d5c6 2104 align = bs->bl.request_alignment;
efa6e2ed
EB
2105 aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2106 aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2107
636cb512
EB
2108 ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2109 aligned_bytes, pnum, &local_map,
2110 &local_file);
2111 if (ret < 0) {
2112 *pnum = 0;
2113 goto out;
efa6e2ed
EB
2114 }
2115
2e8bc787 2116 /*
636cb512 2117 * The driver's result must be a non-zero multiple of request_alignment.
efa6e2ed 2118 * Clamp pnum and adjust map to original request.
2e8bc787 2119 */
636cb512
EB
2120 assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2121 align > offset - aligned_offset);
efa6e2ed
EB
2122 *pnum -= offset - aligned_offset;
2123 if (*pnum > bytes) {
2124 *pnum = bytes;
61007b31 2125 }
2e8bc787 2126 if (ret & BDRV_BLOCK_OFFSET_VALID) {
efa6e2ed 2127 local_map += offset - aligned_offset;
2e8bc787 2128 }
61007b31
SH
2129
2130 if (ret & BDRV_BLOCK_RAW) {
298a1665 2131 assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2e8bc787
EB
2132 ret = bdrv_co_block_status(local_file, want_zero, local_map,
2133 *pnum, pnum, &local_map, &local_file);
99723548 2134 goto out;
61007b31
SH
2135 }
2136
2137 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2138 ret |= BDRV_BLOCK_ALLOCATED;
c9ce8c4d 2139 } else if (want_zero) {
61007b31
SH
2140 if (bdrv_unallocated_blocks_are_zero(bs)) {
2141 ret |= BDRV_BLOCK_ZERO;
760e0063
KW
2142 } else if (bs->backing) {
2143 BlockDriverState *bs2 = bs->backing->bs;
2e8bc787 2144 int64_t size2 = bdrv_getlength(bs2);
c9ce8c4d 2145
2e8bc787 2146 if (size2 >= 0 && offset >= size2) {
61007b31
SH
2147 ret |= BDRV_BLOCK_ZERO;
2148 }
2149 }
2150 }
2151
c9ce8c4d 2152 if (want_zero && local_file && local_file != bs &&
61007b31
SH
2153 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2154 (ret & BDRV_BLOCK_OFFSET_VALID)) {
2e8bc787
EB
2155 int64_t file_pnum;
2156 int ret2;
61007b31 2157
2e8bc787
EB
2158 ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2159 *pnum, &file_pnum, NULL, NULL);
61007b31
SH
2160 if (ret2 >= 0) {
2161 /* Ignore errors. This is just providing extra information, it
2162 * is useful but not necessary.
2163 */
c61e684e
EB
2164 if (ret2 & BDRV_BLOCK_EOF &&
2165 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2166 /*
2167 * It is valid for the format block driver to read
2168 * beyond the end of the underlying file's current
2169 * size; such areas read as zero.
2170 */
61007b31
SH
2171 ret |= BDRV_BLOCK_ZERO;
2172 } else {
2173 /* Limit request to the range reported by the protocol driver */
2174 *pnum = file_pnum;
2175 ret |= (ret2 & BDRV_BLOCK_ZERO);
2176 }
2177 }
2178 }
2179
99723548
PB
2180out:
2181 bdrv_dec_in_flight(bs);
2e8bc787 2182 if (ret >= 0 && offset + *pnum == total_size) {
fb0d8654
EB
2183 ret |= BDRV_BLOCK_EOF;
2184 }
298a1665
EB
2185early_out:
2186 if (file) {
2187 *file = local_file;
2188 }
2e8bc787
EB
2189 if (map) {
2190 *map = local_map;
2191 }
61007b31
SH
2192 return ret;
2193}
2194
5b648c67
EB
2195static int coroutine_fn bdrv_co_block_status_above(BlockDriverState *bs,
2196 BlockDriverState *base,
2197 bool want_zero,
2198 int64_t offset,
2199 int64_t bytes,
2200 int64_t *pnum,
2201 int64_t *map,
2202 BlockDriverState **file)
ba3f0e25
FZ
2203{
2204 BlockDriverState *p;
5b648c67 2205 int ret = 0;
c61e684e 2206 bool first = true;
ba3f0e25
FZ
2207
2208 assert(bs != base);
760e0063 2209 for (p = bs; p != base; p = backing_bs(p)) {
5b648c67
EB
2210 ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2211 file);
c61e684e
EB
2212 if (ret < 0) {
2213 break;
2214 }
2215 if (ret & BDRV_BLOCK_ZERO && ret & BDRV_BLOCK_EOF && !first) {
2216 /*
2217 * Reading beyond the end of the file continues to read
2218 * zeroes, but we can only widen the result to the
2219 * unallocated length we learned from an earlier
2220 * iteration.
2221 */
5b648c67 2222 *pnum = bytes;
c61e684e
EB
2223 }
2224 if (ret & (BDRV_BLOCK_ZERO | BDRV_BLOCK_DATA)) {
ba3f0e25
FZ
2225 break;
2226 }
5b648c67
EB
2227 /* [offset, pnum] unallocated on this layer, which could be only
2228 * the first part of [offset, bytes]. */
2229 bytes = MIN(bytes, *pnum);
c61e684e 2230 first = false;
ba3f0e25
FZ
2231 }
2232 return ret;
2233}
2234
31826642 2235/* Coroutine wrapper for bdrv_block_status_above() */
5b648c67 2236static void coroutine_fn bdrv_block_status_above_co_entry(void *opaque)
61007b31 2237{
4bcd936e 2238 BdrvCoBlockStatusData *data = opaque;
61007b31 2239
5b648c67
EB
2240 data->ret = bdrv_co_block_status_above(data->bs, data->base,
2241 data->want_zero,
2242 data->offset, data->bytes,
2243 data->pnum, data->map, data->file);
61007b31 2244 data->done = true;
4720cbee 2245 aio_wait_kick();
61007b31
SH
2246}
2247
2248/*
5b648c67 2249 * Synchronous wrapper around bdrv_co_block_status_above().
61007b31 2250 *
5b648c67 2251 * See bdrv_co_block_status_above() for details.
61007b31 2252 */
7ddb99b9
EB
2253static int bdrv_common_block_status_above(BlockDriverState *bs,
2254 BlockDriverState *base,
2255 bool want_zero, int64_t offset,
2256 int64_t bytes, int64_t *pnum,
2257 int64_t *map,
2258 BlockDriverState **file)
61007b31
SH
2259{
2260 Coroutine *co;
4bcd936e 2261 BdrvCoBlockStatusData data = {
61007b31 2262 .bs = bs,
ba3f0e25 2263 .base = base,
c9ce8c4d 2264 .want_zero = want_zero,
7ddb99b9
EB
2265 .offset = offset,
2266 .bytes = bytes,
2267 .pnum = pnum,
2268 .map = map,
c9ce8c4d 2269 .file = file,
61007b31
SH
2270 .done = false,
2271 };
2272
2273 if (qemu_in_coroutine()) {
2274 /* Fast-path if already in coroutine context */
5b648c67 2275 bdrv_block_status_above_co_entry(&data);
61007b31 2276 } else {
5b648c67 2277 co = qemu_coroutine_create(bdrv_block_status_above_co_entry, &data);
e92f0e19 2278 bdrv_coroutine_enter(bs, co);
88b062c2 2279 BDRV_POLL_WHILE(bs, !data.done);
61007b31 2280 }
7ddb99b9 2281 return data.ret;
61007b31
SH
2282}
2283
31826642
EB
2284int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2285 int64_t offset, int64_t bytes, int64_t *pnum,
2286 int64_t *map, BlockDriverState **file)
c9ce8c4d 2287{
31826642
EB
2288 return bdrv_common_block_status_above(bs, base, true, offset, bytes,
2289 pnum, map, file);
c9ce8c4d
EB
2290}
2291
237d78f8
EB
2292int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2293 int64_t *pnum, int64_t *map, BlockDriverState **file)
ba3f0e25 2294{
31826642
EB
2295 return bdrv_block_status_above(bs, backing_bs(bs),
2296 offset, bytes, pnum, map, file);
ba3f0e25
FZ
2297}
2298
d6a644bb
EB
2299int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
2300 int64_t bytes, int64_t *pnum)
61007b31 2301{
7ddb99b9
EB
2302 int ret;
2303 int64_t dummy;
d6a644bb 2304
7ddb99b9
EB
2305 ret = bdrv_common_block_status_above(bs, backing_bs(bs), false, offset,
2306 bytes, pnum ? pnum : &dummy, NULL,
c9ce8c4d 2307 NULL);
61007b31
SH
2308 if (ret < 0) {
2309 return ret;
2310 }
2311 return !!(ret & BDRV_BLOCK_ALLOCATED);
2312}
2313
2314/*
2315 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2316 *
51b0a488
EB
2317 * Return true if (a prefix of) the given range is allocated in any image
2318 * between BASE and TOP (inclusive). BASE can be NULL to check if the given
2319 * offset is allocated in any image of the chain. Return false otherwise,
d6a644bb 2320 * or negative errno on failure.
61007b31 2321 *
51b0a488
EB
2322 * 'pnum' is set to the number of bytes (including and immediately
2323 * following the specified offset) that are known to be in the same
2324 * allocated/unallocated state. Note that a subsequent call starting
2325 * at 'offset + *pnum' may return the same allocation status (in other
2326 * words, the result is not necessarily the maximum possible range);
2327 * but 'pnum' will only be 0 when end of file is reached.
61007b31
SH
2328 *
2329 */
2330int bdrv_is_allocated_above(BlockDriverState *top,
2331 BlockDriverState *base,
51b0a488 2332 int64_t offset, int64_t bytes, int64_t *pnum)
61007b31
SH
2333{
2334 BlockDriverState *intermediate;
51b0a488
EB
2335 int ret;
2336 int64_t n = bytes;
61007b31
SH
2337
2338 intermediate = top;
2339 while (intermediate && intermediate != base) {
d6a644bb 2340 int64_t pnum_inter;
c00716be 2341 int64_t size_inter;
d6a644bb 2342
51b0a488 2343 ret = bdrv_is_allocated(intermediate, offset, bytes, &pnum_inter);
61007b31
SH
2344 if (ret < 0) {
2345 return ret;
d6a644bb 2346 }
d6a644bb 2347 if (ret) {
51b0a488 2348 *pnum = pnum_inter;
61007b31
SH
2349 return 1;
2350 }
2351
51b0a488 2352 size_inter = bdrv_getlength(intermediate);
c00716be
EB
2353 if (size_inter < 0) {
2354 return size_inter;
2355 }
51b0a488
EB
2356 if (n > pnum_inter &&
2357 (intermediate == top || offset + pnum_inter < size_inter)) {
2358 n = pnum_inter;
61007b31
SH
2359 }
2360
760e0063 2361 intermediate = backing_bs(intermediate);
61007b31
SH
2362 }
2363
2364 *pnum = n;
2365 return 0;
2366}
2367
1a8ae822
KW
2368typedef struct BdrvVmstateCo {
2369 BlockDriverState *bs;
2370 QEMUIOVector *qiov;
2371 int64_t pos;
2372 bool is_read;
2373 int ret;
2374} BdrvVmstateCo;
2375
2376static int coroutine_fn
2377bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
2378 bool is_read)
2379{
2380 BlockDriver *drv = bs->drv;
dc88a467
SH
2381 int ret = -ENOTSUP;
2382
2383 bdrv_inc_in_flight(bs);
1a8ae822
KW
2384
2385 if (!drv) {
dc88a467 2386 ret = -ENOMEDIUM;
1a8ae822 2387 } else if (drv->bdrv_load_vmstate) {
dc88a467
SH
2388 if (is_read) {
2389 ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2390 } else {
2391 ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2392 }
1a8ae822 2393 } else if (bs->file) {
dc88a467 2394 ret = bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read);
1a8ae822
KW
2395 }
2396
dc88a467
SH
2397 bdrv_dec_in_flight(bs);
2398 return ret;
1a8ae822
KW
2399}
2400
2401static void coroutine_fn bdrv_co_rw_vmstate_entry(void *opaque)
2402{
2403 BdrvVmstateCo *co = opaque;
2404 co->ret = bdrv_co_rw_vmstate(co->bs, co->qiov, co->pos, co->is_read);
4720cbee 2405 aio_wait_kick();
1a8ae822
KW
2406}
2407
2408static inline int
2409bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
2410 bool is_read)
2411{
2412 if (qemu_in_coroutine()) {
2413 return bdrv_co_rw_vmstate(bs, qiov, pos, is_read);
2414 } else {
2415 BdrvVmstateCo data = {
2416 .bs = bs,
2417 .qiov = qiov,
2418 .pos = pos,
2419 .is_read = is_read,
2420 .ret = -EINPROGRESS,
2421 };
0b8b8753 2422 Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry, &data);
1a8ae822 2423
e92f0e19 2424 bdrv_coroutine_enter(bs, co);
ea17c9d2 2425 BDRV_POLL_WHILE(bs, data.ret == -EINPROGRESS);
1a8ae822
KW
2426 return data.ret;
2427 }
2428}
2429
61007b31
SH
2430int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2431 int64_t pos, int size)
2432{
0d93ed08 2433 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
b433d942 2434 int ret;
61007b31 2435
b433d942
KW
2436 ret = bdrv_writev_vmstate(bs, &qiov, pos);
2437 if (ret < 0) {
2438 return ret;
2439 }
2440
2441 return size;
61007b31
SH
2442}
2443
2444int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2445{
1a8ae822 2446 return bdrv_rw_vmstate(bs, qiov, pos, false);
61007b31
SH
2447}
2448
2449int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2450 int64_t pos, int size)
5ddda0b8 2451{
0d93ed08 2452 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
b433d942 2453 int ret;
5ddda0b8 2454
b433d942
KW
2455 ret = bdrv_readv_vmstate(bs, &qiov, pos);
2456 if (ret < 0) {
2457 return ret;
2458 }
2459
2460 return size;
5ddda0b8
KW
2461}
2462
2463int bdrv_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
61007b31 2464{
1a8ae822 2465 return bdrv_rw_vmstate(bs, qiov, pos, true);
61007b31
SH
2466}
2467
2468/**************************************************************/
2469/* async I/Os */
2470
61007b31
SH
2471void bdrv_aio_cancel(BlockAIOCB *acb)
2472{
2473 qemu_aio_ref(acb);
2474 bdrv_aio_cancel_async(acb);
2475 while (acb->refcnt > 1) {
2476 if (acb->aiocb_info->get_aio_context) {
2477 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2478 } else if (acb->bs) {
2f47da5f
PB
2479 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2480 * assert that we're not using an I/O thread. Thread-safe
2481 * code should use bdrv_aio_cancel_async exclusively.
2482 */
2483 assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
61007b31
SH
2484 aio_poll(bdrv_get_aio_context(acb->bs), true);
2485 } else {
2486 abort();
2487 }
2488 }
2489 qemu_aio_unref(acb);
2490}
2491
2492/* Async version of aio cancel. The caller is not blocked if the acb implements
2493 * cancel_async, otherwise we do nothing and let the request normally complete.
2494 * In either case the completion callback must be called. */
2495void bdrv_aio_cancel_async(BlockAIOCB *acb)
2496{
2497 if (acb->aiocb_info->cancel_async) {
2498 acb->aiocb_info->cancel_async(acb);
2499 }
2500}
2501
61007b31
SH
2502/**************************************************************/
2503/* Coroutine block device emulation */
2504
e293b7a3
KW
2505typedef struct FlushCo {
2506 BlockDriverState *bs;
2507 int ret;
2508} FlushCo;
2509
2510
61007b31
SH
2511static void coroutine_fn bdrv_flush_co_entry(void *opaque)
2512{
e293b7a3 2513 FlushCo *rwco = opaque;
61007b31
SH
2514
2515 rwco->ret = bdrv_co_flush(rwco->bs);
4720cbee 2516 aio_wait_kick();
61007b31
SH
2517}
2518
2519int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2520{
49ca6259
FZ
2521 int current_gen;
2522 int ret = 0;
2523
2524 bdrv_inc_in_flight(bs);
61007b31 2525
e914404e 2526 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
1b6bc94d 2527 bdrv_is_sg(bs)) {
49ca6259 2528 goto early_exit;
61007b31
SH
2529 }
2530
3783fa3d 2531 qemu_co_mutex_lock(&bs->reqs_lock);
47fec599 2532 current_gen = atomic_read(&bs->write_gen);
3ff2f67a
EY
2533
2534 /* Wait until any previous flushes are completed */
99723548 2535 while (bs->active_flush_req) {
3783fa3d 2536 qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
3ff2f67a
EY
2537 }
2538
3783fa3d 2539 /* Flushes reach this point in nondecreasing current_gen order. */
99723548 2540 bs->active_flush_req = true;
3783fa3d 2541 qemu_co_mutex_unlock(&bs->reqs_lock);
3ff2f67a 2542
c32b82af
PD
2543 /* Write back all layers by calling one driver function */
2544 if (bs->drv->bdrv_co_flush) {
2545 ret = bs->drv->bdrv_co_flush(bs);
2546 goto out;
2547 }
2548
61007b31
SH
2549 /* Write back cached data to the OS even with cache=unsafe */
2550 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
2551 if (bs->drv->bdrv_co_flush_to_os) {
2552 ret = bs->drv->bdrv_co_flush_to_os(bs);
2553 if (ret < 0) {
cdb5e315 2554 goto out;
61007b31
SH
2555 }
2556 }
2557
2558 /* But don't actually force it to the disk with cache=unsafe */
2559 if (bs->open_flags & BDRV_O_NO_FLUSH) {
2560 goto flush_parent;
2561 }
2562
3ff2f67a
EY
2563 /* Check if we really need to flush anything */
2564 if (bs->flushed_gen == current_gen) {
2565 goto flush_parent;
2566 }
2567
61007b31 2568 BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
d470ad42
HR
2569 if (!bs->drv) {
2570 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2571 * (even in case of apparent success) */
2572 ret = -ENOMEDIUM;
2573 goto out;
2574 }
61007b31
SH
2575 if (bs->drv->bdrv_co_flush_to_disk) {
2576 ret = bs->drv->bdrv_co_flush_to_disk(bs);
2577 } else if (bs->drv->bdrv_aio_flush) {
2578 BlockAIOCB *acb;
2579 CoroutineIOCompletion co = {
2580 .coroutine = qemu_coroutine_self(),
2581 };
2582
2583 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
2584 if (acb == NULL) {
2585 ret = -EIO;
2586 } else {
2587 qemu_coroutine_yield();
2588 ret = co.ret;
2589 }
2590 } else {
2591 /*
2592 * Some block drivers always operate in either writethrough or unsafe
2593 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2594 * know how the server works (because the behaviour is hardcoded or
2595 * depends on server-side configuration), so we can't ensure that
2596 * everything is safe on disk. Returning an error doesn't work because
2597 * that would break guests even if the server operates in writethrough
2598 * mode.
2599 *
2600 * Let's hope the user knows what he's doing.
2601 */
2602 ret = 0;
2603 }
3ff2f67a 2604
61007b31 2605 if (ret < 0) {
cdb5e315 2606 goto out;
61007b31
SH
2607 }
2608
2609 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2610 * in the case of cache=unsafe, so there are no useless flushes.
2611 */
2612flush_parent:
cdb5e315
FZ
2613 ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2614out:
3ff2f67a 2615 /* Notify any pending flushes that we have completed */
e6af1e08
KW
2616 if (ret == 0) {
2617 bs->flushed_gen = current_gen;
2618 }
3783fa3d
PB
2619
2620 qemu_co_mutex_lock(&bs->reqs_lock);
99723548 2621 bs->active_flush_req = false;
156af3ac
DL
2622 /* Return value is ignored - it's ok if wait queue is empty */
2623 qemu_co_queue_next(&bs->flush_queue);
3783fa3d 2624 qemu_co_mutex_unlock(&bs->reqs_lock);
3ff2f67a 2625
49ca6259 2626early_exit:
99723548 2627 bdrv_dec_in_flight(bs);
cdb5e315 2628 return ret;
61007b31
SH
2629}
2630
2631int bdrv_flush(BlockDriverState *bs)
2632{
2633 Coroutine *co;
e293b7a3 2634 FlushCo flush_co = {
61007b31
SH
2635 .bs = bs,
2636 .ret = NOT_DONE,
2637 };
2638
2639 if (qemu_in_coroutine()) {
2640 /* Fast-path if already in coroutine context */
e293b7a3 2641 bdrv_flush_co_entry(&flush_co);
61007b31 2642 } else {
0b8b8753 2643 co = qemu_coroutine_create(bdrv_flush_co_entry, &flush_co);
e92f0e19 2644 bdrv_coroutine_enter(bs, co);
88b062c2 2645 BDRV_POLL_WHILE(bs, flush_co.ret == NOT_DONE);
61007b31
SH
2646 }
2647
e293b7a3 2648 return flush_co.ret;
61007b31
SH
2649}
2650
2651typedef struct DiscardCo {
0b9fd3f4 2652 BdrvChild *child;
0c51a893 2653 int64_t offset;
f5a5ca79 2654 int bytes;
61007b31
SH
2655 int ret;
2656} DiscardCo;
0c51a893 2657static void coroutine_fn bdrv_pdiscard_co_entry(void *opaque)
61007b31
SH
2658{
2659 DiscardCo *rwco = opaque;
2660
0b9fd3f4 2661 rwco->ret = bdrv_co_pdiscard(rwco->child, rwco->offset, rwco->bytes);
4720cbee 2662 aio_wait_kick();
61007b31
SH
2663}
2664
0b9fd3f4 2665int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset, int bytes)
61007b31 2666{
b1066c87 2667 BdrvTrackedRequest req;
9f1963b3 2668 int max_pdiscard, ret;
3482b9bc 2669 int head, tail, align;
0b9fd3f4 2670 BlockDriverState *bs = child->bs;
61007b31 2671
0b9fd3f4 2672 if (!bs || !bs->drv) {
61007b31
SH
2673 return -ENOMEDIUM;
2674 }
2675
d6883bc9
VSO
2676 if (bdrv_has_readonly_bitmaps(bs)) {
2677 return -EPERM;
2678 }
2679
f5a5ca79 2680 ret = bdrv_check_byte_request(bs, offset, bytes);
61007b31
SH
2681 if (ret < 0) {
2682 return ret;
61007b31
SH
2683 }
2684
61007b31
SH
2685 /* Do nothing if disabled. */
2686 if (!(bs->open_flags & BDRV_O_UNMAP)) {
2687 return 0;
2688 }
2689
02aefe43 2690 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
61007b31
SH
2691 return 0;
2692 }
2693
3482b9bc
EB
2694 /* Discard is advisory, but some devices track and coalesce
2695 * unaligned requests, so we must pass everything down rather than
2696 * round here. Still, most devices will just silently ignore
2697 * unaligned requests (by returning -ENOTSUP), so we must fragment
2698 * the request accordingly. */
02aefe43 2699 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
b8d0a980
EB
2700 assert(align % bs->bl.request_alignment == 0);
2701 head = offset % align;
f5a5ca79 2702 tail = (offset + bytes) % align;
9f1963b3 2703
99723548 2704 bdrv_inc_in_flight(bs);
f5a5ca79 2705 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
50824995 2706
00695c27 2707 ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
ec050f77
DL
2708 if (ret < 0) {
2709 goto out;
2710 }
2711
9f1963b3
EB
2712 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),
2713 align);
3482b9bc 2714 assert(max_pdiscard >= bs->bl.request_alignment);
61007b31 2715
f5a5ca79 2716 while (bytes > 0) {
f5a5ca79 2717 int num = bytes;
3482b9bc
EB
2718
2719 if (head) {
2720 /* Make small requests to get to alignment boundaries. */
f5a5ca79 2721 num = MIN(bytes, align - head);
3482b9bc
EB
2722 if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
2723 num %= bs->bl.request_alignment;
2724 }
2725 head = (head + num) % align;
2726 assert(num < max_pdiscard);
2727 } else if (tail) {
2728 if (num > align) {
2729 /* Shorten the request to the last aligned cluster. */
2730 num -= tail;
2731 } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
2732 tail > bs->bl.request_alignment) {
2733 tail %= bs->bl.request_alignment;
2734 num -= tail;
2735 }
2736 }
2737 /* limit request size */
2738 if (num > max_pdiscard) {
2739 num = max_pdiscard;
2740 }
61007b31 2741
d470ad42
HR
2742 if (!bs->drv) {
2743 ret = -ENOMEDIUM;
2744 goto out;
2745 }
47a5486d
EB
2746 if (bs->drv->bdrv_co_pdiscard) {
2747 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
61007b31
SH
2748 } else {
2749 BlockAIOCB *acb;
2750 CoroutineIOCompletion co = {
2751 .coroutine = qemu_coroutine_self(),
2752 };
2753
4da444a0
EB
2754 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
2755 bdrv_co_io_em_complete, &co);
61007b31 2756 if (acb == NULL) {
b1066c87
FZ
2757 ret = -EIO;
2758 goto out;
61007b31
SH
2759 } else {
2760 qemu_coroutine_yield();
2761 ret = co.ret;
2762 }
2763 }
2764 if (ret && ret != -ENOTSUP) {
b1066c87 2765 goto out;
61007b31
SH
2766 }
2767
9f1963b3 2768 offset += num;
f5a5ca79 2769 bytes -= num;
61007b31 2770 }
b1066c87
FZ
2771 ret = 0;
2772out:
00695c27 2773 bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
b1066c87 2774 tracked_request_end(&req);
99723548 2775 bdrv_dec_in_flight(bs);
b1066c87 2776 return ret;
61007b31
SH
2777}
2778
0b9fd3f4 2779int bdrv_pdiscard(BdrvChild *child, int64_t offset, int bytes)
61007b31
SH
2780{
2781 Coroutine *co;
2782 DiscardCo rwco = {
0b9fd3f4 2783 .child = child,
0c51a893 2784 .offset = offset,
f5a5ca79 2785 .bytes = bytes,
61007b31
SH
2786 .ret = NOT_DONE,
2787 };
2788
2789 if (qemu_in_coroutine()) {
2790 /* Fast-path if already in coroutine context */
0c51a893 2791 bdrv_pdiscard_co_entry(&rwco);
61007b31 2792 } else {
0c51a893 2793 co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco);
0b9fd3f4
FZ
2794 bdrv_coroutine_enter(child->bs, co);
2795 BDRV_POLL_WHILE(child->bs, rwco.ret == NOT_DONE);
61007b31
SH
2796 }
2797
2798 return rwco.ret;
2799}
2800
48af776a 2801int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
61007b31
SH
2802{
2803 BlockDriver *drv = bs->drv;
5c5ae76a
FZ
2804 CoroutineIOCompletion co = {
2805 .coroutine = qemu_coroutine_self(),
2806 };
2807 BlockAIOCB *acb;
61007b31 2808
99723548 2809 bdrv_inc_in_flight(bs);
16a389dc 2810 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
5c5ae76a
FZ
2811 co.ret = -ENOTSUP;
2812 goto out;
2813 }
2814
16a389dc
KW
2815 if (drv->bdrv_co_ioctl) {
2816 co.ret = drv->bdrv_co_ioctl(bs, req, buf);
2817 } else {
2818 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
2819 if (!acb) {
2820 co.ret = -ENOTSUP;
2821 goto out;
2822 }
2823 qemu_coroutine_yield();
5c5ae76a 2824 }
5c5ae76a 2825out:
99723548 2826 bdrv_dec_in_flight(bs);
5c5ae76a
FZ
2827 return co.ret;
2828}
2829
61007b31
SH
2830void *qemu_blockalign(BlockDriverState *bs, size_t size)
2831{
2832 return qemu_memalign(bdrv_opt_mem_align(bs), size);
2833}
2834
2835void *qemu_blockalign0(BlockDriverState *bs, size_t size)
2836{
2837 return memset(qemu_blockalign(bs, size), 0, size);
2838}
2839
2840void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
2841{
2842 size_t align = bdrv_opt_mem_align(bs);
2843
2844 /* Ensure that NULL is never returned on success */
2845 assert(align > 0);
2846 if (size == 0) {
2847 size = align;
2848 }
2849
2850 return qemu_try_memalign(align, size);
2851}
2852
2853void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
2854{
2855 void *mem = qemu_try_blockalign(bs, size);
2856
2857 if (mem) {
2858 memset(mem, 0, size);
2859 }
2860
2861 return mem;
2862}
2863
2864/*
2865 * Check if all memory in this vector is sector aligned.
2866 */
2867bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
2868{
2869 int i;
4196d2f0 2870 size_t alignment = bdrv_min_mem_align(bs);
61007b31
SH
2871
2872 for (i = 0; i < qiov->niov; i++) {
2873 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
2874 return false;
2875 }
2876 if (qiov->iov[i].iov_len % alignment) {
2877 return false;
2878 }
2879 }
2880
2881 return true;
2882}
2883
2884void bdrv_add_before_write_notifier(BlockDriverState *bs,
2885 NotifierWithReturn *notifier)
2886{
2887 notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
2888}
2889
2890void bdrv_io_plug(BlockDriverState *bs)
2891{
6b98bd64
PB
2892 BdrvChild *child;
2893
2894 QLIST_FOREACH(child, &bs->children, next) {
2895 bdrv_io_plug(child->bs);
2896 }
2897
850d54a2 2898 if (atomic_fetch_inc(&bs->io_plugged) == 0) {
6b98bd64
PB
2899 BlockDriver *drv = bs->drv;
2900 if (drv && drv->bdrv_io_plug) {
2901 drv->bdrv_io_plug(bs);
2902 }
61007b31
SH
2903 }
2904}
2905
2906void bdrv_io_unplug(BlockDriverState *bs)
2907{
6b98bd64
PB
2908 BdrvChild *child;
2909
2910 assert(bs->io_plugged);
850d54a2 2911 if (atomic_fetch_dec(&bs->io_plugged) == 1) {
6b98bd64
PB
2912 BlockDriver *drv = bs->drv;
2913 if (drv && drv->bdrv_io_unplug) {
2914 drv->bdrv_io_unplug(bs);
2915 }
2916 }
2917
2918 QLIST_FOREACH(child, &bs->children, next) {
2919 bdrv_io_unplug(child->bs);
61007b31
SH
2920 }
2921}
23d0ba93
FZ
2922
2923void bdrv_register_buf(BlockDriverState *bs, void *host, size_t size)
2924{
2925 BdrvChild *child;
2926
2927 if (bs->drv && bs->drv->bdrv_register_buf) {
2928 bs->drv->bdrv_register_buf(bs, host, size);
2929 }
2930 QLIST_FOREACH(child, &bs->children, next) {
2931 bdrv_register_buf(child->bs, host, size);
2932 }
2933}
2934
2935void bdrv_unregister_buf(BlockDriverState *bs, void *host)
2936{
2937 BdrvChild *child;
2938
2939 if (bs->drv && bs->drv->bdrv_unregister_buf) {
2940 bs->drv->bdrv_unregister_buf(bs, host);
2941 }
2942 QLIST_FOREACH(child, &bs->children, next) {
2943 bdrv_unregister_buf(child->bs, host);
2944 }
2945}
fcc67678 2946
67b51fb9
VSO
2947static int coroutine_fn bdrv_co_copy_range_internal(
2948 BdrvChild *src, uint64_t src_offset, BdrvChild *dst,
2949 uint64_t dst_offset, uint64_t bytes,
2950 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
2951 bool recurse_src)
fcc67678 2952{
999658a0 2953 BdrvTrackedRequest req;
fcc67678
FZ
2954 int ret;
2955
d4d3e5a0 2956 if (!dst || !dst->bs) {
fcc67678
FZ
2957 return -ENOMEDIUM;
2958 }
fcc67678
FZ
2959 ret = bdrv_check_byte_request(dst->bs, dst_offset, bytes);
2960 if (ret) {
2961 return ret;
2962 }
67b51fb9
VSO
2963 if (write_flags & BDRV_REQ_ZERO_WRITE) {
2964 return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
fcc67678
FZ
2965 }
2966
d4d3e5a0
FZ
2967 if (!src || !src->bs) {
2968 return -ENOMEDIUM;
2969 }
2970 ret = bdrv_check_byte_request(src->bs, src_offset, bytes);
2971 if (ret) {
2972 return ret;
2973 }
2974
fcc67678
FZ
2975 if (!src->bs->drv->bdrv_co_copy_range_from
2976 || !dst->bs->drv->bdrv_co_copy_range_to
2977 || src->bs->encrypted || dst->bs->encrypted) {
2978 return -ENOTSUP;
2979 }
37aec7d7 2980
fcc67678 2981 if (recurse_src) {
999658a0
VSO
2982 bdrv_inc_in_flight(src->bs);
2983 tracked_request_begin(&req, src->bs, src_offset, bytes,
2984 BDRV_TRACKED_READ);
2985
09d2f948
VSO
2986 /* BDRV_REQ_SERIALISING is only for write operation */
2987 assert(!(read_flags & BDRV_REQ_SERIALISING));
67b51fb9 2988 if (!(read_flags & BDRV_REQ_NO_SERIALISING)) {
999658a0
VSO
2989 wait_serialising_requests(&req);
2990 }
2991
37aec7d7
FZ
2992 ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
2993 src, src_offset,
2994 dst, dst_offset,
67b51fb9
VSO
2995 bytes,
2996 read_flags, write_flags);
999658a0
VSO
2997
2998 tracked_request_end(&req);
2999 bdrv_dec_in_flight(src->bs);
fcc67678 3000 } else {
999658a0
VSO
3001 bdrv_inc_in_flight(dst->bs);
3002 tracked_request_begin(&req, dst->bs, dst_offset, bytes,
3003 BDRV_TRACKED_WRITE);
0eb1e891
FZ
3004 ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3005 write_flags);
3006 if (!ret) {
3007 ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3008 src, src_offset,
3009 dst, dst_offset,
3010 bytes,
3011 read_flags, write_flags);
3012 }
3013 bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
999658a0
VSO
3014 tracked_request_end(&req);
3015 bdrv_dec_in_flight(dst->bs);
fcc67678 3016 }
999658a0 3017
37aec7d7 3018 return ret;
fcc67678
FZ
3019}
3020
3021/* Copy range from @src to @dst.
3022 *
3023 * See the comment of bdrv_co_copy_range for the parameter and return value
3024 * semantics. */
3025int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, uint64_t src_offset,
3026 BdrvChild *dst, uint64_t dst_offset,
67b51fb9
VSO
3027 uint64_t bytes,
3028 BdrvRequestFlags read_flags,
3029 BdrvRequestFlags write_flags)
fcc67678 3030{
ecc983a5
FZ
3031 trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3032 read_flags, write_flags);
fcc67678 3033 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
67b51fb9 3034 bytes, read_flags, write_flags, true);
fcc67678
FZ
3035}
3036
3037/* Copy range from @src to @dst.
3038 *
3039 * See the comment of bdrv_co_copy_range for the parameter and return value
3040 * semantics. */
3041int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, uint64_t src_offset,
3042 BdrvChild *dst, uint64_t dst_offset,
67b51fb9
VSO
3043 uint64_t bytes,
3044 BdrvRequestFlags read_flags,
3045 BdrvRequestFlags write_flags)
fcc67678 3046{
ecc983a5
FZ
3047 trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3048 read_flags, write_flags);
fcc67678 3049 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
67b51fb9 3050 bytes, read_flags, write_flags, false);
fcc67678
FZ
3051}
3052
3053int coroutine_fn bdrv_co_copy_range(BdrvChild *src, uint64_t src_offset,
3054 BdrvChild *dst, uint64_t dst_offset,
67b51fb9
VSO
3055 uint64_t bytes, BdrvRequestFlags read_flags,
3056 BdrvRequestFlags write_flags)
fcc67678 3057{
37aec7d7
FZ
3058 return bdrv_co_copy_range_from(src, src_offset,
3059 dst, dst_offset,
67b51fb9 3060 bytes, read_flags, write_flags);
fcc67678 3061}
3d9f2d2a
KW
3062
3063static void bdrv_parent_cb_resize(BlockDriverState *bs)
3064{
3065 BdrvChild *c;
3066 QLIST_FOREACH(c, &bs->parents, next_parent) {
3067 if (c->role->resize) {
3068 c->role->resize(c);
3069 }
3070 }
3071}
3072
3073/**
3074 * Truncate file to 'offset' bytes (needed only for file protocols)
3075 */
3076int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset,
3077 PreallocMode prealloc, Error **errp)
3078{
3079 BlockDriverState *bs = child->bs;
3080 BlockDriver *drv = bs->drv;
1bc5f09f
KW
3081 BdrvTrackedRequest req;
3082 int64_t old_size, new_bytes;
3d9f2d2a
KW
3083 int ret;
3084
3d9f2d2a
KW
3085
3086 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3087 if (!drv) {
3088 error_setg(errp, "No medium inserted");
3089 return -ENOMEDIUM;
3090 }
3091 if (offset < 0) {
3092 error_setg(errp, "Image size cannot be negative");
3093 return -EINVAL;
3094 }
3095
1bc5f09f
KW
3096 old_size = bdrv_getlength(bs);
3097 if (old_size < 0) {
3098 error_setg_errno(errp, -old_size, "Failed to get old image size");
3099 return old_size;
3100 }
3101
3102 if (offset > old_size) {
3103 new_bytes = offset - old_size;
3104 } else {
3105 new_bytes = 0;
3106 }
3107
3d9f2d2a 3108 bdrv_inc_in_flight(bs);
5416a11e
FZ
3109 tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3110 BDRV_TRACKED_TRUNCATE);
1bc5f09f
KW
3111
3112 /* If we are growing the image and potentially using preallocation for the
3113 * new area, we need to make sure that no write requests are made to it
3114 * concurrently or they might be overwritten by preallocation. */
3115 if (new_bytes) {
3116 mark_request_serialising(&req, 1);
cd47d792
FZ
3117 }
3118 if (bs->read_only) {
3119 error_setg(errp, "Image is read-only");
3120 ret = -EACCES;
3121 goto out;
3122 }
3123 ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3124 0);
3125 if (ret < 0) {
3126 error_setg_errno(errp, -ret,
3127 "Failed to prepare request for truncation");
3128 goto out;
1bc5f09f 3129 }
3d9f2d2a
KW
3130
3131 if (!drv->bdrv_co_truncate) {
3132 if (bs->file && drv->is_filter) {
3133 ret = bdrv_co_truncate(bs->file, offset, prealloc, errp);
3134 goto out;
3135 }
3136 error_setg(errp, "Image format driver does not support resize");
3137 ret = -ENOTSUP;
3138 goto out;
3139 }
3d9f2d2a
KW
3140
3141 ret = drv->bdrv_co_truncate(bs, offset, prealloc, errp);
3142 if (ret < 0) {
3143 goto out;
3144 }
3145 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3146 if (ret < 0) {
3147 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3148 } else {
3149 offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3150 }
cd47d792
FZ
3151 /* It's possible that truncation succeeded but refresh_total_sectors
3152 * failed, but the latter doesn't affect how we should finish the request.
3153 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3154 bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3d9f2d2a
KW
3155
3156out:
1bc5f09f 3157 tracked_request_end(&req);
3d9f2d2a 3158 bdrv_dec_in_flight(bs);
1bc5f09f 3159
3d9f2d2a
KW
3160 return ret;
3161}
3162
3163typedef struct TruncateCo {
3164 BdrvChild *child;
3165 int64_t offset;
3166 PreallocMode prealloc;
3167 Error **errp;
3168 int ret;
3169} TruncateCo;
3170
3171static void coroutine_fn bdrv_truncate_co_entry(void *opaque)
3172{
3173 TruncateCo *tco = opaque;
3174 tco->ret = bdrv_co_truncate(tco->child, tco->offset, tco->prealloc,
3175 tco->errp);
4720cbee 3176 aio_wait_kick();
3d9f2d2a
KW
3177}
3178
3179int bdrv_truncate(BdrvChild *child, int64_t offset, PreallocMode prealloc,
3180 Error **errp)
3181{
3182 Coroutine *co;
3183 TruncateCo tco = {
3184 .child = child,
3185 .offset = offset,
3186 .prealloc = prealloc,
3187 .errp = errp,
3188 .ret = NOT_DONE,
3189 };
3190
3191 if (qemu_in_coroutine()) {
3192 /* Fast-path if already in coroutine context */
3193 bdrv_truncate_co_entry(&tco);
3194 } else {
3195 co = qemu_coroutine_create(bdrv_truncate_co_entry, &tco);
4720cbee 3196 bdrv_coroutine_enter(child->bs, co);
3d9f2d2a
KW
3197 BDRV_POLL_WHILE(child->bs, tco.ret == NOT_DONE);
3198 }
3199
3200 return tco.ret;
3201}