xref: /qemu/block/mirror.c (revision 3d47eb0a2a42b13734d1beb75c4310b3881f906f)
1893f7ebaSPaolo Bonzini /*
2893f7ebaSPaolo Bonzini  * Image mirroring
3893f7ebaSPaolo Bonzini  *
4893f7ebaSPaolo Bonzini  * Copyright Red Hat, Inc. 2012
5893f7ebaSPaolo Bonzini  *
6893f7ebaSPaolo Bonzini  * Authors:
7893f7ebaSPaolo Bonzini  *  Paolo Bonzini  <pbonzini@redhat.com>
8893f7ebaSPaolo Bonzini  *
9893f7ebaSPaolo Bonzini  * This work is licensed under the terms of the GNU LGPL, version 2 or later.
10893f7ebaSPaolo Bonzini  * See the COPYING.LIB file in the top-level directory.
11893f7ebaSPaolo Bonzini  *
12893f7ebaSPaolo Bonzini  */
13893f7ebaSPaolo Bonzini 
1480c71a24SPeter Maydell #include "qemu/osdep.h"
15fd4a6493SKevin Wolf #include "qemu/cutils.h"
1612aa4082SMax Reitz #include "qemu/coroutine.h"
171181e19aSMax Reitz #include "qemu/range.h"
18893f7ebaSPaolo Bonzini #include "trace.h"
19c87621eaSJohn Snow #include "block/blockjob_int.h"
20737e150eSPaolo Bonzini #include "block/block_int.h"
21e2c1c34fSMarkus Armbruster #include "block/dirty-bitmap.h"
22373340b2SMax Reitz #include "sysemu/block-backend.h"
23da34e65cSMarkus Armbruster #include "qapi/error.h"
24cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
25893f7ebaSPaolo Bonzini #include "qemu/ratelimit.h"
26b812f671SPaolo Bonzini #include "qemu/bitmap.h"
275df022cfSPeter Maydell #include "qemu/memalign.h"
28893f7ebaSPaolo Bonzini 
29402a4741SPaolo Bonzini #define MAX_IN_FLIGHT 16
30b436982fSEric Blake #define MAX_IO_BYTES (1 << 20) /* 1 Mb */
31b436982fSEric Blake #define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
32402a4741SPaolo Bonzini 
33402a4741SPaolo Bonzini /* The mirroring buffer is a list of granularity-sized chunks.
34402a4741SPaolo Bonzini  * Free chunks are organized in a list.
35402a4741SPaolo Bonzini  */
36402a4741SPaolo Bonzini typedef struct MirrorBuffer {
37402a4741SPaolo Bonzini     QSIMPLEQ_ENTRY(MirrorBuffer) next;
38402a4741SPaolo Bonzini } MirrorBuffer;
39893f7ebaSPaolo Bonzini 
4012aa4082SMax Reitz typedef struct MirrorOp MirrorOp;
4112aa4082SMax Reitz 
42893f7ebaSPaolo Bonzini typedef struct MirrorBlockJob {
43893f7ebaSPaolo Bonzini     BlockJob common;
44e253f4b8SKevin Wolf     BlockBackend *target;
454ef85a9cSKevin Wolf     BlockDriverState *mirror_top_bs;
465bc361b8SFam Zheng     BlockDriverState *base;
473f072a7fSMax Reitz     BlockDriverState *base_overlay;
484ef85a9cSKevin Wolf 
4909158f00SBenoît Canet     /* The name of the graph node to replace */
5009158f00SBenoît Canet     char *replaces;
5109158f00SBenoît Canet     /* The BDS to replace */
5209158f00SBenoît Canet     BlockDriverState *to_replace;
5309158f00SBenoît Canet     /* Used to block operations on the drive-mirror-replace target */
5409158f00SBenoît Canet     Error *replace_blocker;
5503544a6eSFam Zheng     bool is_none_mode;
56274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode;
57cdf3bc93SMax Reitz     /* Whether the target image requires explicit zero-initialization */
58cdf3bc93SMax Reitz     bool zero_target;
59d06107adSMax Reitz     MirrorCopyMode copy_mode;
60b952b558SPaolo Bonzini     BlockdevOnError on_source_error, on_target_error;
61d06107adSMax Reitz     /* Set when the target is synced (dirty bitmap is clean, nothing
62d06107adSMax Reitz      * in flight) and the job is running in active mode */
63d06107adSMax Reitz     bool actively_synced;
64d63ffd87SPaolo Bonzini     bool should_complete;
65eee13dfeSPaolo Bonzini     int64_t granularity;
66b812f671SPaolo Bonzini     size_t buf_size;
67b21c7652SMax Reitz     int64_t bdev_length;
68b812f671SPaolo Bonzini     unsigned long *cow_bitmap;
69e4654d2dSFam Zheng     BdrvDirtyBitmap *dirty_bitmap;
70dc162c8eSFam Zheng     BdrvDirtyBitmapIter *dbi;
71893f7ebaSPaolo Bonzini     uint8_t *buf;
72402a4741SPaolo Bonzini     QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
73402a4741SPaolo Bonzini     int buf_free_count;
74bd48bde8SPaolo Bonzini 
7549efb1f5SDenis V. Lunev     uint64_t last_pause_ns;
76402a4741SPaolo Bonzini     unsigned long *in_flight_bitmap;
771b8f7776SDenis V. Lunev     unsigned in_flight;
78b436982fSEric Blake     int64_t bytes_in_flight;
79b58deb34SPaolo Bonzini     QTAILQ_HEAD(, MirrorOp) ops_in_flight;
80bd48bde8SPaolo Bonzini     int ret;
810fc9f8eaSFam Zheng     bool unmap;
82b436982fSEric Blake     int target_cluster_size;
83e5b43573SFam Zheng     int max_iov;
8490ab48ebSAnton Nefedov     bool initial_zeroing_ongoing;
85d06107adSMax Reitz     int in_active_write_counter;
86d69a879bSHanna Reitz     int64_t active_write_bytes_in_flight;
87737efc1eSJohn Snow     bool prepared;
885e771752SSergio Lopez     bool in_drain;
89893f7ebaSPaolo Bonzini } MirrorBlockJob;
90893f7ebaSPaolo Bonzini 
91429076e8SMax Reitz typedef struct MirrorBDSOpaque {
92429076e8SMax Reitz     MirrorBlockJob *job;
93f94dc3b4SMax Reitz     bool stop;
9453431b90SMax Reitz     bool is_commit;
95429076e8SMax Reitz } MirrorBDSOpaque;
96429076e8SMax Reitz 
9712aa4082SMax Reitz struct MirrorOp {
98bd48bde8SPaolo Bonzini     MirrorBlockJob *s;
99bd48bde8SPaolo Bonzini     QEMUIOVector qiov;
100b436982fSEric Blake     int64_t offset;
101b436982fSEric Blake     uint64_t bytes;
1022e1990b2SMax Reitz 
1032e1990b2SMax Reitz     /* The pointee is set by mirror_co_read(), mirror_co_zero(), and
1042e1990b2SMax Reitz      * mirror_co_discard() before yielding for the first time */
1052e1990b2SMax Reitz     int64_t *bytes_handled;
10612aa4082SMax Reitz 
1071181e19aSMax Reitz     bool is_pseudo_op;
108d06107adSMax Reitz     bool is_active_write;
109ce8cabbdSKevin Wolf     bool is_in_flight;
11012aa4082SMax Reitz     CoQueue waiting_requests;
111eed325b9SKevin Wolf     Coroutine *co;
112d44dae1aSVladimir Sementsov-Ogievskiy     MirrorOp *waiting_for_op;
11312aa4082SMax Reitz 
11412aa4082SMax Reitz     QTAILQ_ENTRY(MirrorOp) next;
11512aa4082SMax Reitz };
116bd48bde8SPaolo Bonzini 
1174295c5fcSMax Reitz typedef enum MirrorMethod {
1184295c5fcSMax Reitz     MIRROR_METHOD_COPY,
1194295c5fcSMax Reitz     MIRROR_METHOD_ZERO,
1204295c5fcSMax Reitz     MIRROR_METHOD_DISCARD,
1214295c5fcSMax Reitz } MirrorMethod;
1224295c5fcSMax Reitz 
123b952b558SPaolo Bonzini static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
124b952b558SPaolo Bonzini                                             int error)
125b952b558SPaolo Bonzini {
126d06107adSMax Reitz     s->actively_synced = false;
127b952b558SPaolo Bonzini     if (read) {
12881e254dcSKevin Wolf         return block_job_error_action(&s->common, s->on_source_error,
12981e254dcSKevin Wolf                                       true, error);
130b952b558SPaolo Bonzini     } else {
13181e254dcSKevin Wolf         return block_job_error_action(&s->common, s->on_target_error,
13281e254dcSKevin Wolf                                       false, error);
133b952b558SPaolo Bonzini     }
134b952b558SPaolo Bonzini }
135b952b558SPaolo Bonzini 
1361181e19aSMax Reitz static void coroutine_fn mirror_wait_on_conflicts(MirrorOp *self,
1371181e19aSMax Reitz                                                   MirrorBlockJob *s,
1381181e19aSMax Reitz                                                   uint64_t offset,
1391181e19aSMax Reitz                                                   uint64_t bytes)
1401181e19aSMax Reitz {
1411181e19aSMax Reitz     uint64_t self_start_chunk = offset / s->granularity;
1421181e19aSMax Reitz     uint64_t self_end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1431181e19aSMax Reitz     uint64_t self_nb_chunks = self_end_chunk - self_start_chunk;
1441181e19aSMax Reitz 
1451181e19aSMax Reitz     while (find_next_bit(s->in_flight_bitmap, self_end_chunk,
1461181e19aSMax Reitz                          self_start_chunk) < self_end_chunk &&
1471181e19aSMax Reitz            s->ret >= 0)
1481181e19aSMax Reitz     {
1491181e19aSMax Reitz         MirrorOp *op;
1501181e19aSMax Reitz 
1511181e19aSMax Reitz         QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
1521181e19aSMax Reitz             uint64_t op_start_chunk = op->offset / s->granularity;
1531181e19aSMax Reitz             uint64_t op_nb_chunks = DIV_ROUND_UP(op->offset + op->bytes,
1541181e19aSMax Reitz                                                  s->granularity) -
1551181e19aSMax Reitz                                     op_start_chunk;
1561181e19aSMax Reitz 
1571181e19aSMax Reitz             if (op == self) {
1581181e19aSMax Reitz                 continue;
1591181e19aSMax Reitz             }
1601181e19aSMax Reitz 
1611181e19aSMax Reitz             if (ranges_overlap(self_start_chunk, self_nb_chunks,
1621181e19aSMax Reitz                                op_start_chunk, op_nb_chunks))
1631181e19aSMax Reitz             {
16466fed30cSStefano Garzarella                 if (self) {
165d44dae1aSVladimir Sementsov-Ogievskiy                     /*
16666fed30cSStefano Garzarella                      * If the operation is already (indirectly) waiting for us,
16766fed30cSStefano Garzarella                      * or will wait for us as soon as it wakes up, then just go
16866fed30cSStefano Garzarella                      * on (instead of producing a deadlock in the former case).
169d44dae1aSVladimir Sementsov-Ogievskiy                      */
170d44dae1aSVladimir Sementsov-Ogievskiy                     if (op->waiting_for_op) {
171d44dae1aSVladimir Sementsov-Ogievskiy                         continue;
172d44dae1aSVladimir Sementsov-Ogievskiy                     }
173d44dae1aSVladimir Sementsov-Ogievskiy 
174d44dae1aSVladimir Sementsov-Ogievskiy                     self->waiting_for_op = op;
17566fed30cSStefano Garzarella                 }
17666fed30cSStefano Garzarella 
1771181e19aSMax Reitz                 qemu_co_queue_wait(&op->waiting_requests, NULL);
17866fed30cSStefano Garzarella 
17966fed30cSStefano Garzarella                 if (self) {
180d44dae1aSVladimir Sementsov-Ogievskiy                     self->waiting_for_op = NULL;
18166fed30cSStefano Garzarella                 }
18266fed30cSStefano Garzarella 
1831181e19aSMax Reitz                 break;
1841181e19aSMax Reitz             }
1851181e19aSMax Reitz         }
1861181e19aSMax Reitz     }
1871181e19aSMax Reitz }
1881181e19aSMax Reitz 
1892e1990b2SMax Reitz static void coroutine_fn mirror_iteration_done(MirrorOp *op, int ret)
190bd48bde8SPaolo Bonzini {
191bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
192402a4741SPaolo Bonzini     struct iovec *iov;
193bd48bde8SPaolo Bonzini     int64_t chunk_num;
194b436982fSEric Blake     int i, nb_chunks;
195bd48bde8SPaolo Bonzini 
196b436982fSEric Blake     trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
197bd48bde8SPaolo Bonzini 
198bd48bde8SPaolo Bonzini     s->in_flight--;
199b436982fSEric Blake     s->bytes_in_flight -= op->bytes;
200402a4741SPaolo Bonzini     iov = op->qiov.iov;
201402a4741SPaolo Bonzini     for (i = 0; i < op->qiov.niov; i++) {
202402a4741SPaolo Bonzini         MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
203402a4741SPaolo Bonzini         QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
204402a4741SPaolo Bonzini         s->buf_free_count++;
205402a4741SPaolo Bonzini     }
206402a4741SPaolo Bonzini 
207b436982fSEric Blake     chunk_num = op->offset / s->granularity;
208b436982fSEric Blake     nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
20912aa4082SMax Reitz 
210402a4741SPaolo Bonzini     bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
21112aa4082SMax Reitz     QTAILQ_REMOVE(&s->ops_in_flight, op, next);
212b21c7652SMax Reitz     if (ret >= 0) {
213b21c7652SMax Reitz         if (s->cow_bitmap) {
214bd48bde8SPaolo Bonzini             bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
215bd48bde8SPaolo Bonzini         }
21690ab48ebSAnton Nefedov         if (!s->initial_zeroing_ongoing) {
21730a5c887SKevin Wolf             job_progress_update(&s->common.job, op->bytes);
218b21c7652SMax Reitz         }
21990ab48ebSAnton Nefedov     }
2206df3bf8eSZhang Min     qemu_iovec_destroy(&op->qiov);
2217b770c72SStefan Hajnoczi 
22212aa4082SMax Reitz     qemu_co_queue_restart_all(&op->waiting_requests);
22312aa4082SMax Reitz     g_free(op);
2247b770c72SStefan Hajnoczi }
225bd48bde8SPaolo Bonzini 
2262e1990b2SMax Reitz static void coroutine_fn mirror_write_complete(MirrorOp *op, int ret)
227bd48bde8SPaolo Bonzini {
228bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
229b9e413ddSPaolo Bonzini 
230bd48bde8SPaolo Bonzini     if (ret < 0) {
231bd48bde8SPaolo Bonzini         BlockErrorAction action;
232bd48bde8SPaolo Bonzini 
233e0d7f73eSEric Blake         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
234bd48bde8SPaolo Bonzini         action = mirror_error_action(s, false, -ret);
235a589569fSWenchao Xia         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
236bd48bde8SPaolo Bonzini             s->ret = ret;
237bd48bde8SPaolo Bonzini         }
238bd48bde8SPaolo Bonzini     }
239d12ade57SVladimir Sementsov-Ogievskiy 
240bd48bde8SPaolo Bonzini     mirror_iteration_done(op, ret);
241bd48bde8SPaolo Bonzini }
242bd48bde8SPaolo Bonzini 
2432e1990b2SMax Reitz static void coroutine_fn mirror_read_complete(MirrorOp *op, int ret)
244bd48bde8SPaolo Bonzini {
245bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
246b9e413ddSPaolo Bonzini 
247bd48bde8SPaolo Bonzini     if (ret < 0) {
248bd48bde8SPaolo Bonzini         BlockErrorAction action;
249bd48bde8SPaolo Bonzini 
250e0d7f73eSEric Blake         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
251bd48bde8SPaolo Bonzini         action = mirror_error_action(s, true, -ret);
252a589569fSWenchao Xia         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
253bd48bde8SPaolo Bonzini             s->ret = ret;
254bd48bde8SPaolo Bonzini         }
255bd48bde8SPaolo Bonzini 
256bd48bde8SPaolo Bonzini         mirror_iteration_done(op, ret);
257d12ade57SVladimir Sementsov-Ogievskiy         return;
258bd48bde8SPaolo Bonzini     }
259d12ade57SVladimir Sementsov-Ogievskiy 
260d12ade57SVladimir Sementsov-Ogievskiy     ret = blk_co_pwritev(s->target, op->offset, op->qiov.size, &op->qiov, 0);
261d12ade57SVladimir Sementsov-Ogievskiy     mirror_write_complete(op, ret);
262b9e413ddSPaolo Bonzini }
263bd48bde8SPaolo Bonzini 
264782d97efSEric Blake /* Clip bytes relative to offset to not exceed end-of-file */
265782d97efSEric Blake static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
266782d97efSEric Blake                                         int64_t offset,
267782d97efSEric Blake                                         int64_t bytes)
268782d97efSEric Blake {
269782d97efSEric Blake     return MIN(bytes, s->bdev_length - offset);
270782d97efSEric Blake }
271782d97efSEric Blake 
272782d97efSEric Blake /* Round offset and/or bytes to target cluster if COW is needed, and
273782d97efSEric Blake  * return the offset of the adjusted tail against original. */
274782d97efSEric Blake static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
275ae4cc877SEric Blake                             uint64_t *bytes)
276893f7ebaSPaolo Bonzini {
277e5b43573SFam Zheng     bool need_cow;
278e5b43573SFam Zheng     int ret = 0;
279782d97efSEric Blake     int64_t align_offset = *offset;
2807cfd5275SEric Blake     int64_t align_bytes = *bytes;
281782d97efSEric Blake     int max_bytes = s->granularity * s->max_iov;
282893f7ebaSPaolo Bonzini 
283782d97efSEric Blake     need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
284782d97efSEric Blake     need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
285e5b43573SFam Zheng                           s->cow_bitmap);
286e5b43573SFam Zheng     if (need_cow) {
287782d97efSEric Blake         bdrv_round_to_clusters(blk_bs(s->target), *offset, *bytes,
288782d97efSEric Blake                                &align_offset, &align_bytes);
2898f0720ecSPaolo Bonzini     }
2908f0720ecSPaolo Bonzini 
291782d97efSEric Blake     if (align_bytes > max_bytes) {
292782d97efSEric Blake         align_bytes = max_bytes;
293e5b43573SFam Zheng         if (need_cow) {
294782d97efSEric Blake             align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
295e5b43573SFam Zheng         }
296e5b43573SFam Zheng     }
297782d97efSEric Blake     /* Clipping may result in align_bytes unaligned to chunk boundary, but
2984150ae60SFam Zheng      * that doesn't matter because it's already the end of source image. */
299782d97efSEric Blake     align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
300402a4741SPaolo Bonzini 
301782d97efSEric Blake     ret = align_offset + align_bytes - (*offset + *bytes);
302782d97efSEric Blake     *offset = align_offset;
303782d97efSEric Blake     *bytes = align_bytes;
304e5b43573SFam Zheng     assert(ret >= 0);
305e5b43573SFam Zheng     return ret;
306e5b43573SFam Zheng }
307e5b43573SFam Zheng 
308537c3d4fSStefan Hajnoczi static inline void coroutine_fn
309eb994912SHanna Reitz mirror_wait_for_free_in_flight_slot(MirrorBlockJob *s)
31021cd917fSFam Zheng {
31112aa4082SMax Reitz     MirrorOp *op;
31212aa4082SMax Reitz 
3131181e19aSMax Reitz     QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
314eb994912SHanna Reitz         /*
315eb994912SHanna Reitz          * Do not wait on pseudo ops, because it may in turn wait on
3161181e19aSMax Reitz          * some other operation to start, which may in fact be the
3171181e19aSMax Reitz          * caller of this function.  Since there is only one pseudo op
3181181e19aSMax Reitz          * at any given time, we will always find some real operation
319eb994912SHanna Reitz          * to wait on.
320eb994912SHanna Reitz          * Also, do not wait on active operations, because they do not
321eb994912SHanna Reitz          * use up in-flight slots.
322eb994912SHanna Reitz          */
323eb994912SHanna Reitz         if (!op->is_pseudo_op && op->is_in_flight && !op->is_active_write) {
32412aa4082SMax Reitz             qemu_co_queue_wait(&op->waiting_requests, NULL);
3251181e19aSMax Reitz             return;
3261181e19aSMax Reitz         }
3271181e19aSMax Reitz     }
3281181e19aSMax Reitz     abort();
32921cd917fSFam Zheng }
33021cd917fSFam Zheng 
3312e1990b2SMax Reitz /* Perform a mirror copy operation.
3322e1990b2SMax Reitz  *
3332e1990b2SMax Reitz  * *op->bytes_handled is set to the number of bytes copied after and
3342e1990b2SMax Reitz  * including offset, excluding any bytes copied prior to offset due
3352e1990b2SMax Reitz  * to alignment.  This will be op->bytes if no alignment is necessary,
3362e1990b2SMax Reitz  * or (new_end - op->offset) if the tail is rounded up or down due to
337e5b43573SFam Zheng  * alignment or buffer limit.
338402a4741SPaolo Bonzini  */
3392e1990b2SMax Reitz static void coroutine_fn mirror_co_read(void *opaque)
340e5b43573SFam Zheng {
3412e1990b2SMax Reitz     MirrorOp *op = opaque;
3422e1990b2SMax Reitz     MirrorBlockJob *s = op->s;
343ae4cc877SEric Blake     int nb_chunks;
344ae4cc877SEric Blake     uint64_t ret;
345ae4cc877SEric Blake     uint64_t max_bytes;
346402a4741SPaolo Bonzini 
347ae4cc877SEric Blake     max_bytes = s->granularity * s->max_iov;
348e5b43573SFam Zheng 
349e5b43573SFam Zheng     /* We can only handle as much as buf_size at a time. */
3502e1990b2SMax Reitz     op->bytes = MIN(s->buf_size, MIN(max_bytes, op->bytes));
3512e1990b2SMax Reitz     assert(op->bytes);
3522e1990b2SMax Reitz     assert(op->bytes < BDRV_REQUEST_MAX_BYTES);
3532e1990b2SMax Reitz     *op->bytes_handled = op->bytes;
354e5b43573SFam Zheng 
355e5b43573SFam Zheng     if (s->cow_bitmap) {
3562e1990b2SMax Reitz         *op->bytes_handled += mirror_cow_align(s, &op->offset, &op->bytes);
357e5b43573SFam Zheng     }
3582e1990b2SMax Reitz     /* Cannot exceed BDRV_REQUEST_MAX_BYTES + INT_MAX */
3592e1990b2SMax Reitz     assert(*op->bytes_handled <= UINT_MAX);
3602e1990b2SMax Reitz     assert(op->bytes <= s->buf_size);
361ae4cc877SEric Blake     /* The offset is granularity-aligned because:
362e5b43573SFam Zheng      * 1) Caller passes in aligned values;
363e5b43573SFam Zheng      * 2) mirror_cow_align is used only when target cluster is larger. */
3642e1990b2SMax Reitz     assert(QEMU_IS_ALIGNED(op->offset, s->granularity));
365ae4cc877SEric Blake     /* The range is sector-aligned, since bdrv_getlength() rounds up. */
3662e1990b2SMax Reitz     assert(QEMU_IS_ALIGNED(op->bytes, BDRV_SECTOR_SIZE));
3672e1990b2SMax Reitz     nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
368e5b43573SFam Zheng 
369e5b43573SFam Zheng     while (s->buf_free_count < nb_chunks) {
3702e1990b2SMax Reitz         trace_mirror_yield_in_flight(s, op->offset, s->in_flight);
3719178f4feSKevin Wolf         mirror_wait_for_free_in_flight_slot(s);
372b812f671SPaolo Bonzini     }
373b812f671SPaolo Bonzini 
374402a4741SPaolo Bonzini     /* Now make a QEMUIOVector taking enough granularity-sized chunks
375402a4741SPaolo Bonzini      * from s->buf_free.
376402a4741SPaolo Bonzini      */
377402a4741SPaolo Bonzini     qemu_iovec_init(&op->qiov, nb_chunks);
378402a4741SPaolo Bonzini     while (nb_chunks-- > 0) {
379402a4741SPaolo Bonzini         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
3802e1990b2SMax Reitz         size_t remaining = op->bytes - op->qiov.size;
3815a0f6fd5SKevin Wolf 
382402a4741SPaolo Bonzini         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
383402a4741SPaolo Bonzini         s->buf_free_count--;
3845a0f6fd5SKevin Wolf         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
385402a4741SPaolo Bonzini     }
386402a4741SPaolo Bonzini 
387893f7ebaSPaolo Bonzini     /* Copy the dirty cluster.  */
388bd48bde8SPaolo Bonzini     s->in_flight++;
3892e1990b2SMax Reitz     s->bytes_in_flight += op->bytes;
390ce8cabbdSKevin Wolf     op->is_in_flight = true;
3912e1990b2SMax Reitz     trace_mirror_one_iteration(s, op->offset, op->bytes);
392dcfb3bebSFam Zheng 
393138f9fffSMax Reitz     ret = bdrv_co_preadv(s->mirror_top_bs->backing, op->offset, op->bytes,
394138f9fffSMax Reitz                          &op->qiov, 0);
3952e1990b2SMax Reitz     mirror_read_complete(op, ret);
396e5b43573SFam Zheng }
397e5b43573SFam Zheng 
3982e1990b2SMax Reitz static void coroutine_fn mirror_co_zero(void *opaque)
399e5b43573SFam Zheng {
4002e1990b2SMax Reitz     MirrorOp *op = opaque;
4012e1990b2SMax Reitz     int ret;
402e5b43573SFam Zheng 
4032e1990b2SMax Reitz     op->s->in_flight++;
4042e1990b2SMax Reitz     op->s->bytes_in_flight += op->bytes;
4052e1990b2SMax Reitz     *op->bytes_handled = op->bytes;
406ce8cabbdSKevin Wolf     op->is_in_flight = true;
407e5b43573SFam Zheng 
4082e1990b2SMax Reitz     ret = blk_co_pwrite_zeroes(op->s->target, op->offset, op->bytes,
4092e1990b2SMax Reitz                                op->s->unmap ? BDRV_REQ_MAY_UNMAP : 0);
4102e1990b2SMax Reitz     mirror_write_complete(op, ret);
411e5b43573SFam Zheng }
4122e1990b2SMax Reitz 
4132e1990b2SMax Reitz static void coroutine_fn mirror_co_discard(void *opaque)
4142e1990b2SMax Reitz {
4152e1990b2SMax Reitz     MirrorOp *op = opaque;
4162e1990b2SMax Reitz     int ret;
4172e1990b2SMax Reitz 
4182e1990b2SMax Reitz     op->s->in_flight++;
4192e1990b2SMax Reitz     op->s->bytes_in_flight += op->bytes;
4202e1990b2SMax Reitz     *op->bytes_handled = op->bytes;
421ce8cabbdSKevin Wolf     op->is_in_flight = true;
4222e1990b2SMax Reitz 
4232e1990b2SMax Reitz     ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes);
4242e1990b2SMax Reitz     mirror_write_complete(op, ret);
425e5b43573SFam Zheng }
426e5b43573SFam Zheng 
4274295c5fcSMax Reitz static unsigned mirror_perform(MirrorBlockJob *s, int64_t offset,
4284295c5fcSMax Reitz                                unsigned bytes, MirrorMethod mirror_method)
4294295c5fcSMax Reitz {
4302e1990b2SMax Reitz     MirrorOp *op;
4312e1990b2SMax Reitz     Coroutine *co;
4322e1990b2SMax Reitz     int64_t bytes_handled = -1;
4332e1990b2SMax Reitz 
4342e1990b2SMax Reitz     op = g_new(MirrorOp, 1);
4352e1990b2SMax Reitz     *op = (MirrorOp){
4362e1990b2SMax Reitz         .s              = s,
4372e1990b2SMax Reitz         .offset         = offset,
4382e1990b2SMax Reitz         .bytes          = bytes,
4392e1990b2SMax Reitz         .bytes_handled  = &bytes_handled,
4402e1990b2SMax Reitz     };
44112aa4082SMax Reitz     qemu_co_queue_init(&op->waiting_requests);
4422e1990b2SMax Reitz 
4434295c5fcSMax Reitz     switch (mirror_method) {
4444295c5fcSMax Reitz     case MIRROR_METHOD_COPY:
4452e1990b2SMax Reitz         co = qemu_coroutine_create(mirror_co_read, op);
4462e1990b2SMax Reitz         break;
4474295c5fcSMax Reitz     case MIRROR_METHOD_ZERO:
4482e1990b2SMax Reitz         co = qemu_coroutine_create(mirror_co_zero, op);
4492e1990b2SMax Reitz         break;
4504295c5fcSMax Reitz     case MIRROR_METHOD_DISCARD:
4512e1990b2SMax Reitz         co = qemu_coroutine_create(mirror_co_discard, op);
4522e1990b2SMax Reitz         break;
4534295c5fcSMax Reitz     default:
4544295c5fcSMax Reitz         abort();
4554295c5fcSMax Reitz     }
456eed325b9SKevin Wolf     op->co = co;
4572e1990b2SMax Reitz 
45812aa4082SMax Reitz     QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
4592e1990b2SMax Reitz     qemu_coroutine_enter(co);
4602e1990b2SMax Reitz     /* At this point, ownership of op has been moved to the coroutine
4612e1990b2SMax Reitz      * and the object may already be freed */
4622e1990b2SMax Reitz 
4632e1990b2SMax Reitz     /* Assert that this value has been set */
4642e1990b2SMax Reitz     assert(bytes_handled >= 0);
4652e1990b2SMax Reitz 
4662e1990b2SMax Reitz     /* Same assertion as in mirror_co_read() (and for mirror_co_read()
4672e1990b2SMax Reitz      * and mirror_co_discard(), bytes_handled == op->bytes, which
4682e1990b2SMax Reitz      * is the @bytes parameter given to this function) */
4692e1990b2SMax Reitz     assert(bytes_handled <= UINT_MAX);
4702e1990b2SMax Reitz     return bytes_handled;
4714295c5fcSMax Reitz }
4724295c5fcSMax Reitz 
473e5b43573SFam Zheng static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
474e5b43573SFam Zheng {
475138f9fffSMax Reitz     BlockDriverState *source = s->mirror_top_bs->backing->bs;
4761181e19aSMax Reitz     MirrorOp *pseudo_op;
4771181e19aSMax Reitz     int64_t offset;
4781181e19aSMax Reitz     uint64_t delay_ns = 0, ret = 0;
479e5b43573SFam Zheng     /* At least the first dirty chunk is mirrored in one iteration. */
480e5b43573SFam Zheng     int nb_chunks = 1;
4814b5004d9SDenis V. Lunev     bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
482b436982fSEric Blake     int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
483e5b43573SFam Zheng 
484b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_lock(s->dirty_bitmap);
485f798184cSEric Blake     offset = bdrv_dirty_iter_next(s->dbi);
486fb2ef791SEric Blake     if (offset < 0) {
487dc162c8eSFam Zheng         bdrv_set_dirty_iter(s->dbi, 0);
488f798184cSEric Blake         offset = bdrv_dirty_iter_next(s->dbi);
4899a46dba7SEric Blake         trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
490fb2ef791SEric Blake         assert(offset >= 0);
491e5b43573SFam Zheng     }
492b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
493e5b43573SFam Zheng 
494d69a879bSHanna Reitz     /*
495d69a879bSHanna Reitz      * Wait for concurrent requests to @offset.  The next loop will limit the
496d69a879bSHanna Reitz      * copied area based on in_flight_bitmap so we only copy an area that does
497d69a879bSHanna Reitz      * not overlap with concurrent in-flight requests.  Still, we would like to
498d69a879bSHanna Reitz      * copy something, so wait until there are at least no more requests to the
499d69a879bSHanna Reitz      * very beginning of the area.
500d69a879bSHanna Reitz      */
5011181e19aSMax Reitz     mirror_wait_on_conflicts(NULL, s, offset, 1);
5029c83625bSMax Reitz 
503da01ff7fSKevin Wolf     job_pause_point(&s->common.job);
504565ac01fSStefan Hajnoczi 
505e5b43573SFam Zheng     /* Find the number of consective dirty chunks following the first dirty
506e5b43573SFam Zheng      * one, and wait for in flight requests in them. */
507b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_lock(s->dirty_bitmap);
508fb2ef791SEric Blake     while (nb_chunks * s->granularity < s->buf_size) {
509dc162c8eSFam Zheng         int64_t next_dirty;
510fb2ef791SEric Blake         int64_t next_offset = offset + nb_chunks * s->granularity;
511fb2ef791SEric Blake         int64_t next_chunk = next_offset / s->granularity;
512fb2ef791SEric Blake         if (next_offset >= s->bdev_length ||
51328636b82SJohn Snow             !bdrv_dirty_bitmap_get_locked(s->dirty_bitmap, next_offset)) {
514e5b43573SFam Zheng             break;
515e5b43573SFam Zheng         }
516e5b43573SFam Zheng         if (test_bit(next_chunk, s->in_flight_bitmap)) {
517e5b43573SFam Zheng             break;
518e5b43573SFam Zheng         }
5199c83625bSMax Reitz 
520f798184cSEric Blake         next_dirty = bdrv_dirty_iter_next(s->dbi);
521fb2ef791SEric Blake         if (next_dirty > next_offset || next_dirty < 0) {
522f27a2742SMax Reitz             /* The bitmap iterator's cache is stale, refresh it */
523715a74d8SEric Blake             bdrv_set_dirty_iter(s->dbi, next_offset);
524f798184cSEric Blake             next_dirty = bdrv_dirty_iter_next(s->dbi);
525f27a2742SMax Reitz         }
526fb2ef791SEric Blake         assert(next_dirty == next_offset);
527e5b43573SFam Zheng         nb_chunks++;
528e5b43573SFam Zheng     }
529e5b43573SFam Zheng 
530e5b43573SFam Zheng     /* Clear dirty bits before querying the block status, because
53131826642SEric Blake      * calling bdrv_block_status_above could yield - if some blocks are
532e5b43573SFam Zheng      * marked dirty in this window, we need to know.
533e5b43573SFam Zheng      */
534e0d7f73eSEric Blake     bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
535e0d7f73eSEric Blake                                    nb_chunks * s->granularity);
536b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
537b64bd51eSPaolo Bonzini 
5381181e19aSMax Reitz     /* Before claiming an area in the in-flight bitmap, we have to
5391181e19aSMax Reitz      * create a MirrorOp for it so that conflicting requests can wait
5401181e19aSMax Reitz      * for it.  mirror_perform() will create the real MirrorOps later,
5411181e19aSMax Reitz      * for now we just create a pseudo operation that will wake up all
5421181e19aSMax Reitz      * conflicting requests once all real operations have been
5431181e19aSMax Reitz      * launched. */
5441181e19aSMax Reitz     pseudo_op = g_new(MirrorOp, 1);
5451181e19aSMax Reitz     *pseudo_op = (MirrorOp){
5461181e19aSMax Reitz         .offset         = offset,
5471181e19aSMax Reitz         .bytes          = nb_chunks * s->granularity,
5481181e19aSMax Reitz         .is_pseudo_op   = true,
5491181e19aSMax Reitz     };
5501181e19aSMax Reitz     qemu_co_queue_init(&pseudo_op->waiting_requests);
5511181e19aSMax Reitz     QTAILQ_INSERT_TAIL(&s->ops_in_flight, pseudo_op, next);
5521181e19aSMax Reitz 
553fb2ef791SEric Blake     bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
554fb2ef791SEric Blake     while (nb_chunks > 0 && offset < s->bdev_length) {
55531826642SEric Blake         int ret;
5567cfd5275SEric Blake         int64_t io_bytes;
557f3e4ce4aSEric Blake         int64_t io_bytes_acct;
5584295c5fcSMax Reitz         MirrorMethod mirror_method = MIRROR_METHOD_COPY;
559e5b43573SFam Zheng 
560fb2ef791SEric Blake         assert(!(offset % s->granularity));
56131826642SEric Blake         ret = bdrv_block_status_above(source, NULL, offset,
56231826642SEric Blake                                       nb_chunks * s->granularity,
56331826642SEric Blake                                       &io_bytes, NULL, NULL);
564e5b43573SFam Zheng         if (ret < 0) {
565fb2ef791SEric Blake             io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
5660965a41eSVladimir Sementsov-Ogievskiy         } else if (ret & BDRV_BLOCK_DATA) {
567fb2ef791SEric Blake             io_bytes = MIN(io_bytes, max_io_bytes);
568e5b43573SFam Zheng         }
569e5b43573SFam Zheng 
570fb2ef791SEric Blake         io_bytes -= io_bytes % s->granularity;
571fb2ef791SEric Blake         if (io_bytes < s->granularity) {
572fb2ef791SEric Blake             io_bytes = s->granularity;
573e5b43573SFam Zheng         } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
574fb2ef791SEric Blake             int64_t target_offset;
5757cfd5275SEric Blake             int64_t target_bytes;
576fb2ef791SEric Blake             bdrv_round_to_clusters(blk_bs(s->target), offset, io_bytes,
577fb2ef791SEric Blake                                    &target_offset, &target_bytes);
578fb2ef791SEric Blake             if (target_offset == offset &&
579fb2ef791SEric Blake                 target_bytes == io_bytes) {
580e5b43573SFam Zheng                 mirror_method = ret & BDRV_BLOCK_ZERO ?
581e5b43573SFam Zheng                                     MIRROR_METHOD_ZERO :
582e5b43573SFam Zheng                                     MIRROR_METHOD_DISCARD;
583e5b43573SFam Zheng             }
584e5b43573SFam Zheng         }
585e5b43573SFam Zheng 
586cf56a3c6SDenis V. Lunev         while (s->in_flight >= MAX_IN_FLIGHT) {
587fb2ef791SEric Blake             trace_mirror_yield_in_flight(s, offset, s->in_flight);
5889178f4feSKevin Wolf             mirror_wait_for_free_in_flight_slot(s);
589cf56a3c6SDenis V. Lunev         }
590cf56a3c6SDenis V. Lunev 
591dbaa7b57SVladimir Sementsov-Ogievskiy         if (s->ret < 0) {
5921181e19aSMax Reitz             ret = 0;
5931181e19aSMax Reitz             goto fail;
594dbaa7b57SVladimir Sementsov-Ogievskiy         }
595dbaa7b57SVladimir Sementsov-Ogievskiy 
596fb2ef791SEric Blake         io_bytes = mirror_clip_bytes(s, offset, io_bytes);
5974295c5fcSMax Reitz         io_bytes = mirror_perform(s, offset, io_bytes, mirror_method);
5984295c5fcSMax Reitz         if (mirror_method != MIRROR_METHOD_COPY && write_zeroes_ok) {
599f3e4ce4aSEric Blake             io_bytes_acct = 0;
6004b5004d9SDenis V. Lunev         } else {
601fb2ef791SEric Blake             io_bytes_acct = io_bytes;
6024b5004d9SDenis V. Lunev         }
603fb2ef791SEric Blake         assert(io_bytes);
604fb2ef791SEric Blake         offset += io_bytes;
605fb2ef791SEric Blake         nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
606dee81d51SKevin Wolf         delay_ns = block_job_ratelimit_get_delay(&s->common, io_bytes_acct);
607dcfb3bebSFam Zheng     }
6081181e19aSMax Reitz 
6091181e19aSMax Reitz     ret = delay_ns;
6101181e19aSMax Reitz fail:
6111181e19aSMax Reitz     QTAILQ_REMOVE(&s->ops_in_flight, pseudo_op, next);
6121181e19aSMax Reitz     qemu_co_queue_restart_all(&pseudo_op->waiting_requests);
6131181e19aSMax Reitz     g_free(pseudo_op);
6141181e19aSMax Reitz 
6151181e19aSMax Reitz     return ret;
616893f7ebaSPaolo Bonzini }
617b952b558SPaolo Bonzini 
618402a4741SPaolo Bonzini static void mirror_free_init(MirrorBlockJob *s)
619402a4741SPaolo Bonzini {
620402a4741SPaolo Bonzini     int granularity = s->granularity;
621402a4741SPaolo Bonzini     size_t buf_size = s->buf_size;
622402a4741SPaolo Bonzini     uint8_t *buf = s->buf;
623402a4741SPaolo Bonzini 
624402a4741SPaolo Bonzini     assert(s->buf_free_count == 0);
625402a4741SPaolo Bonzini     QSIMPLEQ_INIT(&s->buf_free);
626402a4741SPaolo Bonzini     while (buf_size != 0) {
627402a4741SPaolo Bonzini         MirrorBuffer *cur = (MirrorBuffer *)buf;
628402a4741SPaolo Bonzini         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
629402a4741SPaolo Bonzini         s->buf_free_count++;
630402a4741SPaolo Bonzini         buf_size -= granularity;
631402a4741SPaolo Bonzini         buf += granularity;
632402a4741SPaolo Bonzini     }
633402a4741SPaolo Bonzini }
634402a4741SPaolo Bonzini 
635bae8196dSPaolo Bonzini /* This is also used for the .pause callback. There is no matching
636bae8196dSPaolo Bonzini  * mirror_resume() because mirror_run() will begin iterating again
637bae8196dSPaolo Bonzini  * when the job is resumed.
638bae8196dSPaolo Bonzini  */
639537c3d4fSStefan Hajnoczi static void coroutine_fn mirror_wait_for_all_io(MirrorBlockJob *s)
640bd48bde8SPaolo Bonzini {
641bd48bde8SPaolo Bonzini     while (s->in_flight > 0) {
6429178f4feSKevin Wolf         mirror_wait_for_free_in_flight_slot(s);
643bd48bde8SPaolo Bonzini     }
644893f7ebaSPaolo Bonzini }
645893f7ebaSPaolo Bonzini 
646737efc1eSJohn Snow /**
647737efc1eSJohn Snow  * mirror_exit_common: handle both abort() and prepare() cases.
648737efc1eSJohn Snow  * for .prepare, returns 0 on success and -errno on failure.
649737efc1eSJohn Snow  * for .abort cases, denoted by abort = true, MUST return 0.
650737efc1eSJohn Snow  */
651737efc1eSJohn Snow static int mirror_exit_common(Job *job)
6525a7e7a0bSStefan Hajnoczi {
6531908a559SKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
6541908a559SKevin Wolf     BlockJob *bjob = &s->common;
655f93c3addSMax Reitz     MirrorBDSOpaque *bs_opaque;
6565a7e7a0bSStefan Hajnoczi     AioContext *replace_aio_context = NULL;
657f93c3addSMax Reitz     BlockDriverState *src;
658f93c3addSMax Reitz     BlockDriverState *target_bs;
659f93c3addSMax Reitz     BlockDriverState *mirror_top_bs;
66012fa4af6SKevin Wolf     Error *local_err = NULL;
661737efc1eSJohn Snow     bool abort = job->ret < 0;
662737efc1eSJohn Snow     int ret = 0;
663737efc1eSJohn Snow 
664737efc1eSJohn Snow     if (s->prepared) {
665737efc1eSJohn Snow         return 0;
666737efc1eSJohn Snow     }
667737efc1eSJohn Snow     s->prepared = true;
6683f09bfbcSKevin Wolf 
669f93c3addSMax Reitz     mirror_top_bs = s->mirror_top_bs;
670f93c3addSMax Reitz     bs_opaque = mirror_top_bs->opaque;
671f93c3addSMax Reitz     src = mirror_top_bs->backing->bs;
672f93c3addSMax Reitz     target_bs = blk_bs(s->target);
673f93c3addSMax Reitz 
674ef53dc09SAlberto Garcia     if (bdrv_chain_contains(src, target_bs)) {
675ef53dc09SAlberto Garcia         bdrv_unfreeze_backing_chain(mirror_top_bs, target_bs);
676ef53dc09SAlberto Garcia     }
677ef53dc09SAlberto Garcia 
6785deb6cbdSVladimir Sementsov-Ogievskiy     bdrv_release_dirty_bitmap(s->dirty_bitmap);
6792119882cSPaolo Bonzini 
6807b508f6bSJohn Snow     /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
6817b508f6bSJohn Snow      * before we can call bdrv_drained_end */
6823f09bfbcSKevin Wolf     bdrv_ref(src);
6834ef85a9cSKevin Wolf     bdrv_ref(mirror_top_bs);
6847d9fcb39SKevin Wolf     bdrv_ref(target_bs);
6857d9fcb39SKevin Wolf 
686bb0c9409SVladimir Sementsov-Ogievskiy     /*
687bb0c9409SVladimir Sementsov-Ogievskiy      * Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
6887d9fcb39SKevin Wolf      * inserting target_bs at s->to_replace, where we might not be able to get
68963c8ef28SKevin Wolf      * these permissions.
690bb0c9409SVladimir Sementsov-Ogievskiy      */
6917d9fcb39SKevin Wolf     blk_unref(s->target);
6927d9fcb39SKevin Wolf     s->target = NULL;
6934ef85a9cSKevin Wolf 
6944ef85a9cSKevin Wolf     /* We don't access the source any more. Dropping any WRITE/RESIZE is
695d2da5e28SKevin Wolf      * required before it could become a backing file of target_bs. Not having
696d2da5e28SKevin Wolf      * these permissions any more means that we can't allow any new requests on
697d2da5e28SKevin Wolf      * mirror_top_bs from now on, so keep it drained. */
698d2da5e28SKevin Wolf     bdrv_drained_begin(mirror_top_bs);
699f94dc3b4SMax Reitz     bs_opaque->stop = true;
700f94dc3b4SMax Reitz     bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
7014ef85a9cSKevin Wolf                              &error_abort);
702737efc1eSJohn Snow     if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
7034ef85a9cSKevin Wolf         BlockDriverState *backing = s->is_none_mode ? src : s->base;
7043f072a7fSMax Reitz         BlockDriverState *unfiltered_target = bdrv_skip_filters(target_bs);
7053f072a7fSMax Reitz 
7063f072a7fSMax Reitz         if (bdrv_cow_bs(unfiltered_target) != backing) {
7073f072a7fSMax Reitz             bdrv_set_backing_hd(unfiltered_target, backing, &local_err);
70812fa4af6SKevin Wolf             if (local_err) {
70912fa4af6SKevin Wolf                 error_report_err(local_err);
71066c8672dSVladimir Sementsov-Ogievskiy                 local_err = NULL;
7117b508f6bSJohn Snow                 ret = -EPERM;
71212fa4af6SKevin Wolf             }
7134ef85a9cSKevin Wolf         }
714c41f5b96SMax Reitz     } else if (!abort && s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
715c41f5b96SMax Reitz         assert(!bdrv_backing_chain_next(target_bs));
716c41f5b96SMax Reitz         ret = bdrv_open_backing_file(bdrv_skip_filters(target_bs), NULL,
717c41f5b96SMax Reitz                                      "backing", &local_err);
718c41f5b96SMax Reitz         if (ret < 0) {
719c41f5b96SMax Reitz             error_report_err(local_err);
720c41f5b96SMax Reitz             local_err = NULL;
721c41f5b96SMax Reitz         }
7224ef85a9cSKevin Wolf     }
7235a7e7a0bSStefan Hajnoczi 
7245a7e7a0bSStefan Hajnoczi     if (s->to_replace) {
7255a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(s->to_replace);
7265a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
7275a7e7a0bSStefan Hajnoczi     }
7285a7e7a0bSStefan Hajnoczi 
729737efc1eSJohn Snow     if (s->should_complete && !abort) {
730737efc1eSJohn Snow         BlockDriverState *to_replace = s->to_replace ?: src;
7311ba79388SAlberto Garcia         bool ro = bdrv_is_read_only(to_replace);
73240365552SKevin Wolf 
7331ba79388SAlberto Garcia         if (ro != bdrv_is_read_only(target_bs)) {
7341ba79388SAlberto Garcia             bdrv_reopen_set_read_only(target_bs, ro, NULL);
7355a7e7a0bSStefan Hajnoczi         }
736b8804815SKevin Wolf 
737b8804815SKevin Wolf         /* The mirror job has no requests in flight any more, but we need to
738b8804815SKevin Wolf          * drain potential other users of the BDS before changing the graph. */
7395e771752SSergio Lopez         assert(s->in_drain);
740e253f4b8SKevin Wolf         bdrv_drained_begin(target_bs);
7416e9cc051SMax Reitz         /*
7426e9cc051SMax Reitz          * Cannot use check_to_replace_node() here, because that would
7436e9cc051SMax Reitz          * check for an op blocker on @to_replace, and we have our own
7446e9cc051SMax Reitz          * there.
7456e9cc051SMax Reitz          */
7466e9cc051SMax Reitz         if (bdrv_recurse_can_replace(src, to_replace)) {
7475fe31c25SKevin Wolf             bdrv_replace_node(to_replace, target_bs, &local_err);
7486e9cc051SMax Reitz         } else {
7496e9cc051SMax Reitz             error_setg(&local_err, "Can no longer replace '%s' by '%s', "
7506e9cc051SMax Reitz                        "because it can no longer be guaranteed that doing so "
7516e9cc051SMax Reitz                        "would not lead to an abrupt change of visible data",
7526e9cc051SMax Reitz                        to_replace->node_name, target_bs->node_name);
7536e9cc051SMax Reitz         }
754e253f4b8SKevin Wolf         bdrv_drained_end(target_bs);
7555fe31c25SKevin Wolf         if (local_err) {
7565fe31c25SKevin Wolf             error_report_err(local_err);
7577b508f6bSJohn Snow             ret = -EPERM;
7585fe31c25SKevin Wolf         }
7595a7e7a0bSStefan Hajnoczi     }
7605a7e7a0bSStefan Hajnoczi     if (s->to_replace) {
7615a7e7a0bSStefan Hajnoczi         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
7625a7e7a0bSStefan Hajnoczi         error_free(s->replace_blocker);
7635a7e7a0bSStefan Hajnoczi         bdrv_unref(s->to_replace);
7645a7e7a0bSStefan Hajnoczi     }
7655a7e7a0bSStefan Hajnoczi     if (replace_aio_context) {
7665a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
7675a7e7a0bSStefan Hajnoczi     }
7685a7e7a0bSStefan Hajnoczi     g_free(s->replaces);
7697d9fcb39SKevin Wolf     bdrv_unref(target_bs);
7704ef85a9cSKevin Wolf 
771f94dc3b4SMax Reitz     /*
772f94dc3b4SMax Reitz      * Remove the mirror filter driver from the graph. Before this, get rid of
7734ef85a9cSKevin Wolf      * the blockers on the intermediate nodes so that the resulting state is
774f94dc3b4SMax Reitz      * valid.
775f94dc3b4SMax Reitz      */
7761908a559SKevin Wolf     block_job_remove_all_bdrv(bjob);
7773f072a7fSMax Reitz     bdrv_replace_node(mirror_top_bs, mirror_top_bs->backing->bs, &error_abort);
7784ef85a9cSKevin Wolf 
779429076e8SMax Reitz     bs_opaque->job = NULL;
7804ef85a9cSKevin Wolf 
781176c3699SFam Zheng     bdrv_drained_end(src);
782d2da5e28SKevin Wolf     bdrv_drained_end(mirror_top_bs);
7835e771752SSergio Lopez     s->in_drain = false;
7844ef85a9cSKevin Wolf     bdrv_unref(mirror_top_bs);
7853f09bfbcSKevin Wolf     bdrv_unref(src);
7867b508f6bSJohn Snow 
787737efc1eSJohn Snow     return ret;
788737efc1eSJohn Snow }
789737efc1eSJohn Snow 
790737efc1eSJohn Snow static int mirror_prepare(Job *job)
791737efc1eSJohn Snow {
792737efc1eSJohn Snow     return mirror_exit_common(job);
793737efc1eSJohn Snow }
794737efc1eSJohn Snow 
795737efc1eSJohn Snow static void mirror_abort(Job *job)
796737efc1eSJohn Snow {
797737efc1eSJohn Snow     int ret = mirror_exit_common(job);
798737efc1eSJohn Snow     assert(ret == 0);
7995a7e7a0bSStefan Hajnoczi }
8005a7e7a0bSStefan Hajnoczi 
801537c3d4fSStefan Hajnoczi static void coroutine_fn mirror_throttle(MirrorBlockJob *s)
80249efb1f5SDenis V. Lunev {
80349efb1f5SDenis V. Lunev     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
80449efb1f5SDenis V. Lunev 
80518bb6928SKevin Wolf     if (now - s->last_pause_ns > BLOCK_JOB_SLICE_TIME) {
80649efb1f5SDenis V. Lunev         s->last_pause_ns = now;
8075d43e86eSKevin Wolf         job_sleep_ns(&s->common.job, 0);
80849efb1f5SDenis V. Lunev     } else {
809da01ff7fSKevin Wolf         job_pause_point(&s->common.job);
81049efb1f5SDenis V. Lunev     }
81149efb1f5SDenis V. Lunev }
81249efb1f5SDenis V. Lunev 
813c0b363adSDenis V. Lunev static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
814c0b363adSDenis V. Lunev {
81523ca459aSEric Blake     int64_t offset;
816138f9fffSMax Reitz     BlockDriverState *bs = s->mirror_top_bs->backing->bs;
817c0b363adSDenis V. Lunev     BlockDriverState *target_bs = blk_bs(s->target);
81823ca459aSEric Blake     int ret;
81951b0a488SEric Blake     int64_t count;
820c0b363adSDenis V. Lunev 
821cdf3bc93SMax Reitz     if (s->zero_target) {
822c7c2769cSDenis V. Lunev         if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
823e0d7f73eSEric Blake             bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
824b7d5062cSDenis V. Lunev             return 0;
825b7d5062cSDenis V. Lunev         }
826b7d5062cSDenis V. Lunev 
82790ab48ebSAnton Nefedov         s->initial_zeroing_ongoing = true;
82823ca459aSEric Blake         for (offset = 0; offset < s->bdev_length; ) {
82923ca459aSEric Blake             int bytes = MIN(s->bdev_length - offset,
83023ca459aSEric Blake                             QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
831c7c2769cSDenis V. Lunev 
832c7c2769cSDenis V. Lunev             mirror_throttle(s);
833c7c2769cSDenis V. Lunev 
834daa7f2f9SKevin Wolf             if (job_is_cancelled(&s->common.job)) {
83590ab48ebSAnton Nefedov                 s->initial_zeroing_ongoing = false;
836c7c2769cSDenis V. Lunev                 return 0;
837c7c2769cSDenis V. Lunev             }
838c7c2769cSDenis V. Lunev 
839c7c2769cSDenis V. Lunev             if (s->in_flight >= MAX_IN_FLIGHT) {
84067adf4b3SEric Blake                 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
84167adf4b3SEric Blake                                    s->in_flight);
8429178f4feSKevin Wolf                 mirror_wait_for_free_in_flight_slot(s);
843c7c2769cSDenis V. Lunev                 continue;
844c7c2769cSDenis V. Lunev             }
845c7c2769cSDenis V. Lunev 
8464295c5fcSMax Reitz             mirror_perform(s, offset, bytes, MIRROR_METHOD_ZERO);
84723ca459aSEric Blake             offset += bytes;
848c7c2769cSDenis V. Lunev         }
849c7c2769cSDenis V. Lunev 
850bae8196dSPaolo Bonzini         mirror_wait_for_all_io(s);
85190ab48ebSAnton Nefedov         s->initial_zeroing_ongoing = false;
852c7c2769cSDenis V. Lunev     }
853c7c2769cSDenis V. Lunev 
854c0b363adSDenis V. Lunev     /* First part, loop on the sectors and initialize the dirty bitmap.  */
85523ca459aSEric Blake     for (offset = 0; offset < s->bdev_length; ) {
856c0b363adSDenis V. Lunev         /* Just to make sure we are not exceeding int limit. */
85723ca459aSEric Blake         int bytes = MIN(s->bdev_length - offset,
85823ca459aSEric Blake                         QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
859c0b363adSDenis V. Lunev 
860c0b363adSDenis V. Lunev         mirror_throttle(s);
861c0b363adSDenis V. Lunev 
862daa7f2f9SKevin Wolf         if (job_is_cancelled(&s->common.job)) {
863c0b363adSDenis V. Lunev             return 0;
864c0b363adSDenis V. Lunev         }
865c0b363adSDenis V. Lunev 
8663f072a7fSMax Reitz         ret = bdrv_is_allocated_above(bs, s->base_overlay, true, offset, bytes,
8673f072a7fSMax Reitz                                       &count);
868c0b363adSDenis V. Lunev         if (ret < 0) {
869c0b363adSDenis V. Lunev             return ret;
870c0b363adSDenis V. Lunev         }
871c0b363adSDenis V. Lunev 
87223ca459aSEric Blake         assert(count);
873a92b1b06SEric Blake         if (ret > 0) {
87423ca459aSEric Blake             bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
875c0b363adSDenis V. Lunev         }
87623ca459aSEric Blake         offset += count;
877c0b363adSDenis V. Lunev     }
878c0b363adSDenis V. Lunev     return 0;
879c0b363adSDenis V. Lunev }
880c0b363adSDenis V. Lunev 
881bdffb31dSPaolo Bonzini /* Called when going out of the streaming phase to flush the bulk of the
882bdffb31dSPaolo Bonzini  * data to the medium, or just before completing.
883bdffb31dSPaolo Bonzini  */
884bdffb31dSPaolo Bonzini static int mirror_flush(MirrorBlockJob *s)
885bdffb31dSPaolo Bonzini {
886bdffb31dSPaolo Bonzini     int ret = blk_flush(s->target);
887bdffb31dSPaolo Bonzini     if (ret < 0) {
888bdffb31dSPaolo Bonzini         if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
889bdffb31dSPaolo Bonzini             s->ret = ret;
890bdffb31dSPaolo Bonzini         }
891bdffb31dSPaolo Bonzini     }
892bdffb31dSPaolo Bonzini     return ret;
893bdffb31dSPaolo Bonzini }
894bdffb31dSPaolo Bonzini 
895f67432a2SJohn Snow static int coroutine_fn mirror_run(Job *job, Error **errp)
896893f7ebaSPaolo Bonzini {
897f67432a2SJohn Snow     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
898138f9fffSMax Reitz     BlockDriverState *bs = s->mirror_top_bs->backing->bs;
899e253f4b8SKevin Wolf     BlockDriverState *target_bs = blk_bs(s->target);
9009a0cec66SPaolo Bonzini     bool need_drain = true;
901d59cb66dSEmanuele Giuseppe Esposito     BlockDeviceIoStatus iostatus;
902c0b363adSDenis V. Lunev     int64_t length;
903e83dd680SKevin Wolf     int64_t target_length;
904b812f671SPaolo Bonzini     BlockDriverInfo bdi;
9051d33936eSJeff Cody     char backing_filename[2]; /* we only need 2 characters because we are only
9061d33936eSJeff Cody                                  checking for a NULL string */
907893f7ebaSPaolo Bonzini     int ret = 0;
908893f7ebaSPaolo Bonzini 
909daa7f2f9SKevin Wolf     if (job_is_cancelled(&s->common.job)) {
910893f7ebaSPaolo Bonzini         goto immediate_exit;
911893f7ebaSPaolo Bonzini     }
912893f7ebaSPaolo Bonzini 
913c86422c5SEmanuele Giuseppe Esposito     s->bdev_length = bdrv_co_getlength(bs);
914b21c7652SMax Reitz     if (s->bdev_length < 0) {
915b21c7652SMax Reitz         ret = s->bdev_length;
916373df5b1SFam Zheng         goto immediate_exit;
917becc347eSKevin Wolf     }
918becc347eSKevin Wolf 
919c86422c5SEmanuele Giuseppe Esposito     target_length = blk_co_getlength(s->target);
920e83dd680SKevin Wolf     if (target_length < 0) {
921e83dd680SKevin Wolf         ret = target_length;
922becc347eSKevin Wolf         goto immediate_exit;
923becc347eSKevin Wolf     }
924becc347eSKevin Wolf 
925e83dd680SKevin Wolf     /* Active commit must resize the base image if its size differs from the
926e83dd680SKevin Wolf      * active layer. */
927e83dd680SKevin Wolf     if (s->base == blk_bs(s->target)) {
928e83dd680SKevin Wolf         if (s->bdev_length > target_length) {
92988276216SAlberto Faria             ret = blk_co_truncate(s->target, s->bdev_length, false,
9308c6242b6SKevin Wolf                                   PREALLOC_MODE_OFF, 0, NULL);
931becc347eSKevin Wolf             if (ret < 0) {
932becc347eSKevin Wolf                 goto immediate_exit;
933becc347eSKevin Wolf             }
934becc347eSKevin Wolf         }
935e83dd680SKevin Wolf     } else if (s->bdev_length != target_length) {
936e83dd680SKevin Wolf         error_setg(errp, "Source and target image have different sizes");
937e83dd680SKevin Wolf         ret = -EINVAL;
938e83dd680SKevin Wolf         goto immediate_exit;
939becc347eSKevin Wolf     }
940becc347eSKevin Wolf 
941becc347eSKevin Wolf     if (s->bdev_length == 0) {
9422e1795b5SKevin Wolf         /* Transition to the READY state and wait for complete. */
9432e1795b5SKevin Wolf         job_transition_to_ready(&s->common.job);
944d06107adSMax Reitz         s->actively_synced = true;
94508b83bffSHanna Reitz         while (!job_cancel_requested(&s->common.job) && !s->should_complete) {
946198c49ccSKevin Wolf             job_yield(&s->common.job);
9479e48b025SFam Zheng         }
9489e48b025SFam Zheng         goto immediate_exit;
949893f7ebaSPaolo Bonzini     }
950893f7ebaSPaolo Bonzini 
951b21c7652SMax Reitz     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
952402a4741SPaolo Bonzini     s->in_flight_bitmap = bitmap_new(length);
953402a4741SPaolo Bonzini 
954b812f671SPaolo Bonzini     /* If we have no backing file yet in the destination, we cannot let
955b812f671SPaolo Bonzini      * the destination do COW.  Instead, we copy sectors around the
956b812f671SPaolo Bonzini      * dirty data if needed.  We need a bitmap to do that.
957b812f671SPaolo Bonzini      */
958e253f4b8SKevin Wolf     bdrv_get_backing_filename(target_bs, backing_filename,
959b812f671SPaolo Bonzini                               sizeof(backing_filename));
960*3d47eb0aSEmanuele Giuseppe Esposito     if (!bdrv_co_get_info(target_bs, &bdi) && bdi.cluster_size) {
961b436982fSEric Blake         s->target_cluster_size = bdi.cluster_size;
962b436982fSEric Blake     } else {
963b436982fSEric Blake         s->target_cluster_size = BDRV_SECTOR_SIZE;
964c3cc95bdSFam Zheng     }
9653f072a7fSMax Reitz     if (backing_filename[0] && !bdrv_backing_chain_next(target_bs) &&
966b436982fSEric Blake         s->granularity < s->target_cluster_size) {
967b436982fSEric Blake         s->buf_size = MAX(s->buf_size, s->target_cluster_size);
968b812f671SPaolo Bonzini         s->cow_bitmap = bitmap_new(length);
969b812f671SPaolo Bonzini     }
970e253f4b8SKevin Wolf     s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
971b812f671SPaolo Bonzini 
9727504edf4SKevin Wolf     s->buf = qemu_try_blockalign(bs, s->buf_size);
9737504edf4SKevin Wolf     if (s->buf == NULL) {
9747504edf4SKevin Wolf         ret = -ENOMEM;
9757504edf4SKevin Wolf         goto immediate_exit;
9767504edf4SKevin Wolf     }
9777504edf4SKevin Wolf 
978402a4741SPaolo Bonzini     mirror_free_init(s);
979893f7ebaSPaolo Bonzini 
98049efb1f5SDenis V. Lunev     s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
98103544a6eSFam Zheng     if (!s->is_none_mode) {
982c0b363adSDenis V. Lunev         ret = mirror_dirty_init(s);
983daa7f2f9SKevin Wolf         if (ret < 0 || job_is_cancelled(&s->common.job)) {
9844c0cbd6fSFam Zheng             goto immediate_exit;
9854c0cbd6fSFam Zheng         }
986893f7ebaSPaolo Bonzini     }
987893f7ebaSPaolo Bonzini 
988dc162c8eSFam Zheng     assert(!s->dbi);
989715a74d8SEric Blake     s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
990893f7ebaSPaolo Bonzini     for (;;) {
991cc8c9d6cSPaolo Bonzini         uint64_t delay_ns = 0;
99249efb1f5SDenis V. Lunev         int64_t cnt, delta;
993893f7ebaSPaolo Bonzini         bool should_complete;
994893f7ebaSPaolo Bonzini 
995bd48bde8SPaolo Bonzini         if (s->ret < 0) {
996bd48bde8SPaolo Bonzini             ret = s->ret;
997893f7ebaSPaolo Bonzini             goto immediate_exit;
998893f7ebaSPaolo Bonzini         }
999bd48bde8SPaolo Bonzini 
1000da01ff7fSKevin Wolf         job_pause_point(&s->common.job);
1001565ac01fSStefan Hajnoczi 
10024feeec7eSHanna Reitz         if (job_is_cancelled(&s->common.job)) {
10034feeec7eSHanna Reitz             ret = 0;
10044feeec7eSHanna Reitz             goto immediate_exit;
10054feeec7eSHanna Reitz         }
10064feeec7eSHanna Reitz 
100720dca810SJohn Snow         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
100805df8a6aSKevin Wolf         /* cnt is the number of dirty bytes remaining and s->bytes_in_flight is
100905df8a6aSKevin Wolf          * the number of bytes currently being processed; together those are
101005df8a6aSKevin Wolf          * the current remaining operation length */
1011d69a879bSHanna Reitz         job_progress_set_remaining(&s->common.job,
1012d69a879bSHanna Reitz                                    s->bytes_in_flight + cnt +
1013d69a879bSHanna Reitz                                    s->active_write_bytes_in_flight);
1014bd48bde8SPaolo Bonzini 
1015bd48bde8SPaolo Bonzini         /* Note that even when no rate limit is applied we need to yield
1016a7282330SFam Zheng          * periodically with no pending I/O so that bdrv_drain_all() returns.
101718bb6928SKevin Wolf          * We do so every BLKOCK_JOB_SLICE_TIME nanoseconds, or when there is
101818bb6928SKevin Wolf          * an error, or when the source is clean, whichever comes first. */
101949efb1f5SDenis V. Lunev         delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
1020d59cb66dSEmanuele Giuseppe Esposito         WITH_JOB_LOCK_GUARD() {
1021d59cb66dSEmanuele Giuseppe Esposito             iostatus = s->common.iostatus;
1022d59cb66dSEmanuele Giuseppe Esposito         }
102318bb6928SKevin Wolf         if (delta < BLOCK_JOB_SLICE_TIME &&
1024d59cb66dSEmanuele Giuseppe Esposito             iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
1025cf56a3c6SDenis V. Lunev             if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
1026402a4741SPaolo Bonzini                 (cnt == 0 && s->in_flight > 0)) {
10279a46dba7SEric Blake                 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
10289178f4feSKevin Wolf                 mirror_wait_for_free_in_flight_slot(s);
1029bd48bde8SPaolo Bonzini                 continue;
1030bd48bde8SPaolo Bonzini             } else if (cnt != 0) {
1031cc8c9d6cSPaolo Bonzini                 delay_ns = mirror_iteration(s);
1032893f7ebaSPaolo Bonzini             }
1033cc8c9d6cSPaolo Bonzini         }
1034893f7ebaSPaolo Bonzini 
1035893f7ebaSPaolo Bonzini         should_complete = false;
1036bd48bde8SPaolo Bonzini         if (s->in_flight == 0 && cnt == 0) {
1037893f7ebaSPaolo Bonzini             trace_mirror_before_flush(s);
103844716224SHanna Reitz             if (!job_is_ready(&s->common.job)) {
1039bdffb31dSPaolo Bonzini                 if (mirror_flush(s) < 0) {
1040bdffb31dSPaolo Bonzini                     /* Go check s->ret.  */
1041bdffb31dSPaolo Bonzini                     continue;
1042893f7ebaSPaolo Bonzini                 }
1043893f7ebaSPaolo Bonzini                 /* We're out of the streaming phase.  From now on, if the job
1044893f7ebaSPaolo Bonzini                  * is cancelled we will actually complete all pending I/O and
1045893f7ebaSPaolo Bonzini                  * report completion.  This way, block-job-cancel will leave
1046893f7ebaSPaolo Bonzini                  * the target in a consistent state.
1047893f7ebaSPaolo Bonzini                  */
10482e1795b5SKevin Wolf                 job_transition_to_ready(&s->common.job);
1049d06107adSMax Reitz                 if (s->copy_mode != MIRROR_COPY_MODE_BACKGROUND) {
1050d06107adSMax Reitz                     s->actively_synced = true;
1051d06107adSMax Reitz                 }
1052d63ffd87SPaolo Bonzini             }
1053d63ffd87SPaolo Bonzini 
1054d63ffd87SPaolo Bonzini             should_complete = s->should_complete ||
105508b83bffSHanna Reitz                 job_cancel_requested(&s->common.job);
105620dca810SJohn Snow             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1057893f7ebaSPaolo Bonzini         }
1058893f7ebaSPaolo Bonzini 
1059893f7ebaSPaolo Bonzini         if (cnt == 0 && should_complete) {
1060893f7ebaSPaolo Bonzini             /* The dirty bitmap is not updated while operations are pending.
1061893f7ebaSPaolo Bonzini              * If we're about to exit, wait for pending operations before
1062893f7ebaSPaolo Bonzini              * calling bdrv_get_dirty_count(bs), or we may exit while the
1063893f7ebaSPaolo Bonzini              * source has dirty data to copy!
1064893f7ebaSPaolo Bonzini              *
1065893f7ebaSPaolo Bonzini              * Note that I/O can be submitted by the guest while
10669a0cec66SPaolo Bonzini              * mirror_populate runs, so pause it now.  Before deciding
10679a0cec66SPaolo Bonzini              * whether to switch to target check one last time if I/O has
10689a0cec66SPaolo Bonzini              * come in the meanwhile, and if not flush the data to disk.
1069893f7ebaSPaolo Bonzini              */
10709a46dba7SEric Blake             trace_mirror_before_drain(s, cnt);
10719a0cec66SPaolo Bonzini 
10725e771752SSergio Lopez             s->in_drain = true;
10739a0cec66SPaolo Bonzini             bdrv_drained_begin(bs);
1074d69a879bSHanna Reitz 
1075d69a879bSHanna Reitz             /* Must be zero because we are drained */
1076d69a879bSHanna Reitz             assert(s->in_active_write_counter == 0);
1077d69a879bSHanna Reitz 
107820dca810SJohn Snow             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1079bdffb31dSPaolo Bonzini             if (cnt > 0 || mirror_flush(s) < 0) {
10809a0cec66SPaolo Bonzini                 bdrv_drained_end(bs);
10815e771752SSergio Lopez                 s->in_drain = false;
10829a0cec66SPaolo Bonzini                 continue;
10839a0cec66SPaolo Bonzini             }
10849a0cec66SPaolo Bonzini 
10859a0cec66SPaolo Bonzini             /* The two disks are in sync.  Exit and report successful
10869a0cec66SPaolo Bonzini              * completion.
10879a0cec66SPaolo Bonzini              */
10889a0cec66SPaolo Bonzini             assert(QLIST_EMPTY(&bs->tracked_requests));
10899a0cec66SPaolo Bonzini             need_drain = false;
10909a0cec66SPaolo Bonzini             break;
1091893f7ebaSPaolo Bonzini         }
1092893f7ebaSPaolo Bonzini 
109344716224SHanna Reitz         if (job_is_ready(&s->common.job) && !should_complete) {
109418bb6928SKevin Wolf             delay_ns = (s->in_flight == 0 &&
109518bb6928SKevin Wolf                         cnt == 0 ? BLOCK_JOB_SLICE_TIME : 0);
1096ddc4115eSStefan Hajnoczi         }
109744716224SHanna Reitz         trace_mirror_before_sleep(s, cnt, job_is_ready(&s->common.job),
109844716224SHanna Reitz                                   delay_ns);
10995d43e86eSKevin Wolf         job_sleep_ns(&s->common.job, delay_ns);
110049efb1f5SDenis V. Lunev         s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1101893f7ebaSPaolo Bonzini     }
1102893f7ebaSPaolo Bonzini 
1103893f7ebaSPaolo Bonzini immediate_exit:
1104bd48bde8SPaolo Bonzini     if (s->in_flight > 0) {
1105bd48bde8SPaolo Bonzini         /* We get here only if something went wrong.  Either the job failed,
1106bd48bde8SPaolo Bonzini          * or it was cancelled prematurely so that we do not guarantee that
1107bd48bde8SPaolo Bonzini          * the target is a copy of the source.
1108bd48bde8SPaolo Bonzini          */
110908b83bffSHanna Reitz         assert(ret < 0 || job_is_cancelled(&s->common.job));
11109a0cec66SPaolo Bonzini         assert(need_drain);
1111bae8196dSPaolo Bonzini         mirror_wait_for_all_io(s);
1112bd48bde8SPaolo Bonzini     }
1113bd48bde8SPaolo Bonzini 
1114bd48bde8SPaolo Bonzini     assert(s->in_flight == 0);
11157191bf31SMarkus Armbruster     qemu_vfree(s->buf);
1116b812f671SPaolo Bonzini     g_free(s->cow_bitmap);
1117402a4741SPaolo Bonzini     g_free(s->in_flight_bitmap);
1118dc162c8eSFam Zheng     bdrv_dirty_iter_free(s->dbi);
11195a7e7a0bSStefan Hajnoczi 
11209a0cec66SPaolo Bonzini     if (need_drain) {
11215e771752SSergio Lopez         s->in_drain = true;
1122e253f4b8SKevin Wolf         bdrv_drained_begin(bs);
11239a0cec66SPaolo Bonzini     }
1124f67432a2SJohn Snow 
1125f67432a2SJohn Snow     return ret;
1126893f7ebaSPaolo Bonzini }
1127893f7ebaSPaolo Bonzini 
11283453d972SKevin Wolf static void mirror_complete(Job *job, Error **errp)
1129d63ffd87SPaolo Bonzini {
11303453d972SKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1131274fcceeSMax Reitz 
113244716224SHanna Reitz     if (!job_is_ready(job)) {
11339df229c3SAlberto Garcia         error_setg(errp, "The active block job '%s' cannot be completed",
11343453d972SKevin Wolf                    job->id);
1135d63ffd87SPaolo Bonzini         return;
1136d63ffd87SPaolo Bonzini     }
1137d63ffd87SPaolo Bonzini 
113815d67298SChanglong Xie     /* block all operations on to_replace bs */
113909158f00SBenoît Canet     if (s->replaces) {
11405a7e7a0bSStefan Hajnoczi         AioContext *replace_aio_context;
11415a7e7a0bSStefan Hajnoczi 
1142e12f3784SWen Congyang         s->to_replace = bdrv_find_node(s->replaces);
114309158f00SBenoît Canet         if (!s->to_replace) {
1144e12f3784SWen Congyang             error_setg(errp, "Node name '%s' not found", s->replaces);
114509158f00SBenoît Canet             return;
114609158f00SBenoît Canet         }
114709158f00SBenoît Canet 
11485a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(s->to_replace);
11495a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
11505a7e7a0bSStefan Hajnoczi 
115164631f36SVladimir Sementsov-Ogievskiy         /* TODO Translate this into child freeze system. */
115209158f00SBenoît Canet         error_setg(&s->replace_blocker,
115309158f00SBenoît Canet                    "block device is in use by block-job-complete");
115409158f00SBenoît Canet         bdrv_op_block_all(s->to_replace, s->replace_blocker);
115509158f00SBenoît Canet         bdrv_ref(s->to_replace);
11565a7e7a0bSStefan Hajnoczi 
11575a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
115809158f00SBenoît Canet     }
115909158f00SBenoît Canet 
1160d63ffd87SPaolo Bonzini     s->should_complete = true;
116100769414SMax Reitz 
116200769414SMax Reitz     /* If the job is paused, it will be re-entered when it is resumed */
1163279ac06eSEmanuele Giuseppe Esposito     WITH_JOB_LOCK_GUARD() {
116400769414SMax Reitz         if (!job->paused) {
1165279ac06eSEmanuele Giuseppe Esposito             job_enter_cond_locked(job, NULL);
1166279ac06eSEmanuele Giuseppe Esposito         }
1167d63ffd87SPaolo Bonzini     }
116800769414SMax Reitz }
1169d63ffd87SPaolo Bonzini 
1170537c3d4fSStefan Hajnoczi static void coroutine_fn mirror_pause(Job *job)
1171565ac01fSStefan Hajnoczi {
1172da01ff7fSKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1173565ac01fSStefan Hajnoczi 
1174bae8196dSPaolo Bonzini     mirror_wait_for_all_io(s);
1175565ac01fSStefan Hajnoczi }
1176565ac01fSStefan Hajnoczi 
117789bd0305SKevin Wolf static bool mirror_drained_poll(BlockJob *job)
117889bd0305SKevin Wolf {
117989bd0305SKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
11805e771752SSergio Lopez 
11815e771752SSergio Lopez     /* If the job isn't paused nor cancelled, we can't be sure that it won't
11825e771752SSergio Lopez      * issue more requests. We make an exception if we've reached this point
11835e771752SSergio Lopez      * from one of our own drain sections, to avoid a deadlock waiting for
11845e771752SSergio Lopez      * ourselves.
11855e771752SSergio Lopez      */
1186279ac06eSEmanuele Giuseppe Esposito     WITH_JOB_LOCK_GUARD() {
1187279ac06eSEmanuele Giuseppe Esposito         if (!s->common.job.paused && !job_is_cancelled_locked(&job->job)
1188279ac06eSEmanuele Giuseppe Esposito             && !s->in_drain) {
11895e771752SSergio Lopez             return true;
11905e771752SSergio Lopez         }
1191279ac06eSEmanuele Giuseppe Esposito     }
11925e771752SSergio Lopez 
119389bd0305SKevin Wolf     return !!s->in_flight;
119489bd0305SKevin Wolf }
119589bd0305SKevin Wolf 
119673895f38SHanna Reitz static bool mirror_cancel(Job *job, bool force)
1197521ff8b7SVladimir Sementsov-Ogievskiy {
1198521ff8b7SVladimir Sementsov-Ogievskiy     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1199521ff8b7SVladimir Sementsov-Ogievskiy     BlockDriverState *target = blk_bs(s->target);
1200521ff8b7SVladimir Sementsov-Ogievskiy 
120173895f38SHanna Reitz     /*
120273895f38SHanna Reitz      * Before the job is READY, we treat any cancellation like a
120373895f38SHanna Reitz      * force-cancellation.
120473895f38SHanna Reitz      */
120573895f38SHanna Reitz     force = force || !job_is_ready(job);
120673895f38SHanna Reitz 
120773895f38SHanna Reitz     if (force) {
1208521ff8b7SVladimir Sementsov-Ogievskiy         bdrv_cancel_in_flight(target);
1209521ff8b7SVladimir Sementsov-Ogievskiy     }
121073895f38SHanna Reitz     return force;
121173895f38SHanna Reitz }
121273895f38SHanna Reitz 
121373895f38SHanna Reitz static bool commit_active_cancel(Job *job, bool force)
121473895f38SHanna Reitz {
121573895f38SHanna Reitz     /* Same as above in mirror_cancel() */
121673895f38SHanna Reitz     return force || !job_is_ready(job);
12179c785cd7SVladimir Sementsov-Ogievskiy }
1218521ff8b7SVladimir Sementsov-Ogievskiy 
12193fc4b10aSFam Zheng static const BlockJobDriver mirror_job_driver = {
122033e9e9bdSKevin Wolf     .job_driver = {
1221893f7ebaSPaolo Bonzini         .instance_size          = sizeof(MirrorBlockJob),
12228e4c8700SKevin Wolf         .job_type               = JOB_TYPE_MIRROR,
122380fa2c75SKevin Wolf         .free                   = block_job_free,
1224b15de828SKevin Wolf         .user_resume            = block_job_user_resume,
1225f67432a2SJohn Snow         .run                    = mirror_run,
1226737efc1eSJohn Snow         .prepare                = mirror_prepare,
1227737efc1eSJohn Snow         .abort                  = mirror_abort,
1228565ac01fSStefan Hajnoczi         .pause                  = mirror_pause,
1229da01ff7fSKevin Wolf         .complete               = mirror_complete,
1230521ff8b7SVladimir Sementsov-Ogievskiy         .cancel                 = mirror_cancel,
12313453d972SKevin Wolf     },
123289bd0305SKevin Wolf     .drained_poll           = mirror_drained_poll,
1233893f7ebaSPaolo Bonzini };
1234893f7ebaSPaolo Bonzini 
123503544a6eSFam Zheng static const BlockJobDriver commit_active_job_driver = {
123633e9e9bdSKevin Wolf     .job_driver = {
123703544a6eSFam Zheng         .instance_size          = sizeof(MirrorBlockJob),
12388e4c8700SKevin Wolf         .job_type               = JOB_TYPE_COMMIT,
123980fa2c75SKevin Wolf         .free                   = block_job_free,
1240b15de828SKevin Wolf         .user_resume            = block_job_user_resume,
1241f67432a2SJohn Snow         .run                    = mirror_run,
1242737efc1eSJohn Snow         .prepare                = mirror_prepare,
1243737efc1eSJohn Snow         .abort                  = mirror_abort,
1244565ac01fSStefan Hajnoczi         .pause                  = mirror_pause,
1245da01ff7fSKevin Wolf         .complete               = mirror_complete,
124673895f38SHanna Reitz         .cancel                 = commit_active_cancel,
12473453d972SKevin Wolf     },
124889bd0305SKevin Wolf     .drained_poll           = mirror_drained_poll,
124903544a6eSFam Zheng };
125003544a6eSFam Zheng 
1251537c3d4fSStefan Hajnoczi static void coroutine_fn
1252537c3d4fSStefan Hajnoczi do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
1253d06107adSMax Reitz                      uint64_t offset, uint64_t bytes,
1254d06107adSMax Reitz                      QEMUIOVector *qiov, int flags)
1255d06107adSMax Reitz {
1256d06107adSMax Reitz     int ret;
1257dbdf699cSVladimir Sementsov-Ogievskiy     size_t qiov_offset = 0;
1258dbdf699cSVladimir Sementsov-Ogievskiy     int64_t bitmap_offset, bitmap_end;
1259d06107adSMax Reitz 
1260dbdf699cSVladimir Sementsov-Ogievskiy     if (!QEMU_IS_ALIGNED(offset, job->granularity) &&
1261dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_dirty_bitmap_get(job->dirty_bitmap, offset))
1262dbdf699cSVladimir Sementsov-Ogievskiy     {
1263dbdf699cSVladimir Sementsov-Ogievskiy             /*
1264dbdf699cSVladimir Sementsov-Ogievskiy              * Dirty unaligned padding: ignore it.
1265dbdf699cSVladimir Sementsov-Ogievskiy              *
1266dbdf699cSVladimir Sementsov-Ogievskiy              * Reasoning:
1267dbdf699cSVladimir Sementsov-Ogievskiy              * 1. If we copy it, we can't reset corresponding bit in
1268dbdf699cSVladimir Sementsov-Ogievskiy              *    dirty_bitmap as there may be some "dirty" bytes still not
1269dbdf699cSVladimir Sementsov-Ogievskiy              *    copied.
1270dbdf699cSVladimir Sementsov-Ogievskiy              * 2. It's already dirty, so skipping it we don't diverge mirror
1271dbdf699cSVladimir Sementsov-Ogievskiy              *    progress.
1272dbdf699cSVladimir Sementsov-Ogievskiy              *
1273dbdf699cSVladimir Sementsov-Ogievskiy              * Note, that because of this, guest write may have no contribution
1274dbdf699cSVladimir Sementsov-Ogievskiy              * into mirror converge, but that's not bad, as we have background
1275dbdf699cSVladimir Sementsov-Ogievskiy              * process of mirroring. If under some bad circumstances (high guest
1276dbdf699cSVladimir Sementsov-Ogievskiy              * IO load) background process starve, we will not converge anyway,
1277dbdf699cSVladimir Sementsov-Ogievskiy              * even if each write will contribute, as guest is not guaranteed to
1278dbdf699cSVladimir Sementsov-Ogievskiy              * rewrite the whole disk.
1279dbdf699cSVladimir Sementsov-Ogievskiy              */
1280dbdf699cSVladimir Sementsov-Ogievskiy             qiov_offset = QEMU_ALIGN_UP(offset, job->granularity) - offset;
1281dbdf699cSVladimir Sementsov-Ogievskiy             if (bytes <= qiov_offset) {
1282dbdf699cSVladimir Sementsov-Ogievskiy                 /* nothing to do after shrink */
1283dbdf699cSVladimir Sementsov-Ogievskiy                 return;
1284dbdf699cSVladimir Sementsov-Ogievskiy             }
1285dbdf699cSVladimir Sementsov-Ogievskiy             offset += qiov_offset;
1286dbdf699cSVladimir Sementsov-Ogievskiy             bytes -= qiov_offset;
1287dbdf699cSVladimir Sementsov-Ogievskiy     }
1288dbdf699cSVladimir Sementsov-Ogievskiy 
1289dbdf699cSVladimir Sementsov-Ogievskiy     if (!QEMU_IS_ALIGNED(offset + bytes, job->granularity) &&
1290dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_dirty_bitmap_get(job->dirty_bitmap, offset + bytes - 1))
1291dbdf699cSVladimir Sementsov-Ogievskiy     {
1292dbdf699cSVladimir Sementsov-Ogievskiy         uint64_t tail = (offset + bytes) % job->granularity;
1293dbdf699cSVladimir Sementsov-Ogievskiy 
1294dbdf699cSVladimir Sementsov-Ogievskiy         if (bytes <= tail) {
1295dbdf699cSVladimir Sementsov-Ogievskiy             /* nothing to do after shrink */
1296dbdf699cSVladimir Sementsov-Ogievskiy             return;
1297dbdf699cSVladimir Sementsov-Ogievskiy         }
1298dbdf699cSVladimir Sementsov-Ogievskiy         bytes -= tail;
1299dbdf699cSVladimir Sementsov-Ogievskiy     }
1300dbdf699cSVladimir Sementsov-Ogievskiy 
1301dbdf699cSVladimir Sementsov-Ogievskiy     /*
1302dbdf699cSVladimir Sementsov-Ogievskiy      * Tails are either clean or shrunk, so for bitmap resetting
1303dbdf699cSVladimir Sementsov-Ogievskiy      * we safely align the range down.
1304dbdf699cSVladimir Sementsov-Ogievskiy      */
1305dbdf699cSVladimir Sementsov-Ogievskiy     bitmap_offset = QEMU_ALIGN_UP(offset, job->granularity);
1306dbdf699cSVladimir Sementsov-Ogievskiy     bitmap_end = QEMU_ALIGN_DOWN(offset + bytes, job->granularity);
1307dbdf699cSVladimir Sementsov-Ogievskiy     if (bitmap_offset < bitmap_end) {
1308dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_reset_dirty_bitmap(job->dirty_bitmap, bitmap_offset,
1309dbdf699cSVladimir Sementsov-Ogievskiy                                 bitmap_end - bitmap_offset);
1310dbdf699cSVladimir Sementsov-Ogievskiy     }
1311d06107adSMax Reitz 
13125c511ac3SVladimir Sementsov-Ogievskiy     job_progress_increase_remaining(&job->common.job, bytes);
1313d69a879bSHanna Reitz     job->active_write_bytes_in_flight += bytes;
1314d06107adSMax Reitz 
1315d06107adSMax Reitz     switch (method) {
1316d06107adSMax Reitz     case MIRROR_METHOD_COPY:
1317dbdf699cSVladimir Sementsov-Ogievskiy         ret = blk_co_pwritev_part(job->target, offset, bytes,
1318dbdf699cSVladimir Sementsov-Ogievskiy                                   qiov, qiov_offset, flags);
1319d06107adSMax Reitz         break;
1320d06107adSMax Reitz 
1321d06107adSMax Reitz     case MIRROR_METHOD_ZERO:
1322d06107adSMax Reitz         assert(!qiov);
13235c511ac3SVladimir Sementsov-Ogievskiy         ret = blk_co_pwrite_zeroes(job->target, offset, bytes, flags);
1324d06107adSMax Reitz         break;
1325d06107adSMax Reitz 
1326d06107adSMax Reitz     case MIRROR_METHOD_DISCARD:
1327d06107adSMax Reitz         assert(!qiov);
13285c511ac3SVladimir Sementsov-Ogievskiy         ret = blk_co_pdiscard(job->target, offset, bytes);
1329d06107adSMax Reitz         break;
1330d06107adSMax Reitz 
1331d06107adSMax Reitz     default:
1332d06107adSMax Reitz         abort();
1333d06107adSMax Reitz     }
1334d06107adSMax Reitz 
1335d69a879bSHanna Reitz     job->active_write_bytes_in_flight -= bytes;
1336d06107adSMax Reitz     if (ret >= 0) {
13375c511ac3SVladimir Sementsov-Ogievskiy         job_progress_update(&job->common.job, bytes);
1338d06107adSMax Reitz     } else {
1339d06107adSMax Reitz         BlockErrorAction action;
1340d06107adSMax Reitz 
1341dbdf699cSVladimir Sementsov-Ogievskiy         /*
1342dbdf699cSVladimir Sementsov-Ogievskiy          * We failed, so we should mark dirty the whole area, aligned up.
1343dbdf699cSVladimir Sementsov-Ogievskiy          * Note that we don't care about shrunk tails if any: they were dirty
1344dbdf699cSVladimir Sementsov-Ogievskiy          * at function start, and they must be still dirty, as we've locked
1345dbdf699cSVladimir Sementsov-Ogievskiy          * the region for in-flight op.
1346dbdf699cSVladimir Sementsov-Ogievskiy          */
1347dbdf699cSVladimir Sementsov-Ogievskiy         bitmap_offset = QEMU_ALIGN_DOWN(offset, job->granularity);
1348dbdf699cSVladimir Sementsov-Ogievskiy         bitmap_end = QEMU_ALIGN_UP(offset + bytes, job->granularity);
1349dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_set_dirty_bitmap(job->dirty_bitmap, bitmap_offset,
1350dbdf699cSVladimir Sementsov-Ogievskiy                               bitmap_end - bitmap_offset);
1351d06107adSMax Reitz         job->actively_synced = false;
1352d06107adSMax Reitz 
1353d06107adSMax Reitz         action = mirror_error_action(job, false, -ret);
1354d06107adSMax Reitz         if (action == BLOCK_ERROR_ACTION_REPORT) {
1355d06107adSMax Reitz             if (!job->ret) {
1356d06107adSMax Reitz                 job->ret = ret;
1357d06107adSMax Reitz             }
1358d06107adSMax Reitz         }
1359d06107adSMax Reitz     }
1360d06107adSMax Reitz }
1361d06107adSMax Reitz 
1362d06107adSMax Reitz static MirrorOp *coroutine_fn active_write_prepare(MirrorBlockJob *s,
1363d06107adSMax Reitz                                                    uint64_t offset,
1364d06107adSMax Reitz                                                    uint64_t bytes)
1365d06107adSMax Reitz {
1366d06107adSMax Reitz     MirrorOp *op;
1367d06107adSMax Reitz     uint64_t start_chunk = offset / s->granularity;
1368d06107adSMax Reitz     uint64_t end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1369d06107adSMax Reitz 
1370d06107adSMax Reitz     op = g_new(MirrorOp, 1);
1371d06107adSMax Reitz     *op = (MirrorOp){
1372d06107adSMax Reitz         .s                  = s,
1373d06107adSMax Reitz         .offset             = offset,
1374d06107adSMax Reitz         .bytes              = bytes,
1375d06107adSMax Reitz         .is_active_write    = true,
1376ce8cabbdSKevin Wolf         .is_in_flight       = true,
1377ead3f1bfSVladimir Sementsov-Ogievskiy         .co                 = qemu_coroutine_self(),
1378d06107adSMax Reitz     };
1379d06107adSMax Reitz     qemu_co_queue_init(&op->waiting_requests);
1380d06107adSMax Reitz     QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
1381d06107adSMax Reitz 
1382d06107adSMax Reitz     s->in_active_write_counter++;
1383d06107adSMax Reitz 
1384d69a879bSHanna Reitz     /*
1385d69a879bSHanna Reitz      * Wait for concurrent requests affecting the area.  If there are already
1386d69a879bSHanna Reitz      * running requests that are copying off now-to-be stale data in the area,
1387d69a879bSHanna Reitz      * we must wait for them to finish before we begin writing fresh data to the
1388d69a879bSHanna Reitz      * target so that the write operations appear in the correct order.
1389d69a879bSHanna Reitz      * Note that background requests (see mirror_iteration()) in contrast only
1390d69a879bSHanna Reitz      * wait for conflicting requests at the start of the dirty area, and then
1391d69a879bSHanna Reitz      * (based on the in_flight_bitmap) truncate the area to copy so it will not
1392d69a879bSHanna Reitz      * conflict with any requests beyond that.  For active writes, however, we
1393d69a879bSHanna Reitz      * cannot truncate that area.  The request from our parent must be blocked
1394d69a879bSHanna Reitz      * until the area is copied in full.  Therefore, we must wait for the whole
1395d69a879bSHanna Reitz      * area to become free of concurrent requests.
1396d69a879bSHanna Reitz      */
1397d06107adSMax Reitz     mirror_wait_on_conflicts(op, s, offset, bytes);
1398d06107adSMax Reitz 
1399d06107adSMax Reitz     bitmap_set(s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1400d06107adSMax Reitz 
1401d06107adSMax Reitz     return op;
1402d06107adSMax Reitz }
1403d06107adSMax Reitz 
1404d06107adSMax Reitz static void coroutine_fn active_write_settle(MirrorOp *op)
1405d06107adSMax Reitz {
1406d06107adSMax Reitz     uint64_t start_chunk = op->offset / op->s->granularity;
1407d06107adSMax Reitz     uint64_t end_chunk = DIV_ROUND_UP(op->offset + op->bytes,
1408d06107adSMax Reitz                                       op->s->granularity);
1409d06107adSMax Reitz 
1410d06107adSMax Reitz     if (!--op->s->in_active_write_counter && op->s->actively_synced) {
1411d06107adSMax Reitz         BdrvChild *source = op->s->mirror_top_bs->backing;
1412d06107adSMax Reitz 
1413d06107adSMax Reitz         if (QLIST_FIRST(&source->bs->parents) == source &&
1414d06107adSMax Reitz             QLIST_NEXT(source, next_parent) == NULL)
1415d06107adSMax Reitz         {
1416d06107adSMax Reitz             /* Assert that we are back in sync once all active write
1417d06107adSMax Reitz              * operations are settled.
1418d06107adSMax Reitz              * Note that we can only assert this if the mirror node
1419d06107adSMax Reitz              * is the source node's only parent. */
1420d06107adSMax Reitz             assert(!bdrv_get_dirty_count(op->s->dirty_bitmap));
1421d06107adSMax Reitz         }
1422d06107adSMax Reitz     }
1423d06107adSMax Reitz     bitmap_clear(op->s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1424d06107adSMax Reitz     QTAILQ_REMOVE(&op->s->ops_in_flight, op, next);
1425d06107adSMax Reitz     qemu_co_queue_restart_all(&op->waiting_requests);
1426d06107adSMax Reitz     g_free(op);
1427d06107adSMax Reitz }
1428d06107adSMax Reitz 
14294ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_preadv(BlockDriverState *bs,
1430f7ef38ddSVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes, QEMUIOVector *qiov, BdrvRequestFlags flags)
14314ef85a9cSKevin Wolf {
14324ef85a9cSKevin Wolf     return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
14334ef85a9cSKevin Wolf }
14344ef85a9cSKevin Wolf 
1435d06107adSMax Reitz static int coroutine_fn bdrv_mirror_top_do_write(BlockDriverState *bs,
1436d06107adSMax Reitz     MirrorMethod method, uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
1437d06107adSMax Reitz     int flags)
1438d06107adSMax Reitz {
1439d06107adSMax Reitz     MirrorOp *op = NULL;
1440d06107adSMax Reitz     MirrorBDSOpaque *s = bs->opaque;
1441d06107adSMax Reitz     int ret = 0;
1442da93d5c8SHanna Reitz     bool copy_to_target = false;
1443d06107adSMax Reitz 
1444da93d5c8SHanna Reitz     if (s->job) {
1445d06107adSMax Reitz         copy_to_target = s->job->ret >= 0 &&
14469b230ef9SHanna Reitz                          !job_is_cancelled(&s->job->common.job) &&
1447d06107adSMax Reitz                          s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1448da93d5c8SHanna Reitz     }
1449d06107adSMax Reitz 
1450d06107adSMax Reitz     if (copy_to_target) {
1451d06107adSMax Reitz         op = active_write_prepare(s->job, offset, bytes);
1452d06107adSMax Reitz     }
1453d06107adSMax Reitz 
1454d06107adSMax Reitz     switch (method) {
1455d06107adSMax Reitz     case MIRROR_METHOD_COPY:
1456d06107adSMax Reitz         ret = bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1457d06107adSMax Reitz         break;
1458d06107adSMax Reitz 
1459d06107adSMax Reitz     case MIRROR_METHOD_ZERO:
1460d06107adSMax Reitz         ret = bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
1461d06107adSMax Reitz         break;
1462d06107adSMax Reitz 
1463d06107adSMax Reitz     case MIRROR_METHOD_DISCARD:
14640b9fd3f4SFam Zheng         ret = bdrv_co_pdiscard(bs->backing, offset, bytes);
1465d06107adSMax Reitz         break;
1466d06107adSMax Reitz 
1467d06107adSMax Reitz     default:
1468d06107adSMax Reitz         abort();
1469d06107adSMax Reitz     }
1470d06107adSMax Reitz 
1471d06107adSMax Reitz     if (ret < 0) {
1472d06107adSMax Reitz         goto out;
1473d06107adSMax Reitz     }
1474d06107adSMax Reitz 
1475d06107adSMax Reitz     if (copy_to_target) {
1476d06107adSMax Reitz         do_sync_target_write(s->job, method, offset, bytes, qiov, flags);
1477d06107adSMax Reitz     }
1478d06107adSMax Reitz 
1479d06107adSMax Reitz out:
1480d06107adSMax Reitz     if (copy_to_target) {
1481d06107adSMax Reitz         active_write_settle(op);
1482d06107adSMax Reitz     }
1483d06107adSMax Reitz     return ret;
1484d06107adSMax Reitz }
1485d06107adSMax Reitz 
14864ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_pwritev(BlockDriverState *bs,
1487e75abedaSVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes, QEMUIOVector *qiov, BdrvRequestFlags flags)
14884ef85a9cSKevin Wolf {
1489d06107adSMax Reitz     MirrorBDSOpaque *s = bs->opaque;
1490d06107adSMax Reitz     QEMUIOVector bounce_qiov;
1491d06107adSMax Reitz     void *bounce_buf;
1492d06107adSMax Reitz     int ret = 0;
1493da93d5c8SHanna Reitz     bool copy_to_target = false;
1494d06107adSMax Reitz 
1495da93d5c8SHanna Reitz     if (s->job) {
1496d06107adSMax Reitz         copy_to_target = s->job->ret >= 0 &&
14979b230ef9SHanna Reitz                          !job_is_cancelled(&s->job->common.job) &&
1498d06107adSMax Reitz                          s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1499da93d5c8SHanna Reitz     }
1500d06107adSMax Reitz 
1501d06107adSMax Reitz     if (copy_to_target) {
1502d06107adSMax Reitz         /* The guest might concurrently modify the data to write; but
1503d06107adSMax Reitz          * the data on source and destination must match, so we have
1504d06107adSMax Reitz          * to use a bounce buffer if we are going to write to the
1505d06107adSMax Reitz          * target now. */
1506d06107adSMax Reitz         bounce_buf = qemu_blockalign(bs, bytes);
1507d06107adSMax Reitz         iov_to_buf_full(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
1508d06107adSMax Reitz 
1509d06107adSMax Reitz         qemu_iovec_init(&bounce_qiov, 1);
1510d06107adSMax Reitz         qemu_iovec_add(&bounce_qiov, bounce_buf, bytes);
1511d06107adSMax Reitz         qiov = &bounce_qiov;
1512e8b65355SStefan Hajnoczi 
1513e8b65355SStefan Hajnoczi         flags &= ~BDRV_REQ_REGISTERED_BUF;
1514d06107adSMax Reitz     }
1515d06107adSMax Reitz 
1516d06107adSMax Reitz     ret = bdrv_mirror_top_do_write(bs, MIRROR_METHOD_COPY, offset, bytes, qiov,
1517d06107adSMax Reitz                                    flags);
1518d06107adSMax Reitz 
1519d06107adSMax Reitz     if (copy_to_target) {
1520d06107adSMax Reitz         qemu_iovec_destroy(&bounce_qiov);
1521d06107adSMax Reitz         qemu_vfree(bounce_buf);
1522d06107adSMax Reitz     }
1523d06107adSMax Reitz 
1524d06107adSMax Reitz     return ret;
15254ef85a9cSKevin Wolf }
15264ef85a9cSKevin Wolf 
15274ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_flush(BlockDriverState *bs)
15284ef85a9cSKevin Wolf {
1529ce960aa9SVladimir Sementsov-Ogievskiy     if (bs->backing == NULL) {
1530ce960aa9SVladimir Sementsov-Ogievskiy         /* we can be here after failed bdrv_append in mirror_start_job */
1531ce960aa9SVladimir Sementsov-Ogievskiy         return 0;
1532ce960aa9SVladimir Sementsov-Ogievskiy     }
15334ef85a9cSKevin Wolf     return bdrv_co_flush(bs->backing->bs);
15344ef85a9cSKevin Wolf }
15354ef85a9cSKevin Wolf 
15364ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs,
1537f34b2bcfSVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes, BdrvRequestFlags flags)
15384ef85a9cSKevin Wolf {
1539d06107adSMax Reitz     return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_ZERO, offset, bytes, NULL,
1540d06107adSMax Reitz                                     flags);
15414ef85a9cSKevin Wolf }
15424ef85a9cSKevin Wolf 
15434ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_pdiscard(BlockDriverState *bs,
15440c802287SVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes)
15454ef85a9cSKevin Wolf {
1546d06107adSMax Reitz     return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_DISCARD, offset, bytes,
1547d06107adSMax Reitz                                     NULL, 0);
15484ef85a9cSKevin Wolf }
15494ef85a9cSKevin Wolf 
1550998b3a1eSMax Reitz static void bdrv_mirror_top_refresh_filename(BlockDriverState *bs)
1551fd4a6493SKevin Wolf {
155218775ff3SVladimir Sementsov-Ogievskiy     if (bs->backing == NULL) {
155318775ff3SVladimir Sementsov-Ogievskiy         /* we can be here after failed bdrv_attach_child in
155418775ff3SVladimir Sementsov-Ogievskiy          * bdrv_set_backing_hd */
155518775ff3SVladimir Sementsov-Ogievskiy         return;
155618775ff3SVladimir Sementsov-Ogievskiy     }
1557fd4a6493SKevin Wolf     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1558fd4a6493SKevin Wolf             bs->backing->bs->filename);
1559fd4a6493SKevin Wolf }
1560fd4a6493SKevin Wolf 
15614ef85a9cSKevin Wolf static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1562bf8e925eSMax Reitz                                        BdrvChildRole role,
1563e0995dc3SKevin Wolf                                        BlockReopenQueue *reopen_queue,
15644ef85a9cSKevin Wolf                                        uint64_t perm, uint64_t shared,
15654ef85a9cSKevin Wolf                                        uint64_t *nperm, uint64_t *nshared)
15664ef85a9cSKevin Wolf {
1567f94dc3b4SMax Reitz     MirrorBDSOpaque *s = bs->opaque;
1568f94dc3b4SMax Reitz 
1569f94dc3b4SMax Reitz     if (s->stop) {
1570f94dc3b4SMax Reitz         /*
1571f94dc3b4SMax Reitz          * If the job is to be stopped, we do not need to forward
1572f94dc3b4SMax Reitz          * anything to the real image.
1573f94dc3b4SMax Reitz          */
1574f94dc3b4SMax Reitz         *nperm = 0;
1575f94dc3b4SMax Reitz         *nshared = BLK_PERM_ALL;
1576f94dc3b4SMax Reitz         return;
1577f94dc3b4SMax Reitz     }
1578f94dc3b4SMax Reitz 
157953431b90SMax Reitz     bdrv_default_perms(bs, c, role, reopen_queue,
158053431b90SMax Reitz                        perm, shared, nperm, nshared);
15814ef85a9cSKevin Wolf 
158253431b90SMax Reitz     if (s->is_commit) {
158353431b90SMax Reitz         /*
158453431b90SMax Reitz          * For commit jobs, we cannot take CONSISTENT_READ, because
158553431b90SMax Reitz          * that permission is unshared for everything above the base
158653431b90SMax Reitz          * node (except for filters on the base node).
158753431b90SMax Reitz          * We also have to force-share the WRITE permission, or
158853431b90SMax Reitz          * otherwise we would block ourselves at the base node (if
158953431b90SMax Reitz          * writes are blocked for a node, they are also blocked for
159053431b90SMax Reitz          * its backing file).
159153431b90SMax Reitz          * (We could also share RESIZE, because it may be needed for
159253431b90SMax Reitz          * the target if its size is less than the top node's; but
159353431b90SMax Reitz          * bdrv_default_perms_for_cow() automatically shares RESIZE
159453431b90SMax Reitz          * for backing nodes if WRITE is shared, so there is no need
159553431b90SMax Reitz          * to do it here.)
159653431b90SMax Reitz          */
159753431b90SMax Reitz         *nperm &= ~BLK_PERM_CONSISTENT_READ;
159853431b90SMax Reitz         *nshared |= BLK_PERM_WRITE;
159953431b90SMax Reitz     }
16004ef85a9cSKevin Wolf }
16014ef85a9cSKevin Wolf 
16024ef85a9cSKevin Wolf /* Dummy node that provides consistent read to its users without requiring it
16034ef85a9cSKevin Wolf  * from its backing file and that allows writes on the backing file chain. */
16044ef85a9cSKevin Wolf static BlockDriver bdrv_mirror_top = {
16054ef85a9cSKevin Wolf     .format_name                = "mirror_top",
16064ef85a9cSKevin Wolf     .bdrv_co_preadv             = bdrv_mirror_top_preadv,
16074ef85a9cSKevin Wolf     .bdrv_co_pwritev            = bdrv_mirror_top_pwritev,
16084ef85a9cSKevin Wolf     .bdrv_co_pwrite_zeroes      = bdrv_mirror_top_pwrite_zeroes,
16094ef85a9cSKevin Wolf     .bdrv_co_pdiscard           = bdrv_mirror_top_pdiscard,
16104ef85a9cSKevin Wolf     .bdrv_co_flush              = bdrv_mirror_top_flush,
1611fd4a6493SKevin Wolf     .bdrv_refresh_filename      = bdrv_mirror_top_refresh_filename,
16124ef85a9cSKevin Wolf     .bdrv_child_perm            = bdrv_mirror_top_child_perm,
16136540fd15SMax Reitz 
16146540fd15SMax Reitz     .is_filter                  = true,
1615046fd84fSVladimir Sementsov-Ogievskiy     .filtered_child_is_backing  = true,
16164ef85a9cSKevin Wolf };
16174ef85a9cSKevin Wolf 
1618cc19f177SVladimir Sementsov-Ogievskiy static BlockJob *mirror_start_job(
1619cc19f177SVladimir Sementsov-Ogievskiy                              const char *job_id, BlockDriverState *bs,
162047970dfbSJohn Snow                              int creation_flags, BlockDriverState *target,
162147970dfbSJohn Snow                              const char *replaces, int64_t speed,
162247970dfbSJohn Snow                              uint32_t granularity, int64_t buf_size,
1623274fcceeSMax Reitz                              BlockMirrorBackingMode backing_mode,
1624cdf3bc93SMax Reitz                              bool zero_target,
162503544a6eSFam Zheng                              BlockdevOnError on_source_error,
1626b952b558SPaolo Bonzini                              BlockdevOnError on_target_error,
16270fc9f8eaSFam Zheng                              bool unmap,
1628097310b5SMarkus Armbruster                              BlockCompletionFunc *cb,
162951ccfa2dSFam Zheng                              void *opaque,
163003544a6eSFam Zheng                              const BlockJobDriver *driver,
1631b49f7eadSWen Congyang                              bool is_none_mode, BlockDriverState *base,
163251ccfa2dSFam Zheng                              bool auto_complete, const char *filter_node_name,
1633481debaaSMax Reitz                              bool is_mirror, MirrorCopyMode copy_mode,
163451ccfa2dSFam Zheng                              Error **errp)
1635893f7ebaSPaolo Bonzini {
1636893f7ebaSPaolo Bonzini     MirrorBlockJob *s;
1637429076e8SMax Reitz     MirrorBDSOpaque *bs_opaque;
16384ef85a9cSKevin Wolf     BlockDriverState *mirror_top_bs;
16394ef85a9cSKevin Wolf     bool target_is_backing;
16403f072a7fSMax Reitz     uint64_t target_perms, target_shared_perms;
1641d7086422SKevin Wolf     int ret;
1642893f7ebaSPaolo Bonzini 
1643eee13dfeSPaolo Bonzini     if (granularity == 0) {
1644341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(target);
1645eee13dfeSPaolo Bonzini     }
1646eee13dfeSPaolo Bonzini 
164731826642SEric Blake     assert(is_power_of_2(granularity));
1648eee13dfeSPaolo Bonzini 
164948ac0a4dSWen Congyang     if (buf_size < 0) {
165048ac0a4dSWen Congyang         error_setg(errp, "Invalid parameter 'buf-size'");
1651cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
165248ac0a4dSWen Congyang     }
165348ac0a4dSWen Congyang 
165448ac0a4dSWen Congyang     if (buf_size == 0) {
165548ac0a4dSWen Congyang         buf_size = DEFAULT_MIRROR_BUF_SIZE;
165648ac0a4dSWen Congyang     }
16575bc361b8SFam Zheng 
16583f072a7fSMax Reitz     if (bdrv_skip_filters(bs) == bdrv_skip_filters(target)) {
165986fae10cSKevin Wolf         error_setg(errp, "Can't mirror node into itself");
1660cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
166186fae10cSKevin Wolf     }
166286fae10cSKevin Wolf 
166353431b90SMax Reitz     target_is_backing = bdrv_chain_contains(bs, target);
166453431b90SMax Reitz 
16654ef85a9cSKevin Wolf     /* In the case of active commit, add dummy driver to provide consistent
16664ef85a9cSKevin Wolf      * reads on the top, while disabling it in the intermediate nodes, and make
16674ef85a9cSKevin Wolf      * the backing chain writable. */
16686cdbceb1SKevin Wolf     mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
16696cdbceb1SKevin Wolf                                          BDRV_O_RDWR, errp);
16704ef85a9cSKevin Wolf     if (mirror_top_bs == NULL) {
1671cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
1672893f7ebaSPaolo Bonzini     }
1673d3c8c674SKevin Wolf     if (!filter_node_name) {
1674d3c8c674SKevin Wolf         mirror_top_bs->implicit = true;
1675d3c8c674SKevin Wolf     }
1676e5182c1cSMax Reitz 
1677e5182c1cSMax Reitz     /* So that we can always drop this node */
1678e5182c1cSMax Reitz     mirror_top_bs->never_freeze = true;
1679e5182c1cSMax Reitz 
16804ef85a9cSKevin Wolf     mirror_top_bs->total_sectors = bs->total_sectors;
1681228345bfSMax Reitz     mirror_top_bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED;
168280f5c33fSKevin Wolf     mirror_top_bs->supported_zero_flags = BDRV_REQ_WRITE_UNCHANGED |
168380f5c33fSKevin Wolf                                           BDRV_REQ_NO_FALLBACK;
1684429076e8SMax Reitz     bs_opaque = g_new0(MirrorBDSOpaque, 1);
1685429076e8SMax Reitz     mirror_top_bs->opaque = bs_opaque;
1686893f7ebaSPaolo Bonzini 
168753431b90SMax Reitz     bs_opaque->is_commit = target_is_backing;
168853431b90SMax Reitz 
16894ef85a9cSKevin Wolf     bdrv_drained_begin(bs);
1690934aee14SVladimir Sementsov-Ogievskiy     ret = bdrv_append(mirror_top_bs, bs, errp);
16914ef85a9cSKevin Wolf     bdrv_drained_end(bs);
16924ef85a9cSKevin Wolf 
1693934aee14SVladimir Sementsov-Ogievskiy     if (ret < 0) {
1694b2c2832cSKevin Wolf         bdrv_unref(mirror_top_bs);
1695cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
1696b2c2832cSKevin Wolf     }
1697b2c2832cSKevin Wolf 
16984ef85a9cSKevin Wolf     /* Make sure that the source is not resized while the job is running */
169975859b94SJohn Snow     s = block_job_create(job_id, driver, NULL, mirror_top_bs,
17004ef85a9cSKevin Wolf                          BLK_PERM_CONSISTENT_READ,
17014ef85a9cSKevin Wolf                          BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
170264631f36SVladimir Sementsov-Ogievskiy                          BLK_PERM_WRITE, speed,
17034ef85a9cSKevin Wolf                          creation_flags, cb, opaque, errp);
17044ef85a9cSKevin Wolf     if (!s) {
17054ef85a9cSKevin Wolf         goto fail;
17064ef85a9cSKevin Wolf     }
1707429076e8SMax Reitz     bs_opaque->job = s;
1708429076e8SMax Reitz 
17097a25fcd0SMax Reitz     /* The block job now has a reference to this node */
17107a25fcd0SMax Reitz     bdrv_unref(mirror_top_bs);
17117a25fcd0SMax Reitz 
17124ef85a9cSKevin Wolf     s->mirror_top_bs = mirror_top_bs;
17134ef85a9cSKevin Wolf 
17144ef85a9cSKevin Wolf     /* No resize for the target either; while the mirror is still running, a
17154ef85a9cSKevin Wolf      * consistent read isn't necessarily possible. We could possibly allow
17164ef85a9cSKevin Wolf      * writes and graph modifications, though it would likely defeat the
17174ef85a9cSKevin Wolf      * purpose of a mirror, so leave them blocked for now.
17184ef85a9cSKevin Wolf      *
17194ef85a9cSKevin Wolf      * In the case of active commit, things look a bit different, though,
17204ef85a9cSKevin Wolf      * because the target is an already populated backing file in active use.
17214ef85a9cSKevin Wolf      * We can allow anything except resize there.*/
17223f072a7fSMax Reitz 
17233f072a7fSMax Reitz     target_perms = BLK_PERM_WRITE;
17243f072a7fSMax Reitz     target_shared_perms = BLK_PERM_WRITE_UNCHANGED;
17253f072a7fSMax Reitz 
17263f072a7fSMax Reitz     if (target_is_backing) {
17273f072a7fSMax Reitz         int64_t bs_size, target_size;
17283f072a7fSMax Reitz         bs_size = bdrv_getlength(bs);
17293f072a7fSMax Reitz         if (bs_size < 0) {
17303f072a7fSMax Reitz             error_setg_errno(errp, -bs_size,
17313f072a7fSMax Reitz                              "Could not inquire top image size");
17323f072a7fSMax Reitz             goto fail;
17333f072a7fSMax Reitz         }
17343f072a7fSMax Reitz 
17353f072a7fSMax Reitz         target_size = bdrv_getlength(target);
17363f072a7fSMax Reitz         if (target_size < 0) {
17373f072a7fSMax Reitz             error_setg_errno(errp, -target_size,
17383f072a7fSMax Reitz                              "Could not inquire base image size");
17393f072a7fSMax Reitz             goto fail;
17403f072a7fSMax Reitz         }
17413f072a7fSMax Reitz 
17423f072a7fSMax Reitz         if (target_size < bs_size) {
17433f072a7fSMax Reitz             target_perms |= BLK_PERM_RESIZE;
17443f072a7fSMax Reitz         }
17453f072a7fSMax Reitz 
174664631f36SVladimir Sementsov-Ogievskiy         target_shared_perms |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE;
17473f072a7fSMax Reitz     } else if (bdrv_chain_contains(bs, bdrv_skip_filters(target))) {
17483f072a7fSMax Reitz         /*
17493f072a7fSMax Reitz          * We may want to allow this in the future, but it would
17503f072a7fSMax Reitz          * require taking some extra care.
17513f072a7fSMax Reitz          */
17523f072a7fSMax Reitz         error_setg(errp, "Cannot mirror to a filter on top of a node in the "
17533f072a7fSMax Reitz                    "source's backing chain");
17543f072a7fSMax Reitz         goto fail;
17553f072a7fSMax Reitz     }
17563f072a7fSMax Reitz 
1757d861ab3aSKevin Wolf     s->target = blk_new(s->common.job.aio_context,
17583f072a7fSMax Reitz                         target_perms, target_shared_perms);
1759d7086422SKevin Wolf     ret = blk_insert_bs(s->target, target, errp);
1760d7086422SKevin Wolf     if (ret < 0) {
17614ef85a9cSKevin Wolf         goto fail;
1762d7086422SKevin Wolf     }
1763045a2f82SFam Zheng     if (is_mirror) {
1764045a2f82SFam Zheng         /* XXX: Mirror target could be a NBD server of target QEMU in the case
1765045a2f82SFam Zheng          * of non-shared block migration. To allow migration completion, we
1766045a2f82SFam Zheng          * have to allow "inactivate" of the target BB.  When that happens, we
1767045a2f82SFam Zheng          * know the job is drained, and the vcpus are stopped, so no write
1768045a2f82SFam Zheng          * operation will be performed. Block layer already has assertions to
1769045a2f82SFam Zheng          * ensure that. */
1770045a2f82SFam Zheng         blk_set_force_allow_inactivate(s->target);
1771045a2f82SFam Zheng     }
17729ff7f0dfSKevin Wolf     blk_set_allow_aio_context_change(s->target, true);
1773cf312932SKevin Wolf     blk_set_disable_request_queuing(s->target, true);
1774e253f4b8SKevin Wolf 
177509158f00SBenoît Canet     s->replaces = g_strdup(replaces);
1776b952b558SPaolo Bonzini     s->on_source_error = on_source_error;
1777b952b558SPaolo Bonzini     s->on_target_error = on_target_error;
177803544a6eSFam Zheng     s->is_none_mode = is_none_mode;
1779274fcceeSMax Reitz     s->backing_mode = backing_mode;
1780cdf3bc93SMax Reitz     s->zero_target = zero_target;
1781481debaaSMax Reitz     s->copy_mode = copy_mode;
17825bc361b8SFam Zheng     s->base = base;
17833f072a7fSMax Reitz     s->base_overlay = bdrv_find_overlay(bs, base);
1784eee13dfeSPaolo Bonzini     s->granularity = granularity;
178548ac0a4dSWen Congyang     s->buf_size = ROUND_UP(buf_size, granularity);
17860fc9f8eaSFam Zheng     s->unmap = unmap;
1787b49f7eadSWen Congyang     if (auto_complete) {
1788b49f7eadSWen Congyang         s->should_complete = true;
1789b49f7eadSWen Congyang     }
1790b812f671SPaolo Bonzini 
17910db6e54aSFam Zheng     s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
1792b8afb520SFam Zheng     if (!s->dirty_bitmap) {
179388f9d1b3SKevin Wolf         goto fail;
1794b8afb520SFam Zheng     }
1795dbdf699cSVladimir Sementsov-Ogievskiy     if (s->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING) {
1796dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_disable_dirty_bitmap(s->dirty_bitmap);
1797dbdf699cSVladimir Sementsov-Ogievskiy     }
179810f3cd15SAlberto Garcia 
179967b24427SAlberto Garcia     ret = block_job_add_bdrv(&s->common, "source", bs, 0,
180067b24427SAlberto Garcia                              BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE |
180167b24427SAlberto Garcia                              BLK_PERM_CONSISTENT_READ,
180267b24427SAlberto Garcia                              errp);
180367b24427SAlberto Garcia     if (ret < 0) {
180467b24427SAlberto Garcia         goto fail;
180567b24427SAlberto Garcia     }
180667b24427SAlberto Garcia 
18074ef85a9cSKevin Wolf     /* Required permissions are already taken with blk_new() */
180876d554e2SKevin Wolf     block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
180976d554e2SKevin Wolf                        &error_abort);
181076d554e2SKevin Wolf 
1811f3ede4b0SAlberto Garcia     /* In commit_active_start() all intermediate nodes disappear, so
1812f3ede4b0SAlberto Garcia      * any jobs in them must be blocked */
18134ef85a9cSKevin Wolf     if (target_is_backing) {
18143f072a7fSMax Reitz         BlockDriverState *iter, *filtered_target;
18153f072a7fSMax Reitz         uint64_t iter_shared_perms;
18163f072a7fSMax Reitz 
18173f072a7fSMax Reitz         /*
18183f072a7fSMax Reitz          * The topmost node with
18193f072a7fSMax Reitz          * bdrv_skip_filters(filtered_target) == bdrv_skip_filters(target)
18203f072a7fSMax Reitz          */
18213f072a7fSMax Reitz         filtered_target = bdrv_cow_bs(bdrv_find_overlay(bs, target));
18223f072a7fSMax Reitz 
18233f072a7fSMax Reitz         assert(bdrv_skip_filters(filtered_target) ==
18243f072a7fSMax Reitz                bdrv_skip_filters(target));
18253f072a7fSMax Reitz 
18263f072a7fSMax Reitz         /*
18273f072a7fSMax Reitz          * XXX BLK_PERM_WRITE needs to be allowed so we don't block
18284ef85a9cSKevin Wolf          * ourselves at s->base (if writes are blocked for a node, they are
18294ef85a9cSKevin Wolf          * also blocked for its backing file). The other options would be a
18303f072a7fSMax Reitz          * second filter driver above s->base (== target).
18313f072a7fSMax Reitz          */
18323f072a7fSMax Reitz         iter_shared_perms = BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE;
18333f072a7fSMax Reitz 
18343f072a7fSMax Reitz         for (iter = bdrv_filter_or_cow_bs(bs); iter != target;
18353f072a7fSMax Reitz              iter = bdrv_filter_or_cow_bs(iter))
18363f072a7fSMax Reitz         {
18373f072a7fSMax Reitz             if (iter == filtered_target) {
18383f072a7fSMax Reitz                 /*
18393f072a7fSMax Reitz                  * From here on, all nodes are filters on the base.
18403f072a7fSMax Reitz                  * This allows us to share BLK_PERM_CONSISTENT_READ.
18413f072a7fSMax Reitz                  */
18423f072a7fSMax Reitz                 iter_shared_perms |= BLK_PERM_CONSISTENT_READ;
18433f072a7fSMax Reitz             }
18443f072a7fSMax Reitz 
18454ef85a9cSKevin Wolf             ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
18463f072a7fSMax Reitz                                      iter_shared_perms, errp);
18474ef85a9cSKevin Wolf             if (ret < 0) {
18484ef85a9cSKevin Wolf                 goto fail;
18494ef85a9cSKevin Wolf             }
1850f3ede4b0SAlberto Garcia         }
1851ef53dc09SAlberto Garcia 
1852ef53dc09SAlberto Garcia         if (bdrv_freeze_backing_chain(mirror_top_bs, target, errp) < 0) {
1853ef53dc09SAlberto Garcia             goto fail;
1854ef53dc09SAlberto Garcia         }
1855f3ede4b0SAlberto Garcia     }
185610f3cd15SAlberto Garcia 
185712aa4082SMax Reitz     QTAILQ_INIT(&s->ops_in_flight);
185812aa4082SMax Reitz 
18595ccac6f1SJohn Snow     trace_mirror_start(bs, s, opaque);
1860da01ff7fSKevin Wolf     job_start(&s->common.job);
1861cc19f177SVladimir Sementsov-Ogievskiy 
1862cc19f177SVladimir Sementsov-Ogievskiy     return &s->common;
18634ef85a9cSKevin Wolf 
18644ef85a9cSKevin Wolf fail:
18654ef85a9cSKevin Wolf     if (s) {
18667a25fcd0SMax Reitz         /* Make sure this BDS does not go away until we have completed the graph
18677a25fcd0SMax Reitz          * changes below */
18687a25fcd0SMax Reitz         bdrv_ref(mirror_top_bs);
18697a25fcd0SMax Reitz 
18704ef85a9cSKevin Wolf         g_free(s->replaces);
18714ef85a9cSKevin Wolf         blk_unref(s->target);
1872429076e8SMax Reitz         bs_opaque->job = NULL;
1873e917e2cbSAlberto Garcia         if (s->dirty_bitmap) {
18745deb6cbdSVladimir Sementsov-Ogievskiy             bdrv_release_dirty_bitmap(s->dirty_bitmap);
1875e917e2cbSAlberto Garcia         }
18764ad35181SKevin Wolf         job_early_fail(&s->common.job);
18774ef85a9cSKevin Wolf     }
18784ef85a9cSKevin Wolf 
1879f94dc3b4SMax Reitz     bs_opaque->stop = true;
1880f94dc3b4SMax Reitz     bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
1881c1cef672SFam Zheng                              &error_abort);
18823f072a7fSMax Reitz     bdrv_replace_node(mirror_top_bs, mirror_top_bs->backing->bs, &error_abort);
18837a25fcd0SMax Reitz 
18847a25fcd0SMax Reitz     bdrv_unref(mirror_top_bs);
1885cc19f177SVladimir Sementsov-Ogievskiy 
1886cc19f177SVladimir Sementsov-Ogievskiy     return NULL;
1887893f7ebaSPaolo Bonzini }
188803544a6eSFam Zheng 
188971aa9867SAlberto Garcia void mirror_start(const char *job_id, BlockDriverState *bs,
189071aa9867SAlberto Garcia                   BlockDriverState *target, const char *replaces,
1891a1999b33SJohn Snow                   int creation_flags, int64_t speed,
1892a1999b33SJohn Snow                   uint32_t granularity, int64_t buf_size,
1893274fcceeSMax Reitz                   MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
1894cdf3bc93SMax Reitz                   bool zero_target,
1895274fcceeSMax Reitz                   BlockdevOnError on_source_error,
189603544a6eSFam Zheng                   BlockdevOnError on_target_error,
1897481debaaSMax Reitz                   bool unmap, const char *filter_node_name,
1898481debaaSMax Reitz                   MirrorCopyMode copy_mode, Error **errp)
189903544a6eSFam Zheng {
190003544a6eSFam Zheng     bool is_none_mode;
190103544a6eSFam Zheng     BlockDriverState *base;
190203544a6eSFam Zheng 
1903b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1904b4ad82aaSEmanuele Giuseppe Esposito 
1905c8b56501SJohn Snow     if ((mode == MIRROR_SYNC_MODE_INCREMENTAL) ||
1906c8b56501SJohn Snow         (mode == MIRROR_SYNC_MODE_BITMAP)) {
1907c8b56501SJohn Snow         error_setg(errp, "Sync mode '%s' not supported",
1908c8b56501SJohn Snow                    MirrorSyncMode_str(mode));
1909d58d8453SJohn Snow         return;
1910d58d8453SJohn Snow     }
191103544a6eSFam Zheng     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
19123f072a7fSMax Reitz     base = mode == MIRROR_SYNC_MODE_TOP ? bdrv_backing_chain_next(bs) : NULL;
1913a1999b33SJohn Snow     mirror_start_job(job_id, bs, creation_flags, target, replaces,
1914cdf3bc93SMax Reitz                      speed, granularity, buf_size, backing_mode, zero_target,
191551ccfa2dSFam Zheng                      on_source_error, on_target_error, unmap, NULL, NULL,
19166cdbceb1SKevin Wolf                      &mirror_job_driver, is_none_mode, base, false,
1917481debaaSMax Reitz                      filter_node_name, true, copy_mode, errp);
191803544a6eSFam Zheng }
191903544a6eSFam Zheng 
1920cc19f177SVladimir Sementsov-Ogievskiy BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
192147970dfbSJohn Snow                               BlockDriverState *base, int creation_flags,
192247970dfbSJohn Snow                               int64_t speed, BlockdevOnError on_error,
19230db832f4SKevin Wolf                               const char *filter_node_name,
192478bbd910SFam Zheng                               BlockCompletionFunc *cb, void *opaque,
192578bbd910SFam Zheng                               bool auto_complete, Error **errp)
192603544a6eSFam Zheng {
19271ba79388SAlberto Garcia     bool base_read_only;
1928eb5becc1SVladimir Sementsov-Ogievskiy     BlockJob *job;
19294da83585SJeff Cody 
1930b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1931b4ad82aaSEmanuele Giuseppe Esposito 
19321ba79388SAlberto Garcia     base_read_only = bdrv_is_read_only(base);
19334da83585SJeff Cody 
19341ba79388SAlberto Garcia     if (base_read_only) {
19351ba79388SAlberto Garcia         if (bdrv_reopen_set_read_only(base, false, errp) < 0) {
1936cc19f177SVladimir Sementsov-Ogievskiy             return NULL;
193720a63d2cSFam Zheng         }
19381ba79388SAlberto Garcia     }
19394da83585SJeff Cody 
1940eb5becc1SVladimir Sementsov-Ogievskiy     job = mirror_start_job(
1941cc19f177SVladimir Sementsov-Ogievskiy                      job_id, bs, creation_flags, base, NULL, speed, 0, 0,
1942cdf3bc93SMax Reitz                      MIRROR_LEAVE_BACKING_CHAIN, false,
194351ccfa2dSFam Zheng                      on_error, on_error, true, cb, opaque,
19446cdbceb1SKevin Wolf                      &commit_active_job_driver, false, base, auto_complete,
1945481debaaSMax Reitz                      filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
1946eb5becc1SVladimir Sementsov-Ogievskiy                      errp);
1947eb5becc1SVladimir Sementsov-Ogievskiy     if (!job) {
19484da83585SJeff Cody         goto error_restore_flags;
19494da83585SJeff Cody     }
19504da83585SJeff Cody 
1951eb5becc1SVladimir Sementsov-Ogievskiy     return job;
19524da83585SJeff Cody 
19534da83585SJeff Cody error_restore_flags:
19544da83585SJeff Cody     /* ignore error and errp for bdrv_reopen, because we want to propagate
19554da83585SJeff Cody      * the original error */
19561ba79388SAlberto Garcia     if (base_read_only) {
19571ba79388SAlberto Garcia         bdrv_reopen_set_read_only(base, true, NULL);
19581ba79388SAlberto Garcia     }
1959cc19f177SVladimir Sementsov-Ogievskiy     return NULL;
196003544a6eSFam Zheng }
1961