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