xref: /qemu/block/mirror.c (revision 0c8022876f2183f93e23a7314862140c94ee62e7)
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"
21373340b2SMax Reitz #include "sysemu/block-backend.h"
22da34e65cSMarkus Armbruster #include "qapi/error.h"
23cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
24893f7ebaSPaolo Bonzini #include "qemu/ratelimit.h"
25b812f671SPaolo Bonzini #include "qemu/bitmap.h"
26893f7ebaSPaolo Bonzini 
27402a4741SPaolo Bonzini #define MAX_IN_FLIGHT 16
28b436982fSEric Blake #define MAX_IO_BYTES (1 << 20) /* 1 Mb */
29b436982fSEric Blake #define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
30402a4741SPaolo Bonzini 
31402a4741SPaolo Bonzini /* The mirroring buffer is a list of granularity-sized chunks.
32402a4741SPaolo Bonzini  * Free chunks are organized in a list.
33402a4741SPaolo Bonzini  */
34402a4741SPaolo Bonzini typedef struct MirrorBuffer {
35402a4741SPaolo Bonzini     QSIMPLEQ_ENTRY(MirrorBuffer) next;
36402a4741SPaolo Bonzini } MirrorBuffer;
37893f7ebaSPaolo Bonzini 
3812aa4082SMax Reitz typedef struct MirrorOp MirrorOp;
3912aa4082SMax Reitz 
40893f7ebaSPaolo Bonzini typedef struct MirrorBlockJob {
41893f7ebaSPaolo Bonzini     BlockJob common;
42e253f4b8SKevin Wolf     BlockBackend *target;
434ef85a9cSKevin Wolf     BlockDriverState *mirror_top_bs;
445bc361b8SFam Zheng     BlockDriverState *base;
453f072a7fSMax Reitz     BlockDriverState *base_overlay;
464ef85a9cSKevin Wolf 
4709158f00SBenoît Canet     /* The name of the graph node to replace */
4809158f00SBenoît Canet     char *replaces;
4909158f00SBenoît Canet     /* The BDS to replace */
5009158f00SBenoît Canet     BlockDriverState *to_replace;
5109158f00SBenoît Canet     /* Used to block operations on the drive-mirror-replace target */
5209158f00SBenoît Canet     Error *replace_blocker;
5303544a6eSFam Zheng     bool is_none_mode;
54274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode;
55cdf3bc93SMax Reitz     /* Whether the target image requires explicit zero-initialization */
56cdf3bc93SMax Reitz     bool zero_target;
57d06107adSMax Reitz     MirrorCopyMode copy_mode;
58b952b558SPaolo Bonzini     BlockdevOnError on_source_error, on_target_error;
59d63ffd87SPaolo Bonzini     bool synced;
60d06107adSMax Reitz     /* Set when the target is synced (dirty bitmap is clean, nothing
61d06107adSMax Reitz      * in flight) and the job is running in active mode */
62d06107adSMax Reitz     bool actively_synced;
63d63ffd87SPaolo Bonzini     bool should_complete;
64eee13dfeSPaolo Bonzini     int64_t granularity;
65b812f671SPaolo Bonzini     size_t buf_size;
66b21c7652SMax Reitz     int64_t bdev_length;
67b812f671SPaolo Bonzini     unsigned long *cow_bitmap;
68e4654d2dSFam Zheng     BdrvDirtyBitmap *dirty_bitmap;
69dc162c8eSFam Zheng     BdrvDirtyBitmapIter *dbi;
70893f7ebaSPaolo Bonzini     uint8_t *buf;
71402a4741SPaolo Bonzini     QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
72402a4741SPaolo Bonzini     int buf_free_count;
73bd48bde8SPaolo Bonzini 
7449efb1f5SDenis V. Lunev     uint64_t last_pause_ns;
75402a4741SPaolo Bonzini     unsigned long *in_flight_bitmap;
76bd48bde8SPaolo Bonzini     int in_flight;
77b436982fSEric Blake     int64_t bytes_in_flight;
78b58deb34SPaolo Bonzini     QTAILQ_HEAD(, MirrorOp) ops_in_flight;
79bd48bde8SPaolo Bonzini     int ret;
800fc9f8eaSFam Zheng     bool unmap;
81b436982fSEric Blake     int target_cluster_size;
82e5b43573SFam Zheng     int max_iov;
8390ab48ebSAnton Nefedov     bool initial_zeroing_ongoing;
84d06107adSMax Reitz     int in_active_write_counter;
85737efc1eSJohn Snow     bool prepared;
865e771752SSergio Lopez     bool in_drain;
87893f7ebaSPaolo Bonzini } MirrorBlockJob;
88893f7ebaSPaolo Bonzini 
89429076e8SMax Reitz typedef struct MirrorBDSOpaque {
90429076e8SMax Reitz     MirrorBlockJob *job;
91f94dc3b4SMax Reitz     bool stop;
9253431b90SMax Reitz     bool is_commit;
93429076e8SMax Reitz } MirrorBDSOpaque;
94429076e8SMax Reitz 
9512aa4082SMax Reitz struct MirrorOp {
96bd48bde8SPaolo Bonzini     MirrorBlockJob *s;
97bd48bde8SPaolo Bonzini     QEMUIOVector qiov;
98b436982fSEric Blake     int64_t offset;
99b436982fSEric Blake     uint64_t bytes;
1002e1990b2SMax Reitz 
1012e1990b2SMax Reitz     /* The pointee is set by mirror_co_read(), mirror_co_zero(), and
1022e1990b2SMax Reitz      * mirror_co_discard() before yielding for the first time */
1032e1990b2SMax Reitz     int64_t *bytes_handled;
10412aa4082SMax Reitz 
1051181e19aSMax Reitz     bool is_pseudo_op;
106d06107adSMax Reitz     bool is_active_write;
107ce8cabbdSKevin Wolf     bool is_in_flight;
10812aa4082SMax Reitz     CoQueue waiting_requests;
109eed325b9SKevin Wolf     Coroutine *co;
110d44dae1aSVladimir Sementsov-Ogievskiy     MirrorOp *waiting_for_op;
11112aa4082SMax Reitz 
11212aa4082SMax Reitz     QTAILQ_ENTRY(MirrorOp) next;
11312aa4082SMax Reitz };
114bd48bde8SPaolo Bonzini 
1154295c5fcSMax Reitz typedef enum MirrorMethod {
1164295c5fcSMax Reitz     MIRROR_METHOD_COPY,
1174295c5fcSMax Reitz     MIRROR_METHOD_ZERO,
1184295c5fcSMax Reitz     MIRROR_METHOD_DISCARD,
1194295c5fcSMax Reitz } MirrorMethod;
1204295c5fcSMax Reitz 
121b952b558SPaolo Bonzini static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
122b952b558SPaolo Bonzini                                             int error)
123b952b558SPaolo Bonzini {
124b952b558SPaolo Bonzini     s->synced = false;
125d06107adSMax Reitz     s->actively_synced = false;
126b952b558SPaolo Bonzini     if (read) {
12781e254dcSKevin Wolf         return block_job_error_action(&s->common, s->on_source_error,
12881e254dcSKevin Wolf                                       true, error);
129b952b558SPaolo Bonzini     } else {
13081e254dcSKevin Wolf         return block_job_error_action(&s->common, s->on_target_error,
13181e254dcSKevin Wolf                                       false, error);
132b952b558SPaolo Bonzini     }
133b952b558SPaolo Bonzini }
134b952b558SPaolo Bonzini 
1351181e19aSMax Reitz static void coroutine_fn mirror_wait_on_conflicts(MirrorOp *self,
1361181e19aSMax Reitz                                                   MirrorBlockJob *s,
1371181e19aSMax Reitz                                                   uint64_t offset,
1381181e19aSMax Reitz                                                   uint64_t bytes)
1391181e19aSMax Reitz {
1401181e19aSMax Reitz     uint64_t self_start_chunk = offset / s->granularity;
1411181e19aSMax Reitz     uint64_t self_end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1421181e19aSMax Reitz     uint64_t self_nb_chunks = self_end_chunk - self_start_chunk;
1431181e19aSMax Reitz 
1441181e19aSMax Reitz     while (find_next_bit(s->in_flight_bitmap, self_end_chunk,
1451181e19aSMax Reitz                          self_start_chunk) < self_end_chunk &&
1461181e19aSMax Reitz            s->ret >= 0)
1471181e19aSMax Reitz     {
1481181e19aSMax Reitz         MirrorOp *op;
1491181e19aSMax Reitz 
1501181e19aSMax Reitz         QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
1511181e19aSMax Reitz             uint64_t op_start_chunk = op->offset / s->granularity;
1521181e19aSMax Reitz             uint64_t op_nb_chunks = DIV_ROUND_UP(op->offset + op->bytes,
1531181e19aSMax Reitz                                                  s->granularity) -
1541181e19aSMax Reitz                                     op_start_chunk;
1551181e19aSMax Reitz 
1561181e19aSMax Reitz             if (op == self) {
1571181e19aSMax Reitz                 continue;
1581181e19aSMax Reitz             }
1591181e19aSMax Reitz 
1601181e19aSMax Reitz             if (ranges_overlap(self_start_chunk, self_nb_chunks,
1611181e19aSMax Reitz                                op_start_chunk, op_nb_chunks))
1621181e19aSMax Reitz             {
16366fed30cSStefano Garzarella                 if (self) {
164d44dae1aSVladimir Sementsov-Ogievskiy                     /*
16566fed30cSStefano Garzarella                      * If the operation is already (indirectly) waiting for us,
16666fed30cSStefano Garzarella                      * or will wait for us as soon as it wakes up, then just go
16766fed30cSStefano Garzarella                      * on (instead of producing a deadlock in the former case).
168d44dae1aSVladimir Sementsov-Ogievskiy                      */
169d44dae1aSVladimir Sementsov-Ogievskiy                     if (op->waiting_for_op) {
170d44dae1aSVladimir Sementsov-Ogievskiy                         continue;
171d44dae1aSVladimir Sementsov-Ogievskiy                     }
172d44dae1aSVladimir Sementsov-Ogievskiy 
173d44dae1aSVladimir Sementsov-Ogievskiy                     self->waiting_for_op = op;
17466fed30cSStefano Garzarella                 }
17566fed30cSStefano Garzarella 
1761181e19aSMax Reitz                 qemu_co_queue_wait(&op->waiting_requests, NULL);
17766fed30cSStefano Garzarella 
17866fed30cSStefano Garzarella                 if (self) {
179d44dae1aSVladimir Sementsov-Ogievskiy                     self->waiting_for_op = NULL;
18066fed30cSStefano Garzarella                 }
18166fed30cSStefano Garzarella 
1821181e19aSMax Reitz                 break;
1831181e19aSMax Reitz             }
1841181e19aSMax Reitz         }
1851181e19aSMax Reitz     }
1861181e19aSMax Reitz }
1871181e19aSMax Reitz 
1882e1990b2SMax Reitz static void coroutine_fn mirror_iteration_done(MirrorOp *op, int ret)
189bd48bde8SPaolo Bonzini {
190bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
191402a4741SPaolo Bonzini     struct iovec *iov;
192bd48bde8SPaolo Bonzini     int64_t chunk_num;
193b436982fSEric Blake     int i, nb_chunks;
194bd48bde8SPaolo Bonzini 
195b436982fSEric Blake     trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
196bd48bde8SPaolo Bonzini 
197bd48bde8SPaolo Bonzini     s->in_flight--;
198b436982fSEric Blake     s->bytes_in_flight -= op->bytes;
199402a4741SPaolo Bonzini     iov = op->qiov.iov;
200402a4741SPaolo Bonzini     for (i = 0; i < op->qiov.niov; i++) {
201402a4741SPaolo Bonzini         MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
202402a4741SPaolo Bonzini         QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
203402a4741SPaolo Bonzini         s->buf_free_count++;
204402a4741SPaolo Bonzini     }
205402a4741SPaolo Bonzini 
206b436982fSEric Blake     chunk_num = op->offset / s->granularity;
207b436982fSEric Blake     nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
20812aa4082SMax Reitz 
209402a4741SPaolo Bonzini     bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
21012aa4082SMax Reitz     QTAILQ_REMOVE(&s->ops_in_flight, op, next);
211b21c7652SMax Reitz     if (ret >= 0) {
212b21c7652SMax Reitz         if (s->cow_bitmap) {
213bd48bde8SPaolo Bonzini             bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
214bd48bde8SPaolo Bonzini         }
21590ab48ebSAnton Nefedov         if (!s->initial_zeroing_ongoing) {
21630a5c887SKevin Wolf             job_progress_update(&s->common.job, op->bytes);
217b21c7652SMax Reitz         }
21890ab48ebSAnton Nefedov     }
2196df3bf8eSZhang Min     qemu_iovec_destroy(&op->qiov);
2207b770c72SStefan Hajnoczi 
22112aa4082SMax Reitz     qemu_co_queue_restart_all(&op->waiting_requests);
22212aa4082SMax Reitz     g_free(op);
2237b770c72SStefan Hajnoczi }
224bd48bde8SPaolo Bonzini 
2252e1990b2SMax Reitz static void coroutine_fn mirror_write_complete(MirrorOp *op, int ret)
226bd48bde8SPaolo Bonzini {
227bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
228b9e413ddSPaolo Bonzini 
229bd48bde8SPaolo Bonzini     if (ret < 0) {
230bd48bde8SPaolo Bonzini         BlockErrorAction action;
231bd48bde8SPaolo Bonzini 
232e0d7f73eSEric Blake         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
233bd48bde8SPaolo Bonzini         action = mirror_error_action(s, false, -ret);
234a589569fSWenchao Xia         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
235bd48bde8SPaolo Bonzini             s->ret = ret;
236bd48bde8SPaolo Bonzini         }
237bd48bde8SPaolo Bonzini     }
238d12ade57SVladimir Sementsov-Ogievskiy 
239bd48bde8SPaolo Bonzini     mirror_iteration_done(op, ret);
240bd48bde8SPaolo Bonzini }
241bd48bde8SPaolo Bonzini 
2422e1990b2SMax Reitz static void coroutine_fn mirror_read_complete(MirrorOp *op, int ret)
243bd48bde8SPaolo Bonzini {
244bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
245b9e413ddSPaolo Bonzini 
246bd48bde8SPaolo Bonzini     if (ret < 0) {
247bd48bde8SPaolo Bonzini         BlockErrorAction action;
248bd48bde8SPaolo Bonzini 
249e0d7f73eSEric Blake         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
250bd48bde8SPaolo Bonzini         action = mirror_error_action(s, true, -ret);
251a589569fSWenchao Xia         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
252bd48bde8SPaolo Bonzini             s->ret = ret;
253bd48bde8SPaolo Bonzini         }
254bd48bde8SPaolo Bonzini 
255bd48bde8SPaolo Bonzini         mirror_iteration_done(op, ret);
256d12ade57SVladimir Sementsov-Ogievskiy         return;
257bd48bde8SPaolo Bonzini     }
258d12ade57SVladimir Sementsov-Ogievskiy 
259d12ade57SVladimir Sementsov-Ogievskiy     ret = blk_co_pwritev(s->target, op->offset, op->qiov.size, &op->qiov, 0);
260d12ade57SVladimir Sementsov-Ogievskiy     mirror_write_complete(op, ret);
261b9e413ddSPaolo Bonzini }
262bd48bde8SPaolo Bonzini 
263782d97efSEric Blake /* Clip bytes relative to offset to not exceed end-of-file */
264782d97efSEric Blake static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
265782d97efSEric Blake                                         int64_t offset,
266782d97efSEric Blake                                         int64_t bytes)
267782d97efSEric Blake {
268782d97efSEric Blake     return MIN(bytes, s->bdev_length - offset);
269782d97efSEric Blake }
270782d97efSEric Blake 
271782d97efSEric Blake /* Round offset and/or bytes to target cluster if COW is needed, and
272782d97efSEric Blake  * return the offset of the adjusted tail against original. */
273782d97efSEric Blake static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
274ae4cc877SEric Blake                             uint64_t *bytes)
275893f7ebaSPaolo Bonzini {
276e5b43573SFam Zheng     bool need_cow;
277e5b43573SFam Zheng     int ret = 0;
278782d97efSEric Blake     int64_t align_offset = *offset;
2797cfd5275SEric Blake     int64_t align_bytes = *bytes;
280782d97efSEric Blake     int max_bytes = s->granularity * s->max_iov;
281893f7ebaSPaolo Bonzini 
282782d97efSEric Blake     need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
283782d97efSEric Blake     need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
284e5b43573SFam Zheng                           s->cow_bitmap);
285e5b43573SFam Zheng     if (need_cow) {
286782d97efSEric Blake         bdrv_round_to_clusters(blk_bs(s->target), *offset, *bytes,
287782d97efSEric Blake                                &align_offset, &align_bytes);
2888f0720ecSPaolo Bonzini     }
2898f0720ecSPaolo Bonzini 
290782d97efSEric Blake     if (align_bytes > max_bytes) {
291782d97efSEric Blake         align_bytes = max_bytes;
292e5b43573SFam Zheng         if (need_cow) {
293782d97efSEric Blake             align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
294e5b43573SFam Zheng         }
295e5b43573SFam Zheng     }
296782d97efSEric Blake     /* Clipping may result in align_bytes unaligned to chunk boundary, but
2974150ae60SFam Zheng      * that doesn't matter because it's already the end of source image. */
298782d97efSEric Blake     align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
299402a4741SPaolo Bonzini 
300782d97efSEric Blake     ret = align_offset + align_bytes - (*offset + *bytes);
301782d97efSEric Blake     *offset = align_offset;
302782d97efSEric Blake     *bytes = align_bytes;
303e5b43573SFam Zheng     assert(ret >= 0);
304e5b43573SFam Zheng     return ret;
305e5b43573SFam Zheng }
306e5b43573SFam Zheng 
307537c3d4fSStefan Hajnoczi static inline void coroutine_fn
3089178f4feSKevin Wolf mirror_wait_for_any_operation(MirrorBlockJob *s, bool active)
30921cd917fSFam Zheng {
31012aa4082SMax Reitz     MirrorOp *op;
31112aa4082SMax Reitz 
3121181e19aSMax Reitz     QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
3131181e19aSMax Reitz         /* Do not wait on pseudo ops, because it may in turn wait on
3141181e19aSMax Reitz          * some other operation to start, which may in fact be the
3151181e19aSMax Reitz          * caller of this function.  Since there is only one pseudo op
3161181e19aSMax Reitz          * at any given time, we will always find some real operation
3171181e19aSMax Reitz          * to wait on. */
318ce8cabbdSKevin Wolf         if (!op->is_pseudo_op && op->is_in_flight &&
319ce8cabbdSKevin Wolf             op->is_active_write == active)
320ce8cabbdSKevin Wolf         {
32112aa4082SMax Reitz             qemu_co_queue_wait(&op->waiting_requests, NULL);
3221181e19aSMax Reitz             return;
3231181e19aSMax Reitz         }
3241181e19aSMax Reitz     }
3251181e19aSMax Reitz     abort();
32621cd917fSFam Zheng }
32721cd917fSFam Zheng 
328537c3d4fSStefan Hajnoczi static inline void coroutine_fn
3299178f4feSKevin Wolf mirror_wait_for_free_in_flight_slot(MirrorBlockJob *s)
330d06107adSMax Reitz {
331d06107adSMax Reitz     /* Only non-active operations use up in-flight slots */
3329178f4feSKevin Wolf     mirror_wait_for_any_operation(s, false);
333d06107adSMax Reitz }
334d06107adSMax Reitz 
3352e1990b2SMax Reitz /* Perform a mirror copy operation.
3362e1990b2SMax Reitz  *
3372e1990b2SMax Reitz  * *op->bytes_handled is set to the number of bytes copied after and
3382e1990b2SMax Reitz  * including offset, excluding any bytes copied prior to offset due
3392e1990b2SMax Reitz  * to alignment.  This will be op->bytes if no alignment is necessary,
3402e1990b2SMax Reitz  * or (new_end - op->offset) if the tail is rounded up or down due to
341e5b43573SFam Zheng  * alignment or buffer limit.
342402a4741SPaolo Bonzini  */
3432e1990b2SMax Reitz static void coroutine_fn mirror_co_read(void *opaque)
344e5b43573SFam Zheng {
3452e1990b2SMax Reitz     MirrorOp *op = opaque;
3462e1990b2SMax Reitz     MirrorBlockJob *s = op->s;
347ae4cc877SEric Blake     int nb_chunks;
348ae4cc877SEric Blake     uint64_t ret;
349ae4cc877SEric Blake     uint64_t max_bytes;
350402a4741SPaolo Bonzini 
351ae4cc877SEric Blake     max_bytes = s->granularity * s->max_iov;
352e5b43573SFam Zheng 
353e5b43573SFam Zheng     /* We can only handle as much as buf_size at a time. */
3542e1990b2SMax Reitz     op->bytes = MIN(s->buf_size, MIN(max_bytes, op->bytes));
3552e1990b2SMax Reitz     assert(op->bytes);
3562e1990b2SMax Reitz     assert(op->bytes < BDRV_REQUEST_MAX_BYTES);
3572e1990b2SMax Reitz     *op->bytes_handled = op->bytes;
358e5b43573SFam Zheng 
359e5b43573SFam Zheng     if (s->cow_bitmap) {
3602e1990b2SMax Reitz         *op->bytes_handled += mirror_cow_align(s, &op->offset, &op->bytes);
361e5b43573SFam Zheng     }
3622e1990b2SMax Reitz     /* Cannot exceed BDRV_REQUEST_MAX_BYTES + INT_MAX */
3632e1990b2SMax Reitz     assert(*op->bytes_handled <= UINT_MAX);
3642e1990b2SMax Reitz     assert(op->bytes <= s->buf_size);
365ae4cc877SEric Blake     /* The offset is granularity-aligned because:
366e5b43573SFam Zheng      * 1) Caller passes in aligned values;
367e5b43573SFam Zheng      * 2) mirror_cow_align is used only when target cluster is larger. */
3682e1990b2SMax Reitz     assert(QEMU_IS_ALIGNED(op->offset, s->granularity));
369ae4cc877SEric Blake     /* The range is sector-aligned, since bdrv_getlength() rounds up. */
3702e1990b2SMax Reitz     assert(QEMU_IS_ALIGNED(op->bytes, BDRV_SECTOR_SIZE));
3712e1990b2SMax Reitz     nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
372e5b43573SFam Zheng 
373e5b43573SFam Zheng     while (s->buf_free_count < nb_chunks) {
3742e1990b2SMax Reitz         trace_mirror_yield_in_flight(s, op->offset, s->in_flight);
3759178f4feSKevin Wolf         mirror_wait_for_free_in_flight_slot(s);
376b812f671SPaolo Bonzini     }
377b812f671SPaolo Bonzini 
378402a4741SPaolo Bonzini     /* Now make a QEMUIOVector taking enough granularity-sized chunks
379402a4741SPaolo Bonzini      * from s->buf_free.
380402a4741SPaolo Bonzini      */
381402a4741SPaolo Bonzini     qemu_iovec_init(&op->qiov, nb_chunks);
382402a4741SPaolo Bonzini     while (nb_chunks-- > 0) {
383402a4741SPaolo Bonzini         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
3842e1990b2SMax Reitz         size_t remaining = op->bytes - op->qiov.size;
3855a0f6fd5SKevin Wolf 
386402a4741SPaolo Bonzini         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
387402a4741SPaolo Bonzini         s->buf_free_count--;
3885a0f6fd5SKevin Wolf         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
389402a4741SPaolo Bonzini     }
390402a4741SPaolo Bonzini 
391893f7ebaSPaolo Bonzini     /* Copy the dirty cluster.  */
392bd48bde8SPaolo Bonzini     s->in_flight++;
3932e1990b2SMax Reitz     s->bytes_in_flight += op->bytes;
394ce8cabbdSKevin Wolf     op->is_in_flight = true;
3952e1990b2SMax Reitz     trace_mirror_one_iteration(s, op->offset, op->bytes);
396dcfb3bebSFam Zheng 
397138f9fffSMax Reitz     ret = bdrv_co_preadv(s->mirror_top_bs->backing, op->offset, op->bytes,
398138f9fffSMax Reitz                          &op->qiov, 0);
3992e1990b2SMax Reitz     mirror_read_complete(op, ret);
400e5b43573SFam Zheng }
401e5b43573SFam Zheng 
4022e1990b2SMax Reitz static void coroutine_fn mirror_co_zero(void *opaque)
403e5b43573SFam Zheng {
4042e1990b2SMax Reitz     MirrorOp *op = opaque;
4052e1990b2SMax Reitz     int ret;
406e5b43573SFam Zheng 
4072e1990b2SMax Reitz     op->s->in_flight++;
4082e1990b2SMax Reitz     op->s->bytes_in_flight += op->bytes;
4092e1990b2SMax Reitz     *op->bytes_handled = op->bytes;
410ce8cabbdSKevin Wolf     op->is_in_flight = true;
411e5b43573SFam Zheng 
4122e1990b2SMax Reitz     ret = blk_co_pwrite_zeroes(op->s->target, op->offset, op->bytes,
4132e1990b2SMax Reitz                                op->s->unmap ? BDRV_REQ_MAY_UNMAP : 0);
4142e1990b2SMax Reitz     mirror_write_complete(op, ret);
415e5b43573SFam Zheng }
4162e1990b2SMax Reitz 
4172e1990b2SMax Reitz static void coroutine_fn mirror_co_discard(void *opaque)
4182e1990b2SMax Reitz {
4192e1990b2SMax Reitz     MirrorOp *op = opaque;
4202e1990b2SMax Reitz     int ret;
4212e1990b2SMax Reitz 
4222e1990b2SMax Reitz     op->s->in_flight++;
4232e1990b2SMax Reitz     op->s->bytes_in_flight += op->bytes;
4242e1990b2SMax Reitz     *op->bytes_handled = op->bytes;
425ce8cabbdSKevin Wolf     op->is_in_flight = true;
4262e1990b2SMax Reitz 
4272e1990b2SMax Reitz     ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes);
4282e1990b2SMax Reitz     mirror_write_complete(op, ret);
429e5b43573SFam Zheng }
430e5b43573SFam Zheng 
4314295c5fcSMax Reitz static unsigned mirror_perform(MirrorBlockJob *s, int64_t offset,
4324295c5fcSMax Reitz                                unsigned bytes, MirrorMethod mirror_method)
4334295c5fcSMax Reitz {
4342e1990b2SMax Reitz     MirrorOp *op;
4352e1990b2SMax Reitz     Coroutine *co;
4362e1990b2SMax Reitz     int64_t bytes_handled = -1;
4372e1990b2SMax Reitz 
4382e1990b2SMax Reitz     op = g_new(MirrorOp, 1);
4392e1990b2SMax Reitz     *op = (MirrorOp){
4402e1990b2SMax Reitz         .s              = s,
4412e1990b2SMax Reitz         .offset         = offset,
4422e1990b2SMax Reitz         .bytes          = bytes,
4432e1990b2SMax Reitz         .bytes_handled  = &bytes_handled,
4442e1990b2SMax Reitz     };
44512aa4082SMax Reitz     qemu_co_queue_init(&op->waiting_requests);
4462e1990b2SMax Reitz 
4474295c5fcSMax Reitz     switch (mirror_method) {
4484295c5fcSMax Reitz     case MIRROR_METHOD_COPY:
4492e1990b2SMax Reitz         co = qemu_coroutine_create(mirror_co_read, op);
4502e1990b2SMax Reitz         break;
4514295c5fcSMax Reitz     case MIRROR_METHOD_ZERO:
4522e1990b2SMax Reitz         co = qemu_coroutine_create(mirror_co_zero, op);
4532e1990b2SMax Reitz         break;
4544295c5fcSMax Reitz     case MIRROR_METHOD_DISCARD:
4552e1990b2SMax Reitz         co = qemu_coroutine_create(mirror_co_discard, op);
4562e1990b2SMax Reitz         break;
4574295c5fcSMax Reitz     default:
4584295c5fcSMax Reitz         abort();
4594295c5fcSMax Reitz     }
460eed325b9SKevin Wolf     op->co = co;
4612e1990b2SMax Reitz 
46212aa4082SMax Reitz     QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
4632e1990b2SMax Reitz     qemu_coroutine_enter(co);
4642e1990b2SMax Reitz     /* At this point, ownership of op has been moved to the coroutine
4652e1990b2SMax Reitz      * and the object may already be freed */
4662e1990b2SMax Reitz 
4672e1990b2SMax Reitz     /* Assert that this value has been set */
4682e1990b2SMax Reitz     assert(bytes_handled >= 0);
4692e1990b2SMax Reitz 
4702e1990b2SMax Reitz     /* Same assertion as in mirror_co_read() (and for mirror_co_read()
4712e1990b2SMax Reitz      * and mirror_co_discard(), bytes_handled == op->bytes, which
4722e1990b2SMax Reitz      * is the @bytes parameter given to this function) */
4732e1990b2SMax Reitz     assert(bytes_handled <= UINT_MAX);
4742e1990b2SMax Reitz     return bytes_handled;
4754295c5fcSMax Reitz }
4764295c5fcSMax Reitz 
477e5b43573SFam Zheng static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
478e5b43573SFam Zheng {
479138f9fffSMax Reitz     BlockDriverState *source = s->mirror_top_bs->backing->bs;
4801181e19aSMax Reitz     MirrorOp *pseudo_op;
4811181e19aSMax Reitz     int64_t offset;
4821181e19aSMax Reitz     uint64_t delay_ns = 0, ret = 0;
483e5b43573SFam Zheng     /* At least the first dirty chunk is mirrored in one iteration. */
484e5b43573SFam Zheng     int nb_chunks = 1;
4854b5004d9SDenis V. Lunev     bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
486b436982fSEric Blake     int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
487e5b43573SFam Zheng 
488b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_lock(s->dirty_bitmap);
489f798184cSEric Blake     offset = bdrv_dirty_iter_next(s->dbi);
490fb2ef791SEric Blake     if (offset < 0) {
491dc162c8eSFam Zheng         bdrv_set_dirty_iter(s->dbi, 0);
492f798184cSEric Blake         offset = bdrv_dirty_iter_next(s->dbi);
4939a46dba7SEric Blake         trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
494fb2ef791SEric Blake         assert(offset >= 0);
495e5b43573SFam Zheng     }
496b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
497e5b43573SFam Zheng 
4981181e19aSMax Reitz     mirror_wait_on_conflicts(NULL, s, offset, 1);
4999c83625bSMax Reitz 
500da01ff7fSKevin Wolf     job_pause_point(&s->common.job);
501565ac01fSStefan Hajnoczi 
502e5b43573SFam Zheng     /* Find the number of consective dirty chunks following the first dirty
503e5b43573SFam Zheng      * one, and wait for in flight requests in them. */
504b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_lock(s->dirty_bitmap);
505fb2ef791SEric Blake     while (nb_chunks * s->granularity < s->buf_size) {
506dc162c8eSFam Zheng         int64_t next_dirty;
507fb2ef791SEric Blake         int64_t next_offset = offset + nb_chunks * s->granularity;
508fb2ef791SEric Blake         int64_t next_chunk = next_offset / s->granularity;
509fb2ef791SEric Blake         if (next_offset >= s->bdev_length ||
51028636b82SJohn Snow             !bdrv_dirty_bitmap_get_locked(s->dirty_bitmap, next_offset)) {
511e5b43573SFam Zheng             break;
512e5b43573SFam Zheng         }
513e5b43573SFam Zheng         if (test_bit(next_chunk, s->in_flight_bitmap)) {
514e5b43573SFam Zheng             break;
515e5b43573SFam Zheng         }
5169c83625bSMax Reitz 
517f798184cSEric Blake         next_dirty = bdrv_dirty_iter_next(s->dbi);
518fb2ef791SEric Blake         if (next_dirty > next_offset || next_dirty < 0) {
519f27a2742SMax Reitz             /* The bitmap iterator's cache is stale, refresh it */
520715a74d8SEric Blake             bdrv_set_dirty_iter(s->dbi, next_offset);
521f798184cSEric Blake             next_dirty = bdrv_dirty_iter_next(s->dbi);
522f27a2742SMax Reitz         }
523fb2ef791SEric Blake         assert(next_dirty == next_offset);
524e5b43573SFam Zheng         nb_chunks++;
525e5b43573SFam Zheng     }
526e5b43573SFam Zheng 
527e5b43573SFam Zheng     /* Clear dirty bits before querying the block status, because
52831826642SEric Blake      * calling bdrv_block_status_above could yield - if some blocks are
529e5b43573SFam Zheng      * marked dirty in this window, we need to know.
530e5b43573SFam Zheng      */
531e0d7f73eSEric Blake     bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
532e0d7f73eSEric Blake                                    nb_chunks * s->granularity);
533b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
534b64bd51eSPaolo Bonzini 
5351181e19aSMax Reitz     /* Before claiming an area in the in-flight bitmap, we have to
5361181e19aSMax Reitz      * create a MirrorOp for it so that conflicting requests can wait
5371181e19aSMax Reitz      * for it.  mirror_perform() will create the real MirrorOps later,
5381181e19aSMax Reitz      * for now we just create a pseudo operation that will wake up all
5391181e19aSMax Reitz      * conflicting requests once all real operations have been
5401181e19aSMax Reitz      * launched. */
5411181e19aSMax Reitz     pseudo_op = g_new(MirrorOp, 1);
5421181e19aSMax Reitz     *pseudo_op = (MirrorOp){
5431181e19aSMax Reitz         .offset         = offset,
5441181e19aSMax Reitz         .bytes          = nb_chunks * s->granularity,
5451181e19aSMax Reitz         .is_pseudo_op   = true,
5461181e19aSMax Reitz     };
5471181e19aSMax Reitz     qemu_co_queue_init(&pseudo_op->waiting_requests);
5481181e19aSMax Reitz     QTAILQ_INSERT_TAIL(&s->ops_in_flight, pseudo_op, next);
5491181e19aSMax Reitz 
550fb2ef791SEric Blake     bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
551fb2ef791SEric Blake     while (nb_chunks > 0 && offset < s->bdev_length) {
55231826642SEric Blake         int ret;
5537cfd5275SEric Blake         int64_t io_bytes;
554f3e4ce4aSEric Blake         int64_t io_bytes_acct;
5554295c5fcSMax Reitz         MirrorMethod mirror_method = MIRROR_METHOD_COPY;
556e5b43573SFam Zheng 
557fb2ef791SEric Blake         assert(!(offset % s->granularity));
55831826642SEric Blake         ret = bdrv_block_status_above(source, NULL, offset,
55931826642SEric Blake                                       nb_chunks * s->granularity,
56031826642SEric Blake                                       &io_bytes, NULL, NULL);
561e5b43573SFam Zheng         if (ret < 0) {
562fb2ef791SEric Blake             io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
5630965a41eSVladimir Sementsov-Ogievskiy         } else if (ret & BDRV_BLOCK_DATA) {
564fb2ef791SEric Blake             io_bytes = MIN(io_bytes, max_io_bytes);
565e5b43573SFam Zheng         }
566e5b43573SFam Zheng 
567fb2ef791SEric Blake         io_bytes -= io_bytes % s->granularity;
568fb2ef791SEric Blake         if (io_bytes < s->granularity) {
569fb2ef791SEric Blake             io_bytes = s->granularity;
570e5b43573SFam Zheng         } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
571fb2ef791SEric Blake             int64_t target_offset;
5727cfd5275SEric Blake             int64_t target_bytes;
573fb2ef791SEric Blake             bdrv_round_to_clusters(blk_bs(s->target), offset, io_bytes,
574fb2ef791SEric Blake                                    &target_offset, &target_bytes);
575fb2ef791SEric Blake             if (target_offset == offset &&
576fb2ef791SEric Blake                 target_bytes == io_bytes) {
577e5b43573SFam Zheng                 mirror_method = ret & BDRV_BLOCK_ZERO ?
578e5b43573SFam Zheng                                     MIRROR_METHOD_ZERO :
579e5b43573SFam Zheng                                     MIRROR_METHOD_DISCARD;
580e5b43573SFam Zheng             }
581e5b43573SFam Zheng         }
582e5b43573SFam Zheng 
583cf56a3c6SDenis V. Lunev         while (s->in_flight >= MAX_IN_FLIGHT) {
584fb2ef791SEric Blake             trace_mirror_yield_in_flight(s, offset, s->in_flight);
5859178f4feSKevin Wolf             mirror_wait_for_free_in_flight_slot(s);
586cf56a3c6SDenis V. Lunev         }
587cf56a3c6SDenis V. Lunev 
588dbaa7b57SVladimir Sementsov-Ogievskiy         if (s->ret < 0) {
5891181e19aSMax Reitz             ret = 0;
5901181e19aSMax Reitz             goto fail;
591dbaa7b57SVladimir Sementsov-Ogievskiy         }
592dbaa7b57SVladimir Sementsov-Ogievskiy 
593fb2ef791SEric Blake         io_bytes = mirror_clip_bytes(s, offset, io_bytes);
5944295c5fcSMax Reitz         io_bytes = mirror_perform(s, offset, io_bytes, mirror_method);
5954295c5fcSMax Reitz         if (mirror_method != MIRROR_METHOD_COPY && write_zeroes_ok) {
596f3e4ce4aSEric Blake             io_bytes_acct = 0;
5974b5004d9SDenis V. Lunev         } else {
598fb2ef791SEric Blake             io_bytes_acct = io_bytes;
5994b5004d9SDenis V. Lunev         }
600fb2ef791SEric Blake         assert(io_bytes);
601fb2ef791SEric Blake         offset += io_bytes;
602fb2ef791SEric Blake         nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
603dee81d51SKevin Wolf         delay_ns = block_job_ratelimit_get_delay(&s->common, io_bytes_acct);
604dcfb3bebSFam Zheng     }
6051181e19aSMax Reitz 
6061181e19aSMax Reitz     ret = delay_ns;
6071181e19aSMax Reitz fail:
6081181e19aSMax Reitz     QTAILQ_REMOVE(&s->ops_in_flight, pseudo_op, next);
6091181e19aSMax Reitz     qemu_co_queue_restart_all(&pseudo_op->waiting_requests);
6101181e19aSMax Reitz     g_free(pseudo_op);
6111181e19aSMax Reitz 
6121181e19aSMax Reitz     return ret;
613893f7ebaSPaolo Bonzini }
614b952b558SPaolo Bonzini 
615402a4741SPaolo Bonzini static void mirror_free_init(MirrorBlockJob *s)
616402a4741SPaolo Bonzini {
617402a4741SPaolo Bonzini     int granularity = s->granularity;
618402a4741SPaolo Bonzini     size_t buf_size = s->buf_size;
619402a4741SPaolo Bonzini     uint8_t *buf = s->buf;
620402a4741SPaolo Bonzini 
621402a4741SPaolo Bonzini     assert(s->buf_free_count == 0);
622402a4741SPaolo Bonzini     QSIMPLEQ_INIT(&s->buf_free);
623402a4741SPaolo Bonzini     while (buf_size != 0) {
624402a4741SPaolo Bonzini         MirrorBuffer *cur = (MirrorBuffer *)buf;
625402a4741SPaolo Bonzini         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
626402a4741SPaolo Bonzini         s->buf_free_count++;
627402a4741SPaolo Bonzini         buf_size -= granularity;
628402a4741SPaolo Bonzini         buf += granularity;
629402a4741SPaolo Bonzini     }
630402a4741SPaolo Bonzini }
631402a4741SPaolo Bonzini 
632bae8196dSPaolo Bonzini /* This is also used for the .pause callback. There is no matching
633bae8196dSPaolo Bonzini  * mirror_resume() because mirror_run() will begin iterating again
634bae8196dSPaolo Bonzini  * when the job is resumed.
635bae8196dSPaolo Bonzini  */
636537c3d4fSStefan Hajnoczi static void coroutine_fn mirror_wait_for_all_io(MirrorBlockJob *s)
637bd48bde8SPaolo Bonzini {
638bd48bde8SPaolo Bonzini     while (s->in_flight > 0) {
6399178f4feSKevin Wolf         mirror_wait_for_free_in_flight_slot(s);
640bd48bde8SPaolo Bonzini     }
641893f7ebaSPaolo Bonzini }
642893f7ebaSPaolo Bonzini 
643737efc1eSJohn Snow /**
644737efc1eSJohn Snow  * mirror_exit_common: handle both abort() and prepare() cases.
645737efc1eSJohn Snow  * for .prepare, returns 0 on success and -errno on failure.
646737efc1eSJohn Snow  * for .abort cases, denoted by abort = true, MUST return 0.
647737efc1eSJohn Snow  */
648737efc1eSJohn Snow static int mirror_exit_common(Job *job)
6495a7e7a0bSStefan Hajnoczi {
6501908a559SKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
6511908a559SKevin Wolf     BlockJob *bjob = &s->common;
652f93c3addSMax Reitz     MirrorBDSOpaque *bs_opaque;
6535a7e7a0bSStefan Hajnoczi     AioContext *replace_aio_context = NULL;
654f93c3addSMax Reitz     BlockDriverState *src;
655f93c3addSMax Reitz     BlockDriverState *target_bs;
656f93c3addSMax Reitz     BlockDriverState *mirror_top_bs;
65712fa4af6SKevin Wolf     Error *local_err = NULL;
658737efc1eSJohn Snow     bool abort = job->ret < 0;
659737efc1eSJohn Snow     int ret = 0;
660737efc1eSJohn Snow 
661737efc1eSJohn Snow     if (s->prepared) {
662737efc1eSJohn Snow         return 0;
663737efc1eSJohn Snow     }
664737efc1eSJohn Snow     s->prepared = true;
6653f09bfbcSKevin Wolf 
666f93c3addSMax Reitz     mirror_top_bs = s->mirror_top_bs;
667f93c3addSMax Reitz     bs_opaque = mirror_top_bs->opaque;
668f93c3addSMax Reitz     src = mirror_top_bs->backing->bs;
669f93c3addSMax Reitz     target_bs = blk_bs(s->target);
670f93c3addSMax Reitz 
671ef53dc09SAlberto Garcia     if (bdrv_chain_contains(src, target_bs)) {
672ef53dc09SAlberto Garcia         bdrv_unfreeze_backing_chain(mirror_top_bs, target_bs);
673ef53dc09SAlberto Garcia     }
674ef53dc09SAlberto Garcia 
6755deb6cbdSVladimir Sementsov-Ogievskiy     bdrv_release_dirty_bitmap(s->dirty_bitmap);
6762119882cSPaolo Bonzini 
6777b508f6bSJohn Snow     /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
6787b508f6bSJohn Snow      * before we can call bdrv_drained_end */
6793f09bfbcSKevin Wolf     bdrv_ref(src);
6804ef85a9cSKevin Wolf     bdrv_ref(mirror_top_bs);
6817d9fcb39SKevin Wolf     bdrv_ref(target_bs);
6827d9fcb39SKevin Wolf 
683bb0c9409SVladimir Sementsov-Ogievskiy     /*
684bb0c9409SVladimir Sementsov-Ogievskiy      * Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
6857d9fcb39SKevin Wolf      * inserting target_bs at s->to_replace, where we might not be able to get
68663c8ef28SKevin Wolf      * these permissions.
687bb0c9409SVladimir Sementsov-Ogievskiy      */
6887d9fcb39SKevin Wolf     blk_unref(s->target);
6897d9fcb39SKevin Wolf     s->target = NULL;
6904ef85a9cSKevin Wolf 
6914ef85a9cSKevin Wolf     /* We don't access the source any more. Dropping any WRITE/RESIZE is
692d2da5e28SKevin Wolf      * required before it could become a backing file of target_bs. Not having
693d2da5e28SKevin Wolf      * these permissions any more means that we can't allow any new requests on
694d2da5e28SKevin Wolf      * mirror_top_bs from now on, so keep it drained. */
695d2da5e28SKevin Wolf     bdrv_drained_begin(mirror_top_bs);
696f94dc3b4SMax Reitz     bs_opaque->stop = true;
697f94dc3b4SMax Reitz     bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
6984ef85a9cSKevin Wolf                              &error_abort);
699737efc1eSJohn Snow     if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
7004ef85a9cSKevin Wolf         BlockDriverState *backing = s->is_none_mode ? src : s->base;
7013f072a7fSMax Reitz         BlockDriverState *unfiltered_target = bdrv_skip_filters(target_bs);
7023f072a7fSMax Reitz 
7033f072a7fSMax Reitz         if (bdrv_cow_bs(unfiltered_target) != backing) {
7043f072a7fSMax Reitz             bdrv_set_backing_hd(unfiltered_target, backing, &local_err);
70512fa4af6SKevin Wolf             if (local_err) {
70612fa4af6SKevin Wolf                 error_report_err(local_err);
70766c8672dSVladimir Sementsov-Ogievskiy                 local_err = NULL;
7087b508f6bSJohn Snow                 ret = -EPERM;
70912fa4af6SKevin Wolf             }
7104ef85a9cSKevin Wolf         }
711c41f5b96SMax Reitz     } else if (!abort && s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
712c41f5b96SMax Reitz         assert(!bdrv_backing_chain_next(target_bs));
713c41f5b96SMax Reitz         ret = bdrv_open_backing_file(bdrv_skip_filters(target_bs), NULL,
714c41f5b96SMax Reitz                                      "backing", &local_err);
715c41f5b96SMax Reitz         if (ret < 0) {
716c41f5b96SMax Reitz             error_report_err(local_err);
717c41f5b96SMax Reitz             local_err = NULL;
718c41f5b96SMax Reitz         }
7194ef85a9cSKevin Wolf     }
7205a7e7a0bSStefan Hajnoczi 
7215a7e7a0bSStefan Hajnoczi     if (s->to_replace) {
7225a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(s->to_replace);
7235a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
7245a7e7a0bSStefan Hajnoczi     }
7255a7e7a0bSStefan Hajnoczi 
726737efc1eSJohn Snow     if (s->should_complete && !abort) {
727737efc1eSJohn Snow         BlockDriverState *to_replace = s->to_replace ?: src;
7281ba79388SAlberto Garcia         bool ro = bdrv_is_read_only(to_replace);
72940365552SKevin Wolf 
7301ba79388SAlberto Garcia         if (ro != bdrv_is_read_only(target_bs)) {
7311ba79388SAlberto Garcia             bdrv_reopen_set_read_only(target_bs, ro, NULL);
7325a7e7a0bSStefan Hajnoczi         }
733b8804815SKevin Wolf 
734b8804815SKevin Wolf         /* The mirror job has no requests in flight any more, but we need to
735b8804815SKevin Wolf          * drain potential other users of the BDS before changing the graph. */
7365e771752SSergio Lopez         assert(s->in_drain);
737e253f4b8SKevin Wolf         bdrv_drained_begin(target_bs);
7386e9cc051SMax Reitz         /*
7396e9cc051SMax Reitz          * Cannot use check_to_replace_node() here, because that would
7406e9cc051SMax Reitz          * check for an op blocker on @to_replace, and we have our own
7416e9cc051SMax Reitz          * there.
7426e9cc051SMax Reitz          */
7436e9cc051SMax Reitz         if (bdrv_recurse_can_replace(src, to_replace)) {
7445fe31c25SKevin Wolf             bdrv_replace_node(to_replace, target_bs, &local_err);
7456e9cc051SMax Reitz         } else {
7466e9cc051SMax Reitz             error_setg(&local_err, "Can no longer replace '%s' by '%s', "
7476e9cc051SMax Reitz                        "because it can no longer be guaranteed that doing so "
7486e9cc051SMax Reitz                        "would not lead to an abrupt change of visible data",
7496e9cc051SMax Reitz                        to_replace->node_name, target_bs->node_name);
7506e9cc051SMax Reitz         }
751e253f4b8SKevin Wolf         bdrv_drained_end(target_bs);
7525fe31c25SKevin Wolf         if (local_err) {
7535fe31c25SKevin Wolf             error_report_err(local_err);
7547b508f6bSJohn Snow             ret = -EPERM;
7555fe31c25SKevin Wolf         }
7565a7e7a0bSStefan Hajnoczi     }
7575a7e7a0bSStefan Hajnoczi     if (s->to_replace) {
7585a7e7a0bSStefan Hajnoczi         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
7595a7e7a0bSStefan Hajnoczi         error_free(s->replace_blocker);
7605a7e7a0bSStefan Hajnoczi         bdrv_unref(s->to_replace);
7615a7e7a0bSStefan Hajnoczi     }
7625a7e7a0bSStefan Hajnoczi     if (replace_aio_context) {
7635a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
7645a7e7a0bSStefan Hajnoczi     }
7655a7e7a0bSStefan Hajnoczi     g_free(s->replaces);
7667d9fcb39SKevin Wolf     bdrv_unref(target_bs);
7674ef85a9cSKevin Wolf 
768f94dc3b4SMax Reitz     /*
769f94dc3b4SMax Reitz      * Remove the mirror filter driver from the graph. Before this, get rid of
7704ef85a9cSKevin Wolf      * the blockers on the intermediate nodes so that the resulting state is
771f94dc3b4SMax Reitz      * valid.
772f94dc3b4SMax Reitz      */
7731908a559SKevin Wolf     block_job_remove_all_bdrv(bjob);
7743f072a7fSMax Reitz     bdrv_replace_node(mirror_top_bs, mirror_top_bs->backing->bs, &error_abort);
7754ef85a9cSKevin Wolf 
7764ef85a9cSKevin Wolf     /* We just changed the BDS the job BB refers to (with either or both of the
7775fe31c25SKevin Wolf      * bdrv_replace_node() calls), so switch the BB back so the cleanup does
7785fe31c25SKevin Wolf      * the right thing. We don't need any permissions any more now. */
7791908a559SKevin Wolf     blk_remove_bs(bjob->blk);
7801908a559SKevin Wolf     blk_set_perm(bjob->blk, 0, BLK_PERM_ALL, &error_abort);
7811908a559SKevin Wolf     blk_insert_bs(bjob->blk, mirror_top_bs, &error_abort);
7824ef85a9cSKevin Wolf 
783429076e8SMax Reitz     bs_opaque->job = NULL;
7844ef85a9cSKevin Wolf 
785176c3699SFam Zheng     bdrv_drained_end(src);
786d2da5e28SKevin Wolf     bdrv_drained_end(mirror_top_bs);
7875e771752SSergio Lopez     s->in_drain = false;
7884ef85a9cSKevin Wolf     bdrv_unref(mirror_top_bs);
7893f09bfbcSKevin Wolf     bdrv_unref(src);
7907b508f6bSJohn Snow 
791737efc1eSJohn Snow     return ret;
792737efc1eSJohn Snow }
793737efc1eSJohn Snow 
794737efc1eSJohn Snow static int mirror_prepare(Job *job)
795737efc1eSJohn Snow {
796737efc1eSJohn Snow     return mirror_exit_common(job);
797737efc1eSJohn Snow }
798737efc1eSJohn Snow 
799737efc1eSJohn Snow static void mirror_abort(Job *job)
800737efc1eSJohn Snow {
801737efc1eSJohn Snow     int ret = mirror_exit_common(job);
802737efc1eSJohn Snow     assert(ret == 0);
8035a7e7a0bSStefan Hajnoczi }
8045a7e7a0bSStefan Hajnoczi 
805537c3d4fSStefan Hajnoczi static void coroutine_fn mirror_throttle(MirrorBlockJob *s)
80649efb1f5SDenis V. Lunev {
80749efb1f5SDenis V. Lunev     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
80849efb1f5SDenis V. Lunev 
80918bb6928SKevin Wolf     if (now - s->last_pause_ns > BLOCK_JOB_SLICE_TIME) {
81049efb1f5SDenis V. Lunev         s->last_pause_ns = now;
8115d43e86eSKevin Wolf         job_sleep_ns(&s->common.job, 0);
81249efb1f5SDenis V. Lunev     } else {
813da01ff7fSKevin Wolf         job_pause_point(&s->common.job);
81449efb1f5SDenis V. Lunev     }
81549efb1f5SDenis V. Lunev }
81649efb1f5SDenis V. Lunev 
817c0b363adSDenis V. Lunev static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
818c0b363adSDenis V. Lunev {
81923ca459aSEric Blake     int64_t offset;
820138f9fffSMax Reitz     BlockDriverState *bs = s->mirror_top_bs->backing->bs;
821c0b363adSDenis V. Lunev     BlockDriverState *target_bs = blk_bs(s->target);
82223ca459aSEric Blake     int ret;
82351b0a488SEric Blake     int64_t count;
824c0b363adSDenis V. Lunev 
825cdf3bc93SMax Reitz     if (s->zero_target) {
826c7c2769cSDenis V. Lunev         if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
827e0d7f73eSEric Blake             bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
828b7d5062cSDenis V. Lunev             return 0;
829b7d5062cSDenis V. Lunev         }
830b7d5062cSDenis V. Lunev 
83190ab48ebSAnton Nefedov         s->initial_zeroing_ongoing = true;
83223ca459aSEric Blake         for (offset = 0; offset < s->bdev_length; ) {
83323ca459aSEric Blake             int bytes = MIN(s->bdev_length - offset,
83423ca459aSEric Blake                             QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
835c7c2769cSDenis V. Lunev 
836c7c2769cSDenis V. Lunev             mirror_throttle(s);
837c7c2769cSDenis V. Lunev 
838daa7f2f9SKevin Wolf             if (job_is_cancelled(&s->common.job)) {
83990ab48ebSAnton Nefedov                 s->initial_zeroing_ongoing = false;
840c7c2769cSDenis V. Lunev                 return 0;
841c7c2769cSDenis V. Lunev             }
842c7c2769cSDenis V. Lunev 
843c7c2769cSDenis V. Lunev             if (s->in_flight >= MAX_IN_FLIGHT) {
84467adf4b3SEric Blake                 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
84567adf4b3SEric Blake                                    s->in_flight);
8469178f4feSKevin Wolf                 mirror_wait_for_free_in_flight_slot(s);
847c7c2769cSDenis V. Lunev                 continue;
848c7c2769cSDenis V. Lunev             }
849c7c2769cSDenis V. Lunev 
8504295c5fcSMax Reitz             mirror_perform(s, offset, bytes, MIRROR_METHOD_ZERO);
85123ca459aSEric Blake             offset += bytes;
852c7c2769cSDenis V. Lunev         }
853c7c2769cSDenis V. Lunev 
854bae8196dSPaolo Bonzini         mirror_wait_for_all_io(s);
85590ab48ebSAnton Nefedov         s->initial_zeroing_ongoing = false;
856c7c2769cSDenis V. Lunev     }
857c7c2769cSDenis V. Lunev 
858c0b363adSDenis V. Lunev     /* First part, loop on the sectors and initialize the dirty bitmap.  */
85923ca459aSEric Blake     for (offset = 0; offset < s->bdev_length; ) {
860c0b363adSDenis V. Lunev         /* Just to make sure we are not exceeding int limit. */
86123ca459aSEric Blake         int bytes = MIN(s->bdev_length - offset,
86223ca459aSEric Blake                         QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
863c0b363adSDenis V. Lunev 
864c0b363adSDenis V. Lunev         mirror_throttle(s);
865c0b363adSDenis V. Lunev 
866daa7f2f9SKevin Wolf         if (job_is_cancelled(&s->common.job)) {
867c0b363adSDenis V. Lunev             return 0;
868c0b363adSDenis V. Lunev         }
869c0b363adSDenis V. Lunev 
8703f072a7fSMax Reitz         ret = bdrv_is_allocated_above(bs, s->base_overlay, true, offset, bytes,
8713f072a7fSMax Reitz                                       &count);
872c0b363adSDenis V. Lunev         if (ret < 0) {
873c0b363adSDenis V. Lunev             return ret;
874c0b363adSDenis V. Lunev         }
875c0b363adSDenis V. Lunev 
87623ca459aSEric Blake         assert(count);
877a92b1b06SEric Blake         if (ret > 0) {
87823ca459aSEric Blake             bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
879c0b363adSDenis V. Lunev         }
88023ca459aSEric Blake         offset += count;
881c0b363adSDenis V. Lunev     }
882c0b363adSDenis V. Lunev     return 0;
883c0b363adSDenis V. Lunev }
884c0b363adSDenis V. Lunev 
885bdffb31dSPaolo Bonzini /* Called when going out of the streaming phase to flush the bulk of the
886bdffb31dSPaolo Bonzini  * data to the medium, or just before completing.
887bdffb31dSPaolo Bonzini  */
888bdffb31dSPaolo Bonzini static int mirror_flush(MirrorBlockJob *s)
889bdffb31dSPaolo Bonzini {
890bdffb31dSPaolo Bonzini     int ret = blk_flush(s->target);
891bdffb31dSPaolo Bonzini     if (ret < 0) {
892bdffb31dSPaolo Bonzini         if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
893bdffb31dSPaolo Bonzini             s->ret = ret;
894bdffb31dSPaolo Bonzini         }
895bdffb31dSPaolo Bonzini     }
896bdffb31dSPaolo Bonzini     return ret;
897bdffb31dSPaolo Bonzini }
898bdffb31dSPaolo Bonzini 
899f67432a2SJohn Snow static int coroutine_fn mirror_run(Job *job, Error **errp)
900893f7ebaSPaolo Bonzini {
901f67432a2SJohn Snow     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
902138f9fffSMax Reitz     BlockDriverState *bs = s->mirror_top_bs->backing->bs;
903e253f4b8SKevin Wolf     BlockDriverState *target_bs = blk_bs(s->target);
9049a0cec66SPaolo Bonzini     bool need_drain = true;
905c0b363adSDenis V. Lunev     int64_t length;
906e83dd680SKevin Wolf     int64_t target_length;
907b812f671SPaolo Bonzini     BlockDriverInfo bdi;
9081d33936eSJeff Cody     char backing_filename[2]; /* we only need 2 characters because we are only
9091d33936eSJeff Cody                                  checking for a NULL string */
910893f7ebaSPaolo Bonzini     int ret = 0;
911893f7ebaSPaolo Bonzini 
912daa7f2f9SKevin Wolf     if (job_is_cancelled(&s->common.job)) {
913893f7ebaSPaolo Bonzini         goto immediate_exit;
914893f7ebaSPaolo Bonzini     }
915893f7ebaSPaolo Bonzini 
916b21c7652SMax Reitz     s->bdev_length = bdrv_getlength(bs);
917b21c7652SMax Reitz     if (s->bdev_length < 0) {
918b21c7652SMax Reitz         ret = s->bdev_length;
919373df5b1SFam Zheng         goto immediate_exit;
920becc347eSKevin Wolf     }
921becc347eSKevin Wolf 
922e83dd680SKevin Wolf     target_length = blk_getlength(s->target);
923e83dd680SKevin Wolf     if (target_length < 0) {
924e83dd680SKevin Wolf         ret = target_length;
925becc347eSKevin Wolf         goto immediate_exit;
926becc347eSKevin Wolf     }
927becc347eSKevin Wolf 
928e83dd680SKevin Wolf     /* Active commit must resize the base image if its size differs from the
929e83dd680SKevin Wolf      * active layer. */
930e83dd680SKevin Wolf     if (s->base == blk_bs(s->target)) {
931e83dd680SKevin Wolf         if (s->bdev_length > target_length) {
932c80d8b06SMax Reitz             ret = blk_truncate(s->target, s->bdev_length, false,
9338c6242b6SKevin Wolf                                PREALLOC_MODE_OFF, 0, NULL);
934becc347eSKevin Wolf             if (ret < 0) {
935becc347eSKevin Wolf                 goto immediate_exit;
936becc347eSKevin Wolf             }
937becc347eSKevin Wolf         }
938e83dd680SKevin Wolf     } else if (s->bdev_length != target_length) {
939e83dd680SKevin Wolf         error_setg(errp, "Source and target image have different sizes");
940e83dd680SKevin Wolf         ret = -EINVAL;
941e83dd680SKevin Wolf         goto immediate_exit;
942becc347eSKevin Wolf     }
943becc347eSKevin Wolf 
944becc347eSKevin Wolf     if (s->bdev_length == 0) {
9452e1795b5SKevin Wolf         /* Transition to the READY state and wait for complete. */
9462e1795b5SKevin Wolf         job_transition_to_ready(&s->common.job);
9479e48b025SFam Zheng         s->synced = true;
948d06107adSMax Reitz         s->actively_synced = true;
949daa7f2f9SKevin Wolf         while (!job_is_cancelled(&s->common.job) && !s->should_complete) {
950198c49ccSKevin Wolf             job_yield(&s->common.job);
9519e48b025SFam Zheng         }
952daa7f2f9SKevin Wolf         s->common.job.cancelled = false;
9539e48b025SFam Zheng         goto immediate_exit;
954893f7ebaSPaolo Bonzini     }
955893f7ebaSPaolo Bonzini 
956b21c7652SMax Reitz     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
957402a4741SPaolo Bonzini     s->in_flight_bitmap = bitmap_new(length);
958402a4741SPaolo Bonzini 
959b812f671SPaolo Bonzini     /* If we have no backing file yet in the destination, we cannot let
960b812f671SPaolo Bonzini      * the destination do COW.  Instead, we copy sectors around the
961b812f671SPaolo Bonzini      * dirty data if needed.  We need a bitmap to do that.
962b812f671SPaolo Bonzini      */
963e253f4b8SKevin Wolf     bdrv_get_backing_filename(target_bs, backing_filename,
964b812f671SPaolo Bonzini                               sizeof(backing_filename));
965e253f4b8SKevin Wolf     if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
966b436982fSEric Blake         s->target_cluster_size = bdi.cluster_size;
967b436982fSEric Blake     } else {
968b436982fSEric Blake         s->target_cluster_size = BDRV_SECTOR_SIZE;
969c3cc95bdSFam Zheng     }
9703f072a7fSMax Reitz     if (backing_filename[0] && !bdrv_backing_chain_next(target_bs) &&
971b436982fSEric Blake         s->granularity < s->target_cluster_size) {
972b436982fSEric Blake         s->buf_size = MAX(s->buf_size, s->target_cluster_size);
973b812f671SPaolo Bonzini         s->cow_bitmap = bitmap_new(length);
974b812f671SPaolo Bonzini     }
975e253f4b8SKevin Wolf     s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
976b812f671SPaolo Bonzini 
9777504edf4SKevin Wolf     s->buf = qemu_try_blockalign(bs, s->buf_size);
9787504edf4SKevin Wolf     if (s->buf == NULL) {
9797504edf4SKevin Wolf         ret = -ENOMEM;
9807504edf4SKevin Wolf         goto immediate_exit;
9817504edf4SKevin Wolf     }
9827504edf4SKevin Wolf 
983402a4741SPaolo Bonzini     mirror_free_init(s);
984893f7ebaSPaolo Bonzini 
98549efb1f5SDenis V. Lunev     s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
98603544a6eSFam Zheng     if (!s->is_none_mode) {
987c0b363adSDenis V. Lunev         ret = mirror_dirty_init(s);
988daa7f2f9SKevin Wolf         if (ret < 0 || job_is_cancelled(&s->common.job)) {
9894c0cbd6fSFam Zheng             goto immediate_exit;
9904c0cbd6fSFam Zheng         }
991893f7ebaSPaolo Bonzini     }
992893f7ebaSPaolo Bonzini 
993dc162c8eSFam Zheng     assert(!s->dbi);
994715a74d8SEric Blake     s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
995893f7ebaSPaolo Bonzini     for (;;) {
996cc8c9d6cSPaolo Bonzini         uint64_t delay_ns = 0;
99749efb1f5SDenis V. Lunev         int64_t cnt, delta;
998893f7ebaSPaolo Bonzini         bool should_complete;
999893f7ebaSPaolo Bonzini 
1000d06107adSMax Reitz         /* Do not start passive operations while there are active
1001d06107adSMax Reitz          * writes in progress */
1002d06107adSMax Reitz         while (s->in_active_write_counter) {
10039178f4feSKevin Wolf             mirror_wait_for_any_operation(s, true);
1004d06107adSMax Reitz         }
1005d06107adSMax Reitz 
1006bd48bde8SPaolo Bonzini         if (s->ret < 0) {
1007bd48bde8SPaolo Bonzini             ret = s->ret;
1008893f7ebaSPaolo Bonzini             goto immediate_exit;
1009893f7ebaSPaolo Bonzini         }
1010bd48bde8SPaolo Bonzini 
1011da01ff7fSKevin Wolf         job_pause_point(&s->common.job);
1012565ac01fSStefan Hajnoczi 
101320dca810SJohn Snow         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
101405df8a6aSKevin Wolf         /* cnt is the number of dirty bytes remaining and s->bytes_in_flight is
101505df8a6aSKevin Wolf          * the number of bytes currently being processed; together those are
101605df8a6aSKevin Wolf          * the current remaining operation length */
101730a5c887SKevin Wolf         job_progress_set_remaining(&s->common.job, s->bytes_in_flight + cnt);
1018bd48bde8SPaolo Bonzini 
1019bd48bde8SPaolo Bonzini         /* Note that even when no rate limit is applied we need to yield
1020a7282330SFam Zheng          * periodically with no pending I/O so that bdrv_drain_all() returns.
102118bb6928SKevin Wolf          * We do so every BLKOCK_JOB_SLICE_TIME nanoseconds, or when there is
102218bb6928SKevin Wolf          * an error, or when the source is clean, whichever comes first. */
102349efb1f5SDenis V. Lunev         delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
102418bb6928SKevin Wolf         if (delta < BLOCK_JOB_SLICE_TIME &&
1025bd48bde8SPaolo Bonzini             s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
1026cf56a3c6SDenis V. Lunev             if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
1027402a4741SPaolo Bonzini                 (cnt == 0 && s->in_flight > 0)) {
10289a46dba7SEric Blake                 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
10299178f4feSKevin Wolf                 mirror_wait_for_free_in_flight_slot(s);
1030bd48bde8SPaolo Bonzini                 continue;
1031bd48bde8SPaolo Bonzini             } else if (cnt != 0) {
1032cc8c9d6cSPaolo Bonzini                 delay_ns = mirror_iteration(s);
1033893f7ebaSPaolo Bonzini             }
1034cc8c9d6cSPaolo Bonzini         }
1035893f7ebaSPaolo Bonzini 
1036893f7ebaSPaolo Bonzini         should_complete = false;
1037bd48bde8SPaolo Bonzini         if (s->in_flight == 0 && cnt == 0) {
1038893f7ebaSPaolo Bonzini             trace_mirror_before_flush(s);
1039bdffb31dSPaolo Bonzini             if (!s->synced) {
1040bdffb31dSPaolo Bonzini                 if (mirror_flush(s) < 0) {
1041bdffb31dSPaolo Bonzini                     /* Go check s->ret.  */
1042bdffb31dSPaolo Bonzini                     continue;
1043893f7ebaSPaolo Bonzini                 }
1044893f7ebaSPaolo Bonzini                 /* We're out of the streaming phase.  From now on, if the job
1045893f7ebaSPaolo Bonzini                  * is cancelled we will actually complete all pending I/O and
1046893f7ebaSPaolo Bonzini                  * report completion.  This way, block-job-cancel will leave
1047893f7ebaSPaolo Bonzini                  * the target in a consistent state.
1048893f7ebaSPaolo Bonzini                  */
10492e1795b5SKevin Wolf                 job_transition_to_ready(&s->common.job);
1050d63ffd87SPaolo Bonzini                 s->synced = true;
1051d06107adSMax Reitz                 if (s->copy_mode != MIRROR_COPY_MODE_BACKGROUND) {
1052d06107adSMax Reitz                     s->actively_synced = true;
1053d06107adSMax Reitz                 }
1054d63ffd87SPaolo Bonzini             }
1055d63ffd87SPaolo Bonzini 
1056d63ffd87SPaolo Bonzini             should_complete = s->should_complete ||
1057daa7f2f9SKevin Wolf                 job_is_cancelled(&s->common.job);
105820dca810SJohn Snow             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1059893f7ebaSPaolo Bonzini         }
1060893f7ebaSPaolo Bonzini 
1061893f7ebaSPaolo Bonzini         if (cnt == 0 && should_complete) {
1062893f7ebaSPaolo Bonzini             /* The dirty bitmap is not updated while operations are pending.
1063893f7ebaSPaolo Bonzini              * If we're about to exit, wait for pending operations before
1064893f7ebaSPaolo Bonzini              * calling bdrv_get_dirty_count(bs), or we may exit while the
1065893f7ebaSPaolo Bonzini              * source has dirty data to copy!
1066893f7ebaSPaolo Bonzini              *
1067893f7ebaSPaolo Bonzini              * Note that I/O can be submitted by the guest while
10689a0cec66SPaolo Bonzini              * mirror_populate runs, so pause it now.  Before deciding
10699a0cec66SPaolo Bonzini              * whether to switch to target check one last time if I/O has
10709a0cec66SPaolo Bonzini              * come in the meanwhile, and if not flush the data to disk.
1071893f7ebaSPaolo Bonzini              */
10729a46dba7SEric Blake             trace_mirror_before_drain(s, cnt);
10739a0cec66SPaolo Bonzini 
10745e771752SSergio Lopez             s->in_drain = true;
10759a0cec66SPaolo Bonzini             bdrv_drained_begin(bs);
107620dca810SJohn Snow             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1077bdffb31dSPaolo Bonzini             if (cnt > 0 || mirror_flush(s) < 0) {
10789a0cec66SPaolo Bonzini                 bdrv_drained_end(bs);
10795e771752SSergio Lopez                 s->in_drain = false;
10809a0cec66SPaolo Bonzini                 continue;
10819a0cec66SPaolo Bonzini             }
10829a0cec66SPaolo Bonzini 
10839a0cec66SPaolo Bonzini             /* The two disks are in sync.  Exit and report successful
10849a0cec66SPaolo Bonzini              * completion.
10859a0cec66SPaolo Bonzini              */
10869a0cec66SPaolo Bonzini             assert(QLIST_EMPTY(&bs->tracked_requests));
1087daa7f2f9SKevin Wolf             s->common.job.cancelled = false;
10889a0cec66SPaolo Bonzini             need_drain = false;
10899a0cec66SPaolo Bonzini             break;
1090893f7ebaSPaolo Bonzini         }
1091893f7ebaSPaolo Bonzini 
1092893f7ebaSPaolo Bonzini         ret = 0;
1093ddc4115eSStefan Hajnoczi 
1094ddc4115eSStefan Hajnoczi         if (s->synced && !should_complete) {
109518bb6928SKevin Wolf             delay_ns = (s->in_flight == 0 &&
109618bb6928SKevin Wolf                         cnt == 0 ? BLOCK_JOB_SLICE_TIME : 0);
1097ddc4115eSStefan Hajnoczi         }
10989a46dba7SEric Blake         trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
10995d43e86eSKevin Wolf         job_sleep_ns(&s->common.job, delay_ns);
1100daa7f2f9SKevin Wolf         if (job_is_cancelled(&s->common.job) &&
1101004e95dfSKevin Wolf             (!s->synced || s->common.job.force_cancel))
1102eb36639fSMax Reitz         {
1103893f7ebaSPaolo Bonzini             break;
1104893f7ebaSPaolo Bonzini         }
110549efb1f5SDenis V. Lunev         s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1106893f7ebaSPaolo Bonzini     }
1107893f7ebaSPaolo Bonzini 
1108893f7ebaSPaolo Bonzini immediate_exit:
1109bd48bde8SPaolo Bonzini     if (s->in_flight > 0) {
1110bd48bde8SPaolo Bonzini         /* We get here only if something went wrong.  Either the job failed,
1111bd48bde8SPaolo Bonzini          * or it was cancelled prematurely so that we do not guarantee that
1112bd48bde8SPaolo Bonzini          * the target is a copy of the source.
1113bd48bde8SPaolo Bonzini          */
1114004e95dfSKevin Wolf         assert(ret < 0 || ((s->common.job.force_cancel || !s->synced) &&
1115daa7f2f9SKevin Wolf                job_is_cancelled(&s->common.job)));
11169a0cec66SPaolo Bonzini         assert(need_drain);
1117bae8196dSPaolo Bonzini         mirror_wait_for_all_io(s);
1118bd48bde8SPaolo Bonzini     }
1119bd48bde8SPaolo Bonzini 
1120bd48bde8SPaolo Bonzini     assert(s->in_flight == 0);
11217191bf31SMarkus Armbruster     qemu_vfree(s->buf);
1122b812f671SPaolo Bonzini     g_free(s->cow_bitmap);
1123402a4741SPaolo Bonzini     g_free(s->in_flight_bitmap);
1124dc162c8eSFam Zheng     bdrv_dirty_iter_free(s->dbi);
11255a7e7a0bSStefan Hajnoczi 
11269a0cec66SPaolo Bonzini     if (need_drain) {
11275e771752SSergio Lopez         s->in_drain = true;
1128e253f4b8SKevin Wolf         bdrv_drained_begin(bs);
11299a0cec66SPaolo Bonzini     }
1130f67432a2SJohn Snow 
1131f67432a2SJohn Snow     return ret;
1132893f7ebaSPaolo Bonzini }
1133893f7ebaSPaolo Bonzini 
11343453d972SKevin Wolf static void mirror_complete(Job *job, Error **errp)
1135d63ffd87SPaolo Bonzini {
11363453d972SKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1137274fcceeSMax Reitz 
1138d63ffd87SPaolo Bonzini     if (!s->synced) {
11399df229c3SAlberto Garcia         error_setg(errp, "The active block job '%s' cannot be completed",
11403453d972SKevin Wolf                    job->id);
1141d63ffd87SPaolo Bonzini         return;
1142d63ffd87SPaolo Bonzini     }
1143d63ffd87SPaolo Bonzini 
114415d67298SChanglong Xie     /* block all operations on to_replace bs */
114509158f00SBenoît Canet     if (s->replaces) {
11465a7e7a0bSStefan Hajnoczi         AioContext *replace_aio_context;
11475a7e7a0bSStefan Hajnoczi 
1148e12f3784SWen Congyang         s->to_replace = bdrv_find_node(s->replaces);
114909158f00SBenoît Canet         if (!s->to_replace) {
1150e12f3784SWen Congyang             error_setg(errp, "Node name '%s' not found", s->replaces);
115109158f00SBenoît Canet             return;
115209158f00SBenoît Canet         }
115309158f00SBenoît Canet 
11545a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(s->to_replace);
11555a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
11565a7e7a0bSStefan Hajnoczi 
11574ef85a9cSKevin Wolf         /* TODO Translate this into permission system. Current definition of
11584ef85a9cSKevin Wolf          * GRAPH_MOD would require to request it for the parents; they might
11594ef85a9cSKevin Wolf          * not even be BlockDriverStates, however, so a BdrvChild can't address
11604ef85a9cSKevin Wolf          * them. May need redefinition of GRAPH_MOD. */
116109158f00SBenoît Canet         error_setg(&s->replace_blocker,
116209158f00SBenoît Canet                    "block device is in use by block-job-complete");
116309158f00SBenoît Canet         bdrv_op_block_all(s->to_replace, s->replace_blocker);
116409158f00SBenoît Canet         bdrv_ref(s->to_replace);
11655a7e7a0bSStefan Hajnoczi 
11665a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
116709158f00SBenoît Canet     }
116809158f00SBenoît Canet 
1169d63ffd87SPaolo Bonzini     s->should_complete = true;
117000769414SMax Reitz 
117100769414SMax Reitz     /* If the job is paused, it will be re-entered when it is resumed */
117200769414SMax Reitz     if (!job->paused) {
11733d70ff53SKevin Wolf         job_enter(job);
1174d63ffd87SPaolo Bonzini     }
117500769414SMax Reitz }
1176d63ffd87SPaolo Bonzini 
1177537c3d4fSStefan Hajnoczi static void coroutine_fn mirror_pause(Job *job)
1178565ac01fSStefan Hajnoczi {
1179da01ff7fSKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1180565ac01fSStefan Hajnoczi 
1181bae8196dSPaolo Bonzini     mirror_wait_for_all_io(s);
1182565ac01fSStefan Hajnoczi }
1183565ac01fSStefan Hajnoczi 
118489bd0305SKevin Wolf static bool mirror_drained_poll(BlockJob *job)
118589bd0305SKevin Wolf {
118689bd0305SKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
11875e771752SSergio Lopez 
11885e771752SSergio Lopez     /* If the job isn't paused nor cancelled, we can't be sure that it won't
11895e771752SSergio Lopez      * issue more requests. We make an exception if we've reached this point
11905e771752SSergio Lopez      * from one of our own drain sections, to avoid a deadlock waiting for
11915e771752SSergio Lopez      * ourselves.
11925e771752SSergio Lopez      */
11935e771752SSergio Lopez     if (!s->common.job.paused && !s->common.job.cancelled && !s->in_drain) {
11945e771752SSergio Lopez         return true;
11955e771752SSergio Lopez     }
11965e771752SSergio Lopez 
119789bd0305SKevin Wolf     return !!s->in_flight;
119889bd0305SKevin Wolf }
119989bd0305SKevin Wolf 
12009c785cd7SVladimir Sementsov-Ogievskiy static void mirror_cancel(Job *job, bool force)
1201521ff8b7SVladimir Sementsov-Ogievskiy {
1202521ff8b7SVladimir Sementsov-Ogievskiy     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1203521ff8b7SVladimir Sementsov-Ogievskiy     BlockDriverState *target = blk_bs(s->target);
1204521ff8b7SVladimir Sementsov-Ogievskiy 
12059c785cd7SVladimir Sementsov-Ogievskiy     if (force || !job_is_ready(job)) {
1206521ff8b7SVladimir Sementsov-Ogievskiy         bdrv_cancel_in_flight(target);
1207521ff8b7SVladimir Sementsov-Ogievskiy     }
12089c785cd7SVladimir Sementsov-Ogievskiy }
1209521ff8b7SVladimir Sementsov-Ogievskiy 
12103fc4b10aSFam Zheng static const BlockJobDriver mirror_job_driver = {
121133e9e9bdSKevin Wolf     .job_driver = {
1212893f7ebaSPaolo Bonzini         .instance_size          = sizeof(MirrorBlockJob),
12138e4c8700SKevin Wolf         .job_type               = JOB_TYPE_MIRROR,
121480fa2c75SKevin Wolf         .free                   = block_job_free,
1215b15de828SKevin Wolf         .user_resume            = block_job_user_resume,
1216f67432a2SJohn Snow         .run                    = mirror_run,
1217737efc1eSJohn Snow         .prepare                = mirror_prepare,
1218737efc1eSJohn Snow         .abort                  = mirror_abort,
1219565ac01fSStefan Hajnoczi         .pause                  = mirror_pause,
1220da01ff7fSKevin Wolf         .complete               = mirror_complete,
1221521ff8b7SVladimir Sementsov-Ogievskiy         .cancel                 = mirror_cancel,
12223453d972SKevin Wolf     },
122389bd0305SKevin Wolf     .drained_poll           = mirror_drained_poll,
1224893f7ebaSPaolo Bonzini };
1225893f7ebaSPaolo Bonzini 
122603544a6eSFam Zheng static const BlockJobDriver commit_active_job_driver = {
122733e9e9bdSKevin Wolf     .job_driver = {
122803544a6eSFam Zheng         .instance_size          = sizeof(MirrorBlockJob),
12298e4c8700SKevin Wolf         .job_type               = JOB_TYPE_COMMIT,
123080fa2c75SKevin Wolf         .free                   = block_job_free,
1231b15de828SKevin Wolf         .user_resume            = block_job_user_resume,
1232f67432a2SJohn Snow         .run                    = mirror_run,
1233737efc1eSJohn Snow         .prepare                = mirror_prepare,
1234737efc1eSJohn Snow         .abort                  = mirror_abort,
1235565ac01fSStefan Hajnoczi         .pause                  = mirror_pause,
1236da01ff7fSKevin Wolf         .complete               = mirror_complete,
12373453d972SKevin Wolf     },
123889bd0305SKevin Wolf     .drained_poll           = mirror_drained_poll,
123903544a6eSFam Zheng };
124003544a6eSFam Zheng 
1241537c3d4fSStefan Hajnoczi static void coroutine_fn
1242537c3d4fSStefan Hajnoczi do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
1243d06107adSMax Reitz                      uint64_t offset, uint64_t bytes,
1244d06107adSMax Reitz                      QEMUIOVector *qiov, int flags)
1245d06107adSMax Reitz {
1246d06107adSMax Reitz     int ret;
1247dbdf699cSVladimir Sementsov-Ogievskiy     size_t qiov_offset = 0;
1248dbdf699cSVladimir Sementsov-Ogievskiy     int64_t bitmap_offset, bitmap_end;
1249d06107adSMax Reitz 
1250dbdf699cSVladimir Sementsov-Ogievskiy     if (!QEMU_IS_ALIGNED(offset, job->granularity) &&
1251dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_dirty_bitmap_get(job->dirty_bitmap, offset))
1252dbdf699cSVladimir Sementsov-Ogievskiy     {
1253dbdf699cSVladimir Sementsov-Ogievskiy             /*
1254dbdf699cSVladimir Sementsov-Ogievskiy              * Dirty unaligned padding: ignore it.
1255dbdf699cSVladimir Sementsov-Ogievskiy              *
1256dbdf699cSVladimir Sementsov-Ogievskiy              * Reasoning:
1257dbdf699cSVladimir Sementsov-Ogievskiy              * 1. If we copy it, we can't reset corresponding bit in
1258dbdf699cSVladimir Sementsov-Ogievskiy              *    dirty_bitmap as there may be some "dirty" bytes still not
1259dbdf699cSVladimir Sementsov-Ogievskiy              *    copied.
1260dbdf699cSVladimir Sementsov-Ogievskiy              * 2. It's already dirty, so skipping it we don't diverge mirror
1261dbdf699cSVladimir Sementsov-Ogievskiy              *    progress.
1262dbdf699cSVladimir Sementsov-Ogievskiy              *
1263dbdf699cSVladimir Sementsov-Ogievskiy              * Note, that because of this, guest write may have no contribution
1264dbdf699cSVladimir Sementsov-Ogievskiy              * into mirror converge, but that's not bad, as we have background
1265dbdf699cSVladimir Sementsov-Ogievskiy              * process of mirroring. If under some bad circumstances (high guest
1266dbdf699cSVladimir Sementsov-Ogievskiy              * IO load) background process starve, we will not converge anyway,
1267dbdf699cSVladimir Sementsov-Ogievskiy              * even if each write will contribute, as guest is not guaranteed to
1268dbdf699cSVladimir Sementsov-Ogievskiy              * rewrite the whole disk.
1269dbdf699cSVladimir Sementsov-Ogievskiy              */
1270dbdf699cSVladimir Sementsov-Ogievskiy             qiov_offset = QEMU_ALIGN_UP(offset, job->granularity) - offset;
1271dbdf699cSVladimir Sementsov-Ogievskiy             if (bytes <= qiov_offset) {
1272dbdf699cSVladimir Sementsov-Ogievskiy                 /* nothing to do after shrink */
1273dbdf699cSVladimir Sementsov-Ogievskiy                 return;
1274dbdf699cSVladimir Sementsov-Ogievskiy             }
1275dbdf699cSVladimir Sementsov-Ogievskiy             offset += qiov_offset;
1276dbdf699cSVladimir Sementsov-Ogievskiy             bytes -= qiov_offset;
1277dbdf699cSVladimir Sementsov-Ogievskiy     }
1278dbdf699cSVladimir Sementsov-Ogievskiy 
1279dbdf699cSVladimir Sementsov-Ogievskiy     if (!QEMU_IS_ALIGNED(offset + bytes, job->granularity) &&
1280dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_dirty_bitmap_get(job->dirty_bitmap, offset + bytes - 1))
1281dbdf699cSVladimir Sementsov-Ogievskiy     {
1282dbdf699cSVladimir Sementsov-Ogievskiy         uint64_t tail = (offset + bytes) % job->granularity;
1283dbdf699cSVladimir Sementsov-Ogievskiy 
1284dbdf699cSVladimir Sementsov-Ogievskiy         if (bytes <= tail) {
1285dbdf699cSVladimir Sementsov-Ogievskiy             /* nothing to do after shrink */
1286dbdf699cSVladimir Sementsov-Ogievskiy             return;
1287dbdf699cSVladimir Sementsov-Ogievskiy         }
1288dbdf699cSVladimir Sementsov-Ogievskiy         bytes -= tail;
1289dbdf699cSVladimir Sementsov-Ogievskiy     }
1290dbdf699cSVladimir Sementsov-Ogievskiy 
1291dbdf699cSVladimir Sementsov-Ogievskiy     /*
1292dbdf699cSVladimir Sementsov-Ogievskiy      * Tails are either clean or shrunk, so for bitmap resetting
1293dbdf699cSVladimir Sementsov-Ogievskiy      * we safely align the range down.
1294dbdf699cSVladimir Sementsov-Ogievskiy      */
1295dbdf699cSVladimir Sementsov-Ogievskiy     bitmap_offset = QEMU_ALIGN_UP(offset, job->granularity);
1296dbdf699cSVladimir Sementsov-Ogievskiy     bitmap_end = QEMU_ALIGN_DOWN(offset + bytes, job->granularity);
1297dbdf699cSVladimir Sementsov-Ogievskiy     if (bitmap_offset < bitmap_end) {
1298dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_reset_dirty_bitmap(job->dirty_bitmap, bitmap_offset,
1299dbdf699cSVladimir Sementsov-Ogievskiy                                 bitmap_end - bitmap_offset);
1300dbdf699cSVladimir Sementsov-Ogievskiy     }
1301d06107adSMax Reitz 
13025c511ac3SVladimir Sementsov-Ogievskiy     job_progress_increase_remaining(&job->common.job, bytes);
1303d06107adSMax Reitz 
1304d06107adSMax Reitz     switch (method) {
1305d06107adSMax Reitz     case MIRROR_METHOD_COPY:
1306dbdf699cSVladimir Sementsov-Ogievskiy         ret = blk_co_pwritev_part(job->target, offset, bytes,
1307dbdf699cSVladimir Sementsov-Ogievskiy                                   qiov, qiov_offset, flags);
1308d06107adSMax Reitz         break;
1309d06107adSMax Reitz 
1310d06107adSMax Reitz     case MIRROR_METHOD_ZERO:
1311d06107adSMax Reitz         assert(!qiov);
13125c511ac3SVladimir Sementsov-Ogievskiy         ret = blk_co_pwrite_zeroes(job->target, offset, bytes, flags);
1313d06107adSMax Reitz         break;
1314d06107adSMax Reitz 
1315d06107adSMax Reitz     case MIRROR_METHOD_DISCARD:
1316d06107adSMax Reitz         assert(!qiov);
13175c511ac3SVladimir Sementsov-Ogievskiy         ret = blk_co_pdiscard(job->target, offset, bytes);
1318d06107adSMax Reitz         break;
1319d06107adSMax Reitz 
1320d06107adSMax Reitz     default:
1321d06107adSMax Reitz         abort();
1322d06107adSMax Reitz     }
1323d06107adSMax Reitz 
1324d06107adSMax Reitz     if (ret >= 0) {
13255c511ac3SVladimir Sementsov-Ogievskiy         job_progress_update(&job->common.job, bytes);
1326d06107adSMax Reitz     } else {
1327d06107adSMax Reitz         BlockErrorAction action;
1328d06107adSMax Reitz 
1329dbdf699cSVladimir Sementsov-Ogievskiy         /*
1330dbdf699cSVladimir Sementsov-Ogievskiy          * We failed, so we should mark dirty the whole area, aligned up.
1331dbdf699cSVladimir Sementsov-Ogievskiy          * Note that we don't care about shrunk tails if any: they were dirty
1332dbdf699cSVladimir Sementsov-Ogievskiy          * at function start, and they must be still dirty, as we've locked
1333dbdf699cSVladimir Sementsov-Ogievskiy          * the region for in-flight op.
1334dbdf699cSVladimir Sementsov-Ogievskiy          */
1335dbdf699cSVladimir Sementsov-Ogievskiy         bitmap_offset = QEMU_ALIGN_DOWN(offset, job->granularity);
1336dbdf699cSVladimir Sementsov-Ogievskiy         bitmap_end = QEMU_ALIGN_UP(offset + bytes, job->granularity);
1337dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_set_dirty_bitmap(job->dirty_bitmap, bitmap_offset,
1338dbdf699cSVladimir Sementsov-Ogievskiy                               bitmap_end - bitmap_offset);
1339d06107adSMax Reitz         job->actively_synced = false;
1340d06107adSMax Reitz 
1341d06107adSMax Reitz         action = mirror_error_action(job, false, -ret);
1342d06107adSMax Reitz         if (action == BLOCK_ERROR_ACTION_REPORT) {
1343d06107adSMax Reitz             if (!job->ret) {
1344d06107adSMax Reitz                 job->ret = ret;
1345d06107adSMax Reitz             }
1346d06107adSMax Reitz         }
1347d06107adSMax Reitz     }
1348d06107adSMax Reitz }
1349d06107adSMax Reitz 
1350d06107adSMax Reitz static MirrorOp *coroutine_fn active_write_prepare(MirrorBlockJob *s,
1351d06107adSMax Reitz                                                    uint64_t offset,
1352d06107adSMax Reitz                                                    uint64_t bytes)
1353d06107adSMax Reitz {
1354d06107adSMax Reitz     MirrorOp *op;
1355d06107adSMax Reitz     uint64_t start_chunk = offset / s->granularity;
1356d06107adSMax Reitz     uint64_t end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1357d06107adSMax Reitz 
1358d06107adSMax Reitz     op = g_new(MirrorOp, 1);
1359d06107adSMax Reitz     *op = (MirrorOp){
1360d06107adSMax Reitz         .s                  = s,
1361d06107adSMax Reitz         .offset             = offset,
1362d06107adSMax Reitz         .bytes              = bytes,
1363d06107adSMax Reitz         .is_active_write    = true,
1364ce8cabbdSKevin Wolf         .is_in_flight       = true,
1365ead3f1bfSVladimir Sementsov-Ogievskiy         .co                 = qemu_coroutine_self(),
1366d06107adSMax Reitz     };
1367d06107adSMax Reitz     qemu_co_queue_init(&op->waiting_requests);
1368d06107adSMax Reitz     QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
1369d06107adSMax Reitz 
1370d06107adSMax Reitz     s->in_active_write_counter++;
1371d06107adSMax Reitz 
1372d06107adSMax Reitz     mirror_wait_on_conflicts(op, s, offset, bytes);
1373d06107adSMax Reitz 
1374d06107adSMax Reitz     bitmap_set(s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1375d06107adSMax Reitz 
1376d06107adSMax Reitz     return op;
1377d06107adSMax Reitz }
1378d06107adSMax Reitz 
1379d06107adSMax Reitz static void coroutine_fn active_write_settle(MirrorOp *op)
1380d06107adSMax Reitz {
1381d06107adSMax Reitz     uint64_t start_chunk = op->offset / op->s->granularity;
1382d06107adSMax Reitz     uint64_t end_chunk = DIV_ROUND_UP(op->offset + op->bytes,
1383d06107adSMax Reitz                                       op->s->granularity);
1384d06107adSMax Reitz 
1385d06107adSMax Reitz     if (!--op->s->in_active_write_counter && op->s->actively_synced) {
1386d06107adSMax Reitz         BdrvChild *source = op->s->mirror_top_bs->backing;
1387d06107adSMax Reitz 
1388d06107adSMax Reitz         if (QLIST_FIRST(&source->bs->parents) == source &&
1389d06107adSMax Reitz             QLIST_NEXT(source, next_parent) == NULL)
1390d06107adSMax Reitz         {
1391d06107adSMax Reitz             /* Assert that we are back in sync once all active write
1392d06107adSMax Reitz              * operations are settled.
1393d06107adSMax Reitz              * Note that we can only assert this if the mirror node
1394d06107adSMax Reitz              * is the source node's only parent. */
1395d06107adSMax Reitz             assert(!bdrv_get_dirty_count(op->s->dirty_bitmap));
1396d06107adSMax Reitz         }
1397d06107adSMax Reitz     }
1398d06107adSMax Reitz     bitmap_clear(op->s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1399d06107adSMax Reitz     QTAILQ_REMOVE(&op->s->ops_in_flight, op, next);
1400d06107adSMax Reitz     qemu_co_queue_restart_all(&op->waiting_requests);
1401d06107adSMax Reitz     g_free(op);
1402d06107adSMax Reitz }
1403d06107adSMax Reitz 
14044ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_preadv(BlockDriverState *bs,
1405f7ef38ddSVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes, QEMUIOVector *qiov, BdrvRequestFlags flags)
14064ef85a9cSKevin Wolf {
14074ef85a9cSKevin Wolf     return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
14084ef85a9cSKevin Wolf }
14094ef85a9cSKevin Wolf 
1410d06107adSMax Reitz static int coroutine_fn bdrv_mirror_top_do_write(BlockDriverState *bs,
1411d06107adSMax Reitz     MirrorMethod method, uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
1412d06107adSMax Reitz     int flags)
1413d06107adSMax Reitz {
1414d06107adSMax Reitz     MirrorOp *op = NULL;
1415d06107adSMax Reitz     MirrorBDSOpaque *s = bs->opaque;
1416d06107adSMax Reitz     int ret = 0;
1417d06107adSMax Reitz     bool copy_to_target;
1418d06107adSMax Reitz 
1419d06107adSMax Reitz     copy_to_target = s->job->ret >= 0 &&
1420d06107adSMax Reitz                      s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1421d06107adSMax Reitz 
1422d06107adSMax Reitz     if (copy_to_target) {
1423d06107adSMax Reitz         op = active_write_prepare(s->job, offset, bytes);
1424d06107adSMax Reitz     }
1425d06107adSMax Reitz 
1426d06107adSMax Reitz     switch (method) {
1427d06107adSMax Reitz     case MIRROR_METHOD_COPY:
1428d06107adSMax Reitz         ret = bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1429d06107adSMax Reitz         break;
1430d06107adSMax Reitz 
1431d06107adSMax Reitz     case MIRROR_METHOD_ZERO:
1432d06107adSMax Reitz         ret = bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
1433d06107adSMax Reitz         break;
1434d06107adSMax Reitz 
1435d06107adSMax Reitz     case MIRROR_METHOD_DISCARD:
14360b9fd3f4SFam Zheng         ret = bdrv_co_pdiscard(bs->backing, offset, bytes);
1437d06107adSMax Reitz         break;
1438d06107adSMax Reitz 
1439d06107adSMax Reitz     default:
1440d06107adSMax Reitz         abort();
1441d06107adSMax Reitz     }
1442d06107adSMax Reitz 
1443d06107adSMax Reitz     if (ret < 0) {
1444d06107adSMax Reitz         goto out;
1445d06107adSMax Reitz     }
1446d06107adSMax Reitz 
1447d06107adSMax Reitz     if (copy_to_target) {
1448d06107adSMax Reitz         do_sync_target_write(s->job, method, offset, bytes, qiov, flags);
1449d06107adSMax Reitz     }
1450d06107adSMax Reitz 
1451d06107adSMax Reitz out:
1452d06107adSMax Reitz     if (copy_to_target) {
1453d06107adSMax Reitz         active_write_settle(op);
1454d06107adSMax Reitz     }
1455d06107adSMax Reitz     return ret;
1456d06107adSMax Reitz }
1457d06107adSMax Reitz 
14584ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_pwritev(BlockDriverState *bs,
1459e75abedaSVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes, QEMUIOVector *qiov, BdrvRequestFlags flags)
14604ef85a9cSKevin Wolf {
1461d06107adSMax Reitz     MirrorBDSOpaque *s = bs->opaque;
1462d06107adSMax Reitz     QEMUIOVector bounce_qiov;
1463d06107adSMax Reitz     void *bounce_buf;
1464d06107adSMax Reitz     int ret = 0;
1465d06107adSMax Reitz     bool copy_to_target;
1466d06107adSMax Reitz 
1467d06107adSMax Reitz     copy_to_target = s->job->ret >= 0 &&
1468d06107adSMax Reitz                      s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1469d06107adSMax Reitz 
1470d06107adSMax Reitz     if (copy_to_target) {
1471d06107adSMax Reitz         /* The guest might concurrently modify the data to write; but
1472d06107adSMax Reitz          * the data on source and destination must match, so we have
1473d06107adSMax Reitz          * to use a bounce buffer if we are going to write to the
1474d06107adSMax Reitz          * target now. */
1475d06107adSMax Reitz         bounce_buf = qemu_blockalign(bs, bytes);
1476d06107adSMax Reitz         iov_to_buf_full(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
1477d06107adSMax Reitz 
1478d06107adSMax Reitz         qemu_iovec_init(&bounce_qiov, 1);
1479d06107adSMax Reitz         qemu_iovec_add(&bounce_qiov, bounce_buf, bytes);
1480d06107adSMax Reitz         qiov = &bounce_qiov;
1481d06107adSMax Reitz     }
1482d06107adSMax Reitz 
1483d06107adSMax Reitz     ret = bdrv_mirror_top_do_write(bs, MIRROR_METHOD_COPY, offset, bytes, qiov,
1484d06107adSMax Reitz                                    flags);
1485d06107adSMax Reitz 
1486d06107adSMax Reitz     if (copy_to_target) {
1487d06107adSMax Reitz         qemu_iovec_destroy(&bounce_qiov);
1488d06107adSMax Reitz         qemu_vfree(bounce_buf);
1489d06107adSMax Reitz     }
1490d06107adSMax Reitz 
1491d06107adSMax Reitz     return ret;
14924ef85a9cSKevin Wolf }
14934ef85a9cSKevin Wolf 
14944ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_flush(BlockDriverState *bs)
14954ef85a9cSKevin Wolf {
1496ce960aa9SVladimir Sementsov-Ogievskiy     if (bs->backing == NULL) {
1497ce960aa9SVladimir Sementsov-Ogievskiy         /* we can be here after failed bdrv_append in mirror_start_job */
1498ce960aa9SVladimir Sementsov-Ogievskiy         return 0;
1499ce960aa9SVladimir Sementsov-Ogievskiy     }
15004ef85a9cSKevin Wolf     return bdrv_co_flush(bs->backing->bs);
15014ef85a9cSKevin Wolf }
15024ef85a9cSKevin Wolf 
15034ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs,
1504f34b2bcfSVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes, BdrvRequestFlags flags)
15054ef85a9cSKevin Wolf {
1506d06107adSMax Reitz     return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_ZERO, offset, bytes, NULL,
1507d06107adSMax Reitz                                     flags);
15084ef85a9cSKevin Wolf }
15094ef85a9cSKevin Wolf 
15104ef85a9cSKevin Wolf static int coroutine_fn bdrv_mirror_top_pdiscard(BlockDriverState *bs,
1511*0c802287SVladimir Sementsov-Ogievskiy     int64_t offset, int64_t bytes)
15124ef85a9cSKevin Wolf {
1513d06107adSMax Reitz     return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_DISCARD, offset, bytes,
1514d06107adSMax Reitz                                     NULL, 0);
15154ef85a9cSKevin Wolf }
15164ef85a9cSKevin Wolf 
1517998b3a1eSMax Reitz static void bdrv_mirror_top_refresh_filename(BlockDriverState *bs)
1518fd4a6493SKevin Wolf {
151918775ff3SVladimir Sementsov-Ogievskiy     if (bs->backing == NULL) {
152018775ff3SVladimir Sementsov-Ogievskiy         /* we can be here after failed bdrv_attach_child in
152118775ff3SVladimir Sementsov-Ogievskiy          * bdrv_set_backing_hd */
152218775ff3SVladimir Sementsov-Ogievskiy         return;
152318775ff3SVladimir Sementsov-Ogievskiy     }
1524fd4a6493SKevin Wolf     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1525fd4a6493SKevin Wolf             bs->backing->bs->filename);
1526fd4a6493SKevin Wolf }
1527fd4a6493SKevin Wolf 
15284ef85a9cSKevin Wolf static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1529bf8e925eSMax Reitz                                        BdrvChildRole role,
1530e0995dc3SKevin Wolf                                        BlockReopenQueue *reopen_queue,
15314ef85a9cSKevin Wolf                                        uint64_t perm, uint64_t shared,
15324ef85a9cSKevin Wolf                                        uint64_t *nperm, uint64_t *nshared)
15334ef85a9cSKevin Wolf {
1534f94dc3b4SMax Reitz     MirrorBDSOpaque *s = bs->opaque;
1535f94dc3b4SMax Reitz 
1536f94dc3b4SMax Reitz     if (s->stop) {
1537f94dc3b4SMax Reitz         /*
1538f94dc3b4SMax Reitz          * If the job is to be stopped, we do not need to forward
1539f94dc3b4SMax Reitz          * anything to the real image.
1540f94dc3b4SMax Reitz          */
1541f94dc3b4SMax Reitz         *nperm = 0;
1542f94dc3b4SMax Reitz         *nshared = BLK_PERM_ALL;
1543f94dc3b4SMax Reitz         return;
1544f94dc3b4SMax Reitz     }
1545f94dc3b4SMax Reitz 
154653431b90SMax Reitz     bdrv_default_perms(bs, c, role, reopen_queue,
154753431b90SMax Reitz                        perm, shared, nperm, nshared);
15484ef85a9cSKevin Wolf 
154953431b90SMax Reitz     if (s->is_commit) {
155053431b90SMax Reitz         /*
155153431b90SMax Reitz          * For commit jobs, we cannot take CONSISTENT_READ, because
155253431b90SMax Reitz          * that permission is unshared for everything above the base
155353431b90SMax Reitz          * node (except for filters on the base node).
155453431b90SMax Reitz          * We also have to force-share the WRITE permission, or
155553431b90SMax Reitz          * otherwise we would block ourselves at the base node (if
155653431b90SMax Reitz          * writes are blocked for a node, they are also blocked for
155753431b90SMax Reitz          * its backing file).
155853431b90SMax Reitz          * (We could also share RESIZE, because it may be needed for
155953431b90SMax Reitz          * the target if its size is less than the top node's; but
156053431b90SMax Reitz          * bdrv_default_perms_for_cow() automatically shares RESIZE
156153431b90SMax Reitz          * for backing nodes if WRITE is shared, so there is no need
156253431b90SMax Reitz          * to do it here.)
156353431b90SMax Reitz          */
156453431b90SMax Reitz         *nperm &= ~BLK_PERM_CONSISTENT_READ;
156553431b90SMax Reitz         *nshared |= BLK_PERM_WRITE;
156653431b90SMax Reitz     }
15674ef85a9cSKevin Wolf }
15684ef85a9cSKevin Wolf 
15694ef85a9cSKevin Wolf /* Dummy node that provides consistent read to its users without requiring it
15704ef85a9cSKevin Wolf  * from its backing file and that allows writes on the backing file chain. */
15714ef85a9cSKevin Wolf static BlockDriver bdrv_mirror_top = {
15724ef85a9cSKevin Wolf     .format_name                = "mirror_top",
15734ef85a9cSKevin Wolf     .bdrv_co_preadv             = bdrv_mirror_top_preadv,
15744ef85a9cSKevin Wolf     .bdrv_co_pwritev            = bdrv_mirror_top_pwritev,
15754ef85a9cSKevin Wolf     .bdrv_co_pwrite_zeroes      = bdrv_mirror_top_pwrite_zeroes,
15764ef85a9cSKevin Wolf     .bdrv_co_pdiscard           = bdrv_mirror_top_pdiscard,
15774ef85a9cSKevin Wolf     .bdrv_co_flush              = bdrv_mirror_top_flush,
1578fd4a6493SKevin Wolf     .bdrv_refresh_filename      = bdrv_mirror_top_refresh_filename,
15794ef85a9cSKevin Wolf     .bdrv_child_perm            = bdrv_mirror_top_child_perm,
15806540fd15SMax Reitz 
15816540fd15SMax Reitz     .is_filter                  = true,
15824ef85a9cSKevin Wolf };
15834ef85a9cSKevin Wolf 
1584cc19f177SVladimir Sementsov-Ogievskiy static BlockJob *mirror_start_job(
1585cc19f177SVladimir Sementsov-Ogievskiy                              const char *job_id, BlockDriverState *bs,
158647970dfbSJohn Snow                              int creation_flags, BlockDriverState *target,
158747970dfbSJohn Snow                              const char *replaces, int64_t speed,
158847970dfbSJohn Snow                              uint32_t granularity, int64_t buf_size,
1589274fcceeSMax Reitz                              BlockMirrorBackingMode backing_mode,
1590cdf3bc93SMax Reitz                              bool zero_target,
159103544a6eSFam Zheng                              BlockdevOnError on_source_error,
1592b952b558SPaolo Bonzini                              BlockdevOnError on_target_error,
15930fc9f8eaSFam Zheng                              bool unmap,
1594097310b5SMarkus Armbruster                              BlockCompletionFunc *cb,
159551ccfa2dSFam Zheng                              void *opaque,
159603544a6eSFam Zheng                              const BlockJobDriver *driver,
1597b49f7eadSWen Congyang                              bool is_none_mode, BlockDriverState *base,
159851ccfa2dSFam Zheng                              bool auto_complete, const char *filter_node_name,
1599481debaaSMax Reitz                              bool is_mirror, MirrorCopyMode copy_mode,
160051ccfa2dSFam Zheng                              Error **errp)
1601893f7ebaSPaolo Bonzini {
1602893f7ebaSPaolo Bonzini     MirrorBlockJob *s;
1603429076e8SMax Reitz     MirrorBDSOpaque *bs_opaque;
16044ef85a9cSKevin Wolf     BlockDriverState *mirror_top_bs;
16054ef85a9cSKevin Wolf     bool target_is_backing;
16063f072a7fSMax Reitz     uint64_t target_perms, target_shared_perms;
1607d7086422SKevin Wolf     int ret;
1608893f7ebaSPaolo Bonzini 
1609eee13dfeSPaolo Bonzini     if (granularity == 0) {
1610341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(target);
1611eee13dfeSPaolo Bonzini     }
1612eee13dfeSPaolo Bonzini 
161331826642SEric Blake     assert(is_power_of_2(granularity));
1614eee13dfeSPaolo Bonzini 
161548ac0a4dSWen Congyang     if (buf_size < 0) {
161648ac0a4dSWen Congyang         error_setg(errp, "Invalid parameter 'buf-size'");
1617cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
161848ac0a4dSWen Congyang     }
161948ac0a4dSWen Congyang 
162048ac0a4dSWen Congyang     if (buf_size == 0) {
162148ac0a4dSWen Congyang         buf_size = DEFAULT_MIRROR_BUF_SIZE;
162248ac0a4dSWen Congyang     }
16235bc361b8SFam Zheng 
16243f072a7fSMax Reitz     if (bdrv_skip_filters(bs) == bdrv_skip_filters(target)) {
162586fae10cSKevin Wolf         error_setg(errp, "Can't mirror node into itself");
1626cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
162786fae10cSKevin Wolf     }
162886fae10cSKevin Wolf 
162953431b90SMax Reitz     target_is_backing = bdrv_chain_contains(bs, target);
163053431b90SMax Reitz 
16314ef85a9cSKevin Wolf     /* In the case of active commit, add dummy driver to provide consistent
16324ef85a9cSKevin Wolf      * reads on the top, while disabling it in the intermediate nodes, and make
16334ef85a9cSKevin Wolf      * the backing chain writable. */
16346cdbceb1SKevin Wolf     mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
16356cdbceb1SKevin Wolf                                          BDRV_O_RDWR, errp);
16364ef85a9cSKevin Wolf     if (mirror_top_bs == NULL) {
1637cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
1638893f7ebaSPaolo Bonzini     }
1639d3c8c674SKevin Wolf     if (!filter_node_name) {
1640d3c8c674SKevin Wolf         mirror_top_bs->implicit = true;
1641d3c8c674SKevin Wolf     }
1642e5182c1cSMax Reitz 
1643e5182c1cSMax Reitz     /* So that we can always drop this node */
1644e5182c1cSMax Reitz     mirror_top_bs->never_freeze = true;
1645e5182c1cSMax Reitz 
16464ef85a9cSKevin Wolf     mirror_top_bs->total_sectors = bs->total_sectors;
1647228345bfSMax Reitz     mirror_top_bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED;
164880f5c33fSKevin Wolf     mirror_top_bs->supported_zero_flags = BDRV_REQ_WRITE_UNCHANGED |
164980f5c33fSKevin Wolf                                           BDRV_REQ_NO_FALLBACK;
1650429076e8SMax Reitz     bs_opaque = g_new0(MirrorBDSOpaque, 1);
1651429076e8SMax Reitz     mirror_top_bs->opaque = bs_opaque;
1652893f7ebaSPaolo Bonzini 
165353431b90SMax Reitz     bs_opaque->is_commit = target_is_backing;
165453431b90SMax Reitz 
16554ef85a9cSKevin Wolf     bdrv_drained_begin(bs);
1656934aee14SVladimir Sementsov-Ogievskiy     ret = bdrv_append(mirror_top_bs, bs, errp);
16574ef85a9cSKevin Wolf     bdrv_drained_end(bs);
16584ef85a9cSKevin Wolf 
1659934aee14SVladimir Sementsov-Ogievskiy     if (ret < 0) {
1660b2c2832cSKevin Wolf         bdrv_unref(mirror_top_bs);
1661cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
1662b2c2832cSKevin Wolf     }
1663b2c2832cSKevin Wolf 
16644ef85a9cSKevin Wolf     /* Make sure that the source is not resized while the job is running */
166575859b94SJohn Snow     s = block_job_create(job_id, driver, NULL, mirror_top_bs,
16664ef85a9cSKevin Wolf                          BLK_PERM_CONSISTENT_READ,
16674ef85a9cSKevin Wolf                          BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
16684ef85a9cSKevin Wolf                          BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD, speed,
16694ef85a9cSKevin Wolf                          creation_flags, cb, opaque, errp);
16704ef85a9cSKevin Wolf     if (!s) {
16714ef85a9cSKevin Wolf         goto fail;
16724ef85a9cSKevin Wolf     }
1673429076e8SMax Reitz     bs_opaque->job = s;
1674429076e8SMax Reitz 
16757a25fcd0SMax Reitz     /* The block job now has a reference to this node */
16767a25fcd0SMax Reitz     bdrv_unref(mirror_top_bs);
16777a25fcd0SMax Reitz 
16784ef85a9cSKevin Wolf     s->mirror_top_bs = mirror_top_bs;
16794ef85a9cSKevin Wolf 
16804ef85a9cSKevin Wolf     /* No resize for the target either; while the mirror is still running, a
16814ef85a9cSKevin Wolf      * consistent read isn't necessarily possible. We could possibly allow
16824ef85a9cSKevin Wolf      * writes and graph modifications, though it would likely defeat the
16834ef85a9cSKevin Wolf      * purpose of a mirror, so leave them blocked for now.
16844ef85a9cSKevin Wolf      *
16854ef85a9cSKevin Wolf      * In the case of active commit, things look a bit different, though,
16864ef85a9cSKevin Wolf      * because the target is an already populated backing file in active use.
16874ef85a9cSKevin Wolf      * We can allow anything except resize there.*/
16883f072a7fSMax Reitz 
16893f072a7fSMax Reitz     target_perms = BLK_PERM_WRITE;
16903f072a7fSMax Reitz     target_shared_perms = BLK_PERM_WRITE_UNCHANGED;
16913f072a7fSMax Reitz 
16923f072a7fSMax Reitz     if (target_is_backing) {
16933f072a7fSMax Reitz         int64_t bs_size, target_size;
16943f072a7fSMax Reitz         bs_size = bdrv_getlength(bs);
16953f072a7fSMax Reitz         if (bs_size < 0) {
16963f072a7fSMax Reitz             error_setg_errno(errp, -bs_size,
16973f072a7fSMax Reitz                              "Could not inquire top image size");
16983f072a7fSMax Reitz             goto fail;
16993f072a7fSMax Reitz         }
17003f072a7fSMax Reitz 
17013f072a7fSMax Reitz         target_size = bdrv_getlength(target);
17023f072a7fSMax Reitz         if (target_size < 0) {
17033f072a7fSMax Reitz             error_setg_errno(errp, -target_size,
17043f072a7fSMax Reitz                              "Could not inquire base image size");
17053f072a7fSMax Reitz             goto fail;
17063f072a7fSMax Reitz         }
17073f072a7fSMax Reitz 
17083f072a7fSMax Reitz         if (target_size < bs_size) {
17093f072a7fSMax Reitz             target_perms |= BLK_PERM_RESIZE;
17103f072a7fSMax Reitz         }
17113f072a7fSMax Reitz 
17123f072a7fSMax Reitz         target_shared_perms |= BLK_PERM_CONSISTENT_READ
17133f072a7fSMax Reitz                             |  BLK_PERM_WRITE
17143f072a7fSMax Reitz                             |  BLK_PERM_GRAPH_MOD;
17153f072a7fSMax Reitz     } else if (bdrv_chain_contains(bs, bdrv_skip_filters(target))) {
17163f072a7fSMax Reitz         /*
17173f072a7fSMax Reitz          * We may want to allow this in the future, but it would
17183f072a7fSMax Reitz          * require taking some extra care.
17193f072a7fSMax Reitz          */
17203f072a7fSMax Reitz         error_setg(errp, "Cannot mirror to a filter on top of a node in the "
17213f072a7fSMax Reitz                    "source's backing chain");
17223f072a7fSMax Reitz         goto fail;
17233f072a7fSMax Reitz     }
17243f072a7fSMax Reitz 
17253f072a7fSMax Reitz     if (backing_mode != MIRROR_LEAVE_BACKING_CHAIN) {
17263f072a7fSMax Reitz         target_perms |= BLK_PERM_GRAPH_MOD;
17273f072a7fSMax Reitz     }
17283f072a7fSMax Reitz 
1729d861ab3aSKevin Wolf     s->target = blk_new(s->common.job.aio_context,
17303f072a7fSMax Reitz                         target_perms, target_shared_perms);
1731d7086422SKevin Wolf     ret = blk_insert_bs(s->target, target, errp);
1732d7086422SKevin Wolf     if (ret < 0) {
17334ef85a9cSKevin Wolf         goto fail;
1734d7086422SKevin Wolf     }
1735045a2f82SFam Zheng     if (is_mirror) {
1736045a2f82SFam Zheng         /* XXX: Mirror target could be a NBD server of target QEMU in the case
1737045a2f82SFam Zheng          * of non-shared block migration. To allow migration completion, we
1738045a2f82SFam Zheng          * have to allow "inactivate" of the target BB.  When that happens, we
1739045a2f82SFam Zheng          * know the job is drained, and the vcpus are stopped, so no write
1740045a2f82SFam Zheng          * operation will be performed. Block layer already has assertions to
1741045a2f82SFam Zheng          * ensure that. */
1742045a2f82SFam Zheng         blk_set_force_allow_inactivate(s->target);
1743045a2f82SFam Zheng     }
17449ff7f0dfSKevin Wolf     blk_set_allow_aio_context_change(s->target, true);
1745cf312932SKevin Wolf     blk_set_disable_request_queuing(s->target, true);
1746e253f4b8SKevin Wolf 
174709158f00SBenoît Canet     s->replaces = g_strdup(replaces);
1748b952b558SPaolo Bonzini     s->on_source_error = on_source_error;
1749b952b558SPaolo Bonzini     s->on_target_error = on_target_error;
175003544a6eSFam Zheng     s->is_none_mode = is_none_mode;
1751274fcceeSMax Reitz     s->backing_mode = backing_mode;
1752cdf3bc93SMax Reitz     s->zero_target = zero_target;
1753481debaaSMax Reitz     s->copy_mode = copy_mode;
17545bc361b8SFam Zheng     s->base = base;
17553f072a7fSMax Reitz     s->base_overlay = bdrv_find_overlay(bs, base);
1756eee13dfeSPaolo Bonzini     s->granularity = granularity;
175748ac0a4dSWen Congyang     s->buf_size = ROUND_UP(buf_size, granularity);
17580fc9f8eaSFam Zheng     s->unmap = unmap;
1759b49f7eadSWen Congyang     if (auto_complete) {
1760b49f7eadSWen Congyang         s->should_complete = true;
1761b49f7eadSWen Congyang     }
1762b812f671SPaolo Bonzini 
17630db6e54aSFam Zheng     s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
1764b8afb520SFam Zheng     if (!s->dirty_bitmap) {
176588f9d1b3SKevin Wolf         goto fail;
1766b8afb520SFam Zheng     }
1767dbdf699cSVladimir Sementsov-Ogievskiy     if (s->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING) {
1768dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_disable_dirty_bitmap(s->dirty_bitmap);
1769dbdf699cSVladimir Sementsov-Ogievskiy     }
177010f3cd15SAlberto Garcia 
177167b24427SAlberto Garcia     ret = block_job_add_bdrv(&s->common, "source", bs, 0,
177267b24427SAlberto Garcia                              BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE |
177367b24427SAlberto Garcia                              BLK_PERM_CONSISTENT_READ,
177467b24427SAlberto Garcia                              errp);
177567b24427SAlberto Garcia     if (ret < 0) {
177667b24427SAlberto Garcia         goto fail;
177767b24427SAlberto Garcia     }
177867b24427SAlberto Garcia 
17794ef85a9cSKevin Wolf     /* Required permissions are already taken with blk_new() */
178076d554e2SKevin Wolf     block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
178176d554e2SKevin Wolf                        &error_abort);
178276d554e2SKevin Wolf 
1783f3ede4b0SAlberto Garcia     /* In commit_active_start() all intermediate nodes disappear, so
1784f3ede4b0SAlberto Garcia      * any jobs in them must be blocked */
17854ef85a9cSKevin Wolf     if (target_is_backing) {
17863f072a7fSMax Reitz         BlockDriverState *iter, *filtered_target;
17873f072a7fSMax Reitz         uint64_t iter_shared_perms;
17883f072a7fSMax Reitz 
17893f072a7fSMax Reitz         /*
17903f072a7fSMax Reitz          * The topmost node with
17913f072a7fSMax Reitz          * bdrv_skip_filters(filtered_target) == bdrv_skip_filters(target)
17923f072a7fSMax Reitz          */
17933f072a7fSMax Reitz         filtered_target = bdrv_cow_bs(bdrv_find_overlay(bs, target));
17943f072a7fSMax Reitz 
17953f072a7fSMax Reitz         assert(bdrv_skip_filters(filtered_target) ==
17963f072a7fSMax Reitz                bdrv_skip_filters(target));
17973f072a7fSMax Reitz 
17983f072a7fSMax Reitz         /*
17993f072a7fSMax Reitz          * XXX BLK_PERM_WRITE needs to be allowed so we don't block
18004ef85a9cSKevin Wolf          * ourselves at s->base (if writes are blocked for a node, they are
18014ef85a9cSKevin Wolf          * also blocked for its backing file). The other options would be a
18023f072a7fSMax Reitz          * second filter driver above s->base (== target).
18033f072a7fSMax Reitz          */
18043f072a7fSMax Reitz         iter_shared_perms = BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE;
18053f072a7fSMax Reitz 
18063f072a7fSMax Reitz         for (iter = bdrv_filter_or_cow_bs(bs); iter != target;
18073f072a7fSMax Reitz              iter = bdrv_filter_or_cow_bs(iter))
18083f072a7fSMax Reitz         {
18093f072a7fSMax Reitz             if (iter == filtered_target) {
18103f072a7fSMax Reitz                 /*
18113f072a7fSMax Reitz                  * From here on, all nodes are filters on the base.
18123f072a7fSMax Reitz                  * This allows us to share BLK_PERM_CONSISTENT_READ.
18133f072a7fSMax Reitz                  */
18143f072a7fSMax Reitz                 iter_shared_perms |= BLK_PERM_CONSISTENT_READ;
18153f072a7fSMax Reitz             }
18163f072a7fSMax Reitz 
18174ef85a9cSKevin Wolf             ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
18183f072a7fSMax Reitz                                      iter_shared_perms, errp);
18194ef85a9cSKevin Wolf             if (ret < 0) {
18204ef85a9cSKevin Wolf                 goto fail;
18214ef85a9cSKevin Wolf             }
1822f3ede4b0SAlberto Garcia         }
1823ef53dc09SAlberto Garcia 
1824ef53dc09SAlberto Garcia         if (bdrv_freeze_backing_chain(mirror_top_bs, target, errp) < 0) {
1825ef53dc09SAlberto Garcia             goto fail;
1826ef53dc09SAlberto Garcia         }
1827f3ede4b0SAlberto Garcia     }
182810f3cd15SAlberto Garcia 
182912aa4082SMax Reitz     QTAILQ_INIT(&s->ops_in_flight);
183012aa4082SMax Reitz 
18315ccac6f1SJohn Snow     trace_mirror_start(bs, s, opaque);
1832da01ff7fSKevin Wolf     job_start(&s->common.job);
1833cc19f177SVladimir Sementsov-Ogievskiy 
1834cc19f177SVladimir Sementsov-Ogievskiy     return &s->common;
18354ef85a9cSKevin Wolf 
18364ef85a9cSKevin Wolf fail:
18374ef85a9cSKevin Wolf     if (s) {
18387a25fcd0SMax Reitz         /* Make sure this BDS does not go away until we have completed the graph
18397a25fcd0SMax Reitz          * changes below */
18407a25fcd0SMax Reitz         bdrv_ref(mirror_top_bs);
18417a25fcd0SMax Reitz 
18424ef85a9cSKevin Wolf         g_free(s->replaces);
18434ef85a9cSKevin Wolf         blk_unref(s->target);
1844429076e8SMax Reitz         bs_opaque->job = NULL;
1845e917e2cbSAlberto Garcia         if (s->dirty_bitmap) {
18465deb6cbdSVladimir Sementsov-Ogievskiy             bdrv_release_dirty_bitmap(s->dirty_bitmap);
1847e917e2cbSAlberto Garcia         }
18484ad35181SKevin Wolf         job_early_fail(&s->common.job);
18494ef85a9cSKevin Wolf     }
18504ef85a9cSKevin Wolf 
1851f94dc3b4SMax Reitz     bs_opaque->stop = true;
1852f94dc3b4SMax Reitz     bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
1853c1cef672SFam Zheng                              &error_abort);
18543f072a7fSMax Reitz     bdrv_replace_node(mirror_top_bs, mirror_top_bs->backing->bs, &error_abort);
18557a25fcd0SMax Reitz 
18567a25fcd0SMax Reitz     bdrv_unref(mirror_top_bs);
1857cc19f177SVladimir Sementsov-Ogievskiy 
1858cc19f177SVladimir Sementsov-Ogievskiy     return NULL;
1859893f7ebaSPaolo Bonzini }
186003544a6eSFam Zheng 
186171aa9867SAlberto Garcia void mirror_start(const char *job_id, BlockDriverState *bs,
186271aa9867SAlberto Garcia                   BlockDriverState *target, const char *replaces,
1863a1999b33SJohn Snow                   int creation_flags, int64_t speed,
1864a1999b33SJohn Snow                   uint32_t granularity, int64_t buf_size,
1865274fcceeSMax Reitz                   MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
1866cdf3bc93SMax Reitz                   bool zero_target,
1867274fcceeSMax Reitz                   BlockdevOnError on_source_error,
186803544a6eSFam Zheng                   BlockdevOnError on_target_error,
1869481debaaSMax Reitz                   bool unmap, const char *filter_node_name,
1870481debaaSMax Reitz                   MirrorCopyMode copy_mode, Error **errp)
187103544a6eSFam Zheng {
187203544a6eSFam Zheng     bool is_none_mode;
187303544a6eSFam Zheng     BlockDriverState *base;
187403544a6eSFam Zheng 
1875c8b56501SJohn Snow     if ((mode == MIRROR_SYNC_MODE_INCREMENTAL) ||
1876c8b56501SJohn Snow         (mode == MIRROR_SYNC_MODE_BITMAP)) {
1877c8b56501SJohn Snow         error_setg(errp, "Sync mode '%s' not supported",
1878c8b56501SJohn Snow                    MirrorSyncMode_str(mode));
1879d58d8453SJohn Snow         return;
1880d58d8453SJohn Snow     }
188103544a6eSFam Zheng     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
18823f072a7fSMax Reitz     base = mode == MIRROR_SYNC_MODE_TOP ? bdrv_backing_chain_next(bs) : NULL;
1883a1999b33SJohn Snow     mirror_start_job(job_id, bs, creation_flags, target, replaces,
1884cdf3bc93SMax Reitz                      speed, granularity, buf_size, backing_mode, zero_target,
188551ccfa2dSFam Zheng                      on_source_error, on_target_error, unmap, NULL, NULL,
18866cdbceb1SKevin Wolf                      &mirror_job_driver, is_none_mode, base, false,
1887481debaaSMax Reitz                      filter_node_name, true, copy_mode, errp);
188803544a6eSFam Zheng }
188903544a6eSFam Zheng 
1890cc19f177SVladimir Sementsov-Ogievskiy BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
189147970dfbSJohn Snow                               BlockDriverState *base, int creation_flags,
189247970dfbSJohn Snow                               int64_t speed, BlockdevOnError on_error,
18930db832f4SKevin Wolf                               const char *filter_node_name,
189478bbd910SFam Zheng                               BlockCompletionFunc *cb, void *opaque,
189578bbd910SFam Zheng                               bool auto_complete, Error **errp)
189603544a6eSFam Zheng {
18971ba79388SAlberto Garcia     bool base_read_only;
1898eb5becc1SVladimir Sementsov-Ogievskiy     BlockJob *job;
18994da83585SJeff Cody 
19001ba79388SAlberto Garcia     base_read_only = bdrv_is_read_only(base);
19014da83585SJeff Cody 
19021ba79388SAlberto Garcia     if (base_read_only) {
19031ba79388SAlberto Garcia         if (bdrv_reopen_set_read_only(base, false, errp) < 0) {
1904cc19f177SVladimir Sementsov-Ogievskiy             return NULL;
190520a63d2cSFam Zheng         }
19061ba79388SAlberto Garcia     }
19074da83585SJeff Cody 
1908eb5becc1SVladimir Sementsov-Ogievskiy     job = mirror_start_job(
1909cc19f177SVladimir Sementsov-Ogievskiy                      job_id, bs, creation_flags, base, NULL, speed, 0, 0,
1910cdf3bc93SMax Reitz                      MIRROR_LEAVE_BACKING_CHAIN, false,
191151ccfa2dSFam Zheng                      on_error, on_error, true, cb, opaque,
19126cdbceb1SKevin Wolf                      &commit_active_job_driver, false, base, auto_complete,
1913481debaaSMax Reitz                      filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
1914eb5becc1SVladimir Sementsov-Ogievskiy                      errp);
1915eb5becc1SVladimir Sementsov-Ogievskiy     if (!job) {
19164da83585SJeff Cody         goto error_restore_flags;
19174da83585SJeff Cody     }
19184da83585SJeff Cody 
1919eb5becc1SVladimir Sementsov-Ogievskiy     return job;
19204da83585SJeff Cody 
19214da83585SJeff Cody error_restore_flags:
19224da83585SJeff Cody     /* ignore error and errp for bdrv_reopen, because we want to propagate
19234da83585SJeff Cody      * the original error */
19241ba79388SAlberto Garcia     if (base_read_only) {
19251ba79388SAlberto Garcia         bdrv_reopen_set_read_only(base, true, NULL);
19261ba79388SAlberto Garcia     }
1927cc19f177SVladimir Sementsov-Ogievskiy     return NULL;
192803544a6eSFam Zheng }
1929