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