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