]> git.proxmox.com Git - mirror_qemu.git/blame - block/mirror.c
block/mirror: honor ratelimit again
[mirror_qemu.git] / block / mirror.c
CommitLineData
893f7eba
PB
1/*
2 * Image mirroring
3 *
4 * Copyright Red Hat, Inc. 2012
5 *
6 * Authors:
7 * Paolo Bonzini <pbonzini@redhat.com>
8 *
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.
11 *
12 */
13
80c71a24 14#include "qemu/osdep.h"
fd4a6493 15#include "qemu/cutils.h"
893f7eba 16#include "trace.h"
c87621ea 17#include "block/blockjob_int.h"
737e150e 18#include "block/block_int.h"
373340b2 19#include "sysemu/block-backend.h"
da34e65c 20#include "qapi/error.h"
cc7a8ea7 21#include "qapi/qmp/qerror.h"
893f7eba 22#include "qemu/ratelimit.h"
b812f671 23#include "qemu/bitmap.h"
893f7eba 24
402a4741
PB
25#define SLICE_TIME 100000000ULL /* ns */
26#define MAX_IN_FLIGHT 16
b436982f
EB
27#define MAX_IO_BYTES (1 << 20) /* 1 Mb */
28#define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
402a4741
PB
29
30/* The mirroring buffer is a list of granularity-sized chunks.
31 * Free chunks are organized in a list.
32 */
33typedef struct MirrorBuffer {
34 QSIMPLEQ_ENTRY(MirrorBuffer) next;
35} MirrorBuffer;
893f7eba
PB
36
37typedef struct MirrorBlockJob {
38 BlockJob common;
39 RateLimit limit;
e253f4b8 40 BlockBackend *target;
4ef85a9c
KW
41 BlockDriverState *mirror_top_bs;
42 BlockDriverState *source;
5bc361b8 43 BlockDriverState *base;
4ef85a9c 44
09158f00
BC
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;
03544a6e 51 bool is_none_mode;
274fccee 52 BlockMirrorBackingMode backing_mode;
b952b558 53 BlockdevOnError on_source_error, on_target_error;
d63ffd87
PB
54 bool synced;
55 bool should_complete;
eee13dfe 56 int64_t granularity;
b812f671 57 size_t buf_size;
b21c7652 58 int64_t bdev_length;
b812f671 59 unsigned long *cow_bitmap;
e4654d2d 60 BdrvDirtyBitmap *dirty_bitmap;
dc162c8e 61 BdrvDirtyBitmapIter *dbi;
893f7eba 62 uint8_t *buf;
402a4741
PB
63 QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
64 int buf_free_count;
bd48bde8 65
49efb1f5 66 uint64_t last_pause_ns;
402a4741 67 unsigned long *in_flight_bitmap;
bd48bde8 68 int in_flight;
b436982f 69 int64_t bytes_in_flight;
bd48bde8 70 int ret;
0fc9f8ea 71 bool unmap;
e424aff5 72 bool waiting_for_io;
b436982f 73 int target_cluster_size;
e5b43573 74 int max_iov;
90ab48eb 75 bool initial_zeroing_ongoing;
893f7eba
PB
76} MirrorBlockJob;
77
bd48bde8
PB
78typedef struct MirrorOp {
79 MirrorBlockJob *s;
80 QEMUIOVector qiov;
b436982f
EB
81 int64_t offset;
82 uint64_t bytes;
bd48bde8
PB
83} MirrorOp;
84
b952b558
PB
85static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
86 int error)
87{
88 s->synced = false;
89 if (read) {
81e254dc
KW
90 return block_job_error_action(&s->common, s->on_source_error,
91 true, error);
b952b558 92 } else {
81e254dc
KW
93 return block_job_error_action(&s->common, s->on_target_error,
94 false, error);
b952b558
PB
95 }
96}
97
bd48bde8
PB
98static void mirror_iteration_done(MirrorOp *op, int ret)
99{
100 MirrorBlockJob *s = op->s;
402a4741 101 struct iovec *iov;
bd48bde8 102 int64_t chunk_num;
b436982f 103 int i, nb_chunks;
bd48bde8 104
b436982f 105 trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
bd48bde8
PB
106
107 s->in_flight--;
b436982f 108 s->bytes_in_flight -= op->bytes;
402a4741
PB
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++;
114 }
115
b436982f
EB
116 chunk_num = op->offset / s->granularity;
117 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
402a4741 118 bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
b21c7652
HR
119 if (ret >= 0) {
120 if (s->cow_bitmap) {
121 bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
122 }
90ab48eb 123 if (!s->initial_zeroing_ongoing) {
b436982f 124 s->common.offset += op->bytes;
90ab48eb 125 }
bd48bde8 126 }
6df3bf8e 127 qemu_iovec_destroy(&op->qiov);
c84b3192 128 g_free(op);
7b770c72 129
e424aff5 130 if (s->waiting_for_io) {
0b8b8753 131 qemu_coroutine_enter(s->common.co);
7b770c72 132 }
bd48bde8
PB
133}
134
135static void mirror_write_complete(void *opaque, int ret)
136{
137 MirrorOp *op = opaque;
138 MirrorBlockJob *s = op->s;
b9e413dd
PB
139
140 aio_context_acquire(blk_get_aio_context(s->common.blk));
bd48bde8 141 if (ret < 0) {
bd48bde8
PB
142 BlockErrorAction action;
143
e0d7f73e 144 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
bd48bde8 145 action = mirror_error_action(s, false, -ret);
a589569f 146 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
bd48bde8
PB
147 s->ret = ret;
148 }
149 }
150 mirror_iteration_done(op, ret);
b9e413dd 151 aio_context_release(blk_get_aio_context(s->common.blk));
bd48bde8
PB
152}
153
154static void mirror_read_complete(void *opaque, int ret)
155{
156 MirrorOp *op = opaque;
157 MirrorBlockJob *s = op->s;
b9e413dd
PB
158
159 aio_context_acquire(blk_get_aio_context(s->common.blk));
bd48bde8 160 if (ret < 0) {
bd48bde8
PB
161 BlockErrorAction action;
162
e0d7f73e 163 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
bd48bde8 164 action = mirror_error_action(s, true, -ret);
a589569f 165 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
bd48bde8
PB
166 s->ret = ret;
167 }
168
169 mirror_iteration_done(op, ret);
b9e413dd 170 } else {
b436982f 171 blk_aio_pwritev(s->target, op->offset, &op->qiov,
b9e413dd 172 0, mirror_write_complete, op);
bd48bde8 173 }
b9e413dd 174 aio_context_release(blk_get_aio_context(s->common.blk));
bd48bde8
PB
175}
176
782d97ef
EB
177/* Clip bytes relative to offset to not exceed end-of-file */
178static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
179 int64_t offset,
180 int64_t bytes)
181{
182 return MIN(bytes, s->bdev_length - offset);
183}
184
782d97ef
EB
185/* Round offset and/or bytes to target cluster if COW is needed, and
186 * return the offset of the adjusted tail against original. */
187static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
ae4cc877 188 uint64_t *bytes)
893f7eba 189{
e5b43573
FZ
190 bool need_cow;
191 int ret = 0;
782d97ef 192 int64_t align_offset = *offset;
7cfd5275 193 int64_t align_bytes = *bytes;
782d97ef 194 int max_bytes = s->granularity * s->max_iov;
e5b43573 195
782d97ef
EB
196 need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
197 need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
e5b43573
FZ
198 s->cow_bitmap);
199 if (need_cow) {
782d97ef
EB
200 bdrv_round_to_clusters(blk_bs(s->target), *offset, *bytes,
201 &align_offset, &align_bytes);
e5b43573 202 }
3515727f 203
782d97ef
EB
204 if (align_bytes > max_bytes) {
205 align_bytes = max_bytes;
e5b43573 206 if (need_cow) {
782d97ef 207 align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
e5b43573 208 }
8f0720ec 209 }
782d97ef 210 /* Clipping may result in align_bytes unaligned to chunk boundary, but
4150ae60 211 * that doesn't matter because it's already the end of source image. */
782d97ef 212 align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
8f0720ec 213
782d97ef
EB
214 ret = align_offset + align_bytes - (*offset + *bytes);
215 *offset = align_offset;
216 *bytes = align_bytes;
e5b43573
FZ
217 assert(ret >= 0);
218 return ret;
219}
220
21cd917f
FZ
221static inline void mirror_wait_for_io(MirrorBlockJob *s)
222{
223 assert(!s->waiting_for_io);
224 s->waiting_for_io = true;
225 qemu_coroutine_yield();
226 s->waiting_for_io = false;
227}
228
e5b43573 229/* Submit async read while handling COW.
ae4cc877
EB
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
e5b43573
FZ
234 * alignment or buffer limit.
235 */
ae4cc877
EB
236static uint64_t mirror_do_read(MirrorBlockJob *s, int64_t offset,
237 uint64_t bytes)
e5b43573 238{
e253f4b8 239 BlockBackend *source = s->common.blk;
ae4cc877
EB
240 int nb_chunks;
241 uint64_t ret;
e5b43573 242 MirrorOp *op;
ae4cc877 243 uint64_t max_bytes;
e5b43573 244
ae4cc877 245 max_bytes = s->granularity * s->max_iov;
402a4741 246
e5b43573 247 /* We can only handle as much as buf_size at a time. */
ae4cc877
EB
248 bytes = MIN(s->buf_size, MIN(max_bytes, bytes));
249 assert(bytes);
250 assert(bytes < BDRV_REQUEST_MAX_BYTES);
251 ret = bytes;
402a4741 252
e5b43573 253 if (s->cow_bitmap) {
ae4cc877 254 ret += mirror_cow_align(s, &offset, &bytes);
e5b43573 255 }
ae4cc877
EB
256 assert(bytes <= s->buf_size);
257 /* The offset is granularity-aligned because:
e5b43573
FZ
258 * 1) Caller passes in aligned values;
259 * 2) mirror_cow_align is used only when target cluster is larger. */
ae4cc877
EB
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);
e5b43573
FZ
264
265 while (s->buf_free_count < nb_chunks) {
ae4cc877 266 trace_mirror_yield_in_flight(s, offset, s->in_flight);
21cd917f 267 mirror_wait_for_io(s);
b812f671
PB
268 }
269
bd48bde8 270 /* Allocate a MirrorOp that is used as an AIO callback. */
c84b3192 271 op = g_new(MirrorOp, 1);
bd48bde8 272 op->s = s;
ae4cc877
EB
273 op->offset = offset;
274 op->bytes = bytes;
402a4741
PB
275
276 /* Now make a QEMUIOVector taking enough granularity-sized chunks
277 * from s->buf_free.
278 */
279 qemu_iovec_init(&op->qiov, nb_chunks);
402a4741
PB
280 while (nb_chunks-- > 0) {
281 MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
ae4cc877 282 size_t remaining = bytes - op->qiov.size;
5a0f6fd5 283
402a4741
PB
284 QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
285 s->buf_free_count--;
5a0f6fd5 286 qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
402a4741 287 }
bd48bde8 288
893f7eba 289 /* Copy the dirty cluster. */
bd48bde8 290 s->in_flight++;
ae4cc877
EB
291 s->bytes_in_flight += bytes;
292 trace_mirror_one_iteration(s, offset, bytes);
dcfb3beb 293
ae4cc877 294 blk_aio_preadv(source, offset, &op->qiov, 0, mirror_read_complete, op);
e5b43573
FZ
295 return ret;
296}
297
298static void mirror_do_zero_or_discard(MirrorBlockJob *s,
e6f24193
EB
299 int64_t offset,
300 uint64_t bytes,
e5b43573
FZ
301 bool is_discard)
302{
303 MirrorOp *op;
304
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;
e6f24193
EB
309 op->offset = offset;
310 op->bytes = bytes;
e5b43573
FZ
311
312 s->in_flight++;
e6f24193 313 s->bytes_in_flight += bytes;
e5b43573 314 if (is_discard) {
e6f24193 315 blk_aio_pdiscard(s->target, offset,
b436982f 316 op->bytes, mirror_write_complete, op);
e5b43573 317 } else {
e6f24193 318 blk_aio_pwrite_zeroes(s->target, offset,
b436982f 319 op->bytes, s->unmap ? BDRV_REQ_MAY_UNMAP : 0,
dcfb3beb 320 mirror_write_complete, op);
e5b43573
FZ
321 }
322}
323
324static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
325{
4ef85a9c 326 BlockDriverState *source = s->source;
fb2ef791 327 int64_t offset, first_chunk;
e5b43573
FZ
328 uint64_t delay_ns = 0;
329 /* At least the first dirty chunk is mirrored in one iteration. */
330 int nb_chunks = 1;
4b5004d9 331 bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
b436982f 332 int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
e5b43573 333
b64bd51e 334 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
f798184c 335 offset = bdrv_dirty_iter_next(s->dbi);
fb2ef791 336 if (offset < 0) {
dc162c8e 337 bdrv_set_dirty_iter(s->dbi, 0);
f798184c 338 offset = bdrv_dirty_iter_next(s->dbi);
9a46dba7 339 trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
fb2ef791 340 assert(offset >= 0);
e5b43573 341 }
b64bd51e 342 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
e5b43573 343
fb2ef791 344 first_chunk = offset / s->granularity;
9c83625b 345 while (test_bit(first_chunk, s->in_flight_bitmap)) {
fb2ef791 346 trace_mirror_yield_in_flight(s, offset, s->in_flight);
9c83625b
HR
347 mirror_wait_for_io(s);
348 }
349
565ac01f
SH
350 block_job_pause_point(&s->common);
351
e5b43573
FZ
352 /* Find the number of consective dirty chunks following the first dirty
353 * one, and wait for in flight requests in them. */
b64bd51e 354 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
fb2ef791 355 while (nb_chunks * s->granularity < s->buf_size) {
dc162c8e 356 int64_t next_dirty;
fb2ef791
EB
357 int64_t next_offset = offset + nb_chunks * s->granularity;
358 int64_t next_chunk = next_offset / s->granularity;
359 if (next_offset >= s->bdev_length ||
3b5d4df0 360 !bdrv_get_dirty_locked(source, s->dirty_bitmap, next_offset)) {
e5b43573
FZ
361 break;
362 }
363 if (test_bit(next_chunk, s->in_flight_bitmap)) {
9c83625b 364 break;
e5b43573 365 }
9c83625b 366
f798184c 367 next_dirty = bdrv_dirty_iter_next(s->dbi);
fb2ef791 368 if (next_dirty > next_offset || next_dirty < 0) {
f27a2742 369 /* The bitmap iterator's cache is stale, refresh it */
715a74d8 370 bdrv_set_dirty_iter(s->dbi, next_offset);
f798184c 371 next_dirty = bdrv_dirty_iter_next(s->dbi);
f27a2742 372 }
fb2ef791 373 assert(next_dirty == next_offset);
9c83625b 374 nb_chunks++;
e5b43573
FZ
375 }
376
377 /* Clear dirty bits before querying the block status, because
31826642 378 * calling bdrv_block_status_above could yield - if some blocks are
e5b43573
FZ
379 * marked dirty in this window, we need to know.
380 */
e0d7f73e
EB
381 bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
382 nb_chunks * s->granularity);
b64bd51e
PB
383 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
384
fb2ef791
EB
385 bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
386 while (nb_chunks > 0 && offset < s->bdev_length) {
31826642 387 int ret;
7cfd5275 388 int64_t io_bytes;
f3e4ce4a 389 int64_t io_bytes_acct;
e5b43573
FZ
390 enum MirrorMethod {
391 MIRROR_METHOD_COPY,
392 MIRROR_METHOD_ZERO,
393 MIRROR_METHOD_DISCARD
394 } mirror_method = MIRROR_METHOD_COPY;
395
fb2ef791 396 assert(!(offset % s->granularity));
31826642
EB
397 ret = bdrv_block_status_above(source, NULL, offset,
398 nb_chunks * s->granularity,
399 &io_bytes, NULL, NULL);
e5b43573 400 if (ret < 0) {
fb2ef791 401 io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
0965a41e 402 } else if (ret & BDRV_BLOCK_DATA) {
fb2ef791 403 io_bytes = MIN(io_bytes, max_io_bytes);
e5b43573
FZ
404 }
405
fb2ef791
EB
406 io_bytes -= io_bytes % s->granularity;
407 if (io_bytes < s->granularity) {
408 io_bytes = s->granularity;
e5b43573 409 } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
fb2ef791 410 int64_t target_offset;
7cfd5275 411 int64_t target_bytes;
fb2ef791
EB
412 bdrv_round_to_clusters(blk_bs(s->target), offset, io_bytes,
413 &target_offset, &target_bytes);
414 if (target_offset == offset &&
415 target_bytes == io_bytes) {
e5b43573
FZ
416 mirror_method = ret & BDRV_BLOCK_ZERO ?
417 MIRROR_METHOD_ZERO :
418 MIRROR_METHOD_DISCARD;
419 }
420 }
421
cf56a3c6 422 while (s->in_flight >= MAX_IN_FLIGHT) {
fb2ef791 423 trace_mirror_yield_in_flight(s, offset, s->in_flight);
cf56a3c6
DL
424 mirror_wait_for_io(s);
425 }
426
dbaa7b57
VSO
427 if (s->ret < 0) {
428 return 0;
429 }
430
fb2ef791 431 io_bytes = mirror_clip_bytes(s, offset, io_bytes);
e5b43573
FZ
432 switch (mirror_method) {
433 case MIRROR_METHOD_COPY:
fb2ef791 434 io_bytes = io_bytes_acct = mirror_do_read(s, offset, io_bytes);
e5b43573
FZ
435 break;
436 case MIRROR_METHOD_ZERO:
e5b43573 437 case MIRROR_METHOD_DISCARD:
fb2ef791 438 mirror_do_zero_or_discard(s, offset, io_bytes,
4b5004d9
DL
439 mirror_method == MIRROR_METHOD_DISCARD);
440 if (write_zeroes_ok) {
f3e4ce4a 441 io_bytes_acct = 0;
4b5004d9 442 } else {
fb2ef791 443 io_bytes_acct = io_bytes;
4b5004d9 444 }
e5b43573
FZ
445 break;
446 default:
447 abort();
448 }
fb2ef791
EB
449 assert(io_bytes);
450 offset += io_bytes;
451 nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
f14a39cc 452 if (s->common.speed) {
f3e4ce4a 453 delay_ns = ratelimit_calculate_delay(&s->limit, io_bytes_acct);
f14a39cc 454 }
dcfb3beb 455 }
cc8c9d6c 456 return delay_ns;
bd48bde8 457}
b952b558 458
402a4741
PB
459static void mirror_free_init(MirrorBlockJob *s)
460{
461 int granularity = s->granularity;
462 size_t buf_size = s->buf_size;
463 uint8_t *buf = s->buf;
464
465 assert(s->buf_free_count == 0);
466 QSIMPLEQ_INIT(&s->buf_free);
467 while (buf_size != 0) {
468 MirrorBuffer *cur = (MirrorBuffer *)buf;
469 QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
470 s->buf_free_count++;
471 buf_size -= granularity;
472 buf += granularity;
473 }
474}
475
bae8196d
PB
476/* This is also used for the .pause callback. There is no matching
477 * mirror_resume() because mirror_run() will begin iterating again
478 * when the job is resumed.
479 */
480static void mirror_wait_for_all_io(MirrorBlockJob *s)
bd48bde8
PB
481{
482 while (s->in_flight > 0) {
21cd917f 483 mirror_wait_for_io(s);
bd48bde8 484 }
893f7eba
PB
485}
486
5a7e7a0b
SH
487typedef struct {
488 int ret;
489} MirrorExitData;
490
491static void mirror_exit(BlockJob *job, void *opaque)
492{
493 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
494 MirrorExitData *data = opaque;
495 AioContext *replace_aio_context = NULL;
4ef85a9c 496 BlockDriverState *src = s->source;
e253f4b8 497 BlockDriverState *target_bs = blk_bs(s->target);
4ef85a9c 498 BlockDriverState *mirror_top_bs = s->mirror_top_bs;
12fa4af6 499 Error *local_err = NULL;
3f09bfbc 500
2119882c
PB
501 bdrv_release_dirty_bitmap(src, s->dirty_bitmap);
502
3f09bfbc
KW
503 /* Make sure that the source BDS doesn't go away before we called
504 * block_job_completed(). */
505 bdrv_ref(src);
4ef85a9c 506 bdrv_ref(mirror_top_bs);
7d9fcb39
KW
507 bdrv_ref(target_bs);
508
509 /* Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
510 * inserting target_bs at s->to_replace, where we might not be able to get
63c8ef28
KW
511 * these permissions.
512 *
513 * Note that blk_unref() alone doesn't necessarily drop permissions because
514 * we might be running nested inside mirror_drain(), which takes an extra
515 * reference, so use an explicit blk_set_perm() first. */
516 blk_set_perm(s->target, 0, BLK_PERM_ALL, &error_abort);
7d9fcb39
KW
517 blk_unref(s->target);
518 s->target = NULL;
4ef85a9c
KW
519
520 /* We don't access the source any more. Dropping any WRITE/RESIZE is
521 * required before it could become a backing file of target_bs. */
522 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
523 &error_abort);
524 if (s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
525 BlockDriverState *backing = s->is_none_mode ? src : s->base;
526 if (backing_bs(target_bs) != backing) {
12fa4af6
KW
527 bdrv_set_backing_hd(target_bs, backing, &local_err);
528 if (local_err) {
529 error_report_err(local_err);
530 data->ret = -EPERM;
531 }
4ef85a9c
KW
532 }
533 }
5a7e7a0b
SH
534
535 if (s->to_replace) {
536 replace_aio_context = bdrv_get_aio_context(s->to_replace);
537 aio_context_acquire(replace_aio_context);
538 }
539
540 if (s->should_complete && data->ret == 0) {
e253f4b8 541 BlockDriverState *to_replace = src;
5a7e7a0b
SH
542 if (s->to_replace) {
543 to_replace = s->to_replace;
544 }
40365552 545
e253f4b8
KW
546 if (bdrv_get_flags(target_bs) != bdrv_get_flags(to_replace)) {
547 bdrv_reopen(target_bs, bdrv_get_flags(to_replace), NULL);
5a7e7a0b 548 }
b8804815
KW
549
550 /* The mirror job has no requests in flight any more, but we need to
551 * drain potential other users of the BDS before changing the graph. */
e253f4b8 552 bdrv_drained_begin(target_bs);
5fe31c25 553 bdrv_replace_node(to_replace, target_bs, &local_err);
e253f4b8 554 bdrv_drained_end(target_bs);
5fe31c25
KW
555 if (local_err) {
556 error_report_err(local_err);
557 data->ret = -EPERM;
558 }
5a7e7a0b
SH
559 }
560 if (s->to_replace) {
561 bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
562 error_free(s->replace_blocker);
563 bdrv_unref(s->to_replace);
564 }
565 if (replace_aio_context) {
566 aio_context_release(replace_aio_context);
567 }
568 g_free(s->replaces);
7d9fcb39 569 bdrv_unref(target_bs);
4ef85a9c
KW
570
571 /* Remove the mirror filter driver from the graph. Before this, get rid of
572 * the blockers on the intermediate nodes so that the resulting state is
0bf74767
KW
573 * valid. Also give up permissions on mirror_top_bs->backing, which might
574 * block the removal. */
4ef85a9c 575 block_job_remove_all_bdrv(job);
c1cef672
FZ
576 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
577 &error_abort);
5fe31c25 578 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
4ef85a9c
KW
579
580 /* We just changed the BDS the job BB refers to (with either or both of the
5fe31c25
KW
581 * bdrv_replace_node() calls), so switch the BB back so the cleanup does
582 * the right thing. We don't need any permissions any more now. */
4ef85a9c
KW
583 blk_remove_bs(job->blk);
584 blk_set_perm(job->blk, 0, BLK_PERM_ALL, &error_abort);
585 blk_insert_bs(job->blk, mirror_top_bs, &error_abort);
586
5a7e7a0b 587 block_job_completed(&s->common, data->ret);
4ef85a9c 588
5a7e7a0b 589 g_free(data);
176c3699 590 bdrv_drained_end(src);
4ef85a9c 591 bdrv_unref(mirror_top_bs);
3f09bfbc 592 bdrv_unref(src);
5a7e7a0b
SH
593}
594
49efb1f5
DL
595static void mirror_throttle(MirrorBlockJob *s)
596{
597 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
598
599 if (now - s->last_pause_ns > SLICE_TIME) {
600 s->last_pause_ns = now;
5bf1d5a7 601 block_job_sleep_ns(&s->common, 0);
49efb1f5
DL
602 } else {
603 block_job_pause_point(&s->common);
604 }
605}
606
c0b363ad
DL
607static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
608{
23ca459a 609 int64_t offset;
c0b363ad 610 BlockDriverState *base = s->base;
4ef85a9c 611 BlockDriverState *bs = s->source;
c0b363ad 612 BlockDriverState *target_bs = blk_bs(s->target);
23ca459a 613 int ret;
51b0a488 614 int64_t count;
c0b363ad 615
b7d5062c 616 if (base == NULL && !bdrv_has_zero_init(target_bs)) {
c7c2769c 617 if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
e0d7f73e 618 bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
c7c2769c
DL
619 return 0;
620 }
621
90ab48eb 622 s->initial_zeroing_ongoing = true;
23ca459a
EB
623 for (offset = 0; offset < s->bdev_length; ) {
624 int bytes = MIN(s->bdev_length - offset,
625 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
c7c2769c
DL
626
627 mirror_throttle(s);
628
629 if (block_job_is_cancelled(&s->common)) {
90ab48eb 630 s->initial_zeroing_ongoing = false;
c7c2769c
DL
631 return 0;
632 }
633
634 if (s->in_flight >= MAX_IN_FLIGHT) {
67adf4b3
EB
635 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
636 s->in_flight);
c7c2769c
DL
637 mirror_wait_for_io(s);
638 continue;
639 }
640
23ca459a
EB
641 mirror_do_zero_or_discard(s, offset, bytes, false);
642 offset += bytes;
c7c2769c
DL
643 }
644
bae8196d 645 mirror_wait_for_all_io(s);
90ab48eb 646 s->initial_zeroing_ongoing = false;
b7d5062c
DL
647 }
648
c0b363ad 649 /* First part, loop on the sectors and initialize the dirty bitmap. */
23ca459a 650 for (offset = 0; offset < s->bdev_length; ) {
c0b363ad 651 /* Just to make sure we are not exceeding int limit. */
23ca459a
EB
652 int bytes = MIN(s->bdev_length - offset,
653 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
c0b363ad
DL
654
655 mirror_throttle(s);
656
657 if (block_job_is_cancelled(&s->common)) {
658 return 0;
659 }
660
23ca459a 661 ret = bdrv_is_allocated_above(bs, base, offset, bytes, &count);
c0b363ad
DL
662 if (ret < 0) {
663 return ret;
664 }
665
23ca459a 666 assert(count);
b7d5062c 667 if (ret == 1) {
23ca459a 668 bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
c0b363ad 669 }
23ca459a 670 offset += count;
c0b363ad
DL
671 }
672 return 0;
673}
674
bdffb31d
PB
675/* Called when going out of the streaming phase to flush the bulk of the
676 * data to the medium, or just before completing.
677 */
678static int mirror_flush(MirrorBlockJob *s)
679{
680 int ret = blk_flush(s->target);
681 if (ret < 0) {
682 if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
683 s->ret = ret;
684 }
685 }
686 return ret;
687}
688
893f7eba
PB
689static void coroutine_fn mirror_run(void *opaque)
690{
691 MirrorBlockJob *s = opaque;
5a7e7a0b 692 MirrorExitData *data;
4ef85a9c 693 BlockDriverState *bs = s->source;
e253f4b8 694 BlockDriverState *target_bs = blk_bs(s->target);
9a0cec66 695 bool need_drain = true;
c0b363ad 696 int64_t length;
b812f671 697 BlockDriverInfo bdi;
1d33936e
JC
698 char backing_filename[2]; /* we only need 2 characters because we are only
699 checking for a NULL string */
893f7eba 700 int ret = 0;
893f7eba
PB
701
702 if (block_job_is_cancelled(&s->common)) {
703 goto immediate_exit;
704 }
705
b21c7652
HR
706 s->bdev_length = bdrv_getlength(bs);
707 if (s->bdev_length < 0) {
708 ret = s->bdev_length;
373df5b1 709 goto immediate_exit;
becc347e
KW
710 }
711
712 /* Active commit must resize the base image if its size differs from the
713 * active layer. */
714 if (s->base == blk_bs(s->target)) {
715 int64_t base_length;
716
717 base_length = blk_getlength(s->target);
718 if (base_length < 0) {
719 ret = base_length;
720 goto immediate_exit;
721 }
722
723 if (s->bdev_length > base_length) {
3a691c50
HR
724 ret = blk_truncate(s->target, s->bdev_length, PREALLOC_MODE_OFF,
725 NULL);
becc347e
KW
726 if (ret < 0) {
727 goto immediate_exit;
728 }
729 }
730 }
731
732 if (s->bdev_length == 0) {
9e48b025
FZ
733 /* Report BLOCK_JOB_READY and wait for complete. */
734 block_job_event_ready(&s->common);
735 s->synced = true;
736 while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
737 block_job_yield(&s->common);
738 }
739 s->common.cancelled = false;
740 goto immediate_exit;
893f7eba
PB
741 }
742
b21c7652 743 length = DIV_ROUND_UP(s->bdev_length, s->granularity);
402a4741
PB
744 s->in_flight_bitmap = bitmap_new(length);
745
b812f671
PB
746 /* If we have no backing file yet in the destination, we cannot let
747 * the destination do COW. Instead, we copy sectors around the
748 * dirty data if needed. We need a bitmap to do that.
749 */
e253f4b8 750 bdrv_get_backing_filename(target_bs, backing_filename,
b812f671 751 sizeof(backing_filename));
e253f4b8 752 if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
b436982f
EB
753 s->target_cluster_size = bdi.cluster_size;
754 } else {
755 s->target_cluster_size = BDRV_SECTOR_SIZE;
e5b43573 756 }
b436982f
EB
757 if (backing_filename[0] && !target_bs->backing &&
758 s->granularity < s->target_cluster_size) {
759 s->buf_size = MAX(s->buf_size, s->target_cluster_size);
e5b43573 760 s->cow_bitmap = bitmap_new(length);
b812f671 761 }
e253f4b8 762 s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
b812f671 763
7504edf4
KW
764 s->buf = qemu_try_blockalign(bs, s->buf_size);
765 if (s->buf == NULL) {
766 ret = -ENOMEM;
767 goto immediate_exit;
768 }
769
402a4741 770 mirror_free_init(s);
893f7eba 771
49efb1f5 772 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
03544a6e 773 if (!s->is_none_mode) {
c0b363ad
DL
774 ret = mirror_dirty_init(s);
775 if (ret < 0 || block_job_is_cancelled(&s->common)) {
776 goto immediate_exit;
893f7eba
PB
777 }
778 }
779
dc162c8e 780 assert(!s->dbi);
715a74d8 781 s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
893f7eba 782 for (;;) {
cc8c9d6c 783 uint64_t delay_ns = 0;
49efb1f5 784 int64_t cnt, delta;
893f7eba
PB
785 bool should_complete;
786
bd48bde8
PB
787 if (s->ret < 0) {
788 ret = s->ret;
789 goto immediate_exit;
790 }
791
565ac01f
SH
792 block_job_pause_point(&s->common);
793
20dca810 794 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
b21c7652 795 /* s->common.offset contains the number of bytes already processed so
9a46dba7 796 * far, cnt is the number of dirty bytes remaining and
b436982f 797 * s->bytes_in_flight is the number of bytes currently being
b21c7652 798 * processed; together those are the current total operation length */
9a46dba7 799 s->common.len = s->common.offset + s->bytes_in_flight + cnt;
bd48bde8
PB
800
801 /* Note that even when no rate limit is applied we need to yield
a7282330 802 * periodically with no pending I/O so that bdrv_drain_all() returns.
bd48bde8
PB
803 * We do so every SLICE_TIME nanoseconds, or when there is an error,
804 * or when the source is clean, whichever comes first.
805 */
49efb1f5
DL
806 delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
807 if (delta < SLICE_TIME &&
bd48bde8 808 s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
cf56a3c6 809 if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
402a4741 810 (cnt == 0 && s->in_flight > 0)) {
9a46dba7 811 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
21cd917f 812 mirror_wait_for_io(s);
bd48bde8
PB
813 continue;
814 } else if (cnt != 0) {
cc8c9d6c 815 delay_ns = mirror_iteration(s);
893f7eba 816 }
893f7eba
PB
817 }
818
819 should_complete = false;
bd48bde8 820 if (s->in_flight == 0 && cnt == 0) {
893f7eba 821 trace_mirror_before_flush(s);
bdffb31d
PB
822 if (!s->synced) {
823 if (mirror_flush(s) < 0) {
824 /* Go check s->ret. */
825 continue;
b952b558 826 }
b952b558
PB
827 /* We're out of the streaming phase. From now on, if the job
828 * is cancelled we will actually complete all pending I/O and
829 * report completion. This way, block-job-cancel will leave
830 * the target in a consistent state.
831 */
bdffb31d
PB
832 block_job_event_ready(&s->common);
833 s->synced = true;
d63ffd87 834 }
bdffb31d
PB
835
836 should_complete = s->should_complete ||
837 block_job_is_cancelled(&s->common);
838 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
893f7eba
PB
839 }
840
841 if (cnt == 0 && should_complete) {
842 /* The dirty bitmap is not updated while operations are pending.
843 * If we're about to exit, wait for pending operations before
844 * calling bdrv_get_dirty_count(bs), or we may exit while the
845 * source has dirty data to copy!
846 *
847 * Note that I/O can be submitted by the guest while
9a0cec66
PB
848 * mirror_populate runs, so pause it now. Before deciding
849 * whether to switch to target check one last time if I/O has
850 * come in the meanwhile, and if not flush the data to disk.
893f7eba 851 */
9a46dba7 852 trace_mirror_before_drain(s, cnt);
9a0cec66
PB
853
854 bdrv_drained_begin(bs);
20dca810 855 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
bdffb31d 856 if (cnt > 0 || mirror_flush(s) < 0) {
9a0cec66
PB
857 bdrv_drained_end(bs);
858 continue;
859 }
860
861 /* The two disks are in sync. Exit and report successful
862 * completion.
863 */
864 assert(QLIST_EMPTY(&bs->tracked_requests));
865 s->common.cancelled = false;
866 need_drain = false;
867 break;
893f7eba
PB
868 }
869
870 ret = 0;
ddc4115e
SH
871
872 if (s->synced && !should_complete) {
873 delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
874 }
9a46dba7 875 trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
ddc4115e 876 block_job_sleep_ns(&s->common, delay_ns);
b76e4458
LL
877 if (block_job_is_cancelled(&s->common) && s->common.force) {
878 break;
893f7eba 879 }
49efb1f5 880 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
893f7eba
PB
881 }
882
883immediate_exit:
bd48bde8
PB
884 if (s->in_flight > 0) {
885 /* We get here only if something went wrong. Either the job failed,
886 * or it was cancelled prematurely so that we do not guarantee that
887 * the target is a copy of the source.
888 */
b76e4458
LL
889 assert(ret < 0 || ((s->common.force || !s->synced) &&
890 block_job_is_cancelled(&s->common)));
9a0cec66 891 assert(need_drain);
bae8196d 892 mirror_wait_for_all_io(s);
bd48bde8
PB
893 }
894
895 assert(s->in_flight == 0);
7191bf31 896 qemu_vfree(s->buf);
b812f671 897 g_free(s->cow_bitmap);
402a4741 898 g_free(s->in_flight_bitmap);
dc162c8e 899 bdrv_dirty_iter_free(s->dbi);
5a7e7a0b
SH
900
901 data = g_malloc(sizeof(*data));
902 data->ret = ret;
9a0cec66
PB
903
904 if (need_drain) {
905 bdrv_drained_begin(bs);
906 }
5a7e7a0b 907 block_job_defer_to_main_loop(&s->common, mirror_exit, data);
893f7eba
PB
908}
909
910static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)
911{
912 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
913
914 if (speed < 0) {
c6bd8c70 915 error_setg(errp, QERR_INVALID_PARAMETER, "speed");
893f7eba
PB
916 return;
917 }
f3e4ce4a 918 ratelimit_set_speed(&s->limit, speed, SLICE_TIME);
893f7eba
PB
919}
920
d63ffd87
PB
921static void mirror_complete(BlockJob *job, Error **errp)
922{
923 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
4ef85a9c 924 BlockDriverState *target;
274fccee 925
274fccee 926 target = blk_bs(s->target);
d63ffd87 927
d63ffd87 928 if (!s->synced) {
9df229c3
AG
929 error_setg(errp, "The active block job '%s' cannot be completed",
930 job->id);
d63ffd87
PB
931 return;
932 }
933
274fccee
HR
934 if (s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
935 int ret;
936
937 assert(!target->backing);
938 ret = bdrv_open_backing_file(target, NULL, "backing", errp);
939 if (ret < 0) {
940 return;
941 }
942 }
943
15d67298 944 /* block all operations on to_replace bs */
09158f00 945 if (s->replaces) {
5a7e7a0b
SH
946 AioContext *replace_aio_context;
947
e12f3784 948 s->to_replace = bdrv_find_node(s->replaces);
09158f00 949 if (!s->to_replace) {
e12f3784 950 error_setg(errp, "Node name '%s' not found", s->replaces);
09158f00
BC
951 return;
952 }
953
5a7e7a0b
SH
954 replace_aio_context = bdrv_get_aio_context(s->to_replace);
955 aio_context_acquire(replace_aio_context);
956
4ef85a9c
KW
957 /* TODO Translate this into permission system. Current definition of
958 * GRAPH_MOD would require to request it for the parents; they might
959 * not even be BlockDriverStates, however, so a BdrvChild can't address
960 * them. May need redefinition of GRAPH_MOD. */
09158f00
BC
961 error_setg(&s->replace_blocker,
962 "block device is in use by block-job-complete");
963 bdrv_op_block_all(s->to_replace, s->replace_blocker);
964 bdrv_ref(s->to_replace);
5a7e7a0b
SH
965
966 aio_context_release(replace_aio_context);
09158f00
BC
967 }
968
d63ffd87 969 s->should_complete = true;
751ebd76 970 block_job_enter(&s->common);
d63ffd87
PB
971}
972
bae8196d 973static void mirror_pause(BlockJob *job)
565ac01f
SH
974{
975 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
976
bae8196d 977 mirror_wait_for_all_io(s);
565ac01f
SH
978}
979
980static void mirror_attached_aio_context(BlockJob *job, AioContext *new_context)
981{
982 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
983
984 blk_set_aio_context(s->target, new_context);
985}
986
bae8196d
PB
987static void mirror_drain(BlockJob *job)
988{
989 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
990
991 /* Need to keep a reference in case blk_drain triggers execution
992 * of mirror_complete...
993 */
994 if (s->target) {
995 BlockBackend *target = s->target;
996 blk_ref(target);
997 blk_drain(target);
998 blk_unref(target);
999 }
1000}
1001
3fc4b10a 1002static const BlockJobDriver mirror_job_driver = {
565ac01f
SH
1003 .instance_size = sizeof(MirrorBlockJob),
1004 .job_type = BLOCK_JOB_TYPE_MIRROR,
1005 .set_speed = mirror_set_speed,
a7815a76 1006 .start = mirror_run,
565ac01f
SH
1007 .complete = mirror_complete,
1008 .pause = mirror_pause,
1009 .attached_aio_context = mirror_attached_aio_context,
bae8196d 1010 .drain = mirror_drain,
893f7eba
PB
1011};
1012
03544a6e 1013static const BlockJobDriver commit_active_job_driver = {
565ac01f
SH
1014 .instance_size = sizeof(MirrorBlockJob),
1015 .job_type = BLOCK_JOB_TYPE_COMMIT,
1016 .set_speed = mirror_set_speed,
a7815a76 1017 .start = mirror_run,
565ac01f
SH
1018 .complete = mirror_complete,
1019 .pause = mirror_pause,
1020 .attached_aio_context = mirror_attached_aio_context,
bae8196d 1021 .drain = mirror_drain,
03544a6e
FZ
1022};
1023
4ef85a9c
KW
1024static int coroutine_fn bdrv_mirror_top_preadv(BlockDriverState *bs,
1025 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1026{
1027 return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
1028}
1029
1030static int coroutine_fn bdrv_mirror_top_pwritev(BlockDriverState *bs,
1031 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1032{
1033 return bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1034}
1035
1036static int coroutine_fn bdrv_mirror_top_flush(BlockDriverState *bs)
1037{
ce960aa9
VSO
1038 if (bs->backing == NULL) {
1039 /* we can be here after failed bdrv_append in mirror_start_job */
1040 return 0;
1041 }
4ef85a9c
KW
1042 return bdrv_co_flush(bs->backing->bs);
1043}
1044
4ef85a9c 1045static int coroutine_fn bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs,
f5a5ca79 1046 int64_t offset, int bytes, BdrvRequestFlags flags)
4ef85a9c 1047{
f5a5ca79 1048 return bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
4ef85a9c
KW
1049}
1050
1051static int coroutine_fn bdrv_mirror_top_pdiscard(BlockDriverState *bs,
f5a5ca79 1052 int64_t offset, int bytes)
4ef85a9c 1053{
f5a5ca79 1054 return bdrv_co_pdiscard(bs->backing->bs, offset, bytes);
4ef85a9c
KW
1055}
1056
fd4a6493
KW
1057static void bdrv_mirror_top_refresh_filename(BlockDriverState *bs, QDict *opts)
1058{
18775ff3
VSO
1059 if (bs->backing == NULL) {
1060 /* we can be here after failed bdrv_attach_child in
1061 * bdrv_set_backing_hd */
1062 return;
1063 }
fd4a6493
KW
1064 bdrv_refresh_filename(bs->backing->bs);
1065 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1066 bs->backing->bs->filename);
1067}
1068
4ef85a9c
KW
1069static void bdrv_mirror_top_close(BlockDriverState *bs)
1070{
1071}
1072
1073static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1074 const BdrvChildRole *role,
e0995dc3 1075 BlockReopenQueue *reopen_queue,
4ef85a9c
KW
1076 uint64_t perm, uint64_t shared,
1077 uint64_t *nperm, uint64_t *nshared)
1078{
1079 /* Must be able to forward guest writes to the real image */
1080 *nperm = 0;
1081 if (perm & BLK_PERM_WRITE) {
1082 *nperm |= BLK_PERM_WRITE;
1083 }
1084
1085 *nshared = BLK_PERM_ALL;
1086}
1087
1088/* Dummy node that provides consistent read to its users without requiring it
1089 * from its backing file and that allows writes on the backing file chain. */
1090static BlockDriver bdrv_mirror_top = {
1091 .format_name = "mirror_top",
1092 .bdrv_co_preadv = bdrv_mirror_top_preadv,
1093 .bdrv_co_pwritev = bdrv_mirror_top_pwritev,
1094 .bdrv_co_pwrite_zeroes = bdrv_mirror_top_pwrite_zeroes,
1095 .bdrv_co_pdiscard = bdrv_mirror_top_pdiscard,
1096 .bdrv_co_flush = bdrv_mirror_top_flush,
3e4d0e72 1097 .bdrv_co_block_status = bdrv_co_block_status_from_backing,
fd4a6493 1098 .bdrv_refresh_filename = bdrv_mirror_top_refresh_filename,
4ef85a9c
KW
1099 .bdrv_close = bdrv_mirror_top_close,
1100 .bdrv_child_perm = bdrv_mirror_top_child_perm,
1101};
1102
71aa9867 1103static void mirror_start_job(const char *job_id, BlockDriverState *bs,
47970dfb
JS
1104 int creation_flags, BlockDriverState *target,
1105 const char *replaces, int64_t speed,
1106 uint32_t granularity, int64_t buf_size,
274fccee 1107 BlockMirrorBackingMode backing_mode,
09158f00
BC
1108 BlockdevOnError on_source_error,
1109 BlockdevOnError on_target_error,
0fc9f8ea 1110 bool unmap,
097310b5 1111 BlockCompletionFunc *cb,
51ccfa2d 1112 void *opaque,
09158f00 1113 const BlockJobDriver *driver,
b49f7ead 1114 bool is_none_mode, BlockDriverState *base,
51ccfa2d 1115 bool auto_complete, const char *filter_node_name,
045a2f82 1116 bool is_mirror,
51ccfa2d 1117 Error **errp)
893f7eba
PB
1118{
1119 MirrorBlockJob *s;
4ef85a9c
KW
1120 BlockDriverState *mirror_top_bs;
1121 bool target_graph_mod;
1122 bool target_is_backing;
b2c2832c 1123 Error *local_err = NULL;
d7086422 1124 int ret;
893f7eba 1125
eee13dfe 1126 if (granularity == 0) {
341ebc2f 1127 granularity = bdrv_get_default_bitmap_granularity(target);
eee13dfe
PB
1128 }
1129
31826642 1130 assert(is_power_of_2(granularity));
eee13dfe 1131
48ac0a4d
WC
1132 if (buf_size < 0) {
1133 error_setg(errp, "Invalid parameter 'buf-size'");
1134 return;
1135 }
1136
1137 if (buf_size == 0) {
1138 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1139 }
5bc361b8 1140
4ef85a9c
KW
1141 /* In the case of active commit, add dummy driver to provide consistent
1142 * reads on the top, while disabling it in the intermediate nodes, and make
1143 * the backing chain writable. */
6cdbceb1
KW
1144 mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
1145 BDRV_O_RDWR, errp);
4ef85a9c
KW
1146 if (mirror_top_bs == NULL) {
1147 return;
1148 }
d3c8c674
KW
1149 if (!filter_node_name) {
1150 mirror_top_bs->implicit = true;
1151 }
4ef85a9c 1152 mirror_top_bs->total_sectors = bs->total_sectors;
19dd29e8 1153 bdrv_set_aio_context(mirror_top_bs, bdrv_get_aio_context(bs));
4ef85a9c
KW
1154
1155 /* bdrv_append takes ownership of the mirror_top_bs reference, need to keep
7a25fcd0 1156 * it alive until block_job_create() succeeds even if bs has no parent. */
4ef85a9c
KW
1157 bdrv_ref(mirror_top_bs);
1158 bdrv_drained_begin(bs);
b2c2832c 1159 bdrv_append(mirror_top_bs, bs, &local_err);
4ef85a9c
KW
1160 bdrv_drained_end(bs);
1161
b2c2832c
KW
1162 if (local_err) {
1163 bdrv_unref(mirror_top_bs);
1164 error_propagate(errp, local_err);
1165 return;
1166 }
1167
4ef85a9c 1168 /* Make sure that the source is not resized while the job is running */
75859b94 1169 s = block_job_create(job_id, driver, NULL, mirror_top_bs,
4ef85a9c
KW
1170 BLK_PERM_CONSISTENT_READ,
1171 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1172 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD, speed,
c6cc12bf 1173 creation_flags, cb, opaque, errp);
893f7eba 1174 if (!s) {
4ef85a9c 1175 goto fail;
893f7eba 1176 }
7a25fcd0
HR
1177 /* The block job now has a reference to this node */
1178 bdrv_unref(mirror_top_bs);
1179
4ef85a9c
KW
1180 s->source = bs;
1181 s->mirror_top_bs = mirror_top_bs;
1182
1183 /* No resize for the target either; while the mirror is still running, a
1184 * consistent read isn't necessarily possible. We could possibly allow
1185 * writes and graph modifications, though it would likely defeat the
1186 * purpose of a mirror, so leave them blocked for now.
1187 *
1188 * In the case of active commit, things look a bit different, though,
1189 * because the target is an already populated backing file in active use.
1190 * We can allow anything except resize there.*/
1191 target_is_backing = bdrv_chain_contains(bs, target);
1192 target_graph_mod = (backing_mode != MIRROR_LEAVE_BACKING_CHAIN);
1193 s->target = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE |
1194 (target_graph_mod ? BLK_PERM_GRAPH_MOD : 0),
1195 BLK_PERM_WRITE_UNCHANGED |
1196 (target_is_backing ? BLK_PERM_CONSISTENT_READ |
1197 BLK_PERM_WRITE |
1198 BLK_PERM_GRAPH_MOD : 0));
d7086422
KW
1199 ret = blk_insert_bs(s->target, target, errp);
1200 if (ret < 0) {
4ef85a9c 1201 goto fail;
d7086422 1202 }
045a2f82
FZ
1203 if (is_mirror) {
1204 /* XXX: Mirror target could be a NBD server of target QEMU in the case
1205 * of non-shared block migration. To allow migration completion, we
1206 * have to allow "inactivate" of the target BB. When that happens, we
1207 * know the job is drained, and the vcpus are stopped, so no write
1208 * operation will be performed. Block layer already has assertions to
1209 * ensure that. */
1210 blk_set_force_allow_inactivate(s->target);
1211 }
e253f4b8 1212
09158f00 1213 s->replaces = g_strdup(replaces);
b952b558
PB
1214 s->on_source_error = on_source_error;
1215 s->on_target_error = on_target_error;
03544a6e 1216 s->is_none_mode = is_none_mode;
274fccee 1217 s->backing_mode = backing_mode;
5bc361b8 1218 s->base = base;
eee13dfe 1219 s->granularity = granularity;
48ac0a4d 1220 s->buf_size = ROUND_UP(buf_size, granularity);
0fc9f8ea 1221 s->unmap = unmap;
b49f7ead
WC
1222 if (auto_complete) {
1223 s->should_complete = true;
1224 }
b812f671 1225
0db6e54a 1226 s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
b8afb520 1227 if (!s->dirty_bitmap) {
88f9d1b3 1228 goto fail;
b8afb520 1229 }
10f3cd15 1230
4ef85a9c 1231 /* Required permissions are already taken with blk_new() */
76d554e2
KW
1232 block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
1233 &error_abort);
1234
f3ede4b0
AG
1235 /* In commit_active_start() all intermediate nodes disappear, so
1236 * any jobs in them must be blocked */
4ef85a9c 1237 if (target_is_backing) {
f3ede4b0
AG
1238 BlockDriverState *iter;
1239 for (iter = backing_bs(bs); iter != target; iter = backing_bs(iter)) {
4ef85a9c
KW
1240 /* XXX BLK_PERM_WRITE needs to be allowed so we don't block
1241 * ourselves at s->base (if writes are blocked for a node, they are
1242 * also blocked for its backing file). The other options would be a
1243 * second filter driver above s->base (== target). */
1244 ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
1245 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE,
1246 errp);
1247 if (ret < 0) {
1248 goto fail;
1249 }
f3ede4b0
AG
1250 }
1251 }
10f3cd15 1252
5ccac6f1
JS
1253 trace_mirror_start(bs, s, opaque);
1254 block_job_start(&s->common);
4ef85a9c
KW
1255 return;
1256
1257fail:
1258 if (s) {
7a25fcd0
HR
1259 /* Make sure this BDS does not go away until we have completed the graph
1260 * changes below */
1261 bdrv_ref(mirror_top_bs);
1262
4ef85a9c
KW
1263 g_free(s->replaces);
1264 blk_unref(s->target);
05b0d8e3 1265 block_job_early_fail(&s->common);
4ef85a9c
KW
1266 }
1267
c1cef672
FZ
1268 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
1269 &error_abort);
5fe31c25 1270 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
7a25fcd0
HR
1271
1272 bdrv_unref(mirror_top_bs);
893f7eba 1273}
03544a6e 1274
71aa9867
AG
1275void mirror_start(const char *job_id, BlockDriverState *bs,
1276 BlockDriverState *target, const char *replaces,
5fba6c0e 1277 int64_t speed, uint32_t granularity, int64_t buf_size,
274fccee
HR
1278 MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
1279 BlockdevOnError on_source_error,
03544a6e 1280 BlockdevOnError on_target_error,
6cdbceb1 1281 bool unmap, const char *filter_node_name, Error **errp)
03544a6e
FZ
1282{
1283 bool is_none_mode;
1284 BlockDriverState *base;
1285
4b80ab2b
JS
1286 if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
1287 error_setg(errp, "Sync mode 'incremental' not supported");
d58d8453
JS
1288 return;
1289 }
03544a6e 1290 is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
760e0063 1291 base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
47970dfb 1292 mirror_start_job(job_id, bs, BLOCK_JOB_DEFAULT, target, replaces,
274fccee 1293 speed, granularity, buf_size, backing_mode,
51ccfa2d 1294 on_source_error, on_target_error, unmap, NULL, NULL,
6cdbceb1 1295 &mirror_job_driver, is_none_mode, base, false,
045a2f82 1296 filter_node_name, true, errp);
03544a6e
FZ
1297}
1298
fd62c609 1299void commit_active_start(const char *job_id, BlockDriverState *bs,
47970dfb
JS
1300 BlockDriverState *base, int creation_flags,
1301 int64_t speed, BlockdevOnError on_error,
0db832f4 1302 const char *filter_node_name,
78bbd910
FZ
1303 BlockCompletionFunc *cb, void *opaque,
1304 bool auto_complete, Error **errp)
03544a6e 1305{
4da83585 1306 int orig_base_flags;
cc67f4d1 1307 Error *local_err = NULL;
4da83585
JC
1308
1309 orig_base_flags = bdrv_get_flags(base);
1310
20a63d2c
FZ
1311 if (bdrv_reopen(base, bs->open_flags, errp)) {
1312 return;
1313 }
4da83585 1314
47970dfb 1315 mirror_start_job(job_id, bs, creation_flags, base, NULL, speed, 0, 0,
71aa9867 1316 MIRROR_LEAVE_BACKING_CHAIN,
51ccfa2d 1317 on_error, on_error, true, cb, opaque,
6cdbceb1 1318 &commit_active_job_driver, false, base, auto_complete,
045a2f82 1319 filter_node_name, false, &local_err);
0fb6395c 1320 if (local_err) {
cc67f4d1 1321 error_propagate(errp, local_err);
4da83585
JC
1322 goto error_restore_flags;
1323 }
1324
1325 return;
1326
1327error_restore_flags:
1328 /* ignore error and errp for bdrv_reopen, because we want to propagate
1329 * the original error */
1330 bdrv_reopen(base, orig_base_flags, NULL);
1331 return;
03544a6e 1332}