block: Make bdrv_round_to_clusters() signature more useful
[qemu/ericb.git] / block / mirror.c
blobd11706c5664808564c04a3c15b275fcb0fee4bc0
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 "trace.h"
17 #include "block/blockjob_int.h"
18 #include "block/block_int.h"
19 #include "sysemu/block-backend.h"
20 #include "qapi/error.h"
21 #include "qapi/qmp/qerror.h"
22 #include "qemu/ratelimit.h"
23 #include "qemu/bitmap.h"
25 #define SLICE_TIME 100000000ULL /* ns */
26 #define MAX_IN_FLIGHT 16
27 #define MAX_IO_BYTES (1 << 20) /* 1 Mb */
28 #define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
30 /* The mirroring buffer is a list of granularity-sized chunks.
31 * Free chunks are organized in a list.
33 typedef struct MirrorBuffer {
34 QSIMPLEQ_ENTRY(MirrorBuffer) next;
35 } MirrorBuffer;
37 typedef struct MirrorBlockJob {
38 BlockJob common;
39 RateLimit limit;
40 BlockBackend *target;
41 BlockDriverState *mirror_top_bs;
42 BlockDriverState *source;
43 BlockDriverState *base;
45 /* The name of the graph node to replace */
46 char *replaces;
47 /* The BDS to replace */
48 BlockDriverState *to_replace;
49 /* Used to block operations on the drive-mirror-replace target */
50 Error *replace_blocker;
51 bool is_none_mode;
52 BlockMirrorBackingMode backing_mode;
53 BlockdevOnError on_source_error, on_target_error;
54 bool synced;
55 bool should_complete;
56 int64_t granularity;
57 size_t buf_size;
58 int64_t bdev_length;
59 unsigned long *cow_bitmap;
60 BdrvDirtyBitmap *dirty_bitmap;
61 BdrvDirtyBitmapIter *dbi;
62 uint8_t *buf;
63 QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
64 int buf_free_count;
66 uint64_t last_pause_ns;
67 unsigned long *in_flight_bitmap;
68 int in_flight;
69 int64_t bytes_in_flight;
70 int ret;
71 bool unmap;
72 bool waiting_for_io;
73 int target_cluster_size;
74 int max_iov;
75 bool initial_zeroing_ongoing;
76 } MirrorBlockJob;
78 typedef struct MirrorOp {
79 MirrorBlockJob *s;
80 QEMUIOVector qiov;
81 int64_t offset;
82 uint64_t bytes;
83 } MirrorOp;
85 static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
86 int error)
88 s->synced = false;
89 if (read) {
90 return block_job_error_action(&s->common, s->on_source_error,
91 true, error);
92 } else {
93 return block_job_error_action(&s->common, s->on_target_error,
94 false, error);
98 static void mirror_iteration_done(MirrorOp *op, int ret)
100 MirrorBlockJob *s = op->s;
101 struct iovec *iov;
102 int64_t chunk_num;
103 int i, nb_chunks;
105 trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
107 s->in_flight--;
108 s->bytes_in_flight -= op->bytes;
109 iov = op->qiov.iov;
110 for (i = 0; i < op->qiov.niov; i++) {
111 MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
112 QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
113 s->buf_free_count++;
116 chunk_num = op->offset / s->granularity;
117 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
118 bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
119 if (ret >= 0) {
120 if (s->cow_bitmap) {
121 bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
123 if (!s->initial_zeroing_ongoing) {
124 s->common.offset += op->bytes;
127 qemu_iovec_destroy(&op->qiov);
128 g_free(op);
130 if (s->waiting_for_io) {
131 qemu_coroutine_enter(s->common.co);
135 static void mirror_write_complete(void *opaque, int ret)
137 MirrorOp *op = opaque;
138 MirrorBlockJob *s = op->s;
140 aio_context_acquire(blk_get_aio_context(s->common.blk));
141 if (ret < 0) {
142 BlockErrorAction action;
144 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
145 action = mirror_error_action(s, false, -ret);
146 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
147 s->ret = ret;
150 mirror_iteration_done(op, ret);
151 aio_context_release(blk_get_aio_context(s->common.blk));
154 static void mirror_read_complete(void *opaque, int ret)
156 MirrorOp *op = opaque;
157 MirrorBlockJob *s = op->s;
159 aio_context_acquire(blk_get_aio_context(s->common.blk));
160 if (ret < 0) {
161 BlockErrorAction action;
163 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
164 action = mirror_error_action(s, true, -ret);
165 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
166 s->ret = ret;
169 mirror_iteration_done(op, ret);
170 } else {
171 blk_aio_pwritev(s->target, op->offset, &op->qiov,
172 0, mirror_write_complete, op);
174 aio_context_release(blk_get_aio_context(s->common.blk));
177 /* Clip bytes relative to offset to not exceed end-of-file */
178 static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
179 int64_t offset,
180 int64_t bytes)
182 return MIN(bytes, s->bdev_length - offset);
185 /* Round offset and/or bytes to target cluster if COW is needed, and
186 * return the offset of the adjusted tail against original. */
187 static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
188 uint64_t *bytes)
190 bool need_cow;
191 int ret = 0;
192 int64_t align_offset = *offset;
193 int64_t align_bytes = *bytes;
194 int max_bytes = s->granularity * s->max_iov;
196 need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
197 need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
198 s->cow_bitmap);
199 if (need_cow) {
200 bdrv_round_to_clusters(blk_bs(s->target), *offset, *bytes,
201 &align_offset, &align_bytes);
204 if (align_bytes > max_bytes) {
205 align_bytes = max_bytes;
206 if (need_cow) {
207 align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
210 /* Clipping may result in align_bytes unaligned to chunk boundary, but
211 * that doesn't matter because it's already the end of source image. */
212 align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
214 ret = align_offset + align_bytes - (*offset + *bytes);
215 *offset = align_offset;
216 *bytes = align_bytes;
217 assert(ret >= 0);
218 return ret;
221 static inline void mirror_wait_for_io(MirrorBlockJob *s)
223 assert(!s->waiting_for_io);
224 s->waiting_for_io = true;
225 qemu_coroutine_yield();
226 s->waiting_for_io = false;
229 /* Submit async read while handling COW.
230 * Returns: The number of bytes copied after and including offset,
231 * excluding any bytes copied prior to offset due to alignment.
232 * This will be @bytes if no alignment is necessary, or
233 * (new_end - offset) if tail is rounded up or down due to
234 * alignment or buffer limit.
236 static uint64_t mirror_do_read(MirrorBlockJob *s, int64_t offset,
237 uint64_t bytes)
239 BlockBackend *source = s->common.blk;
240 int nb_chunks;
241 uint64_t ret;
242 MirrorOp *op;
243 uint64_t max_bytes;
245 max_bytes = s->granularity * s->max_iov;
247 /* We can only handle as much as buf_size at a time. */
248 bytes = MIN(s->buf_size, MIN(max_bytes, bytes));
249 assert(bytes);
250 assert(bytes < BDRV_REQUEST_MAX_BYTES);
251 ret = bytes;
253 if (s->cow_bitmap) {
254 ret += mirror_cow_align(s, &offset, &bytes);
256 assert(bytes <= s->buf_size);
257 /* The offset is granularity-aligned because:
258 * 1) Caller passes in aligned values;
259 * 2) mirror_cow_align is used only when target cluster is larger. */
260 assert(QEMU_IS_ALIGNED(offset, s->granularity));
261 /* The range is sector-aligned, since bdrv_getlength() rounds up. */
262 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
263 nb_chunks = DIV_ROUND_UP(bytes, s->granularity);
265 while (s->buf_free_count < nb_chunks) {
266 trace_mirror_yield_in_flight(s, offset, s->in_flight);
267 mirror_wait_for_io(s);
270 /* Allocate a MirrorOp that is used as an AIO callback. */
271 op = g_new(MirrorOp, 1);
272 op->s = s;
273 op->offset = offset;
274 op->bytes = bytes;
276 /* Now make a QEMUIOVector taking enough granularity-sized chunks
277 * from s->buf_free.
279 qemu_iovec_init(&op->qiov, nb_chunks);
280 while (nb_chunks-- > 0) {
281 MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
282 size_t remaining = bytes - op->qiov.size;
284 QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
285 s->buf_free_count--;
286 qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
289 /* Copy the dirty cluster. */
290 s->in_flight++;
291 s->bytes_in_flight += bytes;
292 trace_mirror_one_iteration(s, offset, bytes);
294 blk_aio_preadv(source, offset, &op->qiov, 0, mirror_read_complete, op);
295 return ret;
298 static void mirror_do_zero_or_discard(MirrorBlockJob *s,
299 int64_t offset,
300 uint64_t bytes,
301 bool is_discard)
303 MirrorOp *op;
305 /* Allocate a MirrorOp that is used as an AIO callback. The qiov is zeroed
306 * so the freeing in mirror_iteration_done is nop. */
307 op = g_new0(MirrorOp, 1);
308 op->s = s;
309 op->offset = offset;
310 op->bytes = bytes;
312 s->in_flight++;
313 s->bytes_in_flight += bytes;
314 if (is_discard) {
315 blk_aio_pdiscard(s->target, offset,
316 op->bytes, mirror_write_complete, op);
317 } else {
318 blk_aio_pwrite_zeroes(s->target, offset,
319 op->bytes, s->unmap ? BDRV_REQ_MAY_UNMAP : 0,
320 mirror_write_complete, op);
324 static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
326 BlockDriverState *source = s->source;
327 int64_t offset, first_chunk;
328 uint64_t delay_ns = 0;
329 /* At least the first dirty chunk is mirrored in one iteration. */
330 int nb_chunks = 1;
331 int sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
332 bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
333 int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
335 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
336 offset = bdrv_dirty_iter_next(s->dbi);
337 if (offset < 0) {
338 bdrv_set_dirty_iter(s->dbi, 0);
339 offset = bdrv_dirty_iter_next(s->dbi);
340 trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
341 assert(offset >= 0);
343 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
345 first_chunk = offset / s->granularity;
346 while (test_bit(first_chunk, s->in_flight_bitmap)) {
347 trace_mirror_yield_in_flight(s, offset, s->in_flight);
348 mirror_wait_for_io(s);
351 block_job_pause_point(&s->common);
353 /* Find the number of consective dirty chunks following the first dirty
354 * one, and wait for in flight requests in them. */
355 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
356 while (nb_chunks * s->granularity < s->buf_size) {
357 int64_t next_dirty;
358 int64_t next_offset = offset + nb_chunks * s->granularity;
359 int64_t next_chunk = next_offset / s->granularity;
360 if (next_offset >= s->bdev_length ||
361 !bdrv_get_dirty_locked(source, s->dirty_bitmap, next_offset)) {
362 break;
364 if (test_bit(next_chunk, s->in_flight_bitmap)) {
365 break;
368 next_dirty = bdrv_dirty_iter_next(s->dbi);
369 if (next_dirty > next_offset || next_dirty < 0) {
370 /* The bitmap iterator's cache is stale, refresh it */
371 bdrv_set_dirty_iter(s->dbi, next_offset);
372 next_dirty = bdrv_dirty_iter_next(s->dbi);
374 assert(next_dirty == next_offset);
375 nb_chunks++;
378 /* Clear dirty bits before querying the block status, because
379 * calling bdrv_get_block_status_above could yield - if some blocks are
380 * marked dirty in this window, we need to know.
382 bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
383 nb_chunks * s->granularity);
384 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
386 bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
387 while (nb_chunks > 0 && offset < s->bdev_length) {
388 int64_t ret;
389 int io_sectors;
390 int64_t io_bytes;
391 int64_t io_bytes_acct;
392 enum MirrorMethod {
393 MIRROR_METHOD_COPY,
394 MIRROR_METHOD_ZERO,
395 MIRROR_METHOD_DISCARD
396 } mirror_method = MIRROR_METHOD_COPY;
398 assert(!(offset % s->granularity));
399 ret = bdrv_get_block_status_above(source, NULL,
400 offset >> BDRV_SECTOR_BITS,
401 nb_chunks * sectors_per_chunk,
402 &io_sectors, NULL);
403 io_bytes = io_sectors * BDRV_SECTOR_SIZE;
404 if (ret < 0) {
405 io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
406 } else if (ret & BDRV_BLOCK_DATA) {
407 io_bytes = MIN(io_bytes, max_io_bytes);
410 io_bytes -= io_bytes % s->granularity;
411 if (io_bytes < s->granularity) {
412 io_bytes = s->granularity;
413 } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
414 int64_t target_offset;
415 int64_t target_bytes;
416 bdrv_round_to_clusters(blk_bs(s->target), offset, io_bytes,
417 &target_offset, &target_bytes);
418 if (target_offset == offset &&
419 target_bytes == io_bytes) {
420 mirror_method = ret & BDRV_BLOCK_ZERO ?
421 MIRROR_METHOD_ZERO :
422 MIRROR_METHOD_DISCARD;
426 while (s->in_flight >= MAX_IN_FLIGHT) {
427 trace_mirror_yield_in_flight(s, offset, s->in_flight);
428 mirror_wait_for_io(s);
431 if (s->ret < 0) {
432 return 0;
435 io_bytes = mirror_clip_bytes(s, offset, io_bytes);
436 switch (mirror_method) {
437 case MIRROR_METHOD_COPY:
438 io_bytes = io_bytes_acct = mirror_do_read(s, offset, io_bytes);
439 break;
440 case MIRROR_METHOD_ZERO:
441 case MIRROR_METHOD_DISCARD:
442 mirror_do_zero_or_discard(s, offset, io_bytes,
443 mirror_method == MIRROR_METHOD_DISCARD);
444 if (write_zeroes_ok) {
445 io_bytes_acct = 0;
446 } else {
447 io_bytes_acct = io_bytes;
449 break;
450 default:
451 abort();
453 assert(io_bytes);
454 offset += io_bytes;
455 nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
456 if (s->common.speed) {
457 delay_ns = ratelimit_calculate_delay(&s->limit, io_bytes_acct);
460 return delay_ns;
463 static void mirror_free_init(MirrorBlockJob *s)
465 int granularity = s->granularity;
466 size_t buf_size = s->buf_size;
467 uint8_t *buf = s->buf;
469 assert(s->buf_free_count == 0);
470 QSIMPLEQ_INIT(&s->buf_free);
471 while (buf_size != 0) {
472 MirrorBuffer *cur = (MirrorBuffer *)buf;
473 QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
474 s->buf_free_count++;
475 buf_size -= granularity;
476 buf += granularity;
480 /* This is also used for the .pause callback. There is no matching
481 * mirror_resume() because mirror_run() will begin iterating again
482 * when the job is resumed.
484 static void mirror_wait_for_all_io(MirrorBlockJob *s)
486 while (s->in_flight > 0) {
487 mirror_wait_for_io(s);
491 typedef struct {
492 int ret;
493 } MirrorExitData;
495 static void mirror_exit(BlockJob *job, void *opaque)
497 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
498 MirrorExitData *data = opaque;
499 AioContext *replace_aio_context = NULL;
500 BlockDriverState *src = s->source;
501 BlockDriverState *target_bs = blk_bs(s->target);
502 BlockDriverState *mirror_top_bs = s->mirror_top_bs;
503 Error *local_err = NULL;
505 bdrv_release_dirty_bitmap(src, s->dirty_bitmap);
507 /* Make sure that the source BDS doesn't go away before we called
508 * block_job_completed(). */
509 bdrv_ref(src);
510 bdrv_ref(mirror_top_bs);
511 bdrv_ref(target_bs);
513 /* Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
514 * inserting target_bs at s->to_replace, where we might not be able to get
515 * these permissions.
517 * Note that blk_unref() alone doesn't necessarily drop permissions because
518 * we might be running nested inside mirror_drain(), which takes an extra
519 * reference, so use an explicit blk_set_perm() first. */
520 blk_set_perm(s->target, 0, BLK_PERM_ALL, &error_abort);
521 blk_unref(s->target);
522 s->target = NULL;
524 /* We don't access the source any more. Dropping any WRITE/RESIZE is
525 * required before it could become a backing file of target_bs. */
526 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
527 &error_abort);
528 if (s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
529 BlockDriverState *backing = s->is_none_mode ? src : s->base;
530 if (backing_bs(target_bs) != backing) {
531 bdrv_set_backing_hd(target_bs, backing, &local_err);
532 if (local_err) {
533 error_report_err(local_err);
534 data->ret = -EPERM;
539 if (s->to_replace) {
540 replace_aio_context = bdrv_get_aio_context(s->to_replace);
541 aio_context_acquire(replace_aio_context);
544 if (s->should_complete && data->ret == 0) {
545 BlockDriverState *to_replace = src;
546 if (s->to_replace) {
547 to_replace = s->to_replace;
550 if (bdrv_get_flags(target_bs) != bdrv_get_flags(to_replace)) {
551 bdrv_reopen(target_bs, bdrv_get_flags(to_replace), NULL);
554 /* The mirror job has no requests in flight any more, but we need to
555 * drain potential other users of the BDS before changing the graph. */
556 bdrv_drained_begin(target_bs);
557 bdrv_replace_node(to_replace, target_bs, &local_err);
558 bdrv_drained_end(target_bs);
559 if (local_err) {
560 error_report_err(local_err);
561 data->ret = -EPERM;
564 if (s->to_replace) {
565 bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
566 error_free(s->replace_blocker);
567 bdrv_unref(s->to_replace);
569 if (replace_aio_context) {
570 aio_context_release(replace_aio_context);
572 g_free(s->replaces);
573 bdrv_unref(target_bs);
575 /* Remove the mirror filter driver from the graph. Before this, get rid of
576 * the blockers on the intermediate nodes so that the resulting state is
577 * valid. Also give up permissions on mirror_top_bs->backing, which might
578 * block the removal. */
579 block_job_remove_all_bdrv(job);
580 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
581 &error_abort);
582 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
584 /* We just changed the BDS the job BB refers to (with either or both of the
585 * bdrv_replace_node() calls), so switch the BB back so the cleanup does
586 * the right thing. We don't need any permissions any more now. */
587 blk_remove_bs(job->blk);
588 blk_set_perm(job->blk, 0, BLK_PERM_ALL, &error_abort);
589 blk_insert_bs(job->blk, mirror_top_bs, &error_abort);
591 block_job_completed(&s->common, data->ret);
593 g_free(data);
594 bdrv_drained_end(src);
595 bdrv_unref(mirror_top_bs);
596 bdrv_unref(src);
599 static void mirror_throttle(MirrorBlockJob *s)
601 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
603 if (now - s->last_pause_ns > SLICE_TIME) {
604 s->last_pause_ns = now;
605 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, 0);
606 } else {
607 block_job_pause_point(&s->common);
611 static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
613 int64_t offset;
614 BlockDriverState *base = s->base;
615 BlockDriverState *bs = s->source;
616 BlockDriverState *target_bs = blk_bs(s->target);
617 int ret;
618 int64_t count;
620 if (base == NULL && !bdrv_has_zero_init(target_bs)) {
621 if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
622 bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
623 return 0;
626 s->initial_zeroing_ongoing = true;
627 for (offset = 0; offset < s->bdev_length; ) {
628 int bytes = MIN(s->bdev_length - offset,
629 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
631 mirror_throttle(s);
633 if (block_job_is_cancelled(&s->common)) {
634 s->initial_zeroing_ongoing = false;
635 return 0;
638 if (s->in_flight >= MAX_IN_FLIGHT) {
639 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
640 s->in_flight);
641 mirror_wait_for_io(s);
642 continue;
645 mirror_do_zero_or_discard(s, offset, bytes, false);
646 offset += bytes;
649 mirror_wait_for_all_io(s);
650 s->initial_zeroing_ongoing = false;
653 /* First part, loop on the sectors and initialize the dirty bitmap. */
654 for (offset = 0; offset < s->bdev_length; ) {
655 /* Just to make sure we are not exceeding int limit. */
656 int bytes = MIN(s->bdev_length - offset,
657 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
659 mirror_throttle(s);
661 if (block_job_is_cancelled(&s->common)) {
662 return 0;
665 ret = bdrv_is_allocated_above(bs, base, offset, bytes, &count);
666 if (ret < 0) {
667 return ret;
670 assert(count);
671 if (ret == 1) {
672 bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
674 offset += count;
676 return 0;
679 /* Called when going out of the streaming phase to flush the bulk of the
680 * data to the medium, or just before completing.
682 static int mirror_flush(MirrorBlockJob *s)
684 int ret = blk_flush(s->target);
685 if (ret < 0) {
686 if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
687 s->ret = ret;
690 return ret;
693 static void coroutine_fn mirror_run(void *opaque)
695 MirrorBlockJob *s = opaque;
696 MirrorExitData *data;
697 BlockDriverState *bs = s->source;
698 BlockDriverState *target_bs = blk_bs(s->target);
699 bool need_drain = true;
700 int64_t length;
701 BlockDriverInfo bdi;
702 char backing_filename[2]; /* we only need 2 characters because we are only
703 checking for a NULL string */
704 int ret = 0;
706 if (block_job_is_cancelled(&s->common)) {
707 goto immediate_exit;
710 s->bdev_length = bdrv_getlength(bs);
711 if (s->bdev_length < 0) {
712 ret = s->bdev_length;
713 goto immediate_exit;
716 /* Active commit must resize the base image if its size differs from the
717 * active layer. */
718 if (s->base == blk_bs(s->target)) {
719 int64_t base_length;
721 base_length = blk_getlength(s->target);
722 if (base_length < 0) {
723 ret = base_length;
724 goto immediate_exit;
727 if (s->bdev_length > base_length) {
728 ret = blk_truncate(s->target, s->bdev_length, PREALLOC_MODE_OFF,
729 NULL);
730 if (ret < 0) {
731 goto immediate_exit;
736 if (s->bdev_length == 0) {
737 /* Report BLOCK_JOB_READY and wait for complete. */
738 block_job_event_ready(&s->common);
739 s->synced = true;
740 while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
741 block_job_yield(&s->common);
743 s->common.cancelled = false;
744 goto immediate_exit;
747 length = DIV_ROUND_UP(s->bdev_length, s->granularity);
748 s->in_flight_bitmap = bitmap_new(length);
750 /* If we have no backing file yet in the destination, we cannot let
751 * the destination do COW. Instead, we copy sectors around the
752 * dirty data if needed. We need a bitmap to do that.
754 bdrv_get_backing_filename(target_bs, backing_filename,
755 sizeof(backing_filename));
756 if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
757 s->target_cluster_size = bdi.cluster_size;
758 } else {
759 s->target_cluster_size = BDRV_SECTOR_SIZE;
761 if (backing_filename[0] && !target_bs->backing &&
762 s->granularity < s->target_cluster_size) {
763 s->buf_size = MAX(s->buf_size, s->target_cluster_size);
764 s->cow_bitmap = bitmap_new(length);
766 s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
768 s->buf = qemu_try_blockalign(bs, s->buf_size);
769 if (s->buf == NULL) {
770 ret = -ENOMEM;
771 goto immediate_exit;
774 mirror_free_init(s);
776 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
777 if (!s->is_none_mode) {
778 ret = mirror_dirty_init(s);
779 if (ret < 0 || block_job_is_cancelled(&s->common)) {
780 goto immediate_exit;
784 assert(!s->dbi);
785 s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
786 for (;;) {
787 uint64_t delay_ns = 0;
788 int64_t cnt, delta;
789 bool should_complete;
791 if (s->ret < 0) {
792 ret = s->ret;
793 goto immediate_exit;
796 block_job_pause_point(&s->common);
798 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
799 /* s->common.offset contains the number of bytes already processed so
800 * far, cnt is the number of dirty bytes remaining and
801 * s->bytes_in_flight is the number of bytes currently being
802 * processed; together those are the current total operation length */
803 s->common.len = s->common.offset + s->bytes_in_flight + cnt;
805 /* Note that even when no rate limit is applied we need to yield
806 * periodically with no pending I/O so that bdrv_drain_all() returns.
807 * We do so every SLICE_TIME nanoseconds, or when there is an error,
808 * or when the source is clean, whichever comes first.
810 delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
811 if (delta < SLICE_TIME &&
812 s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
813 if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
814 (cnt == 0 && s->in_flight > 0)) {
815 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
816 mirror_wait_for_io(s);
817 continue;
818 } else if (cnt != 0) {
819 delay_ns = mirror_iteration(s);
823 should_complete = false;
824 if (s->in_flight == 0 && cnt == 0) {
825 trace_mirror_before_flush(s);
826 if (!s->synced) {
827 if (mirror_flush(s) < 0) {
828 /* Go check s->ret. */
829 continue;
831 /* We're out of the streaming phase. From now on, if the job
832 * is cancelled we will actually complete all pending I/O and
833 * report completion. This way, block-job-cancel will leave
834 * the target in a consistent state.
836 block_job_event_ready(&s->common);
837 s->synced = true;
840 should_complete = s->should_complete ||
841 block_job_is_cancelled(&s->common);
842 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
845 if (cnt == 0 && should_complete) {
846 /* The dirty bitmap is not updated while operations are pending.
847 * If we're about to exit, wait for pending operations before
848 * calling bdrv_get_dirty_count(bs), or we may exit while the
849 * source has dirty data to copy!
851 * Note that I/O can be submitted by the guest while
852 * mirror_populate runs, so pause it now. Before deciding
853 * whether to switch to target check one last time if I/O has
854 * come in the meanwhile, and if not flush the data to disk.
856 trace_mirror_before_drain(s, cnt);
858 bdrv_drained_begin(bs);
859 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
860 if (cnt > 0 || mirror_flush(s) < 0) {
861 bdrv_drained_end(bs);
862 continue;
865 /* The two disks are in sync. Exit and report successful
866 * completion.
868 assert(QLIST_EMPTY(&bs->tracked_requests));
869 s->common.cancelled = false;
870 need_drain = false;
871 break;
874 ret = 0;
875 trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
876 if (!s->synced) {
877 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
878 if (block_job_is_cancelled(&s->common)) {
879 break;
881 } else if (!should_complete) {
882 delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
883 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
885 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
888 immediate_exit:
889 if (s->in_flight > 0) {
890 /* We get here only if something went wrong. Either the job failed,
891 * or it was cancelled prematurely so that we do not guarantee that
892 * the target is a copy of the source.
894 assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));
895 assert(need_drain);
896 mirror_wait_for_all_io(s);
899 assert(s->in_flight == 0);
900 qemu_vfree(s->buf);
901 g_free(s->cow_bitmap);
902 g_free(s->in_flight_bitmap);
903 bdrv_dirty_iter_free(s->dbi);
905 data = g_malloc(sizeof(*data));
906 data->ret = ret;
908 if (need_drain) {
909 bdrv_drained_begin(bs);
911 block_job_defer_to_main_loop(&s->common, mirror_exit, data);
914 static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)
916 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
918 if (speed < 0) {
919 error_setg(errp, QERR_INVALID_PARAMETER, "speed");
920 return;
922 ratelimit_set_speed(&s->limit, speed, SLICE_TIME);
925 static void mirror_complete(BlockJob *job, Error **errp)
927 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
928 BlockDriverState *target;
930 target = blk_bs(s->target);
932 if (!s->synced) {
933 error_setg(errp, "The active block job '%s' cannot be completed",
934 job->id);
935 return;
938 if (s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
939 int ret;
941 assert(!target->backing);
942 ret = bdrv_open_backing_file(target, NULL, "backing", errp);
943 if (ret < 0) {
944 return;
948 /* block all operations on to_replace bs */
949 if (s->replaces) {
950 AioContext *replace_aio_context;
952 s->to_replace = bdrv_find_node(s->replaces);
953 if (!s->to_replace) {
954 error_setg(errp, "Node name '%s' not found", s->replaces);
955 return;
958 replace_aio_context = bdrv_get_aio_context(s->to_replace);
959 aio_context_acquire(replace_aio_context);
961 /* TODO Translate this into permission system. Current definition of
962 * GRAPH_MOD would require to request it for the parents; they might
963 * not even be BlockDriverStates, however, so a BdrvChild can't address
964 * them. May need redefinition of GRAPH_MOD. */
965 error_setg(&s->replace_blocker,
966 "block device is in use by block-job-complete");
967 bdrv_op_block_all(s->to_replace, s->replace_blocker);
968 bdrv_ref(s->to_replace);
970 aio_context_release(replace_aio_context);
973 s->should_complete = true;
974 block_job_enter(&s->common);
977 static void mirror_pause(BlockJob *job)
979 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
981 mirror_wait_for_all_io(s);
984 static void mirror_attached_aio_context(BlockJob *job, AioContext *new_context)
986 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
988 blk_set_aio_context(s->target, new_context);
991 static void mirror_drain(BlockJob *job)
993 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
995 /* Need to keep a reference in case blk_drain triggers execution
996 * of mirror_complete...
998 if (s->target) {
999 BlockBackend *target = s->target;
1000 blk_ref(target);
1001 blk_drain(target);
1002 blk_unref(target);
1006 static const BlockJobDriver mirror_job_driver = {
1007 .instance_size = sizeof(MirrorBlockJob),
1008 .job_type = BLOCK_JOB_TYPE_MIRROR,
1009 .set_speed = mirror_set_speed,
1010 .start = mirror_run,
1011 .complete = mirror_complete,
1012 .pause = mirror_pause,
1013 .attached_aio_context = mirror_attached_aio_context,
1014 .drain = mirror_drain,
1017 static const BlockJobDriver commit_active_job_driver = {
1018 .instance_size = sizeof(MirrorBlockJob),
1019 .job_type = BLOCK_JOB_TYPE_COMMIT,
1020 .set_speed = mirror_set_speed,
1021 .start = mirror_run,
1022 .complete = mirror_complete,
1023 .pause = mirror_pause,
1024 .attached_aio_context = mirror_attached_aio_context,
1025 .drain = mirror_drain,
1028 static int coroutine_fn bdrv_mirror_top_preadv(BlockDriverState *bs,
1029 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1031 return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
1034 static int coroutine_fn bdrv_mirror_top_pwritev(BlockDriverState *bs,
1035 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1037 return bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1040 static int coroutine_fn bdrv_mirror_top_flush(BlockDriverState *bs)
1042 if (bs->backing == NULL) {
1043 /* we can be here after failed bdrv_append in mirror_start_job */
1044 return 0;
1046 return bdrv_co_flush(bs->backing->bs);
1049 static int coroutine_fn bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs,
1050 int64_t offset, int bytes, BdrvRequestFlags flags)
1052 return bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
1055 static int coroutine_fn bdrv_mirror_top_pdiscard(BlockDriverState *bs,
1056 int64_t offset, int bytes)
1058 return bdrv_co_pdiscard(bs->backing->bs, offset, bytes);
1061 static void bdrv_mirror_top_refresh_filename(BlockDriverState *bs, QDict *opts)
1063 if (bs->backing == NULL) {
1064 /* we can be here after failed bdrv_attach_child in
1065 * bdrv_set_backing_hd */
1066 return;
1068 bdrv_refresh_filename(bs->backing->bs);
1069 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1070 bs->backing->bs->filename);
1073 static void bdrv_mirror_top_close(BlockDriverState *bs)
1077 static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1078 const BdrvChildRole *role,
1079 BlockReopenQueue *reopen_queue,
1080 uint64_t perm, uint64_t shared,
1081 uint64_t *nperm, uint64_t *nshared)
1083 /* Must be able to forward guest writes to the real image */
1084 *nperm = 0;
1085 if (perm & BLK_PERM_WRITE) {
1086 *nperm |= BLK_PERM_WRITE;
1089 *nshared = BLK_PERM_ALL;
1092 /* Dummy node that provides consistent read to its users without requiring it
1093 * from its backing file and that allows writes on the backing file chain. */
1094 static BlockDriver bdrv_mirror_top = {
1095 .format_name = "mirror_top",
1096 .bdrv_co_preadv = bdrv_mirror_top_preadv,
1097 .bdrv_co_pwritev = bdrv_mirror_top_pwritev,
1098 .bdrv_co_pwrite_zeroes = bdrv_mirror_top_pwrite_zeroes,
1099 .bdrv_co_pdiscard = bdrv_mirror_top_pdiscard,
1100 .bdrv_co_flush = bdrv_mirror_top_flush,
1101 .bdrv_co_get_block_status = bdrv_co_get_block_status_from_backing,
1102 .bdrv_refresh_filename = bdrv_mirror_top_refresh_filename,
1103 .bdrv_close = bdrv_mirror_top_close,
1104 .bdrv_child_perm = bdrv_mirror_top_child_perm,
1107 static void mirror_start_job(const char *job_id, BlockDriverState *bs,
1108 int creation_flags, BlockDriverState *target,
1109 const char *replaces, int64_t speed,
1110 uint32_t granularity, int64_t buf_size,
1111 BlockMirrorBackingMode backing_mode,
1112 BlockdevOnError on_source_error,
1113 BlockdevOnError on_target_error,
1114 bool unmap,
1115 BlockCompletionFunc *cb,
1116 void *opaque,
1117 const BlockJobDriver *driver,
1118 bool is_none_mode, BlockDriverState *base,
1119 bool auto_complete, const char *filter_node_name,
1120 bool is_mirror,
1121 Error **errp)
1123 MirrorBlockJob *s;
1124 BlockDriverState *mirror_top_bs;
1125 bool target_graph_mod;
1126 bool target_is_backing;
1127 Error *local_err = NULL;
1128 int ret;
1130 if (granularity == 0) {
1131 granularity = bdrv_get_default_bitmap_granularity(target);
1134 assert ((granularity & (granularity - 1)) == 0);
1135 /* Granularity must be large enough for sector-based dirty bitmap */
1136 assert(granularity >= BDRV_SECTOR_SIZE);
1138 if (buf_size < 0) {
1139 error_setg(errp, "Invalid parameter 'buf-size'");
1140 return;
1143 if (buf_size == 0) {
1144 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1147 /* In the case of active commit, add dummy driver to provide consistent
1148 * reads on the top, while disabling it in the intermediate nodes, and make
1149 * the backing chain writable. */
1150 mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
1151 BDRV_O_RDWR, errp);
1152 if (mirror_top_bs == NULL) {
1153 return;
1155 if (!filter_node_name) {
1156 mirror_top_bs->implicit = true;
1158 mirror_top_bs->total_sectors = bs->total_sectors;
1159 bdrv_set_aio_context(mirror_top_bs, bdrv_get_aio_context(bs));
1161 /* bdrv_append takes ownership of the mirror_top_bs reference, need to keep
1162 * it alive until block_job_create() succeeds even if bs has no parent. */
1163 bdrv_ref(mirror_top_bs);
1164 bdrv_drained_begin(bs);
1165 bdrv_append(mirror_top_bs, bs, &local_err);
1166 bdrv_drained_end(bs);
1168 if (local_err) {
1169 bdrv_unref(mirror_top_bs);
1170 error_propagate(errp, local_err);
1171 return;
1174 /* Make sure that the source is not resized while the job is running */
1175 s = block_job_create(job_id, driver, mirror_top_bs,
1176 BLK_PERM_CONSISTENT_READ,
1177 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1178 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD, speed,
1179 creation_flags, cb, opaque, errp);
1180 if (!s) {
1181 goto fail;
1183 /* The block job now has a reference to this node */
1184 bdrv_unref(mirror_top_bs);
1186 s->source = bs;
1187 s->mirror_top_bs = mirror_top_bs;
1189 /* No resize for the target either; while the mirror is still running, a
1190 * consistent read isn't necessarily possible. We could possibly allow
1191 * writes and graph modifications, though it would likely defeat the
1192 * purpose of a mirror, so leave them blocked for now.
1194 * In the case of active commit, things look a bit different, though,
1195 * because the target is an already populated backing file in active use.
1196 * We can allow anything except resize there.*/
1197 target_is_backing = bdrv_chain_contains(bs, target);
1198 target_graph_mod = (backing_mode != MIRROR_LEAVE_BACKING_CHAIN);
1199 s->target = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE |
1200 (target_graph_mod ? BLK_PERM_GRAPH_MOD : 0),
1201 BLK_PERM_WRITE_UNCHANGED |
1202 (target_is_backing ? BLK_PERM_CONSISTENT_READ |
1203 BLK_PERM_WRITE |
1204 BLK_PERM_GRAPH_MOD : 0));
1205 ret = blk_insert_bs(s->target, target, errp);
1206 if (ret < 0) {
1207 goto fail;
1209 if (is_mirror) {
1210 /* XXX: Mirror target could be a NBD server of target QEMU in the case
1211 * of non-shared block migration. To allow migration completion, we
1212 * have to allow "inactivate" of the target BB. When that happens, we
1213 * know the job is drained, and the vcpus are stopped, so no write
1214 * operation will be performed. Block layer already has assertions to
1215 * ensure that. */
1216 blk_set_force_allow_inactivate(s->target);
1219 s->replaces = g_strdup(replaces);
1220 s->on_source_error = on_source_error;
1221 s->on_target_error = on_target_error;
1222 s->is_none_mode = is_none_mode;
1223 s->backing_mode = backing_mode;
1224 s->base = base;
1225 s->granularity = granularity;
1226 s->buf_size = ROUND_UP(buf_size, granularity);
1227 s->unmap = unmap;
1228 if (auto_complete) {
1229 s->should_complete = true;
1232 s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
1233 if (!s->dirty_bitmap) {
1234 goto fail;
1237 /* Required permissions are already taken with blk_new() */
1238 block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
1239 &error_abort);
1241 /* In commit_active_start() all intermediate nodes disappear, so
1242 * any jobs in them must be blocked */
1243 if (target_is_backing) {
1244 BlockDriverState *iter;
1245 for (iter = backing_bs(bs); iter != target; iter = backing_bs(iter)) {
1246 /* XXX BLK_PERM_WRITE needs to be allowed so we don't block
1247 * ourselves at s->base (if writes are blocked for a node, they are
1248 * also blocked for its backing file). The other options would be a
1249 * second filter driver above s->base (== target). */
1250 ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
1251 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE,
1252 errp);
1253 if (ret < 0) {
1254 goto fail;
1259 trace_mirror_start(bs, s, opaque);
1260 block_job_start(&s->common);
1261 return;
1263 fail:
1264 if (s) {
1265 /* Make sure this BDS does not go away until we have completed the graph
1266 * changes below */
1267 bdrv_ref(mirror_top_bs);
1269 g_free(s->replaces);
1270 blk_unref(s->target);
1271 block_job_early_fail(&s->common);
1274 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
1275 &error_abort);
1276 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
1278 bdrv_unref(mirror_top_bs);
1281 void mirror_start(const char *job_id, BlockDriverState *bs,
1282 BlockDriverState *target, const char *replaces,
1283 int64_t speed, uint32_t granularity, int64_t buf_size,
1284 MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
1285 BlockdevOnError on_source_error,
1286 BlockdevOnError on_target_error,
1287 bool unmap, const char *filter_node_name, Error **errp)
1289 bool is_none_mode;
1290 BlockDriverState *base;
1292 if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
1293 error_setg(errp, "Sync mode 'incremental' not supported");
1294 return;
1296 is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
1297 base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
1298 mirror_start_job(job_id, bs, BLOCK_JOB_DEFAULT, target, replaces,
1299 speed, granularity, buf_size, backing_mode,
1300 on_source_error, on_target_error, unmap, NULL, NULL,
1301 &mirror_job_driver, is_none_mode, base, false,
1302 filter_node_name, true, errp);
1305 void commit_active_start(const char *job_id, BlockDriverState *bs,
1306 BlockDriverState *base, int creation_flags,
1307 int64_t speed, BlockdevOnError on_error,
1308 const char *filter_node_name,
1309 BlockCompletionFunc *cb, void *opaque,
1310 bool auto_complete, Error **errp)
1312 int orig_base_flags;
1313 Error *local_err = NULL;
1315 orig_base_flags = bdrv_get_flags(base);
1317 if (bdrv_reopen(base, bs->open_flags, errp)) {
1318 return;
1321 mirror_start_job(job_id, bs, creation_flags, base, NULL, speed, 0, 0,
1322 MIRROR_LEAVE_BACKING_CHAIN,
1323 on_error, on_error, true, cb, opaque,
1324 &commit_active_job_driver, false, base, auto_complete,
1325 filter_node_name, false, &local_err);
1326 if (local_err) {
1327 error_propagate(errp, local_err);
1328 goto error_restore_flags;
1331 return;
1333 error_restore_flags:
1334 /* ignore error and errp for bdrv_reopen, because we want to propagate
1335 * the original error */
1336 bdrv_reopen(base, orig_base_flags, NULL);
1337 return;