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