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