]> git.proxmox.com Git - mirror_qemu.git/blame - block/mirror.c
block: Mark bdrv_*_dirty_bitmap() and callers GRAPH_RDLOCK
[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"
12aa4082 16#include "qemu/coroutine.h"
1181e19a 17#include "qemu/range.h"
893f7eba 18#include "trace.h"
c87621ea 19#include "block/blockjob_int.h"
737e150e 20#include "block/block_int.h"
e2c1c34f 21#include "block/dirty-bitmap.h"
373340b2 22#include "sysemu/block-backend.h"
da34e65c 23#include "qapi/error.h"
cc7a8ea7 24#include "qapi/qmp/qerror.h"
893f7eba 25#include "qemu/ratelimit.h"
b812f671 26#include "qemu/bitmap.h"
5df022cf 27#include "qemu/memalign.h"
893f7eba 28
402a4741 29#define MAX_IN_FLIGHT 16
b436982f
EB
30#define MAX_IO_BYTES (1 << 20) /* 1 Mb */
31#define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
402a4741
PB
32
33/* The mirroring buffer is a list of granularity-sized chunks.
34 * Free chunks are organized in a list.
35 */
36typedef struct MirrorBuffer {
37 QSIMPLEQ_ENTRY(MirrorBuffer) next;
38} MirrorBuffer;
893f7eba 39
12aa4082
HR
40typedef struct MirrorOp MirrorOp;
41
893f7eba
PB
42typedef struct MirrorBlockJob {
43 BlockJob common;
e253f4b8 44 BlockBackend *target;
4ef85a9c 45 BlockDriverState *mirror_top_bs;
5bc361b8 46 BlockDriverState *base;
3f072a7f 47 BlockDriverState *base_overlay;
4ef85a9c 48
09158f00
BC
49 /* The name of the graph node to replace */
50 char *replaces;
51 /* The BDS to replace */
52 BlockDriverState *to_replace;
53 /* Used to block operations on the drive-mirror-replace target */
54 Error *replace_blocker;
03544a6e 55 bool is_none_mode;
274fccee 56 BlockMirrorBackingMode backing_mode;
cdf3bc93
HR
57 /* Whether the target image requires explicit zero-initialization */
58 bool zero_target;
d06107ad 59 MirrorCopyMode copy_mode;
b952b558 60 BlockdevOnError on_source_error, on_target_error;
d06107ad
HR
61 /* Set when the target is synced (dirty bitmap is clean, nothing
62 * in flight) and the job is running in active mode */
63 bool actively_synced;
d63ffd87 64 bool should_complete;
eee13dfe 65 int64_t granularity;
b812f671 66 size_t buf_size;
b21c7652 67 int64_t bdev_length;
b812f671 68 unsigned long *cow_bitmap;
e4654d2d 69 BdrvDirtyBitmap *dirty_bitmap;
dc162c8e 70 BdrvDirtyBitmapIter *dbi;
893f7eba 71 uint8_t *buf;
402a4741
PB
72 QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
73 int buf_free_count;
bd48bde8 74
49efb1f5 75 uint64_t last_pause_ns;
402a4741 76 unsigned long *in_flight_bitmap;
1b8f7776 77 unsigned in_flight;
b436982f 78 int64_t bytes_in_flight;
b58deb34 79 QTAILQ_HEAD(, MirrorOp) ops_in_flight;
bd48bde8 80 int ret;
0fc9f8ea 81 bool unmap;
b436982f 82 int target_cluster_size;
e5b43573 83 int max_iov;
90ab48eb 84 bool initial_zeroing_ongoing;
d06107ad 85 int in_active_write_counter;
d69a879b 86 int64_t active_write_bytes_in_flight;
737efc1e 87 bool prepared;
5e771752 88 bool in_drain;
893f7eba
PB
89} MirrorBlockJob;
90
429076e8
HR
91typedef struct MirrorBDSOpaque {
92 MirrorBlockJob *job;
f94dc3b4 93 bool stop;
53431b90 94 bool is_commit;
429076e8
HR
95} MirrorBDSOpaque;
96
12aa4082 97struct MirrorOp {
bd48bde8
PB
98 MirrorBlockJob *s;
99 QEMUIOVector qiov;
b436982f
EB
100 int64_t offset;
101 uint64_t bytes;
2e1990b2
HR
102
103 /* The pointee is set by mirror_co_read(), mirror_co_zero(), and
104 * mirror_co_discard() before yielding for the first time */
105 int64_t *bytes_handled;
12aa4082 106
1181e19a 107 bool is_pseudo_op;
d06107ad 108 bool is_active_write;
ce8cabbd 109 bool is_in_flight;
12aa4082 110 CoQueue waiting_requests;
eed325b9 111 Coroutine *co;
d44dae1a 112 MirrorOp *waiting_for_op;
12aa4082
HR
113
114 QTAILQ_ENTRY(MirrorOp) next;
115};
bd48bde8 116
4295c5fc
HR
117typedef enum MirrorMethod {
118 MIRROR_METHOD_COPY,
119 MIRROR_METHOD_ZERO,
120 MIRROR_METHOD_DISCARD,
121} MirrorMethod;
122
b952b558
PB
123static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
124 int error)
125{
d06107ad 126 s->actively_synced = false;
b952b558 127 if (read) {
81e254dc
KW
128 return block_job_error_action(&s->common, s->on_source_error,
129 true, error);
b952b558 130 } else {
81e254dc
KW
131 return block_job_error_action(&s->common, s->on_target_error,
132 false, error);
b952b558
PB
133 }
134}
135
1181e19a
HR
136static void coroutine_fn mirror_wait_on_conflicts(MirrorOp *self,
137 MirrorBlockJob *s,
138 uint64_t offset,
139 uint64_t bytes)
140{
141 uint64_t self_start_chunk = offset / s->granularity;
142 uint64_t self_end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
143 uint64_t self_nb_chunks = self_end_chunk - self_start_chunk;
144
145 while (find_next_bit(s->in_flight_bitmap, self_end_chunk,
146 self_start_chunk) < self_end_chunk &&
147 s->ret >= 0)
148 {
149 MirrorOp *op;
150
151 QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
152 uint64_t op_start_chunk = op->offset / s->granularity;
153 uint64_t op_nb_chunks = DIV_ROUND_UP(op->offset + op->bytes,
154 s->granularity) -
155 op_start_chunk;
156
157 if (op == self) {
158 continue;
159 }
160
161 if (ranges_overlap(self_start_chunk, self_nb_chunks,
162 op_start_chunk, op_nb_chunks))
163 {
66fed30c
SG
164 if (self) {
165 /*
166 * If the operation is already (indirectly) waiting for us,
167 * or will wait for us as soon as it wakes up, then just go
168 * on (instead of producing a deadlock in the former case).
169 */
170 if (op->waiting_for_op) {
171 continue;
172 }
173
174 self->waiting_for_op = op;
d44dae1a
VSO
175 }
176
1181e19a 177 qemu_co_queue_wait(&op->waiting_requests, NULL);
66fed30c
SG
178
179 if (self) {
180 self->waiting_for_op = NULL;
181 }
182
1181e19a
HR
183 break;
184 }
185 }
186 }
187}
188
2e1990b2 189static void coroutine_fn mirror_iteration_done(MirrorOp *op, int ret)
bd48bde8
PB
190{
191 MirrorBlockJob *s = op->s;
402a4741 192 struct iovec *iov;
bd48bde8 193 int64_t chunk_num;
b436982f 194 int i, nb_chunks;
bd48bde8 195
b436982f 196 trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
bd48bde8
PB
197
198 s->in_flight--;
b436982f 199 s->bytes_in_flight -= op->bytes;
402a4741
PB
200 iov = op->qiov.iov;
201 for (i = 0; i < op->qiov.niov; i++) {
202 MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
203 QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
204 s->buf_free_count++;
205 }
206
b436982f
EB
207 chunk_num = op->offset / s->granularity;
208 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
12aa4082 209
402a4741 210 bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
12aa4082 211 QTAILQ_REMOVE(&s->ops_in_flight, op, next);
b21c7652
HR
212 if (ret >= 0) {
213 if (s->cow_bitmap) {
214 bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
215 }
90ab48eb 216 if (!s->initial_zeroing_ongoing) {
30a5c887 217 job_progress_update(&s->common.job, op->bytes);
90ab48eb 218 }
bd48bde8 219 }
6df3bf8e 220 qemu_iovec_destroy(&op->qiov);
7b770c72 221
12aa4082
HR
222 qemu_co_queue_restart_all(&op->waiting_requests);
223 g_free(op);
bd48bde8
PB
224}
225
2e1990b2 226static void coroutine_fn mirror_write_complete(MirrorOp *op, int ret)
bd48bde8 227{
bd48bde8 228 MirrorBlockJob *s = op->s;
b9e413dd 229
bd48bde8 230 if (ret < 0) {
bd48bde8
PB
231 BlockErrorAction action;
232
e0d7f73e 233 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
bd48bde8 234 action = mirror_error_action(s, false, -ret);
a589569f 235 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
bd48bde8
PB
236 s->ret = ret;
237 }
238 }
d12ade57 239
bd48bde8
PB
240 mirror_iteration_done(op, ret);
241}
242
2e1990b2 243static void coroutine_fn mirror_read_complete(MirrorOp *op, int ret)
bd48bde8 244{
bd48bde8 245 MirrorBlockJob *s = op->s;
b9e413dd 246
bd48bde8 247 if (ret < 0) {
bd48bde8
PB
248 BlockErrorAction action;
249
e0d7f73e 250 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
bd48bde8 251 action = mirror_error_action(s, true, -ret);
a589569f 252 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
bd48bde8
PB
253 s->ret = ret;
254 }
255
256 mirror_iteration_done(op, ret);
d12ade57 257 return;
bd48bde8 258 }
d12ade57
VSO
259
260 ret = blk_co_pwritev(s->target, op->offset, op->qiov.size, &op->qiov, 0);
261 mirror_write_complete(op, ret);
bd48bde8
PB
262}
263
782d97ef
EB
264/* Clip bytes relative to offset to not exceed end-of-file */
265static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
266 int64_t offset,
267 int64_t bytes)
268{
269 return MIN(bytes, s->bdev_length - offset);
270}
271
782d97ef
EB
272/* Round offset and/or bytes to target cluster if COW is needed, and
273 * return the offset of the adjusted tail against original. */
274static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
ae4cc877 275 uint64_t *bytes)
893f7eba 276{
e5b43573
FZ
277 bool need_cow;
278 int ret = 0;
782d97ef 279 int64_t align_offset = *offset;
7cfd5275 280 int64_t align_bytes = *bytes;
782d97ef 281 int max_bytes = s->granularity * s->max_iov;
e5b43573 282
782d97ef
EB
283 need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
284 need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
e5b43573
FZ
285 s->cow_bitmap);
286 if (need_cow) {
782d97ef
EB
287 bdrv_round_to_clusters(blk_bs(s->target), *offset, *bytes,
288 &align_offset, &align_bytes);
e5b43573 289 }
3515727f 290
782d97ef
EB
291 if (align_bytes > max_bytes) {
292 align_bytes = max_bytes;
e5b43573 293 if (need_cow) {
782d97ef 294 align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
e5b43573 295 }
8f0720ec 296 }
782d97ef 297 /* Clipping may result in align_bytes unaligned to chunk boundary, but
4150ae60 298 * that doesn't matter because it's already the end of source image. */
782d97ef 299 align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
8f0720ec 300
782d97ef
EB
301 ret = align_offset + align_bytes - (*offset + *bytes);
302 *offset = align_offset;
303 *bytes = align_bytes;
e5b43573
FZ
304 assert(ret >= 0);
305 return ret;
306}
307
537c3d4f 308static inline void coroutine_fn
eb994912 309mirror_wait_for_free_in_flight_slot(MirrorBlockJob *s)
21cd917f 310{
12aa4082
HR
311 MirrorOp *op;
312
1181e19a 313 QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
eb994912
HR
314 /*
315 * Do not wait on pseudo ops, because it may in turn wait on
1181e19a
HR
316 * some other operation to start, which may in fact be the
317 * caller of this function. Since there is only one pseudo op
318 * at any given time, we will always find some real operation
eb994912
HR
319 * to wait on.
320 * Also, do not wait on active operations, because they do not
321 * use up in-flight slots.
322 */
323 if (!op->is_pseudo_op && op->is_in_flight && !op->is_active_write) {
1181e19a
HR
324 qemu_co_queue_wait(&op->waiting_requests, NULL);
325 return;
326 }
327 }
328 abort();
21cd917f
FZ
329}
330
2e1990b2
HR
331/* Perform a mirror copy operation.
332 *
333 * *op->bytes_handled is set to the number of bytes copied after and
334 * including offset, excluding any bytes copied prior to offset due
335 * to alignment. This will be op->bytes if no alignment is necessary,
336 * or (new_end - op->offset) if the tail is rounded up or down due to
337 * alignment or buffer limit.
e5b43573 338 */
2e1990b2 339static void coroutine_fn mirror_co_read(void *opaque)
e5b43573 340{
2e1990b2
HR
341 MirrorOp *op = opaque;
342 MirrorBlockJob *s = op->s;
ae4cc877
EB
343 int nb_chunks;
344 uint64_t ret;
ae4cc877 345 uint64_t max_bytes;
e5b43573 346
ae4cc877 347 max_bytes = s->granularity * s->max_iov;
402a4741 348
e5b43573 349 /* We can only handle as much as buf_size at a time. */
2e1990b2
HR
350 op->bytes = MIN(s->buf_size, MIN(max_bytes, op->bytes));
351 assert(op->bytes);
352 assert(op->bytes < BDRV_REQUEST_MAX_BYTES);
353 *op->bytes_handled = op->bytes;
402a4741 354
e5b43573 355 if (s->cow_bitmap) {
2e1990b2 356 *op->bytes_handled += mirror_cow_align(s, &op->offset, &op->bytes);
e5b43573 357 }
2e1990b2
HR
358 /* Cannot exceed BDRV_REQUEST_MAX_BYTES + INT_MAX */
359 assert(*op->bytes_handled <= UINT_MAX);
360 assert(op->bytes <= s->buf_size);
ae4cc877 361 /* The offset is granularity-aligned because:
e5b43573
FZ
362 * 1) Caller passes in aligned values;
363 * 2) mirror_cow_align is used only when target cluster is larger. */
2e1990b2 364 assert(QEMU_IS_ALIGNED(op->offset, s->granularity));
ae4cc877 365 /* The range is sector-aligned, since bdrv_getlength() rounds up. */
2e1990b2
HR
366 assert(QEMU_IS_ALIGNED(op->bytes, BDRV_SECTOR_SIZE));
367 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
e5b43573
FZ
368
369 while (s->buf_free_count < nb_chunks) {
2e1990b2 370 trace_mirror_yield_in_flight(s, op->offset, s->in_flight);
9178f4fe 371 mirror_wait_for_free_in_flight_slot(s);
b812f671
PB
372 }
373
402a4741
PB
374 /* Now make a QEMUIOVector taking enough granularity-sized chunks
375 * from s->buf_free.
376 */
377 qemu_iovec_init(&op->qiov, nb_chunks);
402a4741
PB
378 while (nb_chunks-- > 0) {
379 MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
2e1990b2 380 size_t remaining = op->bytes - op->qiov.size;
5a0f6fd5 381
402a4741
PB
382 QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
383 s->buf_free_count--;
5a0f6fd5 384 qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
402a4741 385 }
bd48bde8 386
893f7eba 387 /* Copy the dirty cluster. */
bd48bde8 388 s->in_flight++;
2e1990b2 389 s->bytes_in_flight += op->bytes;
ce8cabbd 390 op->is_in_flight = true;
2e1990b2 391 trace_mirror_one_iteration(s, op->offset, op->bytes);
dcfb3beb 392
b9b10c35
KW
393 WITH_GRAPH_RDLOCK_GUARD() {
394 ret = bdrv_co_preadv(s->mirror_top_bs->backing, op->offset, op->bytes,
395 &op->qiov, 0);
396 }
2e1990b2 397 mirror_read_complete(op, ret);
e5b43573
FZ
398}
399
2e1990b2 400static void coroutine_fn mirror_co_zero(void *opaque)
e5b43573 401{
2e1990b2
HR
402 MirrorOp *op = opaque;
403 int ret;
e5b43573 404
2e1990b2
HR
405 op->s->in_flight++;
406 op->s->bytes_in_flight += op->bytes;
407 *op->bytes_handled = op->bytes;
ce8cabbd 408 op->is_in_flight = true;
e5b43573 409
2e1990b2
HR
410 ret = blk_co_pwrite_zeroes(op->s->target, op->offset, op->bytes,
411 op->s->unmap ? BDRV_REQ_MAY_UNMAP : 0);
412 mirror_write_complete(op, ret);
413}
414
415static void coroutine_fn mirror_co_discard(void *opaque)
416{
417 MirrorOp *op = opaque;
418 int ret;
419
420 op->s->in_flight++;
421 op->s->bytes_in_flight += op->bytes;
422 *op->bytes_handled = op->bytes;
ce8cabbd 423 op->is_in_flight = true;
2e1990b2
HR
424
425 ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes);
426 mirror_write_complete(op, ret);
e5b43573
FZ
427}
428
4295c5fc
HR
429static unsigned mirror_perform(MirrorBlockJob *s, int64_t offset,
430 unsigned bytes, MirrorMethod mirror_method)
431{
2e1990b2
HR
432 MirrorOp *op;
433 Coroutine *co;
434 int64_t bytes_handled = -1;
435
436 op = g_new(MirrorOp, 1);
437 *op = (MirrorOp){
438 .s = s,
439 .offset = offset,
440 .bytes = bytes,
441 .bytes_handled = &bytes_handled,
442 };
12aa4082 443 qemu_co_queue_init(&op->waiting_requests);
2e1990b2 444
4295c5fc
HR
445 switch (mirror_method) {
446 case MIRROR_METHOD_COPY:
2e1990b2
HR
447 co = qemu_coroutine_create(mirror_co_read, op);
448 break;
4295c5fc 449 case MIRROR_METHOD_ZERO:
2e1990b2
HR
450 co = qemu_coroutine_create(mirror_co_zero, op);
451 break;
4295c5fc 452 case MIRROR_METHOD_DISCARD:
2e1990b2
HR
453 co = qemu_coroutine_create(mirror_co_discard, op);
454 break;
4295c5fc
HR
455 default:
456 abort();
457 }
eed325b9 458 op->co = co;
2e1990b2 459
12aa4082 460 QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
2e1990b2
HR
461 qemu_coroutine_enter(co);
462 /* At this point, ownership of op has been moved to the coroutine
463 * and the object may already be freed */
464
465 /* Assert that this value has been set */
466 assert(bytes_handled >= 0);
467
468 /* Same assertion as in mirror_co_read() (and for mirror_co_read()
469 * and mirror_co_discard(), bytes_handled == op->bytes, which
470 * is the @bytes parameter given to this function) */
471 assert(bytes_handled <= UINT_MAX);
472 return bytes_handled;
4295c5fc
HR
473}
474
e5b43573
FZ
475static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
476{
138f9fff 477 BlockDriverState *source = s->mirror_top_bs->backing->bs;
1181e19a
HR
478 MirrorOp *pseudo_op;
479 int64_t offset;
480 uint64_t delay_ns = 0, ret = 0;
e5b43573
FZ
481 /* At least the first dirty chunk is mirrored in one iteration. */
482 int nb_chunks = 1;
4b5004d9 483 bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
b436982f 484 int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
e5b43573 485
b64bd51e 486 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
f798184c 487 offset = bdrv_dirty_iter_next(s->dbi);
fb2ef791 488 if (offset < 0) {
dc162c8e 489 bdrv_set_dirty_iter(s->dbi, 0);
f798184c 490 offset = bdrv_dirty_iter_next(s->dbi);
9a46dba7 491 trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
fb2ef791 492 assert(offset >= 0);
e5b43573 493 }
b64bd51e 494 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
e5b43573 495
d69a879b
HR
496 /*
497 * Wait for concurrent requests to @offset. The next loop will limit the
498 * copied area based on in_flight_bitmap so we only copy an area that does
499 * not overlap with concurrent in-flight requests. Still, we would like to
500 * copy something, so wait until there are at least no more requests to the
501 * very beginning of the area.
502 */
1181e19a 503 mirror_wait_on_conflicts(NULL, s, offset, 1);
9c83625b 504
da01ff7f 505 job_pause_point(&s->common.job);
565ac01f 506
e5b43573
FZ
507 /* Find the number of consective dirty chunks following the first dirty
508 * one, and wait for in flight requests in them. */
b64bd51e 509 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
fb2ef791 510 while (nb_chunks * s->granularity < s->buf_size) {
dc162c8e 511 int64_t next_dirty;
fb2ef791
EB
512 int64_t next_offset = offset + nb_chunks * s->granularity;
513 int64_t next_chunk = next_offset / s->granularity;
514 if (next_offset >= s->bdev_length ||
28636b82 515 !bdrv_dirty_bitmap_get_locked(s->dirty_bitmap, next_offset)) {
e5b43573
FZ
516 break;
517 }
518 if (test_bit(next_chunk, s->in_flight_bitmap)) {
9c83625b 519 break;
e5b43573 520 }
9c83625b 521
f798184c 522 next_dirty = bdrv_dirty_iter_next(s->dbi);
fb2ef791 523 if (next_dirty > next_offset || next_dirty < 0) {
f27a2742 524 /* The bitmap iterator's cache is stale, refresh it */
715a74d8 525 bdrv_set_dirty_iter(s->dbi, next_offset);
f798184c 526 next_dirty = bdrv_dirty_iter_next(s->dbi);
f27a2742 527 }
fb2ef791 528 assert(next_dirty == next_offset);
9c83625b 529 nb_chunks++;
e5b43573
FZ
530 }
531
532 /* Clear dirty bits before querying the block status, because
31826642 533 * calling bdrv_block_status_above could yield - if some blocks are
e5b43573
FZ
534 * marked dirty in this window, we need to know.
535 */
e0d7f73e
EB
536 bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
537 nb_chunks * s->granularity);
b64bd51e
PB
538 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
539
1181e19a
HR
540 /* Before claiming an area in the in-flight bitmap, we have to
541 * create a MirrorOp for it so that conflicting requests can wait
542 * for it. mirror_perform() will create the real MirrorOps later,
543 * for now we just create a pseudo operation that will wake up all
544 * conflicting requests once all real operations have been
545 * launched. */
546 pseudo_op = g_new(MirrorOp, 1);
547 *pseudo_op = (MirrorOp){
548 .offset = offset,
549 .bytes = nb_chunks * s->granularity,
550 .is_pseudo_op = true,
551 };
552 qemu_co_queue_init(&pseudo_op->waiting_requests);
553 QTAILQ_INSERT_TAIL(&s->ops_in_flight, pseudo_op, next);
554
fb2ef791
EB
555 bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
556 while (nb_chunks > 0 && offset < s->bdev_length) {
31826642 557 int ret;
7cfd5275 558 int64_t io_bytes;
f3e4ce4a 559 int64_t io_bytes_acct;
4295c5fc 560 MirrorMethod mirror_method = MIRROR_METHOD_COPY;
e5b43573 561
fb2ef791 562 assert(!(offset % s->granularity));
7ff9579e
KW
563 WITH_GRAPH_RDLOCK_GUARD() {
564 ret = bdrv_block_status_above(source, NULL, offset,
565 nb_chunks * s->granularity,
566 &io_bytes, NULL, NULL);
567 }
e5b43573 568 if (ret < 0) {
fb2ef791 569 io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
0965a41e 570 } else if (ret & BDRV_BLOCK_DATA) {
fb2ef791 571 io_bytes = MIN(io_bytes, max_io_bytes);
e5b43573
FZ
572 }
573
fb2ef791
EB
574 io_bytes -= io_bytes % s->granularity;
575 if (io_bytes < s->granularity) {
576 io_bytes = s->granularity;
e5b43573 577 } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
fb2ef791 578 int64_t target_offset;
7cfd5275 579 int64_t target_bytes;
fb2ef791
EB
580 bdrv_round_to_clusters(blk_bs(s->target), offset, io_bytes,
581 &target_offset, &target_bytes);
582 if (target_offset == offset &&
583 target_bytes == io_bytes) {
e5b43573
FZ
584 mirror_method = ret & BDRV_BLOCK_ZERO ?
585 MIRROR_METHOD_ZERO :
586 MIRROR_METHOD_DISCARD;
587 }
588 }
589
cf56a3c6 590 while (s->in_flight >= MAX_IN_FLIGHT) {
fb2ef791 591 trace_mirror_yield_in_flight(s, offset, s->in_flight);
9178f4fe 592 mirror_wait_for_free_in_flight_slot(s);
cf56a3c6
DL
593 }
594
dbaa7b57 595 if (s->ret < 0) {
1181e19a
HR
596 ret = 0;
597 goto fail;
dbaa7b57
VSO
598 }
599
fb2ef791 600 io_bytes = mirror_clip_bytes(s, offset, io_bytes);
4295c5fc
HR
601 io_bytes = mirror_perform(s, offset, io_bytes, mirror_method);
602 if (mirror_method != MIRROR_METHOD_COPY && write_zeroes_ok) {
603 io_bytes_acct = 0;
604 } else {
605 io_bytes_acct = io_bytes;
e5b43573 606 }
fb2ef791
EB
607 assert(io_bytes);
608 offset += io_bytes;
609 nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
dee81d51 610 delay_ns = block_job_ratelimit_get_delay(&s->common, io_bytes_acct);
dcfb3beb 611 }
1181e19a
HR
612
613 ret = delay_ns;
614fail:
615 QTAILQ_REMOVE(&s->ops_in_flight, pseudo_op, next);
616 qemu_co_queue_restart_all(&pseudo_op->waiting_requests);
617 g_free(pseudo_op);
618
619 return ret;
bd48bde8 620}
b952b558 621
402a4741
PB
622static void mirror_free_init(MirrorBlockJob *s)
623{
624 int granularity = s->granularity;
625 size_t buf_size = s->buf_size;
626 uint8_t *buf = s->buf;
627
628 assert(s->buf_free_count == 0);
629 QSIMPLEQ_INIT(&s->buf_free);
630 while (buf_size != 0) {
631 MirrorBuffer *cur = (MirrorBuffer *)buf;
632 QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
633 s->buf_free_count++;
634 buf_size -= granularity;
635 buf += granularity;
636 }
637}
638
bae8196d
PB
639/* This is also used for the .pause callback. There is no matching
640 * mirror_resume() because mirror_run() will begin iterating again
641 * when the job is resumed.
642 */
537c3d4f 643static void coroutine_fn mirror_wait_for_all_io(MirrorBlockJob *s)
bd48bde8
PB
644{
645 while (s->in_flight > 0) {
9178f4fe 646 mirror_wait_for_free_in_flight_slot(s);
bd48bde8 647 }
893f7eba
PB
648}
649
737efc1e
JS
650/**
651 * mirror_exit_common: handle both abort() and prepare() cases.
652 * for .prepare, returns 0 on success and -errno on failure.
653 * for .abort cases, denoted by abort = true, MUST return 0.
654 */
655static int mirror_exit_common(Job *job)
5a7e7a0b 656{
1908a559
KW
657 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
658 BlockJob *bjob = &s->common;
f93c3add 659 MirrorBDSOpaque *bs_opaque;
5a7e7a0b 660 AioContext *replace_aio_context = NULL;
f93c3add
HR
661 BlockDriverState *src;
662 BlockDriverState *target_bs;
663 BlockDriverState *mirror_top_bs;
12fa4af6 664 Error *local_err = NULL;
737efc1e
JS
665 bool abort = job->ret < 0;
666 int ret = 0;
667
668 if (s->prepared) {
669 return 0;
670 }
671 s->prepared = true;
3f09bfbc 672
f93c3add
HR
673 mirror_top_bs = s->mirror_top_bs;
674 bs_opaque = mirror_top_bs->opaque;
675 src = mirror_top_bs->backing->bs;
676 target_bs = blk_bs(s->target);
677
ef53dc09
AG
678 if (bdrv_chain_contains(src, target_bs)) {
679 bdrv_unfreeze_backing_chain(mirror_top_bs, target_bs);
680 }
681
5deb6cbd 682 bdrv_release_dirty_bitmap(s->dirty_bitmap);
2119882c 683
7b508f6b
JS
684 /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
685 * before we can call bdrv_drained_end */
3f09bfbc 686 bdrv_ref(src);
4ef85a9c 687 bdrv_ref(mirror_top_bs);
7d9fcb39
KW
688 bdrv_ref(target_bs);
689
bb0c9409
VSO
690 /*
691 * Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
7d9fcb39 692 * inserting target_bs at s->to_replace, where we might not be able to get
63c8ef28 693 * these permissions.
bb0c9409 694 */
7d9fcb39
KW
695 blk_unref(s->target);
696 s->target = NULL;
4ef85a9c
KW
697
698 /* We don't access the source any more. Dropping any WRITE/RESIZE is
d2da5e28
KW
699 * required before it could become a backing file of target_bs. Not having
700 * these permissions any more means that we can't allow any new requests on
701 * mirror_top_bs from now on, so keep it drained. */
702 bdrv_drained_begin(mirror_top_bs);
f94dc3b4
HR
703 bs_opaque->stop = true;
704 bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
705 &error_abort);
737efc1e 706 if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
4ef85a9c 707 BlockDriverState *backing = s->is_none_mode ? src : s->base;
3f072a7f
HR
708 BlockDriverState *unfiltered_target = bdrv_skip_filters(target_bs);
709
710 if (bdrv_cow_bs(unfiltered_target) != backing) {
711 bdrv_set_backing_hd(unfiltered_target, backing, &local_err);
12fa4af6
KW
712 if (local_err) {
713 error_report_err(local_err);
66c8672d 714 local_err = NULL;
7b508f6b 715 ret = -EPERM;
12fa4af6 716 }
4ef85a9c 717 }
c41f5b96
HR
718 } else if (!abort && s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
719 assert(!bdrv_backing_chain_next(target_bs));
720 ret = bdrv_open_backing_file(bdrv_skip_filters(target_bs), NULL,
721 "backing", &local_err);
722 if (ret < 0) {
723 error_report_err(local_err);
724 local_err = NULL;
725 }
4ef85a9c 726 }
5a7e7a0b
SH
727
728 if (s->to_replace) {
729 replace_aio_context = bdrv_get_aio_context(s->to_replace);
730 aio_context_acquire(replace_aio_context);
731 }
732
737efc1e
JS
733 if (s->should_complete && !abort) {
734 BlockDriverState *to_replace = s->to_replace ?: src;
1ba79388 735 bool ro = bdrv_is_read_only(to_replace);
40365552 736
1ba79388
AG
737 if (ro != bdrv_is_read_only(target_bs)) {
738 bdrv_reopen_set_read_only(target_bs, ro, NULL);
5a7e7a0b 739 }
b8804815
KW
740
741 /* The mirror job has no requests in flight any more, but we need to
742 * drain potential other users of the BDS before changing the graph. */
5e771752 743 assert(s->in_drain);
e253f4b8 744 bdrv_drained_begin(target_bs);
6e9cc051
HR
745 /*
746 * Cannot use check_to_replace_node() here, because that would
747 * check for an op blocker on @to_replace, and we have our own
748 * there.
749 */
750 if (bdrv_recurse_can_replace(src, to_replace)) {
751 bdrv_replace_node(to_replace, target_bs, &local_err);
752 } else {
753 error_setg(&local_err, "Can no longer replace '%s' by '%s', "
754 "because it can no longer be guaranteed that doing so "
755 "would not lead to an abrupt change of visible data",
756 to_replace->node_name, target_bs->node_name);
757 }
e253f4b8 758 bdrv_drained_end(target_bs);
5fe31c25
KW
759 if (local_err) {
760 error_report_err(local_err);
7b508f6b 761 ret = -EPERM;
5fe31c25 762 }
5a7e7a0b
SH
763 }
764 if (s->to_replace) {
765 bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
766 error_free(s->replace_blocker);
767 bdrv_unref(s->to_replace);
768 }
769 if (replace_aio_context) {
770 aio_context_release(replace_aio_context);
771 }
772 g_free(s->replaces);
7d9fcb39 773 bdrv_unref(target_bs);
4ef85a9c 774
f94dc3b4
HR
775 /*
776 * Remove the mirror filter driver from the graph. Before this, get rid of
4ef85a9c 777 * the blockers on the intermediate nodes so that the resulting state is
f94dc3b4
HR
778 * valid.
779 */
1908a559 780 block_job_remove_all_bdrv(bjob);
3f072a7f 781 bdrv_replace_node(mirror_top_bs, mirror_top_bs->backing->bs, &error_abort);
4ef85a9c 782
429076e8 783 bs_opaque->job = NULL;
4ef85a9c 784
176c3699 785 bdrv_drained_end(src);
d2da5e28 786 bdrv_drained_end(mirror_top_bs);
5e771752 787 s->in_drain = false;
4ef85a9c 788 bdrv_unref(mirror_top_bs);
3f09bfbc 789 bdrv_unref(src);
7b508f6b 790
737efc1e
JS
791 return ret;
792}
793
794static int mirror_prepare(Job *job)
795{
796 return mirror_exit_common(job);
797}
798
799static void mirror_abort(Job *job)
800{
801 int ret = mirror_exit_common(job);
802 assert(ret == 0);
5a7e7a0b
SH
803}
804
537c3d4f 805static void coroutine_fn mirror_throttle(MirrorBlockJob *s)
49efb1f5
DL
806{
807 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
808
18bb6928 809 if (now - s->last_pause_ns > BLOCK_JOB_SLICE_TIME) {
49efb1f5 810 s->last_pause_ns = now;
5d43e86e 811 job_sleep_ns(&s->common.job, 0);
49efb1f5 812 } else {
da01ff7f 813 job_pause_point(&s->common.job);
49efb1f5
DL
814 }
815}
816
c0b363ad
DL
817static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
818{
23ca459a 819 int64_t offset;
138f9fff 820 BlockDriverState *bs = s->mirror_top_bs->backing->bs;
c0b363ad 821 BlockDriverState *target_bs = blk_bs(s->target);
23ca459a 822 int ret;
51b0a488 823 int64_t count;
c0b363ad 824
cdf3bc93 825 if (s->zero_target) {
c7c2769c 826 if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
e0d7f73e 827 bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
c7c2769c
DL
828 return 0;
829 }
830
90ab48eb 831 s->initial_zeroing_ongoing = true;
23ca459a
EB
832 for (offset = 0; offset < s->bdev_length; ) {
833 int bytes = MIN(s->bdev_length - offset,
834 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
c7c2769c
DL
835
836 mirror_throttle(s);
837
daa7f2f9 838 if (job_is_cancelled(&s->common.job)) {
90ab48eb 839 s->initial_zeroing_ongoing = false;
c7c2769c
DL
840 return 0;
841 }
842
843 if (s->in_flight >= MAX_IN_FLIGHT) {
67adf4b3
EB
844 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
845 s->in_flight);
9178f4fe 846 mirror_wait_for_free_in_flight_slot(s);
c7c2769c
DL
847 continue;
848 }
849
4295c5fc 850 mirror_perform(s, offset, bytes, MIRROR_METHOD_ZERO);
23ca459a 851 offset += bytes;
c7c2769c
DL
852 }
853
bae8196d 854 mirror_wait_for_all_io(s);
90ab48eb 855 s->initial_zeroing_ongoing = false;
b7d5062c
DL
856 }
857
c0b363ad 858 /* First part, loop on the sectors and initialize the dirty bitmap. */
23ca459a 859 for (offset = 0; offset < s->bdev_length; ) {
c0b363ad 860 /* Just to make sure we are not exceeding int limit. */
23ca459a
EB
861 int bytes = MIN(s->bdev_length - offset,
862 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
c0b363ad
DL
863
864 mirror_throttle(s);
865
daa7f2f9 866 if (job_is_cancelled(&s->common.job)) {
c0b363ad
DL
867 return 0;
868 }
869
7ff9579e
KW
870 WITH_GRAPH_RDLOCK_GUARD() {
871 ret = bdrv_is_allocated_above(bs, s->base_overlay, true, offset,
872 bytes, &count);
873 }
c0b363ad
DL
874 if (ret < 0) {
875 return ret;
876 }
877
23ca459a 878 assert(count);
a92b1b06 879 if (ret > 0) {
23ca459a 880 bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
c0b363ad 881 }
23ca459a 882 offset += count;
c0b363ad
DL
883 }
884 return 0;
885}
886
bdffb31d
PB
887/* Called when going out of the streaming phase to flush the bulk of the
888 * data to the medium, or just before completing.
889 */
890static int mirror_flush(MirrorBlockJob *s)
891{
892 int ret = blk_flush(s->target);
893 if (ret < 0) {
894 if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
895 s->ret = ret;
896 }
897 }
898 return ret;
899}
900
f67432a2 901static int coroutine_fn mirror_run(Job *job, Error **errp)
893f7eba 902{
f67432a2 903 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
138f9fff 904 BlockDriverState *bs = s->mirror_top_bs->backing->bs;
32125b14 905 MirrorBDSOpaque *mirror_top_opaque = s->mirror_top_bs->opaque;
e253f4b8 906 BlockDriverState *target_bs = blk_bs(s->target);
9a0cec66 907 bool need_drain = true;
d59cb66d 908 BlockDeviceIoStatus iostatus;
c0b363ad 909 int64_t length;
e83dd680 910 int64_t target_length;
b812f671 911 BlockDriverInfo bdi;
1d33936e
JC
912 char backing_filename[2]; /* we only need 2 characters because we are only
913 checking for a NULL string */
893f7eba 914 int ret = 0;
893f7eba 915
daa7f2f9 916 if (job_is_cancelled(&s->common.job)) {
893f7eba
PB
917 goto immediate_exit;
918 }
919
c86422c5 920 s->bdev_length = bdrv_co_getlength(bs);
b21c7652
HR
921 if (s->bdev_length < 0) {
922 ret = s->bdev_length;
373df5b1 923 goto immediate_exit;
becc347e
KW
924 }
925
c86422c5 926 target_length = blk_co_getlength(s->target);
e83dd680
KW
927 if (target_length < 0) {
928 ret = target_length;
929 goto immediate_exit;
930 }
931
becc347e
KW
932 /* Active commit must resize the base image if its size differs from the
933 * active layer. */
934 if (s->base == blk_bs(s->target)) {
e83dd680 935 if (s->bdev_length > target_length) {
88276216
AF
936 ret = blk_co_truncate(s->target, s->bdev_length, false,
937 PREALLOC_MODE_OFF, 0, NULL);
becc347e
KW
938 if (ret < 0) {
939 goto immediate_exit;
940 }
941 }
e83dd680
KW
942 } else if (s->bdev_length != target_length) {
943 error_setg(errp, "Source and target image have different sizes");
944 ret = -EINVAL;
945 goto immediate_exit;
becc347e
KW
946 }
947
948 if (s->bdev_length == 0) {
2e1795b5
KW
949 /* Transition to the READY state and wait for complete. */
950 job_transition_to_ready(&s->common.job);
d06107ad 951 s->actively_synced = true;
08b83bff 952 while (!job_cancel_requested(&s->common.job) && !s->should_complete) {
198c49cc 953 job_yield(&s->common.job);
9e48b025 954 }
9e48b025 955 goto immediate_exit;
893f7eba
PB
956 }
957
b21c7652 958 length = DIV_ROUND_UP(s->bdev_length, s->granularity);
402a4741
PB
959 s->in_flight_bitmap = bitmap_new(length);
960
b812f671
PB
961 /* If we have no backing file yet in the destination, we cannot let
962 * the destination do COW. Instead, we copy sectors around the
963 * dirty data if needed. We need a bitmap to do that.
964 */
e253f4b8 965 bdrv_get_backing_filename(target_bs, backing_filename,
b812f671 966 sizeof(backing_filename));
3d47eb0a 967 if (!bdrv_co_get_info(target_bs, &bdi) && bdi.cluster_size) {
b436982f
EB
968 s->target_cluster_size = bdi.cluster_size;
969 } else {
970 s->target_cluster_size = BDRV_SECTOR_SIZE;
e5b43573 971 }
3f072a7f 972 if (backing_filename[0] && !bdrv_backing_chain_next(target_bs) &&
b436982f
EB
973 s->granularity < s->target_cluster_size) {
974 s->buf_size = MAX(s->buf_size, s->target_cluster_size);
e5b43573 975 s->cow_bitmap = bitmap_new(length);
b812f671 976 }
e253f4b8 977 s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
b812f671 978
7504edf4
KW
979 s->buf = qemu_try_blockalign(bs, s->buf_size);
980 if (s->buf == NULL) {
981 ret = -ENOMEM;
982 goto immediate_exit;
983 }
984
402a4741 985 mirror_free_init(s);
893f7eba 986
49efb1f5 987 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
03544a6e 988 if (!s->is_none_mode) {
c0b363ad 989 ret = mirror_dirty_init(s);
daa7f2f9 990 if (ret < 0 || job_is_cancelled(&s->common.job)) {
c0b363ad 991 goto immediate_exit;
893f7eba
PB
992 }
993 }
994
32125b14
KW
995 /*
996 * Only now the job is fully initialised and mirror_top_bs should start
997 * accessing it.
998 */
999 mirror_top_opaque->job = s;
1000
dc162c8e 1001 assert(!s->dbi);
715a74d8 1002 s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
893f7eba 1003 for (;;) {
cc8c9d6c 1004 uint64_t delay_ns = 0;
49efb1f5 1005 int64_t cnt, delta;
893f7eba
PB
1006 bool should_complete;
1007
bd48bde8
PB
1008 if (s->ret < 0) {
1009 ret = s->ret;
1010 goto immediate_exit;
1011 }
1012
da01ff7f 1013 job_pause_point(&s->common.job);
565ac01f 1014
4feeec7e
HR
1015 if (job_is_cancelled(&s->common.job)) {
1016 ret = 0;
1017 goto immediate_exit;
1018 }
1019
20dca810 1020 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
05df8a6a
KW
1021 /* cnt is the number of dirty bytes remaining and s->bytes_in_flight is
1022 * the number of bytes currently being processed; together those are
1023 * the current remaining operation length */
d69a879b
HR
1024 job_progress_set_remaining(&s->common.job,
1025 s->bytes_in_flight + cnt +
1026 s->active_write_bytes_in_flight);
bd48bde8
PB
1027
1028 /* Note that even when no rate limit is applied we need to yield
a7282330 1029 * periodically with no pending I/O so that bdrv_drain_all() returns.
18bb6928
KW
1030 * We do so every BLKOCK_JOB_SLICE_TIME nanoseconds, or when there is
1031 * an error, or when the source is clean, whichever comes first. */
49efb1f5 1032 delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
d59cb66d
EGE
1033 WITH_JOB_LOCK_GUARD() {
1034 iostatus = s->common.iostatus;
1035 }
18bb6928 1036 if (delta < BLOCK_JOB_SLICE_TIME &&
d59cb66d 1037 iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
cf56a3c6 1038 if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
402a4741 1039 (cnt == 0 && s->in_flight > 0)) {
9a46dba7 1040 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
9178f4fe 1041 mirror_wait_for_free_in_flight_slot(s);
bd48bde8
PB
1042 continue;
1043 } else if (cnt != 0) {
cc8c9d6c 1044 delay_ns = mirror_iteration(s);
893f7eba 1045 }
893f7eba
PB
1046 }
1047
1048 should_complete = false;
bd48bde8 1049 if (s->in_flight == 0 && cnt == 0) {
893f7eba 1050 trace_mirror_before_flush(s);
44716224 1051 if (!job_is_ready(&s->common.job)) {
bdffb31d
PB
1052 if (mirror_flush(s) < 0) {
1053 /* Go check s->ret. */
1054 continue;
b952b558 1055 }
b952b558
PB
1056 /* We're out of the streaming phase. From now on, if the job
1057 * is cancelled we will actually complete all pending I/O and
1058 * report completion. This way, block-job-cancel will leave
1059 * the target in a consistent state.
1060 */
2e1795b5 1061 job_transition_to_ready(&s->common.job);
d06107ad
HR
1062 if (s->copy_mode != MIRROR_COPY_MODE_BACKGROUND) {
1063 s->actively_synced = true;
1064 }
d63ffd87 1065 }
bdffb31d
PB
1066
1067 should_complete = s->should_complete ||
08b83bff 1068 job_cancel_requested(&s->common.job);
bdffb31d 1069 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
893f7eba
PB
1070 }
1071
1072 if (cnt == 0 && should_complete) {
1073 /* The dirty bitmap is not updated while operations are pending.
1074 * If we're about to exit, wait for pending operations before
1075 * calling bdrv_get_dirty_count(bs), or we may exit while the
1076 * source has dirty data to copy!
1077 *
1078 * Note that I/O can be submitted by the guest while
9a0cec66
PB
1079 * mirror_populate runs, so pause it now. Before deciding
1080 * whether to switch to target check one last time if I/O has
1081 * come in the meanwhile, and if not flush the data to disk.
893f7eba 1082 */
9a46dba7 1083 trace_mirror_before_drain(s, cnt);
9a0cec66 1084
5e771752 1085 s->in_drain = true;
9a0cec66 1086 bdrv_drained_begin(bs);
d69a879b
HR
1087
1088 /* Must be zero because we are drained */
1089 assert(s->in_active_write_counter == 0);
1090
20dca810 1091 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
bdffb31d 1092 if (cnt > 0 || mirror_flush(s) < 0) {
9a0cec66 1093 bdrv_drained_end(bs);
5e771752 1094 s->in_drain = false;
9a0cec66
PB
1095 continue;
1096 }
1097
1098 /* The two disks are in sync. Exit and report successful
1099 * completion.
1100 */
1101 assert(QLIST_EMPTY(&bs->tracked_requests));
9a0cec66
PB
1102 need_drain = false;
1103 break;
893f7eba
PB
1104 }
1105
44716224 1106 if (job_is_ready(&s->common.job) && !should_complete) {
18bb6928
KW
1107 delay_ns = (s->in_flight == 0 &&
1108 cnt == 0 ? BLOCK_JOB_SLICE_TIME : 0);
ddc4115e 1109 }
44716224
HR
1110 trace_mirror_before_sleep(s, cnt, job_is_ready(&s->common.job),
1111 delay_ns);
5d43e86e 1112 job_sleep_ns(&s->common.job, delay_ns);
49efb1f5 1113 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
893f7eba
PB
1114 }
1115
1116immediate_exit:
bd48bde8
PB
1117 if (s->in_flight > 0) {
1118 /* We get here only if something went wrong. Either the job failed,
1119 * or it was cancelled prematurely so that we do not guarantee that
1120 * the target is a copy of the source.
1121 */
08b83bff 1122 assert(ret < 0 || job_is_cancelled(&s->common.job));
9a0cec66 1123 assert(need_drain);
bae8196d 1124 mirror_wait_for_all_io(s);
bd48bde8
PB
1125 }
1126
1127 assert(s->in_flight == 0);
7191bf31 1128 qemu_vfree(s->buf);
b812f671 1129 g_free(s->cow_bitmap);
402a4741 1130 g_free(s->in_flight_bitmap);
dc162c8e 1131 bdrv_dirty_iter_free(s->dbi);
5a7e7a0b 1132
9a0cec66 1133 if (need_drain) {
5e771752 1134 s->in_drain = true;
9a0cec66
PB
1135 bdrv_drained_begin(bs);
1136 }
f67432a2 1137
f67432a2 1138 return ret;
893f7eba
PB
1139}
1140
3453d972 1141static void mirror_complete(Job *job, Error **errp)
d63ffd87 1142{
3453d972 1143 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
d63ffd87 1144
44716224 1145 if (!job_is_ready(job)) {
9df229c3 1146 error_setg(errp, "The active block job '%s' cannot be completed",
3453d972 1147 job->id);
d63ffd87
PB
1148 return;
1149 }
1150
15d67298 1151 /* block all operations on to_replace bs */
09158f00 1152 if (s->replaces) {
5a7e7a0b
SH
1153 AioContext *replace_aio_context;
1154
e12f3784 1155 s->to_replace = bdrv_find_node(s->replaces);
09158f00 1156 if (!s->to_replace) {
e12f3784 1157 error_setg(errp, "Node name '%s' not found", s->replaces);
09158f00
BC
1158 return;
1159 }
1160
5a7e7a0b
SH
1161 replace_aio_context = bdrv_get_aio_context(s->to_replace);
1162 aio_context_acquire(replace_aio_context);
1163
64631f36 1164 /* TODO Translate this into child freeze system. */
09158f00
BC
1165 error_setg(&s->replace_blocker,
1166 "block device is in use by block-job-complete");
1167 bdrv_op_block_all(s->to_replace, s->replace_blocker);
1168 bdrv_ref(s->to_replace);
5a7e7a0b
SH
1169
1170 aio_context_release(replace_aio_context);
09158f00
BC
1171 }
1172
d63ffd87 1173 s->should_complete = true;
00769414
HR
1174
1175 /* If the job is paused, it will be re-entered when it is resumed */
279ac06e
EGE
1176 WITH_JOB_LOCK_GUARD() {
1177 if (!job->paused) {
1178 job_enter_cond_locked(job, NULL);
1179 }
00769414 1180 }
d63ffd87
PB
1181}
1182
537c3d4f 1183static void coroutine_fn mirror_pause(Job *job)
565ac01f 1184{
da01ff7f 1185 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
565ac01f 1186
bae8196d 1187 mirror_wait_for_all_io(s);
565ac01f
SH
1188}
1189
89bd0305
KW
1190static bool mirror_drained_poll(BlockJob *job)
1191{
1192 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
5e771752
SL
1193
1194 /* If the job isn't paused nor cancelled, we can't be sure that it won't
1195 * issue more requests. We make an exception if we've reached this point
1196 * from one of our own drain sections, to avoid a deadlock waiting for
1197 * ourselves.
1198 */
279ac06e
EGE
1199 WITH_JOB_LOCK_GUARD() {
1200 if (!s->common.job.paused && !job_is_cancelled_locked(&job->job)
1201 && !s->in_drain) {
1202 return true;
1203 }
5e771752
SL
1204 }
1205
89bd0305
KW
1206 return !!s->in_flight;
1207}
1208
73895f38 1209static bool mirror_cancel(Job *job, bool force)
521ff8b7
VSO
1210{
1211 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1212 BlockDriverState *target = blk_bs(s->target);
1213
73895f38
HR
1214 /*
1215 * Before the job is READY, we treat any cancellation like a
1216 * force-cancellation.
1217 */
1218 force = force || !job_is_ready(job);
1219
1220 if (force) {
9c785cd7
VSO
1221 bdrv_cancel_in_flight(target);
1222 }
73895f38
HR
1223 return force;
1224}
1225
1226static bool commit_active_cancel(Job *job, bool force)
1227{
1228 /* Same as above in mirror_cancel() */
1229 return force || !job_is_ready(job);
521ff8b7
VSO
1230}
1231
3fc4b10a 1232static const BlockJobDriver mirror_job_driver = {
33e9e9bd
KW
1233 .job_driver = {
1234 .instance_size = sizeof(MirrorBlockJob),
252291ea 1235 .job_type = JOB_TYPE_MIRROR,
80fa2c75 1236 .free = block_job_free,
b15de828 1237 .user_resume = block_job_user_resume,
f67432a2 1238 .run = mirror_run,
737efc1e
JS
1239 .prepare = mirror_prepare,
1240 .abort = mirror_abort,
da01ff7f 1241 .pause = mirror_pause,
3453d972 1242 .complete = mirror_complete,
521ff8b7 1243 .cancel = mirror_cancel,
33e9e9bd 1244 },
89bd0305 1245 .drained_poll = mirror_drained_poll,
893f7eba
PB
1246};
1247
03544a6e 1248static const BlockJobDriver commit_active_job_driver = {
33e9e9bd
KW
1249 .job_driver = {
1250 .instance_size = sizeof(MirrorBlockJob),
252291ea 1251 .job_type = JOB_TYPE_COMMIT,
80fa2c75 1252 .free = block_job_free,
b15de828 1253 .user_resume = block_job_user_resume,
f67432a2 1254 .run = mirror_run,
737efc1e
JS
1255 .prepare = mirror_prepare,
1256 .abort = mirror_abort,
da01ff7f 1257 .pause = mirror_pause,
3453d972 1258 .complete = mirror_complete,
73895f38 1259 .cancel = commit_active_cancel,
33e9e9bd 1260 },
89bd0305 1261 .drained_poll = mirror_drained_poll,
03544a6e
FZ
1262};
1263
537c3d4f
SH
1264static void coroutine_fn
1265do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
1266 uint64_t offset, uint64_t bytes,
1267 QEMUIOVector *qiov, int flags)
d06107ad 1268{
5c511ac3 1269 int ret;
dbdf699c
VSO
1270 size_t qiov_offset = 0;
1271 int64_t bitmap_offset, bitmap_end;
d06107ad 1272
dbdf699c
VSO
1273 if (!QEMU_IS_ALIGNED(offset, job->granularity) &&
1274 bdrv_dirty_bitmap_get(job->dirty_bitmap, offset))
1275 {
1276 /*
1277 * Dirty unaligned padding: ignore it.
1278 *
1279 * Reasoning:
1280 * 1. If we copy it, we can't reset corresponding bit in
1281 * dirty_bitmap as there may be some "dirty" bytes still not
1282 * copied.
1283 * 2. It's already dirty, so skipping it we don't diverge mirror
1284 * progress.
1285 *
1286 * Note, that because of this, guest write may have no contribution
1287 * into mirror converge, but that's not bad, as we have background
1288 * process of mirroring. If under some bad circumstances (high guest
1289 * IO load) background process starve, we will not converge anyway,
1290 * even if each write will contribute, as guest is not guaranteed to
1291 * rewrite the whole disk.
1292 */
1293 qiov_offset = QEMU_ALIGN_UP(offset, job->granularity) - offset;
1294 if (bytes <= qiov_offset) {
1295 /* nothing to do after shrink */
1296 return;
1297 }
1298 offset += qiov_offset;
1299 bytes -= qiov_offset;
1300 }
1301
1302 if (!QEMU_IS_ALIGNED(offset + bytes, job->granularity) &&
1303 bdrv_dirty_bitmap_get(job->dirty_bitmap, offset + bytes - 1))
1304 {
1305 uint64_t tail = (offset + bytes) % job->granularity;
1306
1307 if (bytes <= tail) {
1308 /* nothing to do after shrink */
1309 return;
1310 }
1311 bytes -= tail;
1312 }
1313
1314 /*
1315 * Tails are either clean or shrunk, so for bitmap resetting
1316 * we safely align the range down.
1317 */
1318 bitmap_offset = QEMU_ALIGN_UP(offset, job->granularity);
1319 bitmap_end = QEMU_ALIGN_DOWN(offset + bytes, job->granularity);
1320 if (bitmap_offset < bitmap_end) {
1321 bdrv_reset_dirty_bitmap(job->dirty_bitmap, bitmap_offset,
1322 bitmap_end - bitmap_offset);
1323 }
d06107ad 1324
5c511ac3 1325 job_progress_increase_remaining(&job->common.job, bytes);
d69a879b 1326 job->active_write_bytes_in_flight += bytes;
d06107ad 1327
5c511ac3
VSO
1328 switch (method) {
1329 case MIRROR_METHOD_COPY:
dbdf699c
VSO
1330 ret = blk_co_pwritev_part(job->target, offset, bytes,
1331 qiov, qiov_offset, flags);
5c511ac3 1332 break;
d06107ad 1333
5c511ac3
VSO
1334 case MIRROR_METHOD_ZERO:
1335 assert(!qiov);
1336 ret = blk_co_pwrite_zeroes(job->target, offset, bytes, flags);
1337 break;
d06107ad 1338
5c511ac3
VSO
1339 case MIRROR_METHOD_DISCARD:
1340 assert(!qiov);
1341 ret = blk_co_pdiscard(job->target, offset, bytes);
1342 break;
d06107ad 1343
5c511ac3
VSO
1344 default:
1345 abort();
1346 }
d06107ad 1347
d69a879b 1348 job->active_write_bytes_in_flight -= bytes;
5c511ac3
VSO
1349 if (ret >= 0) {
1350 job_progress_update(&job->common.job, bytes);
1351 } else {
1352 BlockErrorAction action;
d06107ad 1353
dbdf699c
VSO
1354 /*
1355 * We failed, so we should mark dirty the whole area, aligned up.
1356 * Note that we don't care about shrunk tails if any: they were dirty
1357 * at function start, and they must be still dirty, as we've locked
1358 * the region for in-flight op.
1359 */
1360 bitmap_offset = QEMU_ALIGN_DOWN(offset, job->granularity);
1361 bitmap_end = QEMU_ALIGN_UP(offset + bytes, job->granularity);
1362 bdrv_set_dirty_bitmap(job->dirty_bitmap, bitmap_offset,
1363 bitmap_end - bitmap_offset);
5c511ac3 1364 job->actively_synced = false;
d06107ad 1365
5c511ac3
VSO
1366 action = mirror_error_action(job, false, -ret);
1367 if (action == BLOCK_ERROR_ACTION_REPORT) {
1368 if (!job->ret) {
1369 job->ret = ret;
d06107ad
HR
1370 }
1371 }
d06107ad
HR
1372 }
1373}
1374
1375static MirrorOp *coroutine_fn active_write_prepare(MirrorBlockJob *s,
1376 uint64_t offset,
1377 uint64_t bytes)
1378{
1379 MirrorOp *op;
1380 uint64_t start_chunk = offset / s->granularity;
1381 uint64_t end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1382
1383 op = g_new(MirrorOp, 1);
1384 *op = (MirrorOp){
1385 .s = s,
1386 .offset = offset,
1387 .bytes = bytes,
1388 .is_active_write = true,
ce8cabbd 1389 .is_in_flight = true,
ead3f1bf 1390 .co = qemu_coroutine_self(),
d06107ad
HR
1391 };
1392 qemu_co_queue_init(&op->waiting_requests);
1393 QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
1394
1395 s->in_active_write_counter++;
1396
d69a879b
HR
1397 /*
1398 * Wait for concurrent requests affecting the area. If there are already
1399 * running requests that are copying off now-to-be stale data in the area,
1400 * we must wait for them to finish before we begin writing fresh data to the
1401 * target so that the write operations appear in the correct order.
1402 * Note that background requests (see mirror_iteration()) in contrast only
1403 * wait for conflicting requests at the start of the dirty area, and then
1404 * (based on the in_flight_bitmap) truncate the area to copy so it will not
1405 * conflict with any requests beyond that. For active writes, however, we
1406 * cannot truncate that area. The request from our parent must be blocked
1407 * until the area is copied in full. Therefore, we must wait for the whole
1408 * area to become free of concurrent requests.
1409 */
d06107ad
HR
1410 mirror_wait_on_conflicts(op, s, offset, bytes);
1411
1412 bitmap_set(s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1413
1414 return op;
1415}
1416
1417static void coroutine_fn active_write_settle(MirrorOp *op)
1418{
1419 uint64_t start_chunk = op->offset / op->s->granularity;
1420 uint64_t end_chunk = DIV_ROUND_UP(op->offset + op->bytes,
1421 op->s->granularity);
1422
1423 if (!--op->s->in_active_write_counter && op->s->actively_synced) {
1424 BdrvChild *source = op->s->mirror_top_bs->backing;
1425
1426 if (QLIST_FIRST(&source->bs->parents) == source &&
1427 QLIST_NEXT(source, next_parent) == NULL)
1428 {
1429 /* Assert that we are back in sync once all active write
1430 * operations are settled.
1431 * Note that we can only assert this if the mirror node
1432 * is the source node's only parent. */
1433 assert(!bdrv_get_dirty_count(op->s->dirty_bitmap));
1434 }
1435 }
1436 bitmap_clear(op->s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1437 QTAILQ_REMOVE(&op->s->ops_in_flight, op, next);
1438 qemu_co_queue_restart_all(&op->waiting_requests);
1439 g_free(op);
1440}
1441
b9b10c35
KW
1442static int coroutine_fn GRAPH_RDLOCK
1443bdrv_mirror_top_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
1444 QEMUIOVector *qiov, BdrvRequestFlags flags)
4ef85a9c
KW
1445{
1446 return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
1447}
1448
9a5a1c62
EGE
1449static int coroutine_fn GRAPH_RDLOCK
1450bdrv_mirror_top_do_write(BlockDriverState *bs, MirrorMethod method,
1451 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
1452 int flags)
d06107ad
HR
1453{
1454 MirrorOp *op = NULL;
1455 MirrorBDSOpaque *s = bs->opaque;
1456 int ret = 0;
da93d5c8 1457 bool copy_to_target = false;
d06107ad 1458
da93d5c8
HR
1459 if (s->job) {
1460 copy_to_target = s->job->ret >= 0 &&
1461 !job_is_cancelled(&s->job->common.job) &&
1462 s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1463 }
d06107ad
HR
1464
1465 if (copy_to_target) {
1466 op = active_write_prepare(s->job, offset, bytes);
1467 }
1468
1469 switch (method) {
1470 case MIRROR_METHOD_COPY:
1471 ret = bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1472 break;
1473
1474 case MIRROR_METHOD_ZERO:
1475 ret = bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
1476 break;
1477
1478 case MIRROR_METHOD_DISCARD:
0b9fd3f4 1479 ret = bdrv_co_pdiscard(bs->backing, offset, bytes);
d06107ad
HR
1480 break;
1481
1482 default:
1483 abort();
1484 }
1485
1486 if (ret < 0) {
1487 goto out;
1488 }
1489
1490 if (copy_to_target) {
1491 do_sync_target_write(s->job, method, offset, bytes, qiov, flags);
1492 }
1493
1494out:
1495 if (copy_to_target) {
1496 active_write_settle(op);
1497 }
1498 return ret;
1499}
1500
b9b10c35
KW
1501static int coroutine_fn GRAPH_RDLOCK
1502bdrv_mirror_top_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
1503 QEMUIOVector *qiov, BdrvRequestFlags flags)
4ef85a9c 1504{
d06107ad
HR
1505 MirrorBDSOpaque *s = bs->opaque;
1506 QEMUIOVector bounce_qiov;
1507 void *bounce_buf;
1508 int ret = 0;
da93d5c8 1509 bool copy_to_target = false;
d06107ad 1510
da93d5c8
HR
1511 if (s->job) {
1512 copy_to_target = s->job->ret >= 0 &&
1513 !job_is_cancelled(&s->job->common.job) &&
1514 s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1515 }
d06107ad
HR
1516
1517 if (copy_to_target) {
1518 /* The guest might concurrently modify the data to write; but
1519 * the data on source and destination must match, so we have
1520 * to use a bounce buffer if we are going to write to the
1521 * target now. */
1522 bounce_buf = qemu_blockalign(bs, bytes);
1523 iov_to_buf_full(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
1524
1525 qemu_iovec_init(&bounce_qiov, 1);
1526 qemu_iovec_add(&bounce_qiov, bounce_buf, bytes);
1527 qiov = &bounce_qiov;
e8b65355
SH
1528
1529 flags &= ~BDRV_REQ_REGISTERED_BUF;
d06107ad
HR
1530 }
1531
1532 ret = bdrv_mirror_top_do_write(bs, MIRROR_METHOD_COPY, offset, bytes, qiov,
1533 flags);
1534
1535 if (copy_to_target) {
1536 qemu_iovec_destroy(&bounce_qiov);
1537 qemu_vfree(bounce_buf);
1538 }
1539
1540 return ret;
4ef85a9c
KW
1541}
1542
88095349 1543static int coroutine_fn GRAPH_RDLOCK bdrv_mirror_top_flush(BlockDriverState *bs)
4ef85a9c 1544{
ce960aa9
VSO
1545 if (bs->backing == NULL) {
1546 /* we can be here after failed bdrv_append in mirror_start_job */
1547 return 0;
1548 }
4ef85a9c
KW
1549 return bdrv_co_flush(bs->backing->bs);
1550}
1551
abaf8b75
KW
1552static int coroutine_fn GRAPH_RDLOCK
1553bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1554 int64_t bytes, BdrvRequestFlags flags)
4ef85a9c 1555{
d06107ad
HR
1556 return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_ZERO, offset, bytes, NULL,
1557 flags);
4ef85a9c
KW
1558}
1559
9a5a1c62
EGE
1560static int coroutine_fn GRAPH_RDLOCK
1561bdrv_mirror_top_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
4ef85a9c 1562{
d06107ad
HR
1563 return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_DISCARD, offset, bytes,
1564 NULL, 0);
4ef85a9c
KW
1565}
1566
998b3a1e 1567static void bdrv_mirror_top_refresh_filename(BlockDriverState *bs)
fd4a6493 1568{
18775ff3
VSO
1569 if (bs->backing == NULL) {
1570 /* we can be here after failed bdrv_attach_child in
1571 * bdrv_set_backing_hd */
1572 return;
1573 }
fd4a6493
KW
1574 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1575 bs->backing->bs->filename);
1576}
1577
4ef85a9c 1578static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
bf8e925e 1579 BdrvChildRole role,
e0995dc3 1580 BlockReopenQueue *reopen_queue,
4ef85a9c
KW
1581 uint64_t perm, uint64_t shared,
1582 uint64_t *nperm, uint64_t *nshared)
1583{
f94dc3b4
HR
1584 MirrorBDSOpaque *s = bs->opaque;
1585
1586 if (s->stop) {
1587 /*
1588 * If the job is to be stopped, we do not need to forward
1589 * anything to the real image.
1590 */
1591 *nperm = 0;
1592 *nshared = BLK_PERM_ALL;
1593 return;
1594 }
1595
53431b90
HR
1596 bdrv_default_perms(bs, c, role, reopen_queue,
1597 perm, shared, nperm, nshared);
4ef85a9c 1598
53431b90
HR
1599 if (s->is_commit) {
1600 /*
1601 * For commit jobs, we cannot take CONSISTENT_READ, because
1602 * that permission is unshared for everything above the base
1603 * node (except for filters on the base node).
1604 * We also have to force-share the WRITE permission, or
1605 * otherwise we would block ourselves at the base node (if
1606 * writes are blocked for a node, they are also blocked for
1607 * its backing file).
1608 * (We could also share RESIZE, because it may be needed for
1609 * the target if its size is less than the top node's; but
1610 * bdrv_default_perms_for_cow() automatically shares RESIZE
1611 * for backing nodes if WRITE is shared, so there is no need
1612 * to do it here.)
1613 */
1614 *nperm &= ~BLK_PERM_CONSISTENT_READ;
1615 *nshared |= BLK_PERM_WRITE;
1616 }
4ef85a9c
KW
1617}
1618
1619/* Dummy node that provides consistent read to its users without requiring it
1620 * from its backing file and that allows writes on the backing file chain. */
1621static BlockDriver bdrv_mirror_top = {
1622 .format_name = "mirror_top",
1623 .bdrv_co_preadv = bdrv_mirror_top_preadv,
1624 .bdrv_co_pwritev = bdrv_mirror_top_pwritev,
1625 .bdrv_co_pwrite_zeroes = bdrv_mirror_top_pwrite_zeroes,
1626 .bdrv_co_pdiscard = bdrv_mirror_top_pdiscard,
1627 .bdrv_co_flush = bdrv_mirror_top_flush,
fd4a6493 1628 .bdrv_refresh_filename = bdrv_mirror_top_refresh_filename,
4ef85a9c 1629 .bdrv_child_perm = bdrv_mirror_top_child_perm,
6540fd15
HR
1630
1631 .is_filter = true,
046fd84f 1632 .filtered_child_is_backing = true,
4ef85a9c
KW
1633};
1634
cc19f177
VSO
1635static BlockJob *mirror_start_job(
1636 const char *job_id, BlockDriverState *bs,
47970dfb
JS
1637 int creation_flags, BlockDriverState *target,
1638 const char *replaces, int64_t speed,
1639 uint32_t granularity, int64_t buf_size,
274fccee 1640 BlockMirrorBackingMode backing_mode,
cdf3bc93 1641 bool zero_target,
09158f00
BC
1642 BlockdevOnError on_source_error,
1643 BlockdevOnError on_target_error,
0fc9f8ea 1644 bool unmap,
097310b5 1645 BlockCompletionFunc *cb,
51ccfa2d 1646 void *opaque,
09158f00 1647 const BlockJobDriver *driver,
b49f7ead 1648 bool is_none_mode, BlockDriverState *base,
51ccfa2d 1649 bool auto_complete, const char *filter_node_name,
481debaa 1650 bool is_mirror, MirrorCopyMode copy_mode,
51ccfa2d 1651 Error **errp)
893f7eba
PB
1652{
1653 MirrorBlockJob *s;
429076e8 1654 MirrorBDSOpaque *bs_opaque;
4ef85a9c 1655 BlockDriverState *mirror_top_bs;
4ef85a9c 1656 bool target_is_backing;
3f072a7f 1657 uint64_t target_perms, target_shared_perms;
d7086422 1658 int ret;
893f7eba 1659
eee13dfe 1660 if (granularity == 0) {
341ebc2f 1661 granularity = bdrv_get_default_bitmap_granularity(target);
eee13dfe
PB
1662 }
1663
31826642 1664 assert(is_power_of_2(granularity));
eee13dfe 1665
48ac0a4d
WC
1666 if (buf_size < 0) {
1667 error_setg(errp, "Invalid parameter 'buf-size'");
cc19f177 1668 return NULL;
48ac0a4d
WC
1669 }
1670
1671 if (buf_size == 0) {
1672 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1673 }
5bc361b8 1674
3f072a7f 1675 if (bdrv_skip_filters(bs) == bdrv_skip_filters(target)) {
86fae10c 1676 error_setg(errp, "Can't mirror node into itself");
cc19f177 1677 return NULL;
86fae10c
KW
1678 }
1679
53431b90
HR
1680 target_is_backing = bdrv_chain_contains(bs, target);
1681
4ef85a9c
KW
1682 /* In the case of active commit, add dummy driver to provide consistent
1683 * reads on the top, while disabling it in the intermediate nodes, and make
1684 * the backing chain writable. */
6cdbceb1
KW
1685 mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
1686 BDRV_O_RDWR, errp);
4ef85a9c 1687 if (mirror_top_bs == NULL) {
cc19f177 1688 return NULL;
4ef85a9c 1689 }
d3c8c674
KW
1690 if (!filter_node_name) {
1691 mirror_top_bs->implicit = true;
1692 }
e5182c1c
HR
1693
1694 /* So that we can always drop this node */
1695 mirror_top_bs->never_freeze = true;
1696
4ef85a9c 1697 mirror_top_bs->total_sectors = bs->total_sectors;
228345bf 1698 mirror_top_bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED;
80f5c33f
KW
1699 mirror_top_bs->supported_zero_flags = BDRV_REQ_WRITE_UNCHANGED |
1700 BDRV_REQ_NO_FALLBACK;
429076e8
HR
1701 bs_opaque = g_new0(MirrorBDSOpaque, 1);
1702 mirror_top_bs->opaque = bs_opaque;
4ef85a9c 1703
53431b90
HR
1704 bs_opaque->is_commit = target_is_backing;
1705
4ef85a9c 1706 bdrv_drained_begin(bs);
934aee14 1707 ret = bdrv_append(mirror_top_bs, bs, errp);
4ef85a9c
KW
1708 bdrv_drained_end(bs);
1709
934aee14 1710 if (ret < 0) {
b2c2832c 1711 bdrv_unref(mirror_top_bs);
cc19f177 1712 return NULL;
b2c2832c
KW
1713 }
1714
4ef85a9c 1715 /* Make sure that the source is not resized while the job is running */
75859b94 1716 s = block_job_create(job_id, driver, NULL, mirror_top_bs,
4ef85a9c
KW
1717 BLK_PERM_CONSISTENT_READ,
1718 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
64631f36 1719 BLK_PERM_WRITE, speed,
c6cc12bf 1720 creation_flags, cb, opaque, errp);
893f7eba 1721 if (!s) {
4ef85a9c 1722 goto fail;
893f7eba 1723 }
429076e8 1724
7a25fcd0
HR
1725 /* The block job now has a reference to this node */
1726 bdrv_unref(mirror_top_bs);
1727
4ef85a9c
KW
1728 s->mirror_top_bs = mirror_top_bs;
1729
1730 /* No resize for the target either; while the mirror is still running, a
1731 * consistent read isn't necessarily possible. We could possibly allow
1732 * writes and graph modifications, though it would likely defeat the
1733 * purpose of a mirror, so leave them blocked for now.
1734 *
1735 * In the case of active commit, things look a bit different, though,
1736 * because the target is an already populated backing file in active use.
1737 * We can allow anything except resize there.*/
3f072a7f
HR
1738
1739 target_perms = BLK_PERM_WRITE;
1740 target_shared_perms = BLK_PERM_WRITE_UNCHANGED;
1741
3f072a7f
HR
1742 if (target_is_backing) {
1743 int64_t bs_size, target_size;
1744 bs_size = bdrv_getlength(bs);
1745 if (bs_size < 0) {
1746 error_setg_errno(errp, -bs_size,
1747 "Could not inquire top image size");
1748 goto fail;
1749 }
1750
1751 target_size = bdrv_getlength(target);
1752 if (target_size < 0) {
1753 error_setg_errno(errp, -target_size,
1754 "Could not inquire base image size");
1755 goto fail;
1756 }
1757
1758 if (target_size < bs_size) {
1759 target_perms |= BLK_PERM_RESIZE;
1760 }
1761
64631f36 1762 target_shared_perms |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE;
3f072a7f
HR
1763 } else if (bdrv_chain_contains(bs, bdrv_skip_filters(target))) {
1764 /*
1765 * We may want to allow this in the future, but it would
1766 * require taking some extra care.
1767 */
1768 error_setg(errp, "Cannot mirror to a filter on top of a node in the "
1769 "source's backing chain");
1770 goto fail;
1771 }
1772
d861ab3a 1773 s->target = blk_new(s->common.job.aio_context,
3f072a7f 1774 target_perms, target_shared_perms);
d7086422
KW
1775 ret = blk_insert_bs(s->target, target, errp);
1776 if (ret < 0) {
4ef85a9c 1777 goto fail;
d7086422 1778 }
045a2f82
FZ
1779 if (is_mirror) {
1780 /* XXX: Mirror target could be a NBD server of target QEMU in the case
1781 * of non-shared block migration. To allow migration completion, we
1782 * have to allow "inactivate" of the target BB. When that happens, we
1783 * know the job is drained, and the vcpus are stopped, so no write
1784 * operation will be performed. Block layer already has assertions to
1785 * ensure that. */
1786 blk_set_force_allow_inactivate(s->target);
1787 }
9ff7f0df 1788 blk_set_allow_aio_context_change(s->target, true);
cf312932 1789 blk_set_disable_request_queuing(s->target, true);
e253f4b8 1790
09158f00 1791 s->replaces = g_strdup(replaces);
b952b558
PB
1792 s->on_source_error = on_source_error;
1793 s->on_target_error = on_target_error;
03544a6e 1794 s->is_none_mode = is_none_mode;
274fccee 1795 s->backing_mode = backing_mode;
cdf3bc93 1796 s->zero_target = zero_target;
481debaa 1797 s->copy_mode = copy_mode;
5bc361b8 1798 s->base = base;
3f072a7f 1799 s->base_overlay = bdrv_find_overlay(bs, base);
eee13dfe 1800 s->granularity = granularity;
48ac0a4d 1801 s->buf_size = ROUND_UP(buf_size, granularity);
0fc9f8ea 1802 s->unmap = unmap;
b49f7ead
WC
1803 if (auto_complete) {
1804 s->should_complete = true;
1805 }
b812f671 1806
0db6e54a 1807 s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
b8afb520 1808 if (!s->dirty_bitmap) {
88f9d1b3 1809 goto fail;
b8afb520 1810 }
dbdf699c
VSO
1811 if (s->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING) {
1812 bdrv_disable_dirty_bitmap(s->dirty_bitmap);
1813 }
10f3cd15 1814
67b24427
AG
1815 ret = block_job_add_bdrv(&s->common, "source", bs, 0,
1816 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE |
1817 BLK_PERM_CONSISTENT_READ,
1818 errp);
1819 if (ret < 0) {
1820 goto fail;
1821 }
1822
4ef85a9c 1823 /* Required permissions are already taken with blk_new() */
76d554e2
KW
1824 block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
1825 &error_abort);
1826
f3ede4b0
AG
1827 /* In commit_active_start() all intermediate nodes disappear, so
1828 * any jobs in them must be blocked */
4ef85a9c 1829 if (target_is_backing) {
3f072a7f
HR
1830 BlockDriverState *iter, *filtered_target;
1831 uint64_t iter_shared_perms;
1832
1833 /*
1834 * The topmost node with
1835 * bdrv_skip_filters(filtered_target) == bdrv_skip_filters(target)
1836 */
1837 filtered_target = bdrv_cow_bs(bdrv_find_overlay(bs, target));
1838
1839 assert(bdrv_skip_filters(filtered_target) ==
1840 bdrv_skip_filters(target));
1841
1842 /*
1843 * XXX BLK_PERM_WRITE needs to be allowed so we don't block
1844 * ourselves at s->base (if writes are blocked for a node, they are
1845 * also blocked for its backing file). The other options would be a
1846 * second filter driver above s->base (== target).
1847 */
1848 iter_shared_perms = BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE;
1849
1850 for (iter = bdrv_filter_or_cow_bs(bs); iter != target;
1851 iter = bdrv_filter_or_cow_bs(iter))
1852 {
1853 if (iter == filtered_target) {
1854 /*
1855 * From here on, all nodes are filters on the base.
1856 * This allows us to share BLK_PERM_CONSISTENT_READ.
1857 */
1858 iter_shared_perms |= BLK_PERM_CONSISTENT_READ;
1859 }
1860
4ef85a9c 1861 ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
3f072a7f 1862 iter_shared_perms, errp);
4ef85a9c
KW
1863 if (ret < 0) {
1864 goto fail;
1865 }
f3ede4b0 1866 }
ef53dc09
AG
1867
1868 if (bdrv_freeze_backing_chain(mirror_top_bs, target, errp) < 0) {
1869 goto fail;
1870 }
f3ede4b0 1871 }
10f3cd15 1872
12aa4082
HR
1873 QTAILQ_INIT(&s->ops_in_flight);
1874
5ccac6f1 1875 trace_mirror_start(bs, s, opaque);
da01ff7f 1876 job_start(&s->common.job);
cc19f177
VSO
1877
1878 return &s->common;
4ef85a9c
KW
1879
1880fail:
1881 if (s) {
7a25fcd0
HR
1882 /* Make sure this BDS does not go away until we have completed the graph
1883 * changes below */
1884 bdrv_ref(mirror_top_bs);
1885
4ef85a9c
KW
1886 g_free(s->replaces);
1887 blk_unref(s->target);
429076e8 1888 bs_opaque->job = NULL;
e917e2cb 1889 if (s->dirty_bitmap) {
5deb6cbd 1890 bdrv_release_dirty_bitmap(s->dirty_bitmap);
e917e2cb 1891 }
4ad35181 1892 job_early_fail(&s->common.job);
4ef85a9c
KW
1893 }
1894
f94dc3b4
HR
1895 bs_opaque->stop = true;
1896 bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
1897 &error_abort);
3f072a7f 1898 bdrv_replace_node(mirror_top_bs, mirror_top_bs->backing->bs, &error_abort);
7a25fcd0
HR
1899
1900 bdrv_unref(mirror_top_bs);
cc19f177
VSO
1901
1902 return NULL;
893f7eba 1903}
03544a6e 1904
71aa9867
AG
1905void mirror_start(const char *job_id, BlockDriverState *bs,
1906 BlockDriverState *target, const char *replaces,
a1999b33
JS
1907 int creation_flags, int64_t speed,
1908 uint32_t granularity, int64_t buf_size,
274fccee 1909 MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
cdf3bc93 1910 bool zero_target,
274fccee 1911 BlockdevOnError on_source_error,
03544a6e 1912 BlockdevOnError on_target_error,
481debaa
HR
1913 bool unmap, const char *filter_node_name,
1914 MirrorCopyMode copy_mode, Error **errp)
03544a6e
FZ
1915{
1916 bool is_none_mode;
1917 BlockDriverState *base;
1918
b4ad82aa
EGE
1919 GLOBAL_STATE_CODE();
1920
c8b56501
JS
1921 if ((mode == MIRROR_SYNC_MODE_INCREMENTAL) ||
1922 (mode == MIRROR_SYNC_MODE_BITMAP)) {
1923 error_setg(errp, "Sync mode '%s' not supported",
1924 MirrorSyncMode_str(mode));
d58d8453
JS
1925 return;
1926 }
03544a6e 1927 is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
3f072a7f 1928 base = mode == MIRROR_SYNC_MODE_TOP ? bdrv_backing_chain_next(bs) : NULL;
a1999b33 1929 mirror_start_job(job_id, bs, creation_flags, target, replaces,
cdf3bc93 1930 speed, granularity, buf_size, backing_mode, zero_target,
51ccfa2d 1931 on_source_error, on_target_error, unmap, NULL, NULL,
6cdbceb1 1932 &mirror_job_driver, is_none_mode, base, false,
481debaa 1933 filter_node_name, true, copy_mode, errp);
03544a6e
FZ
1934}
1935
cc19f177
VSO
1936BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
1937 BlockDriverState *base, int creation_flags,
1938 int64_t speed, BlockdevOnError on_error,
1939 const char *filter_node_name,
1940 BlockCompletionFunc *cb, void *opaque,
1941 bool auto_complete, Error **errp)
03544a6e 1942{
1ba79388 1943 bool base_read_only;
eb5becc1 1944 BlockJob *job;
4da83585 1945
b4ad82aa
EGE
1946 GLOBAL_STATE_CODE();
1947
1ba79388 1948 base_read_only = bdrv_is_read_only(base);
4da83585 1949
1ba79388
AG
1950 if (base_read_only) {
1951 if (bdrv_reopen_set_read_only(base, false, errp) < 0) {
cc19f177 1952 return NULL;
1ba79388 1953 }
20a63d2c 1954 }
4da83585 1955
eb5becc1 1956 job = mirror_start_job(
cc19f177 1957 job_id, bs, creation_flags, base, NULL, speed, 0, 0,
cdf3bc93 1958 MIRROR_LEAVE_BACKING_CHAIN, false,
51ccfa2d 1959 on_error, on_error, true, cb, opaque,
6cdbceb1 1960 &commit_active_job_driver, false, base, auto_complete,
481debaa 1961 filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
eb5becc1
VSO
1962 errp);
1963 if (!job) {
4da83585
JC
1964 goto error_restore_flags;
1965 }
1966
eb5becc1 1967 return job;
4da83585
JC
1968
1969error_restore_flags:
1970 /* ignore error and errp for bdrv_reopen, because we want to propagate
1971 * the original error */
1ba79388
AG
1972 if (base_read_only) {
1973 bdrv_reopen_set_read_only(base, true, NULL);
1974 }
cc19f177 1975 return NULL;
03544a6e 1976}