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