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