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