docs: clarify that spec-ctrl is only needed for Spectre v2
[qemu/ar7.git] / block / mirror.c
blobeb9a4cdf565378aefd0d0b86fc0d5d3e6141d495
1 /*
2 * Image mirroring
4 * Copyright Red Hat, Inc. 2012
6 * Authors:
7 * Paolo Bonzini <pbonzini@redhat.com>
9 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
10 * See the COPYING.LIB file in the top-level directory.
14 #include "qemu/osdep.h"
15 #include "qemu/cutils.h"
16 #include "qemu/coroutine.h"
17 #include "qemu/range.h"
18 #include "trace.h"
19 #include "block/blockjob_int.h"
20 #include "block/block_int.h"
21 #include "sysemu/block-backend.h"
22 #include "qapi/error.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qemu/ratelimit.h"
25 #include "qemu/bitmap.h"
27 #define MAX_IN_FLIGHT 16
28 #define MAX_IO_BYTES (1 << 20) /* 1 Mb */
29 #define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
31 /* The mirroring buffer is a list of granularity-sized chunks.
32 * Free chunks are organized in a list.
34 typedef struct MirrorBuffer {
35 QSIMPLEQ_ENTRY(MirrorBuffer) next;
36 } MirrorBuffer;
38 typedef struct MirrorOp MirrorOp;
40 typedef struct MirrorBlockJob {
41 BlockJob common;
42 BlockBackend *target;
43 BlockDriverState *mirror_top_bs;
44 BlockDriverState *base;
46 /* The name of the graph node to replace */
47 char *replaces;
48 /* The BDS to replace */
49 BlockDriverState *to_replace;
50 /* Used to block operations on the drive-mirror-replace target */
51 Error *replace_blocker;
52 bool is_none_mode;
53 BlockMirrorBackingMode backing_mode;
54 MirrorCopyMode copy_mode;
55 BlockdevOnError on_source_error, on_target_error;
56 bool synced;
57 /* Set when the target is synced (dirty bitmap is clean, nothing
58 * in flight) and the job is running in active mode */
59 bool actively_synced;
60 bool should_complete;
61 int64_t granularity;
62 size_t buf_size;
63 int64_t bdev_length;
64 unsigned long *cow_bitmap;
65 BdrvDirtyBitmap *dirty_bitmap;
66 BdrvDirtyBitmapIter *dbi;
67 uint8_t *buf;
68 QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
69 int buf_free_count;
71 uint64_t last_pause_ns;
72 unsigned long *in_flight_bitmap;
73 int in_flight;
74 int64_t bytes_in_flight;
75 QTAILQ_HEAD(, MirrorOp) ops_in_flight;
76 int ret;
77 bool unmap;
78 int target_cluster_size;
79 int max_iov;
80 bool initial_zeroing_ongoing;
81 int in_active_write_counter;
82 bool prepared;
83 bool in_drain;
84 } MirrorBlockJob;
86 typedef struct MirrorBDSOpaque {
87 MirrorBlockJob *job;
88 } MirrorBDSOpaque;
90 struct MirrorOp {
91 MirrorBlockJob *s;
92 QEMUIOVector qiov;
93 int64_t offset;
94 uint64_t bytes;
96 /* The pointee is set by mirror_co_read(), mirror_co_zero(), and
97 * mirror_co_discard() before yielding for the first time */
98 int64_t *bytes_handled;
100 bool is_pseudo_op;
101 bool is_active_write;
102 CoQueue waiting_requests;
104 QTAILQ_ENTRY(MirrorOp) next;
107 typedef enum MirrorMethod {
108 MIRROR_METHOD_COPY,
109 MIRROR_METHOD_ZERO,
110 MIRROR_METHOD_DISCARD,
111 } MirrorMethod;
113 static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
114 int error)
116 s->synced = false;
117 s->actively_synced = false;
118 if (read) {
119 return block_job_error_action(&s->common, s->on_source_error,
120 true, error);
121 } else {
122 return block_job_error_action(&s->common, s->on_target_error,
123 false, error);
127 static void coroutine_fn mirror_wait_on_conflicts(MirrorOp *self,
128 MirrorBlockJob *s,
129 uint64_t offset,
130 uint64_t bytes)
132 uint64_t self_start_chunk = offset / s->granularity;
133 uint64_t self_end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
134 uint64_t self_nb_chunks = self_end_chunk - self_start_chunk;
136 while (find_next_bit(s->in_flight_bitmap, self_end_chunk,
137 self_start_chunk) < self_end_chunk &&
138 s->ret >= 0)
140 MirrorOp *op;
142 QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
143 uint64_t op_start_chunk = op->offset / s->granularity;
144 uint64_t op_nb_chunks = DIV_ROUND_UP(op->offset + op->bytes,
145 s->granularity) -
146 op_start_chunk;
148 if (op == self) {
149 continue;
152 if (ranges_overlap(self_start_chunk, self_nb_chunks,
153 op_start_chunk, op_nb_chunks))
155 qemu_co_queue_wait(&op->waiting_requests, NULL);
156 break;
162 static void coroutine_fn mirror_iteration_done(MirrorOp *op, int ret)
164 MirrorBlockJob *s = op->s;
165 struct iovec *iov;
166 int64_t chunk_num;
167 int i, nb_chunks;
169 trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
171 s->in_flight--;
172 s->bytes_in_flight -= op->bytes;
173 iov = op->qiov.iov;
174 for (i = 0; i < op->qiov.niov; i++) {
175 MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
176 QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
177 s->buf_free_count++;
180 chunk_num = op->offset / s->granularity;
181 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
183 bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
184 QTAILQ_REMOVE(&s->ops_in_flight, op, next);
185 if (ret >= 0) {
186 if (s->cow_bitmap) {
187 bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
189 if (!s->initial_zeroing_ongoing) {
190 job_progress_update(&s->common.job, op->bytes);
193 qemu_iovec_destroy(&op->qiov);
195 qemu_co_queue_restart_all(&op->waiting_requests);
196 g_free(op);
199 static void coroutine_fn mirror_write_complete(MirrorOp *op, int ret)
201 MirrorBlockJob *s = op->s;
203 if (ret < 0) {
204 BlockErrorAction action;
206 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
207 action = mirror_error_action(s, false, -ret);
208 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
209 s->ret = ret;
213 mirror_iteration_done(op, ret);
216 static void coroutine_fn mirror_read_complete(MirrorOp *op, int ret)
218 MirrorBlockJob *s = op->s;
220 if (ret < 0) {
221 BlockErrorAction action;
223 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
224 action = mirror_error_action(s, true, -ret);
225 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
226 s->ret = ret;
229 mirror_iteration_done(op, ret);
230 return;
233 ret = blk_co_pwritev(s->target, op->offset, op->qiov.size, &op->qiov, 0);
234 mirror_write_complete(op, ret);
237 /* Clip bytes relative to offset to not exceed end-of-file */
238 static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
239 int64_t offset,
240 int64_t bytes)
242 return MIN(bytes, s->bdev_length - offset);
245 /* Round offset and/or bytes to target cluster if COW is needed, and
246 * return the offset of the adjusted tail against original. */
247 static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
248 uint64_t *bytes)
250 bool need_cow;
251 int ret = 0;
252 int64_t align_offset = *offset;
253 int64_t align_bytes = *bytes;
254 int max_bytes = s->granularity * s->max_iov;
256 need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
257 need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
258 s->cow_bitmap);
259 if (need_cow) {
260 bdrv_round_to_clusters(blk_bs(s->target), *offset, *bytes,
261 &align_offset, &align_bytes);
264 if (align_bytes > max_bytes) {
265 align_bytes = max_bytes;
266 if (need_cow) {
267 align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
270 /* Clipping may result in align_bytes unaligned to chunk boundary, but
271 * that doesn't matter because it's already the end of source image. */
272 align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
274 ret = align_offset + align_bytes - (*offset + *bytes);
275 *offset = align_offset;
276 *bytes = align_bytes;
277 assert(ret >= 0);
278 return ret;
281 static inline void coroutine_fn
282 mirror_wait_for_any_operation(MirrorBlockJob *s, bool active)
284 MirrorOp *op;
286 QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
287 /* Do not wait on pseudo ops, because it may in turn wait on
288 * some other operation to start, which may in fact be the
289 * caller of this function. Since there is only one pseudo op
290 * at any given time, we will always find some real operation
291 * to wait on. */
292 if (!op->is_pseudo_op && op->is_active_write == active) {
293 qemu_co_queue_wait(&op->waiting_requests, NULL);
294 return;
297 abort();
300 static inline void coroutine_fn
301 mirror_wait_for_free_in_flight_slot(MirrorBlockJob *s)
303 /* Only non-active operations use up in-flight slots */
304 mirror_wait_for_any_operation(s, false);
307 /* Perform a mirror copy operation.
309 * *op->bytes_handled is set to the number of bytes copied after and
310 * including offset, excluding any bytes copied prior to offset due
311 * to alignment. This will be op->bytes if no alignment is necessary,
312 * or (new_end - op->offset) if the tail is rounded up or down due to
313 * alignment or buffer limit.
315 static void coroutine_fn mirror_co_read(void *opaque)
317 MirrorOp *op = opaque;
318 MirrorBlockJob *s = op->s;
319 int nb_chunks;
320 uint64_t ret;
321 uint64_t max_bytes;
323 max_bytes = s->granularity * s->max_iov;
325 /* We can only handle as much as buf_size at a time. */
326 op->bytes = MIN(s->buf_size, MIN(max_bytes, op->bytes));
327 assert(op->bytes);
328 assert(op->bytes < BDRV_REQUEST_MAX_BYTES);
329 *op->bytes_handled = op->bytes;
331 if (s->cow_bitmap) {
332 *op->bytes_handled += mirror_cow_align(s, &op->offset, &op->bytes);
334 /* Cannot exceed BDRV_REQUEST_MAX_BYTES + INT_MAX */
335 assert(*op->bytes_handled <= UINT_MAX);
336 assert(op->bytes <= s->buf_size);
337 /* The offset is granularity-aligned because:
338 * 1) Caller passes in aligned values;
339 * 2) mirror_cow_align is used only when target cluster is larger. */
340 assert(QEMU_IS_ALIGNED(op->offset, s->granularity));
341 /* The range is sector-aligned, since bdrv_getlength() rounds up. */
342 assert(QEMU_IS_ALIGNED(op->bytes, BDRV_SECTOR_SIZE));
343 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
345 while (s->buf_free_count < nb_chunks) {
346 trace_mirror_yield_in_flight(s, op->offset, s->in_flight);
347 mirror_wait_for_free_in_flight_slot(s);
350 /* Now make a QEMUIOVector taking enough granularity-sized chunks
351 * from s->buf_free.
353 qemu_iovec_init(&op->qiov, nb_chunks);
354 while (nb_chunks-- > 0) {
355 MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
356 size_t remaining = op->bytes - op->qiov.size;
358 QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
359 s->buf_free_count--;
360 qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
363 /* Copy the dirty cluster. */
364 s->in_flight++;
365 s->bytes_in_flight += op->bytes;
366 trace_mirror_one_iteration(s, op->offset, op->bytes);
368 ret = bdrv_co_preadv(s->mirror_top_bs->backing, op->offset, op->bytes,
369 &op->qiov, 0);
370 mirror_read_complete(op, ret);
373 static void coroutine_fn mirror_co_zero(void *opaque)
375 MirrorOp *op = opaque;
376 int ret;
378 op->s->in_flight++;
379 op->s->bytes_in_flight += op->bytes;
380 *op->bytes_handled = op->bytes;
382 ret = blk_co_pwrite_zeroes(op->s->target, op->offset, op->bytes,
383 op->s->unmap ? BDRV_REQ_MAY_UNMAP : 0);
384 mirror_write_complete(op, ret);
387 static void coroutine_fn mirror_co_discard(void *opaque)
389 MirrorOp *op = opaque;
390 int ret;
392 op->s->in_flight++;
393 op->s->bytes_in_flight += op->bytes;
394 *op->bytes_handled = op->bytes;
396 ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes);
397 mirror_write_complete(op, ret);
400 static unsigned mirror_perform(MirrorBlockJob *s, int64_t offset,
401 unsigned bytes, MirrorMethod mirror_method)
403 MirrorOp *op;
404 Coroutine *co;
405 int64_t bytes_handled = -1;
407 op = g_new(MirrorOp, 1);
408 *op = (MirrorOp){
409 .s = s,
410 .offset = offset,
411 .bytes = bytes,
412 .bytes_handled = &bytes_handled,
414 qemu_co_queue_init(&op->waiting_requests);
416 switch (mirror_method) {
417 case MIRROR_METHOD_COPY:
418 co = qemu_coroutine_create(mirror_co_read, op);
419 break;
420 case MIRROR_METHOD_ZERO:
421 co = qemu_coroutine_create(mirror_co_zero, op);
422 break;
423 case MIRROR_METHOD_DISCARD:
424 co = qemu_coroutine_create(mirror_co_discard, op);
425 break;
426 default:
427 abort();
430 QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
431 qemu_coroutine_enter(co);
432 /* At this point, ownership of op has been moved to the coroutine
433 * and the object may already be freed */
435 /* Assert that this value has been set */
436 assert(bytes_handled >= 0);
438 /* Same assertion as in mirror_co_read() (and for mirror_co_read()
439 * and mirror_co_discard(), bytes_handled == op->bytes, which
440 * is the @bytes parameter given to this function) */
441 assert(bytes_handled <= UINT_MAX);
442 return bytes_handled;
445 static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
447 BlockDriverState *source = s->mirror_top_bs->backing->bs;
448 MirrorOp *pseudo_op;
449 int64_t offset;
450 uint64_t delay_ns = 0, ret = 0;
451 /* At least the first dirty chunk is mirrored in one iteration. */
452 int nb_chunks = 1;
453 bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
454 int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
456 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
457 offset = bdrv_dirty_iter_next(s->dbi);
458 if (offset < 0) {
459 bdrv_set_dirty_iter(s->dbi, 0);
460 offset = bdrv_dirty_iter_next(s->dbi);
461 trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
462 assert(offset >= 0);
464 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
466 mirror_wait_on_conflicts(NULL, s, offset, 1);
468 job_pause_point(&s->common.job);
470 /* Find the number of consective dirty chunks following the first dirty
471 * one, and wait for in flight requests in them. */
472 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
473 while (nb_chunks * s->granularity < s->buf_size) {
474 int64_t next_dirty;
475 int64_t next_offset = offset + nb_chunks * s->granularity;
476 int64_t next_chunk = next_offset / s->granularity;
477 if (next_offset >= s->bdev_length ||
478 !bdrv_get_dirty_locked(source, s->dirty_bitmap, next_offset)) {
479 break;
481 if (test_bit(next_chunk, s->in_flight_bitmap)) {
482 break;
485 next_dirty = bdrv_dirty_iter_next(s->dbi);
486 if (next_dirty > next_offset || next_dirty < 0) {
487 /* The bitmap iterator's cache is stale, refresh it */
488 bdrv_set_dirty_iter(s->dbi, next_offset);
489 next_dirty = bdrv_dirty_iter_next(s->dbi);
491 assert(next_dirty == next_offset);
492 nb_chunks++;
495 /* Clear dirty bits before querying the block status, because
496 * calling bdrv_block_status_above could yield - if some blocks are
497 * marked dirty in this window, we need to know.
499 bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
500 nb_chunks * s->granularity);
501 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
503 /* Before claiming an area in the in-flight bitmap, we have to
504 * create a MirrorOp for it so that conflicting requests can wait
505 * for it. mirror_perform() will create the real MirrorOps later,
506 * for now we just create a pseudo operation that will wake up all
507 * conflicting requests once all real operations have been
508 * launched. */
509 pseudo_op = g_new(MirrorOp, 1);
510 *pseudo_op = (MirrorOp){
511 .offset = offset,
512 .bytes = nb_chunks * s->granularity,
513 .is_pseudo_op = true,
515 qemu_co_queue_init(&pseudo_op->waiting_requests);
516 QTAILQ_INSERT_TAIL(&s->ops_in_flight, pseudo_op, next);
518 bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
519 while (nb_chunks > 0 && offset < s->bdev_length) {
520 int ret;
521 int64_t io_bytes;
522 int64_t io_bytes_acct;
523 MirrorMethod mirror_method = MIRROR_METHOD_COPY;
525 assert(!(offset % s->granularity));
526 ret = bdrv_block_status_above(source, NULL, offset,
527 nb_chunks * s->granularity,
528 &io_bytes, NULL, NULL);
529 if (ret < 0) {
530 io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
531 } else if (ret & BDRV_BLOCK_DATA) {
532 io_bytes = MIN(io_bytes, max_io_bytes);
535 io_bytes -= io_bytes % s->granularity;
536 if (io_bytes < s->granularity) {
537 io_bytes = s->granularity;
538 } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
539 int64_t target_offset;
540 int64_t target_bytes;
541 bdrv_round_to_clusters(blk_bs(s->target), offset, io_bytes,
542 &target_offset, &target_bytes);
543 if (target_offset == offset &&
544 target_bytes == io_bytes) {
545 mirror_method = ret & BDRV_BLOCK_ZERO ?
546 MIRROR_METHOD_ZERO :
547 MIRROR_METHOD_DISCARD;
551 while (s->in_flight >= MAX_IN_FLIGHT) {
552 trace_mirror_yield_in_flight(s, offset, s->in_flight);
553 mirror_wait_for_free_in_flight_slot(s);
556 if (s->ret < 0) {
557 ret = 0;
558 goto fail;
561 io_bytes = mirror_clip_bytes(s, offset, io_bytes);
562 io_bytes = mirror_perform(s, offset, io_bytes, mirror_method);
563 if (mirror_method != MIRROR_METHOD_COPY && write_zeroes_ok) {
564 io_bytes_acct = 0;
565 } else {
566 io_bytes_acct = io_bytes;
568 assert(io_bytes);
569 offset += io_bytes;
570 nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
571 delay_ns = block_job_ratelimit_get_delay(&s->common, io_bytes_acct);
574 ret = delay_ns;
575 fail:
576 QTAILQ_REMOVE(&s->ops_in_flight, pseudo_op, next);
577 qemu_co_queue_restart_all(&pseudo_op->waiting_requests);
578 g_free(pseudo_op);
580 return ret;
583 static void mirror_free_init(MirrorBlockJob *s)
585 int granularity = s->granularity;
586 size_t buf_size = s->buf_size;
587 uint8_t *buf = s->buf;
589 assert(s->buf_free_count == 0);
590 QSIMPLEQ_INIT(&s->buf_free);
591 while (buf_size != 0) {
592 MirrorBuffer *cur = (MirrorBuffer *)buf;
593 QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
594 s->buf_free_count++;
595 buf_size -= granularity;
596 buf += granularity;
600 /* This is also used for the .pause callback. There is no matching
601 * mirror_resume() because mirror_run() will begin iterating again
602 * when the job is resumed.
604 static void coroutine_fn mirror_wait_for_all_io(MirrorBlockJob *s)
606 while (s->in_flight > 0) {
607 mirror_wait_for_free_in_flight_slot(s);
612 * mirror_exit_common: handle both abort() and prepare() cases.
613 * for .prepare, returns 0 on success and -errno on failure.
614 * for .abort cases, denoted by abort = true, MUST return 0.
616 static int mirror_exit_common(Job *job)
618 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
619 BlockJob *bjob = &s->common;
620 MirrorBDSOpaque *bs_opaque = s->mirror_top_bs->opaque;
621 AioContext *replace_aio_context = NULL;
622 BlockDriverState *src = s->mirror_top_bs->backing->bs;
623 BlockDriverState *target_bs = blk_bs(s->target);
624 BlockDriverState *mirror_top_bs = s->mirror_top_bs;
625 Error *local_err = NULL;
626 bool abort = job->ret < 0;
627 int ret = 0;
629 if (s->prepared) {
630 return 0;
632 s->prepared = true;
634 if (bdrv_chain_contains(src, target_bs)) {
635 bdrv_unfreeze_backing_chain(mirror_top_bs, target_bs);
638 bdrv_release_dirty_bitmap(src, s->dirty_bitmap);
640 /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
641 * before we can call bdrv_drained_end */
642 bdrv_ref(src);
643 bdrv_ref(mirror_top_bs);
644 bdrv_ref(target_bs);
646 /* Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
647 * inserting target_bs at s->to_replace, where we might not be able to get
648 * these permissions.
650 * Note that blk_unref() alone doesn't necessarily drop permissions because
651 * we might be running nested inside mirror_drain(), which takes an extra
652 * reference, so use an explicit blk_set_perm() first. */
653 blk_set_perm(s->target, 0, BLK_PERM_ALL, &error_abort);
654 blk_unref(s->target);
655 s->target = NULL;
657 /* We don't access the source any more. Dropping any WRITE/RESIZE is
658 * required before it could become a backing file of target_bs. */
659 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
660 &error_abort);
661 if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
662 BlockDriverState *backing = s->is_none_mode ? src : s->base;
663 if (backing_bs(target_bs) != backing) {
664 bdrv_set_backing_hd(target_bs, backing, &local_err);
665 if (local_err) {
666 error_report_err(local_err);
667 ret = -EPERM;
672 if (s->to_replace) {
673 replace_aio_context = bdrv_get_aio_context(s->to_replace);
674 aio_context_acquire(replace_aio_context);
677 if (s->should_complete && !abort) {
678 BlockDriverState *to_replace = s->to_replace ?: src;
679 bool ro = bdrv_is_read_only(to_replace);
681 if (ro != bdrv_is_read_only(target_bs)) {
682 bdrv_reopen_set_read_only(target_bs, ro, NULL);
685 /* The mirror job has no requests in flight any more, but we need to
686 * drain potential other users of the BDS before changing the graph. */
687 assert(s->in_drain);
688 bdrv_drained_begin(target_bs);
689 bdrv_replace_node(to_replace, target_bs, &local_err);
690 bdrv_drained_end(target_bs);
691 if (local_err) {
692 error_report_err(local_err);
693 ret = -EPERM;
696 if (s->to_replace) {
697 bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
698 error_free(s->replace_blocker);
699 bdrv_unref(s->to_replace);
701 if (replace_aio_context) {
702 aio_context_release(replace_aio_context);
704 g_free(s->replaces);
705 bdrv_unref(target_bs);
707 /* Remove the mirror filter driver from the graph. Before this, get rid of
708 * the blockers on the intermediate nodes so that the resulting state is
709 * valid. Also give up permissions on mirror_top_bs->backing, which might
710 * block the removal. */
711 block_job_remove_all_bdrv(bjob);
712 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
713 &error_abort);
714 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
716 /* We just changed the BDS the job BB refers to (with either or both of the
717 * bdrv_replace_node() calls), so switch the BB back so the cleanup does
718 * the right thing. We don't need any permissions any more now. */
719 blk_remove_bs(bjob->blk);
720 blk_set_perm(bjob->blk, 0, BLK_PERM_ALL, &error_abort);
721 blk_insert_bs(bjob->blk, mirror_top_bs, &error_abort);
723 bs_opaque->job = NULL;
725 bdrv_drained_end(src);
726 s->in_drain = false;
727 bdrv_unref(mirror_top_bs);
728 bdrv_unref(src);
730 return ret;
733 static int mirror_prepare(Job *job)
735 return mirror_exit_common(job);
738 static void mirror_abort(Job *job)
740 int ret = mirror_exit_common(job);
741 assert(ret == 0);
744 static void coroutine_fn mirror_throttle(MirrorBlockJob *s)
746 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
748 if (now - s->last_pause_ns > BLOCK_JOB_SLICE_TIME) {
749 s->last_pause_ns = now;
750 job_sleep_ns(&s->common.job, 0);
751 } else {
752 job_pause_point(&s->common.job);
756 static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
758 int64_t offset;
759 BlockDriverState *base = s->base;
760 BlockDriverState *bs = s->mirror_top_bs->backing->bs;
761 BlockDriverState *target_bs = blk_bs(s->target);
762 int ret;
763 int64_t count;
765 if (base == NULL && !bdrv_has_zero_init(target_bs)) {
766 if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
767 bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
768 return 0;
771 s->initial_zeroing_ongoing = true;
772 for (offset = 0; offset < s->bdev_length; ) {
773 int bytes = MIN(s->bdev_length - offset,
774 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
776 mirror_throttle(s);
778 if (job_is_cancelled(&s->common.job)) {
779 s->initial_zeroing_ongoing = false;
780 return 0;
783 if (s->in_flight >= MAX_IN_FLIGHT) {
784 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
785 s->in_flight);
786 mirror_wait_for_free_in_flight_slot(s);
787 continue;
790 mirror_perform(s, offset, bytes, MIRROR_METHOD_ZERO);
791 offset += bytes;
794 mirror_wait_for_all_io(s);
795 s->initial_zeroing_ongoing = false;
798 /* First part, loop on the sectors and initialize the dirty bitmap. */
799 for (offset = 0; offset < s->bdev_length; ) {
800 /* Just to make sure we are not exceeding int limit. */
801 int bytes = MIN(s->bdev_length - offset,
802 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
804 mirror_throttle(s);
806 if (job_is_cancelled(&s->common.job)) {
807 return 0;
810 ret = bdrv_is_allocated_above(bs, base, offset, bytes, &count);
811 if (ret < 0) {
812 return ret;
815 assert(count);
816 if (ret == 1) {
817 bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
819 offset += count;
821 return 0;
824 /* Called when going out of the streaming phase to flush the bulk of the
825 * data to the medium, or just before completing.
827 static int mirror_flush(MirrorBlockJob *s)
829 int ret = blk_flush(s->target);
830 if (ret < 0) {
831 if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
832 s->ret = ret;
835 return ret;
838 static int coroutine_fn mirror_run(Job *job, Error **errp)
840 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
841 BlockDriverState *bs = s->mirror_top_bs->backing->bs;
842 BlockDriverState *target_bs = blk_bs(s->target);
843 bool need_drain = true;
844 int64_t length;
845 BlockDriverInfo bdi;
846 char backing_filename[2]; /* we only need 2 characters because we are only
847 checking for a NULL string */
848 int ret = 0;
850 if (job_is_cancelled(&s->common.job)) {
851 goto immediate_exit;
854 s->bdev_length = bdrv_getlength(bs);
855 if (s->bdev_length < 0) {
856 ret = s->bdev_length;
857 goto immediate_exit;
860 /* Active commit must resize the base image if its size differs from the
861 * active layer. */
862 if (s->base == blk_bs(s->target)) {
863 int64_t base_length;
865 base_length = blk_getlength(s->target);
866 if (base_length < 0) {
867 ret = base_length;
868 goto immediate_exit;
871 if (s->bdev_length > base_length) {
872 ret = blk_truncate(s->target, s->bdev_length, PREALLOC_MODE_OFF,
873 NULL);
874 if (ret < 0) {
875 goto immediate_exit;
880 if (s->bdev_length == 0) {
881 /* Transition to the READY state and wait for complete. */
882 job_transition_to_ready(&s->common.job);
883 s->synced = true;
884 s->actively_synced = true;
885 while (!job_is_cancelled(&s->common.job) && !s->should_complete) {
886 job_yield(&s->common.job);
888 s->common.job.cancelled = false;
889 goto immediate_exit;
892 length = DIV_ROUND_UP(s->bdev_length, s->granularity);
893 s->in_flight_bitmap = bitmap_new(length);
895 /* If we have no backing file yet in the destination, we cannot let
896 * the destination do COW. Instead, we copy sectors around the
897 * dirty data if needed. We need a bitmap to do that.
899 bdrv_get_backing_filename(target_bs, backing_filename,
900 sizeof(backing_filename));
901 if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
902 s->target_cluster_size = bdi.cluster_size;
903 } else {
904 s->target_cluster_size = BDRV_SECTOR_SIZE;
906 if (backing_filename[0] && !target_bs->backing &&
907 s->granularity < s->target_cluster_size) {
908 s->buf_size = MAX(s->buf_size, s->target_cluster_size);
909 s->cow_bitmap = bitmap_new(length);
911 s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
913 s->buf = qemu_try_blockalign(bs, s->buf_size);
914 if (s->buf == NULL) {
915 ret = -ENOMEM;
916 goto immediate_exit;
919 mirror_free_init(s);
921 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
922 if (!s->is_none_mode) {
923 ret = mirror_dirty_init(s);
924 if (ret < 0 || job_is_cancelled(&s->common.job)) {
925 goto immediate_exit;
929 assert(!s->dbi);
930 s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
931 for (;;) {
932 uint64_t delay_ns = 0;
933 int64_t cnt, delta;
934 bool should_complete;
936 /* Do not start passive operations while there are active
937 * writes in progress */
938 while (s->in_active_write_counter) {
939 mirror_wait_for_any_operation(s, true);
942 if (s->ret < 0) {
943 ret = s->ret;
944 goto immediate_exit;
947 job_pause_point(&s->common.job);
949 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
950 /* cnt is the number of dirty bytes remaining and s->bytes_in_flight is
951 * the number of bytes currently being processed; together those are
952 * the current remaining operation length */
953 job_progress_set_remaining(&s->common.job, s->bytes_in_flight + cnt);
955 /* Note that even when no rate limit is applied we need to yield
956 * periodically with no pending I/O so that bdrv_drain_all() returns.
957 * We do so every BLKOCK_JOB_SLICE_TIME nanoseconds, or when there is
958 * an error, or when the source is clean, whichever comes first. */
959 delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
960 if (delta < BLOCK_JOB_SLICE_TIME &&
961 s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
962 if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
963 (cnt == 0 && s->in_flight > 0)) {
964 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
965 mirror_wait_for_free_in_flight_slot(s);
966 continue;
967 } else if (cnt != 0) {
968 delay_ns = mirror_iteration(s);
972 should_complete = false;
973 if (s->in_flight == 0 && cnt == 0) {
974 trace_mirror_before_flush(s);
975 if (!s->synced) {
976 if (mirror_flush(s) < 0) {
977 /* Go check s->ret. */
978 continue;
980 /* We're out of the streaming phase. From now on, if the job
981 * is cancelled we will actually complete all pending I/O and
982 * report completion. This way, block-job-cancel will leave
983 * the target in a consistent state.
985 job_transition_to_ready(&s->common.job);
986 s->synced = true;
987 if (s->copy_mode != MIRROR_COPY_MODE_BACKGROUND) {
988 s->actively_synced = true;
992 should_complete = s->should_complete ||
993 job_is_cancelled(&s->common.job);
994 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
997 if (cnt == 0 && should_complete) {
998 /* The dirty bitmap is not updated while operations are pending.
999 * If we're about to exit, wait for pending operations before
1000 * calling bdrv_get_dirty_count(bs), or we may exit while the
1001 * source has dirty data to copy!
1003 * Note that I/O can be submitted by the guest while
1004 * mirror_populate runs, so pause it now. Before deciding
1005 * whether to switch to target check one last time if I/O has
1006 * come in the meanwhile, and if not flush the data to disk.
1008 trace_mirror_before_drain(s, cnt);
1010 s->in_drain = true;
1011 bdrv_drained_begin(bs);
1012 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1013 if (cnt > 0 || mirror_flush(s) < 0) {
1014 bdrv_drained_end(bs);
1015 s->in_drain = false;
1016 continue;
1019 /* The two disks are in sync. Exit and report successful
1020 * completion.
1022 assert(QLIST_EMPTY(&bs->tracked_requests));
1023 s->common.job.cancelled = false;
1024 need_drain = false;
1025 break;
1028 ret = 0;
1030 if (s->synced && !should_complete) {
1031 delay_ns = (s->in_flight == 0 &&
1032 cnt == 0 ? BLOCK_JOB_SLICE_TIME : 0);
1034 trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
1035 job_sleep_ns(&s->common.job, delay_ns);
1036 if (job_is_cancelled(&s->common.job) &&
1037 (!s->synced || s->common.job.force_cancel))
1039 break;
1041 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1044 immediate_exit:
1045 if (s->in_flight > 0) {
1046 /* We get here only if something went wrong. Either the job failed,
1047 * or it was cancelled prematurely so that we do not guarantee that
1048 * the target is a copy of the source.
1050 assert(ret < 0 || ((s->common.job.force_cancel || !s->synced) &&
1051 job_is_cancelled(&s->common.job)));
1052 assert(need_drain);
1053 mirror_wait_for_all_io(s);
1056 assert(s->in_flight == 0);
1057 qemu_vfree(s->buf);
1058 g_free(s->cow_bitmap);
1059 g_free(s->in_flight_bitmap);
1060 bdrv_dirty_iter_free(s->dbi);
1062 if (need_drain) {
1063 s->in_drain = true;
1064 bdrv_drained_begin(bs);
1067 return ret;
1070 static void mirror_complete(Job *job, Error **errp)
1072 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1073 BlockDriverState *target;
1075 target = blk_bs(s->target);
1077 if (!s->synced) {
1078 error_setg(errp, "The active block job '%s' cannot be completed",
1079 job->id);
1080 return;
1083 if (s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
1084 int ret;
1086 assert(!target->backing);
1087 ret = bdrv_open_backing_file(target, NULL, "backing", errp);
1088 if (ret < 0) {
1089 return;
1093 /* block all operations on to_replace bs */
1094 if (s->replaces) {
1095 AioContext *replace_aio_context;
1097 s->to_replace = bdrv_find_node(s->replaces);
1098 if (!s->to_replace) {
1099 error_setg(errp, "Node name '%s' not found", s->replaces);
1100 return;
1103 replace_aio_context = bdrv_get_aio_context(s->to_replace);
1104 aio_context_acquire(replace_aio_context);
1106 /* TODO Translate this into permission system. Current definition of
1107 * GRAPH_MOD would require to request it for the parents; they might
1108 * not even be BlockDriverStates, however, so a BdrvChild can't address
1109 * them. May need redefinition of GRAPH_MOD. */
1110 error_setg(&s->replace_blocker,
1111 "block device is in use by block-job-complete");
1112 bdrv_op_block_all(s->to_replace, s->replace_blocker);
1113 bdrv_ref(s->to_replace);
1115 aio_context_release(replace_aio_context);
1118 s->should_complete = true;
1119 job_enter(job);
1122 static void coroutine_fn mirror_pause(Job *job)
1124 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1126 mirror_wait_for_all_io(s);
1129 static bool mirror_drained_poll(BlockJob *job)
1131 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1133 /* If the job isn't paused nor cancelled, we can't be sure that it won't
1134 * issue more requests. We make an exception if we've reached this point
1135 * from one of our own drain sections, to avoid a deadlock waiting for
1136 * ourselves.
1138 if (!s->common.job.paused && !s->common.job.cancelled && !s->in_drain) {
1139 return true;
1142 return !!s->in_flight;
1145 static void mirror_attached_aio_context(BlockJob *job, AioContext *new_context)
1147 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1149 blk_set_aio_context(s->target, new_context);
1152 static void mirror_drain(BlockJob *job)
1154 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1156 /* Need to keep a reference in case blk_drain triggers execution
1157 * of mirror_complete...
1159 if (s->target) {
1160 BlockBackend *target = s->target;
1161 blk_ref(target);
1162 blk_drain(target);
1163 blk_unref(target);
1167 static const BlockJobDriver mirror_job_driver = {
1168 .job_driver = {
1169 .instance_size = sizeof(MirrorBlockJob),
1170 .job_type = JOB_TYPE_MIRROR,
1171 .free = block_job_free,
1172 .user_resume = block_job_user_resume,
1173 .drain = block_job_drain,
1174 .run = mirror_run,
1175 .prepare = mirror_prepare,
1176 .abort = mirror_abort,
1177 .pause = mirror_pause,
1178 .complete = mirror_complete,
1180 .drained_poll = mirror_drained_poll,
1181 .attached_aio_context = mirror_attached_aio_context,
1182 .drain = mirror_drain,
1185 static const BlockJobDriver commit_active_job_driver = {
1186 .job_driver = {
1187 .instance_size = sizeof(MirrorBlockJob),
1188 .job_type = JOB_TYPE_COMMIT,
1189 .free = block_job_free,
1190 .user_resume = block_job_user_resume,
1191 .drain = block_job_drain,
1192 .run = mirror_run,
1193 .prepare = mirror_prepare,
1194 .abort = mirror_abort,
1195 .pause = mirror_pause,
1196 .complete = mirror_complete,
1198 .drained_poll = mirror_drained_poll,
1199 .attached_aio_context = mirror_attached_aio_context,
1200 .drain = mirror_drain,
1203 static void coroutine_fn
1204 do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
1205 uint64_t offset, uint64_t bytes,
1206 QEMUIOVector *qiov, int flags)
1208 QEMUIOVector target_qiov;
1209 uint64_t dirty_offset = offset;
1210 uint64_t dirty_bytes;
1212 if (qiov) {
1213 qemu_iovec_init(&target_qiov, qiov->niov);
1216 while (true) {
1217 bool valid_area;
1218 int ret;
1220 bdrv_dirty_bitmap_lock(job->dirty_bitmap);
1221 dirty_bytes = MIN(offset + bytes - dirty_offset, INT_MAX);
1222 valid_area = bdrv_dirty_bitmap_next_dirty_area(job->dirty_bitmap,
1223 &dirty_offset,
1224 &dirty_bytes);
1225 if (!valid_area) {
1226 bdrv_dirty_bitmap_unlock(job->dirty_bitmap);
1227 break;
1230 bdrv_reset_dirty_bitmap_locked(job->dirty_bitmap,
1231 dirty_offset, dirty_bytes);
1232 bdrv_dirty_bitmap_unlock(job->dirty_bitmap);
1234 job_progress_increase_remaining(&job->common.job, dirty_bytes);
1236 assert(dirty_offset - offset <= SIZE_MAX);
1237 if (qiov) {
1238 qemu_iovec_reset(&target_qiov);
1239 qemu_iovec_concat(&target_qiov, qiov,
1240 dirty_offset - offset, dirty_bytes);
1243 switch (method) {
1244 case MIRROR_METHOD_COPY:
1245 ret = blk_co_pwritev(job->target, dirty_offset, dirty_bytes,
1246 qiov ? &target_qiov : NULL, flags);
1247 break;
1249 case MIRROR_METHOD_ZERO:
1250 assert(!qiov);
1251 ret = blk_co_pwrite_zeroes(job->target, dirty_offset, dirty_bytes,
1252 flags);
1253 break;
1255 case MIRROR_METHOD_DISCARD:
1256 assert(!qiov);
1257 ret = blk_co_pdiscard(job->target, dirty_offset, dirty_bytes);
1258 break;
1260 default:
1261 abort();
1264 if (ret >= 0) {
1265 job_progress_update(&job->common.job, dirty_bytes);
1266 } else {
1267 BlockErrorAction action;
1269 bdrv_set_dirty_bitmap(job->dirty_bitmap, dirty_offset, dirty_bytes);
1270 job->actively_synced = false;
1272 action = mirror_error_action(job, false, -ret);
1273 if (action == BLOCK_ERROR_ACTION_REPORT) {
1274 if (!job->ret) {
1275 job->ret = ret;
1277 break;
1281 dirty_offset += dirty_bytes;
1284 if (qiov) {
1285 qemu_iovec_destroy(&target_qiov);
1289 static MirrorOp *coroutine_fn active_write_prepare(MirrorBlockJob *s,
1290 uint64_t offset,
1291 uint64_t bytes)
1293 MirrorOp *op;
1294 uint64_t start_chunk = offset / s->granularity;
1295 uint64_t end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1297 op = g_new(MirrorOp, 1);
1298 *op = (MirrorOp){
1299 .s = s,
1300 .offset = offset,
1301 .bytes = bytes,
1302 .is_active_write = true,
1304 qemu_co_queue_init(&op->waiting_requests);
1305 QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
1307 s->in_active_write_counter++;
1309 mirror_wait_on_conflicts(op, s, offset, bytes);
1311 bitmap_set(s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1313 return op;
1316 static void coroutine_fn active_write_settle(MirrorOp *op)
1318 uint64_t start_chunk = op->offset / op->s->granularity;
1319 uint64_t end_chunk = DIV_ROUND_UP(op->offset + op->bytes,
1320 op->s->granularity);
1322 if (!--op->s->in_active_write_counter && op->s->actively_synced) {
1323 BdrvChild *source = op->s->mirror_top_bs->backing;
1325 if (QLIST_FIRST(&source->bs->parents) == source &&
1326 QLIST_NEXT(source, next_parent) == NULL)
1328 /* Assert that we are back in sync once all active write
1329 * operations are settled.
1330 * Note that we can only assert this if the mirror node
1331 * is the source node's only parent. */
1332 assert(!bdrv_get_dirty_count(op->s->dirty_bitmap));
1335 bitmap_clear(op->s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1336 QTAILQ_REMOVE(&op->s->ops_in_flight, op, next);
1337 qemu_co_queue_restart_all(&op->waiting_requests);
1338 g_free(op);
1341 static int coroutine_fn bdrv_mirror_top_preadv(BlockDriverState *bs,
1342 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1344 return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
1347 static int coroutine_fn bdrv_mirror_top_do_write(BlockDriverState *bs,
1348 MirrorMethod method, uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
1349 int flags)
1351 MirrorOp *op = NULL;
1352 MirrorBDSOpaque *s = bs->opaque;
1353 int ret = 0;
1354 bool copy_to_target;
1356 copy_to_target = s->job->ret >= 0 &&
1357 s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1359 if (copy_to_target) {
1360 op = active_write_prepare(s->job, offset, bytes);
1363 switch (method) {
1364 case MIRROR_METHOD_COPY:
1365 ret = bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1366 break;
1368 case MIRROR_METHOD_ZERO:
1369 ret = bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
1370 break;
1372 case MIRROR_METHOD_DISCARD:
1373 ret = bdrv_co_pdiscard(bs->backing, offset, bytes);
1374 break;
1376 default:
1377 abort();
1380 if (ret < 0) {
1381 goto out;
1384 if (copy_to_target) {
1385 do_sync_target_write(s->job, method, offset, bytes, qiov, flags);
1388 out:
1389 if (copy_to_target) {
1390 active_write_settle(op);
1392 return ret;
1395 static int coroutine_fn bdrv_mirror_top_pwritev(BlockDriverState *bs,
1396 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1398 MirrorBDSOpaque *s = bs->opaque;
1399 QEMUIOVector bounce_qiov;
1400 void *bounce_buf;
1401 int ret = 0;
1402 bool copy_to_target;
1404 copy_to_target = s->job->ret >= 0 &&
1405 s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1407 if (copy_to_target) {
1408 /* The guest might concurrently modify the data to write; but
1409 * the data on source and destination must match, so we have
1410 * to use a bounce buffer if we are going to write to the
1411 * target now. */
1412 bounce_buf = qemu_blockalign(bs, bytes);
1413 iov_to_buf_full(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
1415 qemu_iovec_init(&bounce_qiov, 1);
1416 qemu_iovec_add(&bounce_qiov, bounce_buf, bytes);
1417 qiov = &bounce_qiov;
1420 ret = bdrv_mirror_top_do_write(bs, MIRROR_METHOD_COPY, offset, bytes, qiov,
1421 flags);
1423 if (copy_to_target) {
1424 qemu_iovec_destroy(&bounce_qiov);
1425 qemu_vfree(bounce_buf);
1428 return ret;
1431 static int coroutine_fn bdrv_mirror_top_flush(BlockDriverState *bs)
1433 if (bs->backing == NULL) {
1434 /* we can be here after failed bdrv_append in mirror_start_job */
1435 return 0;
1437 return bdrv_co_flush(bs->backing->bs);
1440 static int coroutine_fn bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs,
1441 int64_t offset, int bytes, BdrvRequestFlags flags)
1443 return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_ZERO, offset, bytes, NULL,
1444 flags);
1447 static int coroutine_fn bdrv_mirror_top_pdiscard(BlockDriverState *bs,
1448 int64_t offset, int bytes)
1450 return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_DISCARD, offset, bytes,
1451 NULL, 0);
1454 static void bdrv_mirror_top_refresh_filename(BlockDriverState *bs)
1456 if (bs->backing == NULL) {
1457 /* we can be here after failed bdrv_attach_child in
1458 * bdrv_set_backing_hd */
1459 return;
1461 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1462 bs->backing->bs->filename);
1465 static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1466 const BdrvChildRole *role,
1467 BlockReopenQueue *reopen_queue,
1468 uint64_t perm, uint64_t shared,
1469 uint64_t *nperm, uint64_t *nshared)
1471 /* Must be able to forward guest writes to the real image */
1472 *nperm = 0;
1473 if (perm & BLK_PERM_WRITE) {
1474 *nperm |= BLK_PERM_WRITE;
1477 *nshared = BLK_PERM_ALL;
1480 /* Dummy node that provides consistent read to its users without requiring it
1481 * from its backing file and that allows writes on the backing file chain. */
1482 static BlockDriver bdrv_mirror_top = {
1483 .format_name = "mirror_top",
1484 .bdrv_co_preadv = bdrv_mirror_top_preadv,
1485 .bdrv_co_pwritev = bdrv_mirror_top_pwritev,
1486 .bdrv_co_pwrite_zeroes = bdrv_mirror_top_pwrite_zeroes,
1487 .bdrv_co_pdiscard = bdrv_mirror_top_pdiscard,
1488 .bdrv_co_flush = bdrv_mirror_top_flush,
1489 .bdrv_co_block_status = bdrv_co_block_status_from_backing,
1490 .bdrv_refresh_filename = bdrv_mirror_top_refresh_filename,
1491 .bdrv_child_perm = bdrv_mirror_top_child_perm,
1494 static void mirror_start_job(const char *job_id, BlockDriverState *bs,
1495 int creation_flags, BlockDriverState *target,
1496 const char *replaces, int64_t speed,
1497 uint32_t granularity, int64_t buf_size,
1498 BlockMirrorBackingMode backing_mode,
1499 BlockdevOnError on_source_error,
1500 BlockdevOnError on_target_error,
1501 bool unmap,
1502 BlockCompletionFunc *cb,
1503 void *opaque,
1504 const BlockJobDriver *driver,
1505 bool is_none_mode, BlockDriverState *base,
1506 bool auto_complete, const char *filter_node_name,
1507 bool is_mirror, MirrorCopyMode copy_mode,
1508 Error **errp)
1510 MirrorBlockJob *s;
1511 MirrorBDSOpaque *bs_opaque;
1512 BlockDriverState *mirror_top_bs;
1513 bool target_graph_mod;
1514 bool target_is_backing;
1515 Error *local_err = NULL;
1516 int ret;
1518 if (granularity == 0) {
1519 granularity = bdrv_get_default_bitmap_granularity(target);
1522 assert(is_power_of_2(granularity));
1524 if (buf_size < 0) {
1525 error_setg(errp, "Invalid parameter 'buf-size'");
1526 return;
1529 if (buf_size == 0) {
1530 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1533 if (bs == target) {
1534 error_setg(errp, "Can't mirror node into itself");
1535 return;
1538 /* In the case of active commit, add dummy driver to provide consistent
1539 * reads on the top, while disabling it in the intermediate nodes, and make
1540 * the backing chain writable. */
1541 mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
1542 BDRV_O_RDWR, errp);
1543 if (mirror_top_bs == NULL) {
1544 return;
1546 if (!filter_node_name) {
1547 mirror_top_bs->implicit = true;
1549 mirror_top_bs->total_sectors = bs->total_sectors;
1550 mirror_top_bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED;
1551 mirror_top_bs->supported_zero_flags = BDRV_REQ_WRITE_UNCHANGED;
1552 bs_opaque = g_new0(MirrorBDSOpaque, 1);
1553 mirror_top_bs->opaque = bs_opaque;
1554 bdrv_set_aio_context(mirror_top_bs, bdrv_get_aio_context(bs));
1556 /* bdrv_append takes ownership of the mirror_top_bs reference, need to keep
1557 * it alive until block_job_create() succeeds even if bs has no parent. */
1558 bdrv_ref(mirror_top_bs);
1559 bdrv_drained_begin(bs);
1560 bdrv_append(mirror_top_bs, bs, &local_err);
1561 bdrv_drained_end(bs);
1563 if (local_err) {
1564 bdrv_unref(mirror_top_bs);
1565 error_propagate(errp, local_err);
1566 return;
1569 /* Make sure that the source is not resized while the job is running */
1570 s = block_job_create(job_id, driver, NULL, mirror_top_bs,
1571 BLK_PERM_CONSISTENT_READ,
1572 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1573 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD, speed,
1574 creation_flags, cb, opaque, errp);
1575 if (!s) {
1576 goto fail;
1578 bs_opaque->job = s;
1580 /* The block job now has a reference to this node */
1581 bdrv_unref(mirror_top_bs);
1583 s->mirror_top_bs = mirror_top_bs;
1585 /* No resize for the target either; while the mirror is still running, a
1586 * consistent read isn't necessarily possible. We could possibly allow
1587 * writes and graph modifications, though it would likely defeat the
1588 * purpose of a mirror, so leave them blocked for now.
1590 * In the case of active commit, things look a bit different, though,
1591 * because the target is an already populated backing file in active use.
1592 * We can allow anything except resize there.*/
1593 target_is_backing = bdrv_chain_contains(bs, target);
1594 target_graph_mod = (backing_mode != MIRROR_LEAVE_BACKING_CHAIN);
1595 s->target = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE |
1596 (target_graph_mod ? BLK_PERM_GRAPH_MOD : 0),
1597 BLK_PERM_WRITE_UNCHANGED |
1598 (target_is_backing ? BLK_PERM_CONSISTENT_READ |
1599 BLK_PERM_WRITE |
1600 BLK_PERM_GRAPH_MOD : 0));
1601 ret = blk_insert_bs(s->target, target, errp);
1602 if (ret < 0) {
1603 goto fail;
1605 if (is_mirror) {
1606 /* XXX: Mirror target could be a NBD server of target QEMU in the case
1607 * of non-shared block migration. To allow migration completion, we
1608 * have to allow "inactivate" of the target BB. When that happens, we
1609 * know the job is drained, and the vcpus are stopped, so no write
1610 * operation will be performed. Block layer already has assertions to
1611 * ensure that. */
1612 blk_set_force_allow_inactivate(s->target);
1615 s->replaces = g_strdup(replaces);
1616 s->on_source_error = on_source_error;
1617 s->on_target_error = on_target_error;
1618 s->is_none_mode = is_none_mode;
1619 s->backing_mode = backing_mode;
1620 s->copy_mode = copy_mode;
1621 s->base = base;
1622 s->granularity = granularity;
1623 s->buf_size = ROUND_UP(buf_size, granularity);
1624 s->unmap = unmap;
1625 if (auto_complete) {
1626 s->should_complete = true;
1629 s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
1630 if (!s->dirty_bitmap) {
1631 goto fail;
1634 ret = block_job_add_bdrv(&s->common, "source", bs, 0,
1635 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE |
1636 BLK_PERM_CONSISTENT_READ,
1637 errp);
1638 if (ret < 0) {
1639 goto fail;
1642 /* Required permissions are already taken with blk_new() */
1643 block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
1644 &error_abort);
1646 /* In commit_active_start() all intermediate nodes disappear, so
1647 * any jobs in them must be blocked */
1648 if (target_is_backing) {
1649 BlockDriverState *iter;
1650 for (iter = backing_bs(bs); iter != target; iter = backing_bs(iter)) {
1651 /* XXX BLK_PERM_WRITE needs to be allowed so we don't block
1652 * ourselves at s->base (if writes are blocked for a node, they are
1653 * also blocked for its backing file). The other options would be a
1654 * second filter driver above s->base (== target). */
1655 ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
1656 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE,
1657 errp);
1658 if (ret < 0) {
1659 goto fail;
1663 if (bdrv_freeze_backing_chain(mirror_top_bs, target, errp) < 0) {
1664 goto fail;
1668 QTAILQ_INIT(&s->ops_in_flight);
1670 trace_mirror_start(bs, s, opaque);
1671 job_start(&s->common.job);
1672 return;
1674 fail:
1675 if (s) {
1676 /* Make sure this BDS does not go away until we have completed the graph
1677 * changes below */
1678 bdrv_ref(mirror_top_bs);
1680 g_free(s->replaces);
1681 blk_unref(s->target);
1682 bs_opaque->job = NULL;
1683 if (s->dirty_bitmap) {
1684 bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);
1686 job_early_fail(&s->common.job);
1689 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
1690 &error_abort);
1691 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
1693 bdrv_unref(mirror_top_bs);
1696 void mirror_start(const char *job_id, BlockDriverState *bs,
1697 BlockDriverState *target, const char *replaces,
1698 int creation_flags, int64_t speed,
1699 uint32_t granularity, int64_t buf_size,
1700 MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
1701 BlockdevOnError on_source_error,
1702 BlockdevOnError on_target_error,
1703 bool unmap, const char *filter_node_name,
1704 MirrorCopyMode copy_mode, Error **errp)
1706 bool is_none_mode;
1707 BlockDriverState *base;
1709 if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
1710 error_setg(errp, "Sync mode 'incremental' not supported");
1711 return;
1713 is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
1714 base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
1715 mirror_start_job(job_id, bs, creation_flags, target, replaces,
1716 speed, granularity, buf_size, backing_mode,
1717 on_source_error, on_target_error, unmap, NULL, NULL,
1718 &mirror_job_driver, is_none_mode, base, false,
1719 filter_node_name, true, copy_mode, errp);
1722 void commit_active_start(const char *job_id, BlockDriverState *bs,
1723 BlockDriverState *base, int creation_flags,
1724 int64_t speed, BlockdevOnError on_error,
1725 const char *filter_node_name,
1726 BlockCompletionFunc *cb, void *opaque,
1727 bool auto_complete, Error **errp)
1729 bool base_read_only;
1730 Error *local_err = NULL;
1732 base_read_only = bdrv_is_read_only(base);
1734 if (base_read_only) {
1735 if (bdrv_reopen_set_read_only(base, false, errp) < 0) {
1736 return;
1740 mirror_start_job(job_id, bs, creation_flags, base, NULL, speed, 0, 0,
1741 MIRROR_LEAVE_BACKING_CHAIN,
1742 on_error, on_error, true, cb, opaque,
1743 &commit_active_job_driver, false, base, auto_complete,
1744 filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
1745 &local_err);
1746 if (local_err) {
1747 error_propagate(errp, local_err);
1748 goto error_restore_flags;
1751 return;
1753 error_restore_flags:
1754 /* ignore error and errp for bdrv_reopen, because we want to propagate
1755 * the original error */
1756 if (base_read_only) {
1757 bdrv_reopen_set_read_only(base, true, NULL);
1759 return;