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