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