xref: /qemu/block/mirror.c (revision ae5a40e8)
1893f7ebaSPaolo Bonzini /*
2893f7ebaSPaolo Bonzini  * Image mirroring
3893f7ebaSPaolo Bonzini  *
4893f7ebaSPaolo Bonzini  * Copyright Red Hat, Inc. 2012
5893f7ebaSPaolo Bonzini  *
6893f7ebaSPaolo Bonzini  * Authors:
7893f7ebaSPaolo Bonzini  *  Paolo Bonzini  <pbonzini@redhat.com>
8893f7ebaSPaolo Bonzini  *
9893f7ebaSPaolo Bonzini  * This work is licensed under the terms of the GNU LGPL, version 2 or later.
10893f7ebaSPaolo Bonzini  * See the COPYING.LIB file in the top-level directory.
11893f7ebaSPaolo Bonzini  *
12893f7ebaSPaolo Bonzini  */
13893f7ebaSPaolo Bonzini 
1480c71a24SPeter Maydell #include "qemu/osdep.h"
15fd4a6493SKevin Wolf #include "qemu/cutils.h"
1612aa4082SMax Reitz #include "qemu/coroutine.h"
171181e19aSMax Reitz #include "qemu/range.h"
18893f7ebaSPaolo Bonzini #include "trace.h"
19c87621eaSJohn Snow #include "block/blockjob_int.h"
20737e150eSPaolo Bonzini #include "block/block_int.h"
21e2c1c34fSMarkus Armbruster #include "block/dirty-bitmap.h"
22373340b2SMax Reitz #include "sysemu/block-backend.h"
23da34e65cSMarkus Armbruster #include "qapi/error.h"
24893f7ebaSPaolo Bonzini #include "qemu/ratelimit.h"
25b812f671SPaolo Bonzini #include "qemu/bitmap.h"
265df022cfSPeter Maydell #include "qemu/memalign.h"
27893f7ebaSPaolo Bonzini 
28402a4741SPaolo Bonzini #define MAX_IN_FLIGHT 16
29b436982fSEric Blake #define MAX_IO_BYTES (1 << 20) /* 1 Mb */
30b436982fSEric Blake #define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
31402a4741SPaolo Bonzini 
32402a4741SPaolo Bonzini /* The mirroring buffer is a list of granularity-sized chunks.
33402a4741SPaolo Bonzini  * Free chunks are organized in a list.
34402a4741SPaolo Bonzini  */
35402a4741SPaolo Bonzini typedef struct MirrorBuffer {
36402a4741SPaolo Bonzini     QSIMPLEQ_ENTRY(MirrorBuffer) next;
37402a4741SPaolo Bonzini } MirrorBuffer;
38893f7ebaSPaolo Bonzini 
3912aa4082SMax Reitz typedef struct MirrorOp MirrorOp;
4012aa4082SMax Reitz 
41893f7ebaSPaolo Bonzini typedef struct MirrorBlockJob {
42893f7ebaSPaolo Bonzini     BlockJob common;
43e253f4b8SKevin Wolf     BlockBackend *target;
444ef85a9cSKevin Wolf     BlockDriverState *mirror_top_bs;
455bc361b8SFam Zheng     BlockDriverState *base;
463f072a7fSMax Reitz     BlockDriverState *base_overlay;
474ef85a9cSKevin Wolf 
4809158f00SBenoît Canet     /* The name of the graph node to replace */
4909158f00SBenoît Canet     char *replaces;
5009158f00SBenoît Canet     /* The BDS to replace */
5109158f00SBenoît Canet     BlockDriverState *to_replace;
5209158f00SBenoît Canet     /* Used to block operations on the drive-mirror-replace target */
5309158f00SBenoît Canet     Error *replace_blocker;
5403544a6eSFam Zheng     bool is_none_mode;
55274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode;
56cdf3bc93SMax Reitz     /* Whether the target image requires explicit zero-initialization */
57cdf3bc93SMax Reitz     bool zero_target;
582d400d15SFiona Ebner     /*
592d400d15SFiona Ebner      * To be accesssed with atomics. Written only under the BQL (required by the
602d400d15SFiona Ebner      * current implementation of mirror_change()).
612d400d15SFiona Ebner      */
62d06107adSMax Reitz     MirrorCopyMode copy_mode;
63b952b558SPaolo Bonzini     BlockdevOnError on_source_error, on_target_error;
6476cb2f24SFiona Ebner     /*
6576cb2f24SFiona Ebner      * To be accessed with atomics.
6676cb2f24SFiona Ebner      *
6776cb2f24SFiona Ebner      * Set when the target is synced (dirty bitmap is clean, nothing in flight)
6876cb2f24SFiona Ebner      * and the job is running in active mode.
6976cb2f24SFiona Ebner      */
70d06107adSMax Reitz     bool actively_synced;
71d63ffd87SPaolo Bonzini     bool should_complete;
72eee13dfeSPaolo Bonzini     int64_t granularity;
73b812f671SPaolo Bonzini     size_t buf_size;
74b21c7652SMax Reitz     int64_t bdev_length;
75b812f671SPaolo Bonzini     unsigned long *cow_bitmap;
76e4654d2dSFam Zheng     BdrvDirtyBitmap *dirty_bitmap;
77dc162c8eSFam Zheng     BdrvDirtyBitmapIter *dbi;
78893f7ebaSPaolo Bonzini     uint8_t *buf;
79402a4741SPaolo Bonzini     QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
80402a4741SPaolo Bonzini     int buf_free_count;
81bd48bde8SPaolo Bonzini 
8249efb1f5SDenis V. Lunev     uint64_t last_pause_ns;
83402a4741SPaolo Bonzini     unsigned long *in_flight_bitmap;
841b8f7776SDenis V. Lunev     unsigned in_flight;
85b436982fSEric Blake     int64_t bytes_in_flight;
86b58deb34SPaolo Bonzini     QTAILQ_HEAD(, MirrorOp) ops_in_flight;
87bd48bde8SPaolo Bonzini     int ret;
880fc9f8eaSFam Zheng     bool unmap;
89b436982fSEric Blake     int target_cluster_size;
90e5b43573SFam Zheng     int max_iov;
9190ab48ebSAnton Nefedov     bool initial_zeroing_ongoing;
92d06107adSMax Reitz     int in_active_write_counter;
93d69a879bSHanna Reitz     int64_t active_write_bytes_in_flight;
94737efc1eSJohn Snow     bool prepared;
955e771752SSergio Lopez     bool in_drain;
96893f7ebaSPaolo Bonzini } MirrorBlockJob;
97893f7ebaSPaolo Bonzini 
98429076e8SMax Reitz typedef struct MirrorBDSOpaque {
99429076e8SMax Reitz     MirrorBlockJob *job;
100f94dc3b4SMax Reitz     bool stop;
10153431b90SMax Reitz     bool is_commit;
102429076e8SMax Reitz } MirrorBDSOpaque;
103429076e8SMax Reitz 
10412aa4082SMax Reitz struct MirrorOp {
105bd48bde8SPaolo Bonzini     MirrorBlockJob *s;
106bd48bde8SPaolo Bonzini     QEMUIOVector qiov;
107b436982fSEric Blake     int64_t offset;
108b436982fSEric Blake     uint64_t bytes;
1092e1990b2SMax Reitz 
1102e1990b2SMax Reitz     /* The pointee is set by mirror_co_read(), mirror_co_zero(), and
1112e1990b2SMax Reitz      * mirror_co_discard() before yielding for the first time */
1122e1990b2SMax Reitz     int64_t *bytes_handled;
11312aa4082SMax Reitz 
1141181e19aSMax Reitz     bool is_pseudo_op;
115d06107adSMax Reitz     bool is_active_write;
116ce8cabbdSKevin Wolf     bool is_in_flight;
11712aa4082SMax Reitz     CoQueue waiting_requests;
118eed325b9SKevin Wolf     Coroutine *co;
119d44dae1aSVladimir Sementsov-Ogievskiy     MirrorOp *waiting_for_op;
12012aa4082SMax Reitz 
12112aa4082SMax Reitz     QTAILQ_ENTRY(MirrorOp) next;
12212aa4082SMax Reitz };
123bd48bde8SPaolo Bonzini 
1244295c5fcSMax Reitz typedef enum MirrorMethod {
1254295c5fcSMax Reitz     MIRROR_METHOD_COPY,
1264295c5fcSMax Reitz     MIRROR_METHOD_ZERO,
1274295c5fcSMax Reitz     MIRROR_METHOD_DISCARD,
1284295c5fcSMax Reitz } MirrorMethod;
1294295c5fcSMax Reitz 
mirror_error_action(MirrorBlockJob * s,bool read,int error)130b952b558SPaolo Bonzini static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
131b952b558SPaolo Bonzini                                             int error)
132b952b558SPaolo Bonzini {
13376cb2f24SFiona Ebner     qatomic_set(&s->actively_synced, false);
134b952b558SPaolo Bonzini     if (read) {
13581e254dcSKevin Wolf         return block_job_error_action(&s->common, s->on_source_error,
13681e254dcSKevin Wolf                                       true, error);
137b952b558SPaolo Bonzini     } else {
13881e254dcSKevin Wolf         return block_job_error_action(&s->common, s->on_target_error,
13981e254dcSKevin Wolf                                       false, error);
140b952b558SPaolo Bonzini     }
141b952b558SPaolo Bonzini }
142b952b558SPaolo Bonzini 
mirror_wait_on_conflicts(MirrorOp * self,MirrorBlockJob * s,uint64_t offset,uint64_t bytes)1431181e19aSMax Reitz static void coroutine_fn mirror_wait_on_conflicts(MirrorOp *self,
1441181e19aSMax Reitz                                                   MirrorBlockJob *s,
1451181e19aSMax Reitz                                                   uint64_t offset,
1461181e19aSMax Reitz                                                   uint64_t bytes)
1471181e19aSMax Reitz {
1481181e19aSMax Reitz     uint64_t self_start_chunk = offset / s->granularity;
1491181e19aSMax Reitz     uint64_t self_end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1501181e19aSMax Reitz     uint64_t self_nb_chunks = self_end_chunk - self_start_chunk;
1511181e19aSMax Reitz 
1521181e19aSMax Reitz     while (find_next_bit(s->in_flight_bitmap, self_end_chunk,
1531181e19aSMax Reitz                          self_start_chunk) < self_end_chunk &&
1541181e19aSMax Reitz            s->ret >= 0)
1551181e19aSMax Reitz     {
1561181e19aSMax Reitz         MirrorOp *op;
1571181e19aSMax Reitz 
1581181e19aSMax Reitz         QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
1591181e19aSMax Reitz             uint64_t op_start_chunk = op->offset / s->granularity;
1601181e19aSMax Reitz             uint64_t op_nb_chunks = DIV_ROUND_UP(op->offset + op->bytes,
1611181e19aSMax Reitz                                                  s->granularity) -
1621181e19aSMax Reitz                                     op_start_chunk;
1631181e19aSMax Reitz 
1641181e19aSMax Reitz             if (op == self) {
1651181e19aSMax Reitz                 continue;
1661181e19aSMax Reitz             }
1671181e19aSMax Reitz 
1681181e19aSMax Reitz             if (ranges_overlap(self_start_chunk, self_nb_chunks,
1691181e19aSMax Reitz                                op_start_chunk, op_nb_chunks))
1701181e19aSMax Reitz             {
17166fed30cSStefano Garzarella                 if (self) {
172d44dae1aSVladimir Sementsov-Ogievskiy                     /*
17366fed30cSStefano Garzarella                      * If the operation is already (indirectly) waiting for us,
17466fed30cSStefano Garzarella                      * or will wait for us as soon as it wakes up, then just go
17566fed30cSStefano Garzarella                      * on (instead of producing a deadlock in the former case).
176d44dae1aSVladimir Sementsov-Ogievskiy                      */
177d44dae1aSVladimir Sementsov-Ogievskiy                     if (op->waiting_for_op) {
178d44dae1aSVladimir Sementsov-Ogievskiy                         continue;
179d44dae1aSVladimir Sementsov-Ogievskiy                     }
180d44dae1aSVladimir Sementsov-Ogievskiy 
181d44dae1aSVladimir Sementsov-Ogievskiy                     self->waiting_for_op = op;
18266fed30cSStefano Garzarella                 }
18366fed30cSStefano Garzarella 
1841181e19aSMax Reitz                 qemu_co_queue_wait(&op->waiting_requests, NULL);
18566fed30cSStefano Garzarella 
18666fed30cSStefano Garzarella                 if (self) {
187d44dae1aSVladimir Sementsov-Ogievskiy                     self->waiting_for_op = NULL;
18866fed30cSStefano Garzarella                 }
18966fed30cSStefano Garzarella 
1901181e19aSMax Reitz                 break;
1911181e19aSMax Reitz             }
1921181e19aSMax Reitz         }
1931181e19aSMax Reitz     }
1941181e19aSMax Reitz }
1951181e19aSMax Reitz 
mirror_iteration_done(MirrorOp * op,int ret)1962e1990b2SMax Reitz static void coroutine_fn mirror_iteration_done(MirrorOp *op, int ret)
197bd48bde8SPaolo Bonzini {
198bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
199402a4741SPaolo Bonzini     struct iovec *iov;
200bd48bde8SPaolo Bonzini     int64_t chunk_num;
201b436982fSEric Blake     int i, nb_chunks;
202bd48bde8SPaolo Bonzini 
203b436982fSEric Blake     trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
204bd48bde8SPaolo Bonzini 
205bd48bde8SPaolo Bonzini     s->in_flight--;
206b436982fSEric Blake     s->bytes_in_flight -= op->bytes;
207402a4741SPaolo Bonzini     iov = op->qiov.iov;
208402a4741SPaolo Bonzini     for (i = 0; i < op->qiov.niov; i++) {
209402a4741SPaolo Bonzini         MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
210402a4741SPaolo Bonzini         QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
211402a4741SPaolo Bonzini         s->buf_free_count++;
212402a4741SPaolo Bonzini     }
213402a4741SPaolo Bonzini 
214b436982fSEric Blake     chunk_num = op->offset / s->granularity;
215b436982fSEric Blake     nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
21612aa4082SMax Reitz 
217402a4741SPaolo Bonzini     bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
21812aa4082SMax Reitz     QTAILQ_REMOVE(&s->ops_in_flight, op, next);
219b21c7652SMax Reitz     if (ret >= 0) {
220b21c7652SMax Reitz         if (s->cow_bitmap) {
221bd48bde8SPaolo Bonzini             bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
222bd48bde8SPaolo Bonzini         }
22390ab48ebSAnton Nefedov         if (!s->initial_zeroing_ongoing) {
22430a5c887SKevin Wolf             job_progress_update(&s->common.job, op->bytes);
225b21c7652SMax Reitz         }
22690ab48ebSAnton Nefedov     }
2276df3bf8eSZhang Min     qemu_iovec_destroy(&op->qiov);
2287b770c72SStefan Hajnoczi 
22912aa4082SMax Reitz     qemu_co_queue_restart_all(&op->waiting_requests);
23012aa4082SMax Reitz     g_free(op);
2317b770c72SStefan Hajnoczi }
232bd48bde8SPaolo Bonzini 
mirror_write_complete(MirrorOp * op,int ret)2332e1990b2SMax Reitz static void coroutine_fn mirror_write_complete(MirrorOp *op, int ret)
234bd48bde8SPaolo Bonzini {
235bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
236b9e413ddSPaolo Bonzini 
237bd48bde8SPaolo Bonzini     if (ret < 0) {
238bd48bde8SPaolo Bonzini         BlockErrorAction action;
239bd48bde8SPaolo Bonzini 
240e0d7f73eSEric Blake         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
241bd48bde8SPaolo Bonzini         action = mirror_error_action(s, false, -ret);
242a589569fSWenchao Xia         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
243bd48bde8SPaolo Bonzini             s->ret = ret;
244bd48bde8SPaolo Bonzini         }
245bd48bde8SPaolo Bonzini     }
246d12ade57SVladimir Sementsov-Ogievskiy 
247bd48bde8SPaolo Bonzini     mirror_iteration_done(op, ret);
248bd48bde8SPaolo Bonzini }
249bd48bde8SPaolo Bonzini 
mirror_read_complete(MirrorOp * op,int ret)2502e1990b2SMax Reitz static void coroutine_fn mirror_read_complete(MirrorOp *op, int ret)
251bd48bde8SPaolo Bonzini {
252bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
253b9e413ddSPaolo Bonzini 
254bd48bde8SPaolo Bonzini     if (ret < 0) {
255bd48bde8SPaolo Bonzini         BlockErrorAction action;
256bd48bde8SPaolo Bonzini 
257e0d7f73eSEric Blake         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
258bd48bde8SPaolo Bonzini         action = mirror_error_action(s, true, -ret);
259a589569fSWenchao Xia         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
260bd48bde8SPaolo Bonzini             s->ret = ret;
261bd48bde8SPaolo Bonzini         }
262bd48bde8SPaolo Bonzini 
263bd48bde8SPaolo Bonzini         mirror_iteration_done(op, ret);
264d12ade57SVladimir Sementsov-Ogievskiy         return;
265bd48bde8SPaolo Bonzini     }
266d12ade57SVladimir Sementsov-Ogievskiy 
267d12ade57SVladimir Sementsov-Ogievskiy     ret = blk_co_pwritev(s->target, op->offset, op->qiov.size, &op->qiov, 0);
268d12ade57SVladimir Sementsov-Ogievskiy     mirror_write_complete(op, ret);
269b9e413ddSPaolo Bonzini }
270bd48bde8SPaolo Bonzini 
271782d97efSEric Blake /* Clip bytes relative to offset to not exceed end-of-file */
mirror_clip_bytes(MirrorBlockJob * s,int64_t offset,int64_t bytes)272782d97efSEric Blake static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
273782d97efSEric Blake                                         int64_t offset,
274782d97efSEric Blake                                         int64_t bytes)
275782d97efSEric Blake {
276782d97efSEric Blake     return MIN(bytes, s->bdev_length - offset);
277782d97efSEric Blake }
278782d97efSEric Blake 
279782d97efSEric Blake /* Round offset and/or bytes to target cluster if COW is needed, and
280782d97efSEric Blake  * return the offset of the adjusted tail against original. */
mirror_cow_align(MirrorBlockJob * s,int64_t * offset,uint64_t * bytes)28117ac39c3SPaolo Bonzini static int coroutine_fn mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
282ae4cc877SEric Blake                                          uint64_t *bytes)
283893f7ebaSPaolo Bonzini {
284e5b43573SFam Zheng     bool need_cow;
285e5b43573SFam Zheng     int ret = 0;
286782d97efSEric Blake     int64_t align_offset = *offset;
2877cfd5275SEric Blake     int64_t align_bytes = *bytes;
288782d97efSEric Blake     int max_bytes = s->granularity * s->max_iov;
289893f7ebaSPaolo Bonzini 
290782d97efSEric Blake     need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
291782d97efSEric Blake     need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
292e5b43573SFam Zheng                           s->cow_bitmap);
293e5b43573SFam Zheng     if (need_cow) {
294fc6b211fSAndrey Drobyshev         bdrv_round_to_subclusters(blk_bs(s->target), *offset, *bytes,
295782d97efSEric Blake                                   &align_offset, &align_bytes);
2968f0720ecSPaolo Bonzini     }
2978f0720ecSPaolo Bonzini 
298782d97efSEric Blake     if (align_bytes > max_bytes) {
299782d97efSEric Blake         align_bytes = max_bytes;
300e5b43573SFam Zheng         if (need_cow) {
301782d97efSEric Blake             align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
302e5b43573SFam Zheng         }
303e5b43573SFam Zheng     }
304782d97efSEric Blake     /* Clipping may result in align_bytes unaligned to chunk boundary, but
3054150ae60SFam Zheng      * that doesn't matter because it's already the end of source image. */
306782d97efSEric Blake     align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
307402a4741SPaolo Bonzini 
308782d97efSEric Blake     ret = align_offset + align_bytes - (*offset + *bytes);
309782d97efSEric Blake     *offset = align_offset;
310782d97efSEric Blake     *bytes = align_bytes;
311e5b43573SFam Zheng     assert(ret >= 0);
312e5b43573SFam Zheng     return ret;
313e5b43573SFam Zheng }
314e5b43573SFam Zheng 
315537c3d4fSStefan Hajnoczi static inline void coroutine_fn
mirror_wait_for_free_in_flight_slot(MirrorBlockJob * s)316eb994912SHanna Reitz mirror_wait_for_free_in_flight_slot(MirrorBlockJob *s)
31721cd917fSFam Zheng {
31812aa4082SMax Reitz     MirrorOp *op;
31912aa4082SMax Reitz 
3201181e19aSMax Reitz     QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
321eb994912SHanna Reitz         /*
322eb994912SHanna Reitz          * Do not wait on pseudo ops, because it may in turn wait on
3231181e19aSMax Reitz          * some other operation to start, which may in fact be the
3241181e19aSMax Reitz          * caller of this function.  Since there is only one pseudo op
3251181e19aSMax Reitz          * at any given time, we will always find some real operation
326eb994912SHanna Reitz          * to wait on.
327eb994912SHanna Reitz          * Also, do not wait on active operations, because they do not
328eb994912SHanna Reitz          * use up in-flight slots.
329eb994912SHanna Reitz          */
330eb994912SHanna Reitz         if (!op->is_pseudo_op && op->is_in_flight && !op->is_active_write) {
33112aa4082SMax Reitz             qemu_co_queue_wait(&op->waiting_requests, NULL);
3321181e19aSMax Reitz             return;
3331181e19aSMax Reitz         }
3341181e19aSMax Reitz     }
3351181e19aSMax Reitz     abort();
33621cd917fSFam Zheng }
33721cd917fSFam Zheng 
3382e1990b2SMax Reitz /* Perform a mirror copy operation.
3392e1990b2SMax Reitz  *
3402e1990b2SMax Reitz  * *op->bytes_handled is set to the number of bytes copied after and
3412e1990b2SMax Reitz  * including offset, excluding any bytes copied prior to offset due
3422e1990b2SMax Reitz  * to alignment.  This will be op->bytes if no alignment is necessary,
3432e1990b2SMax Reitz  * or (new_end - op->offset) if the tail is rounded up or down due to
344e5b43573SFam Zheng  * alignment or buffer limit.
345402a4741SPaolo Bonzini  */
mirror_co_read(void * opaque)3462e1990b2SMax Reitz static void coroutine_fn mirror_co_read(void *opaque)
347e5b43573SFam Zheng {
3482e1990b2SMax Reitz     MirrorOp *op = opaque;
3492e1990b2SMax Reitz     MirrorBlockJob *s = op->s;
350ae4cc877SEric Blake     int nb_chunks;
351ae4cc877SEric Blake     uint64_t ret;
352ae4cc877SEric Blake     uint64_t max_bytes;
353402a4741SPaolo Bonzini 
354ae4cc877SEric Blake     max_bytes = s->granularity * s->max_iov;
355e5b43573SFam Zheng 
356e5b43573SFam Zheng     /* We can only handle as much as buf_size at a time. */
3572e1990b2SMax Reitz     op->bytes = MIN(s->buf_size, MIN(max_bytes, op->bytes));
3582e1990b2SMax Reitz     assert(op->bytes);
3592e1990b2SMax Reitz     assert(op->bytes < BDRV_REQUEST_MAX_BYTES);
3602e1990b2SMax Reitz     *op->bytes_handled = op->bytes;
361e5b43573SFam Zheng 
362e5b43573SFam Zheng     if (s->cow_bitmap) {
3632e1990b2SMax Reitz         *op->bytes_handled += mirror_cow_align(s, &op->offset, &op->bytes);
364e5b43573SFam Zheng     }
3652e1990b2SMax Reitz     /* Cannot exceed BDRV_REQUEST_MAX_BYTES + INT_MAX */
3662e1990b2SMax Reitz     assert(*op->bytes_handled <= UINT_MAX);
3672e1990b2SMax Reitz     assert(op->bytes <= s->buf_size);
368ae4cc877SEric Blake     /* The offset is granularity-aligned because:
369e5b43573SFam Zheng      * 1) Caller passes in aligned values;
370e5b43573SFam Zheng      * 2) mirror_cow_align is used only when target cluster is larger. */
3712e1990b2SMax Reitz     assert(QEMU_IS_ALIGNED(op->offset, s->granularity));
372ae4cc877SEric Blake     /* The range is sector-aligned, since bdrv_getlength() rounds up. */
3732e1990b2SMax Reitz     assert(QEMU_IS_ALIGNED(op->bytes, BDRV_SECTOR_SIZE));
3742e1990b2SMax Reitz     nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
375e5b43573SFam Zheng 
376e5b43573SFam Zheng     while (s->buf_free_count < nb_chunks) {
3772e1990b2SMax Reitz         trace_mirror_yield_in_flight(s, op->offset, s->in_flight);
3789178f4feSKevin Wolf         mirror_wait_for_free_in_flight_slot(s);
379b812f671SPaolo Bonzini     }
380b812f671SPaolo Bonzini 
381402a4741SPaolo Bonzini     /* Now make a QEMUIOVector taking enough granularity-sized chunks
382402a4741SPaolo Bonzini      * from s->buf_free.
383402a4741SPaolo Bonzini      */
384402a4741SPaolo Bonzini     qemu_iovec_init(&op->qiov, nb_chunks);
385402a4741SPaolo Bonzini     while (nb_chunks-- > 0) {
386402a4741SPaolo Bonzini         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
3872e1990b2SMax Reitz         size_t remaining = op->bytes - op->qiov.size;
3885a0f6fd5SKevin Wolf 
389402a4741SPaolo Bonzini         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
390402a4741SPaolo Bonzini         s->buf_free_count--;
3915a0f6fd5SKevin Wolf         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
392402a4741SPaolo Bonzini     }
393402a4741SPaolo Bonzini 
394893f7ebaSPaolo Bonzini     /* Copy the dirty cluster.  */
395bd48bde8SPaolo Bonzini     s->in_flight++;
3962e1990b2SMax Reitz     s->bytes_in_flight += op->bytes;
397ce8cabbdSKevin Wolf     op->is_in_flight = true;
3982e1990b2SMax Reitz     trace_mirror_one_iteration(s, op->offset, op->bytes);
399dcfb3bebSFam Zheng 
400b9b10c35SKevin Wolf     WITH_GRAPH_RDLOCK_GUARD() {
401138f9fffSMax Reitz         ret = bdrv_co_preadv(s->mirror_top_bs->backing, op->offset, op->bytes,
402138f9fffSMax Reitz                              &op->qiov, 0);
403b9b10c35SKevin Wolf     }
4042e1990b2SMax Reitz     mirror_read_complete(op, ret);
405e5b43573SFam Zheng }
406e5b43573SFam Zheng 
mirror_co_zero(void * opaque)4072e1990b2SMax Reitz static void coroutine_fn mirror_co_zero(void *opaque)
408e5b43573SFam Zheng {
4092e1990b2SMax Reitz     MirrorOp *op = opaque;
4102e1990b2SMax Reitz     int ret;
411e5b43573SFam Zheng 
4122e1990b2SMax Reitz     op->s->in_flight++;
4132e1990b2SMax Reitz     op->s->bytes_in_flight += op->bytes;
4142e1990b2SMax Reitz     *op->bytes_handled = op->bytes;
415ce8cabbdSKevin Wolf     op->is_in_flight = true;
416e5b43573SFam Zheng 
4172e1990b2SMax Reitz     ret = blk_co_pwrite_zeroes(op->s->target, op->offset, op->bytes,
4182e1990b2SMax Reitz                                op->s->unmap ? BDRV_REQ_MAY_UNMAP : 0);
4192e1990b2SMax Reitz     mirror_write_complete(op, ret);
420e5b43573SFam Zheng }
4212e1990b2SMax Reitz 
mirror_co_discard(void * opaque)4222e1990b2SMax Reitz static void coroutine_fn mirror_co_discard(void *opaque)
4232e1990b2SMax Reitz {
4242e1990b2SMax Reitz     MirrorOp *op = opaque;
4252e1990b2SMax Reitz     int ret;
4262e1990b2SMax Reitz 
4272e1990b2SMax Reitz     op->s->in_flight++;
4282e1990b2SMax Reitz     op->s->bytes_in_flight += op->bytes;
4292e1990b2SMax Reitz     *op->bytes_handled = op->bytes;
430ce8cabbdSKevin Wolf     op->is_in_flight = true;
4312e1990b2SMax Reitz 
4322e1990b2SMax Reitz     ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes);
4332e1990b2SMax Reitz     mirror_write_complete(op, ret);
434e5b43573SFam Zheng }
435e5b43573SFam Zheng 
mirror_perform(MirrorBlockJob * s,int64_t offset,unsigned bytes,MirrorMethod mirror_method)4364295c5fcSMax Reitz static unsigned mirror_perform(MirrorBlockJob *s, int64_t offset,
4374295c5fcSMax Reitz                                unsigned bytes, MirrorMethod mirror_method)
4384295c5fcSMax Reitz {
4392e1990b2SMax Reitz     MirrorOp *op;
4402e1990b2SMax Reitz     Coroutine *co;
4412e1990b2SMax Reitz     int64_t bytes_handled = -1;
4422e1990b2SMax Reitz 
4432e1990b2SMax Reitz     op = g_new(MirrorOp, 1);
4442e1990b2SMax Reitz     *op = (MirrorOp){
4452e1990b2SMax Reitz         .s              = s,
4462e1990b2SMax Reitz         .offset         = offset,
4472e1990b2SMax Reitz         .bytes          = bytes,
4482e1990b2SMax Reitz         .bytes_handled  = &bytes_handled,
4492e1990b2SMax Reitz     };
45012aa4082SMax Reitz     qemu_co_queue_init(&op->waiting_requests);
4512e1990b2SMax Reitz 
4524295c5fcSMax Reitz     switch (mirror_method) {
4534295c5fcSMax Reitz     case MIRROR_METHOD_COPY:
4542e1990b2SMax Reitz         co = qemu_coroutine_create(mirror_co_read, op);
4552e1990b2SMax Reitz         break;
4564295c5fcSMax Reitz     case MIRROR_METHOD_ZERO:
4572e1990b2SMax Reitz         co = qemu_coroutine_create(mirror_co_zero, op);
4582e1990b2SMax Reitz         break;
4594295c5fcSMax Reitz     case MIRROR_METHOD_DISCARD:
4602e1990b2SMax Reitz         co = qemu_coroutine_create(mirror_co_discard, op);
4612e1990b2SMax Reitz         break;
4624295c5fcSMax Reitz     default:
4634295c5fcSMax Reitz         abort();
4644295c5fcSMax Reitz     }
465eed325b9SKevin Wolf     op->co = co;
4662e1990b2SMax Reitz 
46712aa4082SMax Reitz     QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
4682e1990b2SMax Reitz     qemu_coroutine_enter(co);
4692e1990b2SMax Reitz     /* At this point, ownership of op has been moved to the coroutine
4702e1990b2SMax Reitz      * and the object may already be freed */
4712e1990b2SMax Reitz 
4722e1990b2SMax Reitz     /* Assert that this value has been set */
4732e1990b2SMax Reitz     assert(bytes_handled >= 0);
4742e1990b2SMax Reitz 
4752e1990b2SMax Reitz     /* Same assertion as in mirror_co_read() (and for mirror_co_read()
4762e1990b2SMax Reitz      * and mirror_co_discard(), bytes_handled == op->bytes, which
4772e1990b2SMax Reitz      * is the @bytes parameter given to this function) */
4782e1990b2SMax Reitz     assert(bytes_handled <= UINT_MAX);
4792e1990b2SMax Reitz     return bytes_handled;
4804295c5fcSMax Reitz }
4814295c5fcSMax Reitz 
mirror_iteration(MirrorBlockJob * s)482*ae5a40e8SKevin Wolf static void coroutine_fn GRAPH_UNLOCKED mirror_iteration(MirrorBlockJob *s)
483e5b43573SFam Zheng {
484*ae5a40e8SKevin Wolf     BlockDriverState *source;
4851181e19aSMax Reitz     MirrorOp *pseudo_op;
4861181e19aSMax Reitz     int64_t offset;
487e5b43573SFam Zheng     /* At least the first dirty chunk is mirrored in one iteration. */
488e5b43573SFam Zheng     int nb_chunks = 1;
4894b5004d9SDenis V. Lunev     bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
490b436982fSEric Blake     int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
491e5b43573SFam Zheng 
492*ae5a40e8SKevin Wolf     bdrv_graph_co_rdlock();
493*ae5a40e8SKevin Wolf     source = s->mirror_top_bs->backing->bs;
494*ae5a40e8SKevin Wolf     bdrv_graph_co_rdunlock();
495*ae5a40e8SKevin Wolf 
496b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_lock(s->dirty_bitmap);
497f798184cSEric Blake     offset = bdrv_dirty_iter_next(s->dbi);
498fb2ef791SEric Blake     if (offset < 0) {
499dc162c8eSFam Zheng         bdrv_set_dirty_iter(s->dbi, 0);
500f798184cSEric Blake         offset = bdrv_dirty_iter_next(s->dbi);
5019a46dba7SEric Blake         trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
502fb2ef791SEric Blake         assert(offset >= 0);
503e5b43573SFam Zheng     }
504b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
505e5b43573SFam Zheng 
506d69a879bSHanna Reitz     /*
507d69a879bSHanna Reitz      * Wait for concurrent requests to @offset.  The next loop will limit the
508d69a879bSHanna Reitz      * copied area based on in_flight_bitmap so we only copy an area that does
509d69a879bSHanna Reitz      * not overlap with concurrent in-flight requests.  Still, we would like to
510d69a879bSHanna Reitz      * copy something, so wait until there are at least no more requests to the
511d69a879bSHanna Reitz      * very beginning of the area.
512d69a879bSHanna Reitz      */
5131181e19aSMax Reitz     mirror_wait_on_conflicts(NULL, s, offset, 1);
5149c83625bSMax Reitz 
515da01ff7fSKevin Wolf     job_pause_point(&s->common.job);
516565ac01fSStefan Hajnoczi 
5173202d8e4SMichael Tokarev     /* Find the number of consecutive dirty chunks following the first dirty
518e5b43573SFam Zheng      * one, and wait for in flight requests in them. */
519b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_lock(s->dirty_bitmap);
520fb2ef791SEric Blake     while (nb_chunks * s->granularity < s->buf_size) {
521dc162c8eSFam Zheng         int64_t next_dirty;
522fb2ef791SEric Blake         int64_t next_offset = offset + nb_chunks * s->granularity;
523fb2ef791SEric Blake         int64_t next_chunk = next_offset / s->granularity;
524fb2ef791SEric Blake         if (next_offset >= s->bdev_length ||
52528636b82SJohn Snow             !bdrv_dirty_bitmap_get_locked(s->dirty_bitmap, next_offset)) {
526e5b43573SFam Zheng             break;
527e5b43573SFam Zheng         }
528e5b43573SFam Zheng         if (test_bit(next_chunk, s->in_flight_bitmap)) {
529e5b43573SFam Zheng             break;
530e5b43573SFam Zheng         }
5319c83625bSMax Reitz 
532f798184cSEric Blake         next_dirty = bdrv_dirty_iter_next(s->dbi);
533fb2ef791SEric Blake         if (next_dirty > next_offset || next_dirty < 0) {
534f27a2742SMax Reitz             /* The bitmap iterator's cache is stale, refresh it */
535715a74d8SEric Blake             bdrv_set_dirty_iter(s->dbi, next_offset);
536f798184cSEric Blake             next_dirty = bdrv_dirty_iter_next(s->dbi);
537f27a2742SMax Reitz         }
538fb2ef791SEric Blake         assert(next_dirty == next_offset);
539e5b43573SFam Zheng         nb_chunks++;
540e5b43573SFam Zheng     }
541e5b43573SFam Zheng 
542e5b43573SFam Zheng     /* Clear dirty bits before querying the block status, because
54331826642SEric Blake      * calling bdrv_block_status_above could yield - if some blocks are
544e5b43573SFam Zheng      * marked dirty in this window, we need to know.
545e5b43573SFam Zheng      */
546e0d7f73eSEric Blake     bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
547e0d7f73eSEric Blake                                    nb_chunks * s->granularity);
548b64bd51eSPaolo Bonzini     bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
549b64bd51eSPaolo Bonzini 
5501181e19aSMax Reitz     /* Before claiming an area in the in-flight bitmap, we have to
5511181e19aSMax Reitz      * create a MirrorOp for it so that conflicting requests can wait
5521181e19aSMax Reitz      * for it.  mirror_perform() will create the real MirrorOps later,
5531181e19aSMax Reitz      * for now we just create a pseudo operation that will wake up all
5541181e19aSMax Reitz      * conflicting requests once all real operations have been
5551181e19aSMax Reitz      * launched. */
5561181e19aSMax Reitz     pseudo_op = g_new(MirrorOp, 1);
5571181e19aSMax Reitz     *pseudo_op = (MirrorOp){
5581181e19aSMax Reitz         .offset         = offset,
5591181e19aSMax Reitz         .bytes          = nb_chunks * s->granularity,
5601181e19aSMax Reitz         .is_pseudo_op   = true,
5611181e19aSMax Reitz     };
5621181e19aSMax Reitz     qemu_co_queue_init(&pseudo_op->waiting_requests);
5631181e19aSMax Reitz     QTAILQ_INSERT_TAIL(&s->ops_in_flight, pseudo_op, next);
5641181e19aSMax Reitz 
565fb2ef791SEric Blake     bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
566fb2ef791SEric Blake     while (nb_chunks > 0 && offset < s->bdev_length) {
56731826642SEric Blake         int ret;
5687cfd5275SEric Blake         int64_t io_bytes;
569f3e4ce4aSEric Blake         int64_t io_bytes_acct;
5704295c5fcSMax Reitz         MirrorMethod mirror_method = MIRROR_METHOD_COPY;
571e5b43573SFam Zheng 
572fb2ef791SEric Blake         assert(!(offset % s->granularity));
5737ff9579eSKevin Wolf         WITH_GRAPH_RDLOCK_GUARD() {
574cc323997SPaolo Bonzini             ret = bdrv_co_block_status_above(source, NULL, offset,
57531826642SEric Blake                                              nb_chunks * s->granularity,
57631826642SEric Blake                                              &io_bytes, NULL, NULL);
5777ff9579eSKevin Wolf         }
578e5b43573SFam Zheng         if (ret < 0) {
579fb2ef791SEric Blake             io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
5800965a41eSVladimir Sementsov-Ogievskiy         } else if (ret & BDRV_BLOCK_DATA) {
581fb2ef791SEric Blake             io_bytes = MIN(io_bytes, max_io_bytes);
582e5b43573SFam Zheng         }
583e5b43573SFam Zheng 
584fb2ef791SEric Blake         io_bytes -= io_bytes % s->granularity;
585fb2ef791SEric Blake         if (io_bytes < s->granularity) {
586fb2ef791SEric Blake             io_bytes = s->granularity;
587e5b43573SFam Zheng         } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
588fb2ef791SEric Blake             int64_t target_offset;
5897cfd5275SEric Blake             int64_t target_bytes;
590a00e70c0SEmanuele Giuseppe Esposito             WITH_GRAPH_RDLOCK_GUARD() {
591fc6b211fSAndrey Drobyshev                 bdrv_round_to_subclusters(blk_bs(s->target), offset, io_bytes,
592fb2ef791SEric Blake                                           &target_offset, &target_bytes);
593a00e70c0SEmanuele Giuseppe Esposito             }
594fb2ef791SEric Blake             if (target_offset == offset &&
595fb2ef791SEric Blake                 target_bytes == io_bytes) {
596e5b43573SFam Zheng                 mirror_method = ret & BDRV_BLOCK_ZERO ?
597e5b43573SFam Zheng                                     MIRROR_METHOD_ZERO :
598e5b43573SFam Zheng                                     MIRROR_METHOD_DISCARD;
599e5b43573SFam Zheng             }
600e5b43573SFam Zheng         }
601e5b43573SFam Zheng 
602cf56a3c6SDenis V. Lunev         while (s->in_flight >= MAX_IN_FLIGHT) {
603fb2ef791SEric Blake             trace_mirror_yield_in_flight(s, offset, s->in_flight);
6049178f4feSKevin Wolf             mirror_wait_for_free_in_flight_slot(s);
605cf56a3c6SDenis V. Lunev         }
606cf56a3c6SDenis V. Lunev 
607dbaa7b57SVladimir Sementsov-Ogievskiy         if (s->ret < 0) {
6081181e19aSMax Reitz             ret = 0;
6091181e19aSMax Reitz             goto fail;
610dbaa7b57SVladimir Sementsov-Ogievskiy         }
611dbaa7b57SVladimir Sementsov-Ogievskiy 
612fb2ef791SEric Blake         io_bytes = mirror_clip_bytes(s, offset, io_bytes);
6134295c5fcSMax Reitz         io_bytes = mirror_perform(s, offset, io_bytes, mirror_method);
6144295c5fcSMax Reitz         if (mirror_method != MIRROR_METHOD_COPY && write_zeroes_ok) {
615f3e4ce4aSEric Blake             io_bytes_acct = 0;
6164b5004d9SDenis V. Lunev         } else {
617fb2ef791SEric Blake             io_bytes_acct = io_bytes;
6184b5004d9SDenis V. Lunev         }
619fb2ef791SEric Blake         assert(io_bytes);
620fb2ef791SEric Blake         offset += io_bytes;
621fb2ef791SEric Blake         nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
622018e5987SKevin Wolf         block_job_ratelimit_processed_bytes(&s->common, io_bytes_acct);
623dcfb3bebSFam Zheng     }
6241181e19aSMax Reitz 
6251181e19aSMax Reitz fail:
6261181e19aSMax Reitz     QTAILQ_REMOVE(&s->ops_in_flight, pseudo_op, next);
6271181e19aSMax Reitz     qemu_co_queue_restart_all(&pseudo_op->waiting_requests);
6281181e19aSMax Reitz     g_free(pseudo_op);
629893f7ebaSPaolo Bonzini }
630b952b558SPaolo Bonzini 
mirror_free_init(MirrorBlockJob * s)631402a4741SPaolo Bonzini static void mirror_free_init(MirrorBlockJob *s)
632402a4741SPaolo Bonzini {
633402a4741SPaolo Bonzini     int granularity = s->granularity;
634402a4741SPaolo Bonzini     size_t buf_size = s->buf_size;
635402a4741SPaolo Bonzini     uint8_t *buf = s->buf;
636402a4741SPaolo Bonzini 
637402a4741SPaolo Bonzini     assert(s->buf_free_count == 0);
638402a4741SPaolo Bonzini     QSIMPLEQ_INIT(&s->buf_free);
639402a4741SPaolo Bonzini     while (buf_size != 0) {
640402a4741SPaolo Bonzini         MirrorBuffer *cur = (MirrorBuffer *)buf;
641402a4741SPaolo Bonzini         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
642402a4741SPaolo Bonzini         s->buf_free_count++;
643402a4741SPaolo Bonzini         buf_size -= granularity;
644402a4741SPaolo Bonzini         buf += granularity;
645402a4741SPaolo Bonzini     }
646402a4741SPaolo Bonzini }
647402a4741SPaolo Bonzini 
648bae8196dSPaolo Bonzini /* This is also used for the .pause callback. There is no matching
649bae8196dSPaolo Bonzini  * mirror_resume() because mirror_run() will begin iterating again
650bae8196dSPaolo Bonzini  * when the job is resumed.
651bae8196dSPaolo Bonzini  */
mirror_wait_for_all_io(MirrorBlockJob * s)652537c3d4fSStefan Hajnoczi static void coroutine_fn mirror_wait_for_all_io(MirrorBlockJob *s)
653bd48bde8SPaolo Bonzini {
654bd48bde8SPaolo Bonzini     while (s->in_flight > 0) {
6559178f4feSKevin Wolf         mirror_wait_for_free_in_flight_slot(s);
656bd48bde8SPaolo Bonzini     }
657893f7ebaSPaolo Bonzini }
658893f7ebaSPaolo Bonzini 
659737efc1eSJohn Snow /**
660737efc1eSJohn Snow  * mirror_exit_common: handle both abort() and prepare() cases.
661737efc1eSJohn Snow  * for .prepare, returns 0 on success and -errno on failure.
662737efc1eSJohn Snow  * for .abort cases, denoted by abort = true, MUST return 0.
663737efc1eSJohn Snow  */
mirror_exit_common(Job * job)664737efc1eSJohn Snow static int mirror_exit_common(Job *job)
6655a7e7a0bSStefan Hajnoczi {
6661908a559SKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
6671908a559SKevin Wolf     BlockJob *bjob = &s->common;
668f93c3addSMax Reitz     MirrorBDSOpaque *bs_opaque;
669f93c3addSMax Reitz     BlockDriverState *src;
670f93c3addSMax Reitz     BlockDriverState *target_bs;
671f93c3addSMax Reitz     BlockDriverState *mirror_top_bs;
67212fa4af6SKevin Wolf     Error *local_err = NULL;
673737efc1eSJohn Snow     bool abort = job->ret < 0;
674737efc1eSJohn Snow     int ret = 0;
675737efc1eSJohn Snow 
6762626d27fSKevin Wolf     GLOBAL_STATE_CODE();
6772626d27fSKevin Wolf 
678737efc1eSJohn Snow     if (s->prepared) {
679737efc1eSJohn Snow         return 0;
680737efc1eSJohn Snow     }
681737efc1eSJohn Snow     s->prepared = true;
6823f09bfbcSKevin Wolf 
6839275fc72SKevin Wolf     bdrv_graph_rdlock_main_loop();
6842626d27fSKevin Wolf 
685f93c3addSMax Reitz     mirror_top_bs = s->mirror_top_bs;
686f93c3addSMax Reitz     bs_opaque = mirror_top_bs->opaque;
687f93c3addSMax Reitz     src = mirror_top_bs->backing->bs;
688f93c3addSMax Reitz     target_bs = blk_bs(s->target);
689f93c3addSMax Reitz 
690ef53dc09SAlberto Garcia     if (bdrv_chain_contains(src, target_bs)) {
691ef53dc09SAlberto Garcia         bdrv_unfreeze_backing_chain(mirror_top_bs, target_bs);
692ef53dc09SAlberto Garcia     }
693ef53dc09SAlberto Garcia 
6945deb6cbdSVladimir Sementsov-Ogievskiy     bdrv_release_dirty_bitmap(s->dirty_bitmap);
6952119882cSPaolo Bonzini 
6967b508f6bSJohn Snow     /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
6977b508f6bSJohn Snow      * before we can call bdrv_drained_end */
6983f09bfbcSKevin Wolf     bdrv_ref(src);
6994ef85a9cSKevin Wolf     bdrv_ref(mirror_top_bs);
7007d9fcb39SKevin Wolf     bdrv_ref(target_bs);
7017d9fcb39SKevin Wolf 
7029275fc72SKevin Wolf     bdrv_graph_rdunlock_main_loop();
7039275fc72SKevin Wolf 
704bb0c9409SVladimir Sementsov-Ogievskiy     /*
705bb0c9409SVladimir Sementsov-Ogievskiy      * Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
7067d9fcb39SKevin Wolf      * inserting target_bs at s->to_replace, where we might not be able to get
70763c8ef28SKevin Wolf      * these permissions.
708bb0c9409SVladimir Sementsov-Ogievskiy      */
7097d9fcb39SKevin Wolf     blk_unref(s->target);
7107d9fcb39SKevin Wolf     s->target = NULL;
7114ef85a9cSKevin Wolf 
7124ef85a9cSKevin Wolf     /* We don't access the source any more. Dropping any WRITE/RESIZE is
713d2da5e28SKevin Wolf      * required before it could become a backing file of target_bs. Not having
714d2da5e28SKevin Wolf      * these permissions any more means that we can't allow any new requests on
715d2da5e28SKevin Wolf      * mirror_top_bs from now on, so keep it drained. */
716d2da5e28SKevin Wolf     bdrv_drained_begin(mirror_top_bs);
717ccd6a379SKevin Wolf     bdrv_drained_begin(target_bs);
718f94dc3b4SMax Reitz     bs_opaque->stop = true;
7193804e3cfSKevin Wolf 
7203804e3cfSKevin Wolf     bdrv_graph_rdlock_main_loop();
721f94dc3b4SMax Reitz     bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
7224ef85a9cSKevin Wolf                              &error_abort);
7233804e3cfSKevin Wolf 
724737efc1eSJohn Snow     if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
7254ef85a9cSKevin Wolf         BlockDriverState *backing = s->is_none_mode ? src : s->base;
7263f072a7fSMax Reitz         BlockDriverState *unfiltered_target = bdrv_skip_filters(target_bs);
7273f072a7fSMax Reitz 
7283f072a7fSMax Reitz         if (bdrv_cow_bs(unfiltered_target) != backing) {
7293f072a7fSMax Reitz             bdrv_set_backing_hd(unfiltered_target, backing, &local_err);
73012fa4af6SKevin Wolf             if (local_err) {
73112fa4af6SKevin Wolf                 error_report_err(local_err);
73266c8672dSVladimir Sementsov-Ogievskiy                 local_err = NULL;
7337b508f6bSJohn Snow                 ret = -EPERM;
73412fa4af6SKevin Wolf             }
7354ef85a9cSKevin Wolf         }
736c41f5b96SMax Reitz     } else if (!abort && s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
737c41f5b96SMax Reitz         assert(!bdrv_backing_chain_next(target_bs));
738c41f5b96SMax Reitz         ret = bdrv_open_backing_file(bdrv_skip_filters(target_bs), NULL,
739c41f5b96SMax Reitz                                      "backing", &local_err);
740c41f5b96SMax Reitz         if (ret < 0) {
741c41f5b96SMax Reitz             error_report_err(local_err);
742c41f5b96SMax Reitz             local_err = NULL;
743c41f5b96SMax Reitz         }
7444ef85a9cSKevin Wolf     }
745ad74751fSKevin Wolf     bdrv_graph_rdunlock_main_loop();
7465a7e7a0bSStefan Hajnoczi 
747737efc1eSJohn Snow     if (s->should_complete && !abort) {
748737efc1eSJohn Snow         BlockDriverState *to_replace = s->to_replace ?: src;
7491ba79388SAlberto Garcia         bool ro = bdrv_is_read_only(to_replace);
75040365552SKevin Wolf 
7511ba79388SAlberto Garcia         if (ro != bdrv_is_read_only(target_bs)) {
7521ba79388SAlberto Garcia             bdrv_reopen_set_read_only(target_bs, ro, NULL);
7535a7e7a0bSStefan Hajnoczi         }
754b8804815SKevin Wolf 
755b8804815SKevin Wolf         /* The mirror job has no requests in flight any more, but we need to
756b8804815SKevin Wolf          * drain potential other users of the BDS before changing the graph. */
7575e771752SSergio Lopez         assert(s->in_drain);
758ccd6a379SKevin Wolf         bdrv_drained_begin(to_replace);
7596e9cc051SMax Reitz         /*
7606e9cc051SMax Reitz          * Cannot use check_to_replace_node() here, because that would
7616e9cc051SMax Reitz          * check for an op blocker on @to_replace, and we have our own
7626e9cc051SMax Reitz          * there.
7636e9cc051SMax Reitz          */
7646bc30f19SStefan Hajnoczi         bdrv_graph_wrlock();
7656e9cc051SMax Reitz         if (bdrv_recurse_can_replace(src, to_replace)) {
7665fe31c25SKevin Wolf             bdrv_replace_node(to_replace, target_bs, &local_err);
7676e9cc051SMax Reitz         } else {
7686e9cc051SMax Reitz             error_setg(&local_err, "Can no longer replace '%s' by '%s', "
7696e9cc051SMax Reitz                        "because it can no longer be guaranteed that doing so "
7706e9cc051SMax Reitz                        "would not lead to an abrupt change of visible data",
7716e9cc051SMax Reitz                        to_replace->node_name, target_bs->node_name);
7726e9cc051SMax Reitz         }
7736bc30f19SStefan Hajnoczi         bdrv_graph_wrunlock();
774ccd6a379SKevin Wolf         bdrv_drained_end(to_replace);
7755fe31c25SKevin Wolf         if (local_err) {
7765fe31c25SKevin Wolf             error_report_err(local_err);
7777b508f6bSJohn Snow             ret = -EPERM;
7785fe31c25SKevin Wolf         }
7795a7e7a0bSStefan Hajnoczi     }
7805a7e7a0bSStefan Hajnoczi     if (s->to_replace) {
7815a7e7a0bSStefan Hajnoczi         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
7825a7e7a0bSStefan Hajnoczi         error_free(s->replace_blocker);
7835a7e7a0bSStefan Hajnoczi         bdrv_unref(s->to_replace);
7845a7e7a0bSStefan Hajnoczi     }
7855a7e7a0bSStefan Hajnoczi     g_free(s->replaces);
7864ef85a9cSKevin Wolf 
787f94dc3b4SMax Reitz     /*
788f94dc3b4SMax Reitz      * Remove the mirror filter driver from the graph. Before this, get rid of
7894ef85a9cSKevin Wolf      * the blockers on the intermediate nodes so that the resulting state is
790f94dc3b4SMax Reitz      * valid.
791f94dc3b4SMax Reitz      */
7921908a559SKevin Wolf     block_job_remove_all_bdrv(bjob);
7936bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
7943f072a7fSMax Reitz     bdrv_replace_node(mirror_top_bs, mirror_top_bs->backing->bs, &error_abort);
7956bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
796ccd6a379SKevin Wolf 
797ccd6a379SKevin Wolf     bdrv_drained_end(target_bs);
798ccd6a379SKevin Wolf     bdrv_unref(target_bs);
7994ef85a9cSKevin Wolf 
800429076e8SMax Reitz     bs_opaque->job = NULL;
8014ef85a9cSKevin Wolf 
802176c3699SFam Zheng     bdrv_drained_end(src);
803d2da5e28SKevin Wolf     bdrv_drained_end(mirror_top_bs);
8045e771752SSergio Lopez     s->in_drain = false;
8054ef85a9cSKevin Wolf     bdrv_unref(mirror_top_bs);
8063f09bfbcSKevin Wolf     bdrv_unref(src);
8077b508f6bSJohn Snow 
808737efc1eSJohn Snow     return ret;
809737efc1eSJohn Snow }
810737efc1eSJohn Snow 
mirror_prepare(Job * job)811737efc1eSJohn Snow static int mirror_prepare(Job *job)
812737efc1eSJohn Snow {
813737efc1eSJohn Snow     return mirror_exit_common(job);
814737efc1eSJohn Snow }
815737efc1eSJohn Snow 
mirror_abort(Job * job)816737efc1eSJohn Snow static void mirror_abort(Job *job)
817737efc1eSJohn Snow {
818737efc1eSJohn Snow     int ret = mirror_exit_common(job);
819737efc1eSJohn Snow     assert(ret == 0);
8205a7e7a0bSStefan Hajnoczi }
8215a7e7a0bSStefan Hajnoczi 
mirror_throttle(MirrorBlockJob * s)822537c3d4fSStefan Hajnoczi static void coroutine_fn mirror_throttle(MirrorBlockJob *s)
82349efb1f5SDenis V. Lunev {
82449efb1f5SDenis V. Lunev     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
82549efb1f5SDenis V. Lunev 
82618bb6928SKevin Wolf     if (now - s->last_pause_ns > BLOCK_JOB_SLICE_TIME) {
82749efb1f5SDenis V. Lunev         s->last_pause_ns = now;
8285d43e86eSKevin Wolf         job_sleep_ns(&s->common.job, 0);
82949efb1f5SDenis V. Lunev     } else {
830da01ff7fSKevin Wolf         job_pause_point(&s->common.job);
83149efb1f5SDenis V. Lunev     }
83249efb1f5SDenis V. Lunev }
83349efb1f5SDenis V. Lunev 
mirror_dirty_init(MirrorBlockJob * s)834004915a9SKevin Wolf static int coroutine_fn GRAPH_UNLOCKED mirror_dirty_init(MirrorBlockJob *s)
835c0b363adSDenis V. Lunev {
83623ca459aSEric Blake     int64_t offset;
837004915a9SKevin Wolf     BlockDriverState *bs;
838c0b363adSDenis V. Lunev     BlockDriverState *target_bs = blk_bs(s->target);
83923ca459aSEric Blake     int ret;
84051b0a488SEric Blake     int64_t count;
841c0b363adSDenis V. Lunev 
842004915a9SKevin Wolf     bdrv_graph_co_rdlock();
843004915a9SKevin Wolf     bs = s->mirror_top_bs->backing->bs;
844004915a9SKevin Wolf     bdrv_graph_co_rdunlock();
845004915a9SKevin Wolf 
846cdf3bc93SMax Reitz     if (s->zero_target) {
847c7c2769cSDenis V. Lunev         if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
848e0d7f73eSEric Blake             bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
849b7d5062cSDenis V. Lunev             return 0;
850b7d5062cSDenis V. Lunev         }
851b7d5062cSDenis V. Lunev 
85290ab48ebSAnton Nefedov         s->initial_zeroing_ongoing = true;
85323ca459aSEric Blake         for (offset = 0; offset < s->bdev_length; ) {
85423ca459aSEric Blake             int bytes = MIN(s->bdev_length - offset,
85523ca459aSEric Blake                             QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
856c7c2769cSDenis V. Lunev 
857c7c2769cSDenis V. Lunev             mirror_throttle(s);
858c7c2769cSDenis V. Lunev 
859daa7f2f9SKevin Wolf             if (job_is_cancelled(&s->common.job)) {
86090ab48ebSAnton Nefedov                 s->initial_zeroing_ongoing = false;
861c7c2769cSDenis V. Lunev                 return 0;
862c7c2769cSDenis V. Lunev             }
863c7c2769cSDenis V. Lunev 
864c7c2769cSDenis V. Lunev             if (s->in_flight >= MAX_IN_FLIGHT) {
86567adf4b3SEric Blake                 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
86667adf4b3SEric Blake                                    s->in_flight);
8679178f4feSKevin Wolf                 mirror_wait_for_free_in_flight_slot(s);
868c7c2769cSDenis V. Lunev                 continue;
869c7c2769cSDenis V. Lunev             }
870c7c2769cSDenis V. Lunev 
8714295c5fcSMax Reitz             mirror_perform(s, offset, bytes, MIRROR_METHOD_ZERO);
87223ca459aSEric Blake             offset += bytes;
873c7c2769cSDenis V. Lunev         }
874c7c2769cSDenis V. Lunev 
875bae8196dSPaolo Bonzini         mirror_wait_for_all_io(s);
87690ab48ebSAnton Nefedov         s->initial_zeroing_ongoing = false;
877c7c2769cSDenis V. Lunev     }
878c7c2769cSDenis V. Lunev 
879c0b363adSDenis V. Lunev     /* First part, loop on the sectors and initialize the dirty bitmap.  */
88023ca459aSEric Blake     for (offset = 0; offset < s->bdev_length; ) {
881c0b363adSDenis V. Lunev         /* Just to make sure we are not exceeding int limit. */
88223ca459aSEric Blake         int bytes = MIN(s->bdev_length - offset,
88323ca459aSEric Blake                         QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
884c0b363adSDenis V. Lunev 
885c0b363adSDenis V. Lunev         mirror_throttle(s);
886c0b363adSDenis V. Lunev 
887daa7f2f9SKevin Wolf         if (job_is_cancelled(&s->common.job)) {
888c0b363adSDenis V. Lunev             return 0;
889c0b363adSDenis V. Lunev         }
890c0b363adSDenis V. Lunev 
8917ff9579eSKevin Wolf         WITH_GRAPH_RDLOCK_GUARD() {
892cc323997SPaolo Bonzini             ret = bdrv_co_is_allocated_above(bs, s->base_overlay, true, offset,
8937ff9579eSKevin Wolf                                              bytes, &count);
8947ff9579eSKevin Wolf         }
895c0b363adSDenis V. Lunev         if (ret < 0) {
896c0b363adSDenis V. Lunev             return ret;
897c0b363adSDenis V. Lunev         }
898c0b363adSDenis V. Lunev 
89923ca459aSEric Blake         assert(count);
900a92b1b06SEric Blake         if (ret > 0) {
90123ca459aSEric Blake             bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
902c0b363adSDenis V. Lunev         }
90323ca459aSEric Blake         offset += count;
904c0b363adSDenis V. Lunev     }
905c0b363adSDenis V. Lunev     return 0;
906c0b363adSDenis V. Lunev }
907c0b363adSDenis V. Lunev 
908bdffb31dSPaolo Bonzini /* Called when going out of the streaming phase to flush the bulk of the
909bdffb31dSPaolo Bonzini  * data to the medium, or just before completing.
910bdffb31dSPaolo Bonzini  */
mirror_flush(MirrorBlockJob * s)91126bef102SPaolo Bonzini static int coroutine_fn mirror_flush(MirrorBlockJob *s)
912bdffb31dSPaolo Bonzini {
91326bef102SPaolo Bonzini     int ret = blk_co_flush(s->target);
914bdffb31dSPaolo Bonzini     if (ret < 0) {
915bdffb31dSPaolo Bonzini         if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
916bdffb31dSPaolo Bonzini             s->ret = ret;
917bdffb31dSPaolo Bonzini         }
918bdffb31dSPaolo Bonzini     }
919bdffb31dSPaolo Bonzini     return ret;
920bdffb31dSPaolo Bonzini }
921bdffb31dSPaolo Bonzini 
mirror_run(Job * job,Error ** errp)922f67432a2SJohn Snow static int coroutine_fn mirror_run(Job *job, Error **errp)
923893f7ebaSPaolo Bonzini {
924f67432a2SJohn Snow     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
925004915a9SKevin Wolf     BlockDriverState *bs;
92632125b14SKevin Wolf     MirrorBDSOpaque *mirror_top_opaque = s->mirror_top_bs->opaque;
927e253f4b8SKevin Wolf     BlockDriverState *target_bs = blk_bs(s->target);
9289a0cec66SPaolo Bonzini     bool need_drain = true;
929d59cb66dSEmanuele Giuseppe Esposito     BlockDeviceIoStatus iostatus;
930c0b363adSDenis V. Lunev     int64_t length;
931e83dd680SKevin Wolf     int64_t target_length;
932b812f671SPaolo Bonzini     BlockDriverInfo bdi;
9331d33936eSJeff Cody     char backing_filename[2]; /* we only need 2 characters because we are only
9341d33936eSJeff Cody                                  checking for a NULL string */
935893f7ebaSPaolo Bonzini     int ret = 0;
936893f7ebaSPaolo Bonzini 
937004915a9SKevin Wolf     bdrv_graph_co_rdlock();
938004915a9SKevin Wolf     bs = bdrv_filter_bs(s->mirror_top_bs);
939004915a9SKevin Wolf     bdrv_graph_co_rdunlock();
940004915a9SKevin Wolf 
941daa7f2f9SKevin Wolf     if (job_is_cancelled(&s->common.job)) {
942893f7ebaSPaolo Bonzini         goto immediate_exit;
943893f7ebaSPaolo Bonzini     }
944893f7ebaSPaolo Bonzini 
9458ab8140aSKevin Wolf     bdrv_graph_co_rdlock();
946c86422c5SEmanuele Giuseppe Esposito     s->bdev_length = bdrv_co_getlength(bs);
9478ab8140aSKevin Wolf     bdrv_graph_co_rdunlock();
9488ab8140aSKevin Wolf 
949b21c7652SMax Reitz     if (s->bdev_length < 0) {
950b21c7652SMax Reitz         ret = s->bdev_length;
951373df5b1SFam Zheng         goto immediate_exit;
952becc347eSKevin Wolf     }
953becc347eSKevin Wolf 
954c86422c5SEmanuele Giuseppe Esposito     target_length = blk_co_getlength(s->target);
955e83dd680SKevin Wolf     if (target_length < 0) {
956e83dd680SKevin Wolf         ret = target_length;
957becc347eSKevin Wolf         goto immediate_exit;
958becc347eSKevin Wolf     }
959becc347eSKevin Wolf 
960e83dd680SKevin Wolf     /* Active commit must resize the base image if its size differs from the
961e83dd680SKevin Wolf      * active layer. */
962e83dd680SKevin Wolf     if (s->base == blk_bs(s->target)) {
963e83dd680SKevin Wolf         if (s->bdev_length > target_length) {
96488276216SAlberto Faria             ret = blk_co_truncate(s->target, s->bdev_length, false,
9658c6242b6SKevin Wolf                                   PREALLOC_MODE_OFF, 0, NULL);
966becc347eSKevin Wolf             if (ret < 0) {
967becc347eSKevin Wolf                 goto immediate_exit;
968becc347eSKevin Wolf             }
969becc347eSKevin Wolf         }
970e83dd680SKevin Wolf     } else if (s->bdev_length != target_length) {
971e83dd680SKevin Wolf         error_setg(errp, "Source and target image have different sizes");
972e83dd680SKevin Wolf         ret = -EINVAL;
973e83dd680SKevin Wolf         goto immediate_exit;
974becc347eSKevin Wolf     }
975becc347eSKevin Wolf 
976becc347eSKevin Wolf     if (s->bdev_length == 0) {
9772e1795b5SKevin Wolf         /* Transition to the READY state and wait for complete. */
9782e1795b5SKevin Wolf         job_transition_to_ready(&s->common.job);
97976cb2f24SFiona Ebner         qatomic_set(&s->actively_synced, true);
98008b83bffSHanna Reitz         while (!job_cancel_requested(&s->common.job) && !s->should_complete) {
981198c49ccSKevin Wolf             job_yield(&s->common.job);
9829e48b025SFam Zheng         }
9839e48b025SFam Zheng         goto immediate_exit;
984893f7ebaSPaolo Bonzini     }
985893f7ebaSPaolo Bonzini 
986b21c7652SMax Reitz     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
987402a4741SPaolo Bonzini     s->in_flight_bitmap = bitmap_new(length);
988402a4741SPaolo Bonzini 
989b812f671SPaolo Bonzini     /* If we have no backing file yet in the destination, we cannot let
990b812f671SPaolo Bonzini      * the destination do COW.  Instead, we copy sectors around the
991b812f671SPaolo Bonzini      * dirty data if needed.  We need a bitmap to do that.
992b812f671SPaolo Bonzini      */
993e253f4b8SKevin Wolf     bdrv_get_backing_filename(target_bs, backing_filename,
994b812f671SPaolo Bonzini                               sizeof(backing_filename));
995a00e70c0SEmanuele Giuseppe Esposito     bdrv_graph_co_rdlock();
9963d47eb0aSEmanuele Giuseppe Esposito     if (!bdrv_co_get_info(target_bs, &bdi) && bdi.cluster_size) {
997b436982fSEric Blake         s->target_cluster_size = bdi.cluster_size;
998b436982fSEric Blake     } else {
999b436982fSEric Blake         s->target_cluster_size = BDRV_SECTOR_SIZE;
1000c3cc95bdSFam Zheng     }
10013f072a7fSMax Reitz     if (backing_filename[0] && !bdrv_backing_chain_next(target_bs) &&
1002b436982fSEric Blake         s->granularity < s->target_cluster_size) {
1003b436982fSEric Blake         s->buf_size = MAX(s->buf_size, s->target_cluster_size);
1004b812f671SPaolo Bonzini         s->cow_bitmap = bitmap_new(length);
1005b812f671SPaolo Bonzini     }
1006e253f4b8SKevin Wolf     s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
1007ad74751fSKevin Wolf     bdrv_graph_co_rdunlock();
1008b812f671SPaolo Bonzini 
10097504edf4SKevin Wolf     s->buf = qemu_try_blockalign(bs, s->buf_size);
10107504edf4SKevin Wolf     if (s->buf == NULL) {
10117504edf4SKevin Wolf         ret = -ENOMEM;
10127504edf4SKevin Wolf         goto immediate_exit;
10137504edf4SKevin Wolf     }
10147504edf4SKevin Wolf 
1015402a4741SPaolo Bonzini     mirror_free_init(s);
1016893f7ebaSPaolo Bonzini 
101749efb1f5SDenis V. Lunev     s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
101803544a6eSFam Zheng     if (!s->is_none_mode) {
1019c0b363adSDenis V. Lunev         ret = mirror_dirty_init(s);
1020daa7f2f9SKevin Wolf         if (ret < 0 || job_is_cancelled(&s->common.job)) {
10214c0cbd6fSFam Zheng             goto immediate_exit;
10224c0cbd6fSFam Zheng         }
1023893f7ebaSPaolo Bonzini     }
1024893f7ebaSPaolo Bonzini 
102532125b14SKevin Wolf     /*
102632125b14SKevin Wolf      * Only now the job is fully initialised and mirror_top_bs should start
102732125b14SKevin Wolf      * accessing it.
102832125b14SKevin Wolf      */
102932125b14SKevin Wolf     mirror_top_opaque->job = s;
103032125b14SKevin Wolf 
1031dc162c8eSFam Zheng     assert(!s->dbi);
1032715a74d8SEric Blake     s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
1033893f7ebaSPaolo Bonzini     for (;;) {
103449efb1f5SDenis V. Lunev         int64_t cnt, delta;
1035893f7ebaSPaolo Bonzini         bool should_complete;
1036893f7ebaSPaolo Bonzini 
1037bd48bde8SPaolo Bonzini         if (s->ret < 0) {
1038bd48bde8SPaolo Bonzini             ret = s->ret;
1039893f7ebaSPaolo Bonzini             goto immediate_exit;
1040893f7ebaSPaolo Bonzini         }
1041bd48bde8SPaolo Bonzini 
1042da01ff7fSKevin Wolf         job_pause_point(&s->common.job);
1043565ac01fSStefan Hajnoczi 
10444feeec7eSHanna Reitz         if (job_is_cancelled(&s->common.job)) {
10454feeec7eSHanna Reitz             ret = 0;
10464feeec7eSHanna Reitz             goto immediate_exit;
10474feeec7eSHanna Reitz         }
10484feeec7eSHanna Reitz 
104920dca810SJohn Snow         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
105005df8a6aSKevin Wolf         /* cnt is the number of dirty bytes remaining and s->bytes_in_flight is
105105df8a6aSKevin Wolf          * the number of bytes currently being processed; together those are
105205df8a6aSKevin Wolf          * the current remaining operation length */
1053d69a879bSHanna Reitz         job_progress_set_remaining(&s->common.job,
1054d69a879bSHanna Reitz                                    s->bytes_in_flight + cnt +
1055d69a879bSHanna Reitz                                    s->active_write_bytes_in_flight);
1056bd48bde8SPaolo Bonzini 
1057bd48bde8SPaolo Bonzini         /* Note that even when no rate limit is applied we need to yield
1058a7282330SFam Zheng          * periodically with no pending I/O so that bdrv_drain_all() returns.
105918bb6928SKevin Wolf          * We do so every BLKOCK_JOB_SLICE_TIME nanoseconds, or when there is
106018bb6928SKevin Wolf          * an error, or when the source is clean, whichever comes first. */
106149efb1f5SDenis V. Lunev         delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
1062d59cb66dSEmanuele Giuseppe Esposito         WITH_JOB_LOCK_GUARD() {
1063d59cb66dSEmanuele Giuseppe Esposito             iostatus = s->common.iostatus;
1064d59cb66dSEmanuele Giuseppe Esposito         }
106518bb6928SKevin Wolf         if (delta < BLOCK_JOB_SLICE_TIME &&
1066d59cb66dSEmanuele Giuseppe Esposito             iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
1067cf56a3c6SDenis V. Lunev             if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
1068402a4741SPaolo Bonzini                 (cnt == 0 && s->in_flight > 0)) {
10699a46dba7SEric Blake                 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
10709178f4feSKevin Wolf                 mirror_wait_for_free_in_flight_slot(s);
1071bd48bde8SPaolo Bonzini                 continue;
1072bd48bde8SPaolo Bonzini             } else if (cnt != 0) {
1073018e5987SKevin Wolf                 mirror_iteration(s);
1074893f7ebaSPaolo Bonzini             }
1075cc8c9d6cSPaolo Bonzini         }
1076893f7ebaSPaolo Bonzini 
1077893f7ebaSPaolo Bonzini         should_complete = false;
1078bd48bde8SPaolo Bonzini         if (s->in_flight == 0 && cnt == 0) {
1079893f7ebaSPaolo Bonzini             trace_mirror_before_flush(s);
108044716224SHanna Reitz             if (!job_is_ready(&s->common.job)) {
1081bdffb31dSPaolo Bonzini                 if (mirror_flush(s) < 0) {
1082bdffb31dSPaolo Bonzini                     /* Go check s->ret.  */
1083bdffb31dSPaolo Bonzini                     continue;
1084893f7ebaSPaolo Bonzini                 }
1085893f7ebaSPaolo Bonzini                 /* We're out of the streaming phase.  From now on, if the job
1086893f7ebaSPaolo Bonzini                  * is cancelled we will actually complete all pending I/O and
1087893f7ebaSPaolo Bonzini                  * report completion.  This way, block-job-cancel will leave
1088893f7ebaSPaolo Bonzini                  * the target in a consistent state.
1089893f7ebaSPaolo Bonzini                  */
10902e1795b5SKevin Wolf                 job_transition_to_ready(&s->common.job);
1091c45d0e1aSFiona Ebner             }
10922d400d15SFiona Ebner             if (qatomic_read(&s->copy_mode) != MIRROR_COPY_MODE_BACKGROUND) {
109376cb2f24SFiona Ebner                 qatomic_set(&s->actively_synced, true);
1094d06107adSMax Reitz             }
1095d63ffd87SPaolo Bonzini 
1096d63ffd87SPaolo Bonzini             should_complete = s->should_complete ||
109708b83bffSHanna Reitz                 job_cancel_requested(&s->common.job);
109820dca810SJohn Snow             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1099893f7ebaSPaolo Bonzini         }
1100893f7ebaSPaolo Bonzini 
1101893f7ebaSPaolo Bonzini         if (cnt == 0 && should_complete) {
1102893f7ebaSPaolo Bonzini             /* The dirty bitmap is not updated while operations are pending.
1103893f7ebaSPaolo Bonzini              * If we're about to exit, wait for pending operations before
1104893f7ebaSPaolo Bonzini              * calling bdrv_get_dirty_count(bs), or we may exit while the
1105893f7ebaSPaolo Bonzini              * source has dirty data to copy!
1106893f7ebaSPaolo Bonzini              *
1107893f7ebaSPaolo Bonzini              * Note that I/O can be submitted by the guest while
11089a0cec66SPaolo Bonzini              * mirror_populate runs, so pause it now.  Before deciding
11099a0cec66SPaolo Bonzini              * whether to switch to target check one last time if I/O has
11109a0cec66SPaolo Bonzini              * come in the meanwhile, and if not flush the data to disk.
1111893f7ebaSPaolo Bonzini              */
11129a46dba7SEric Blake             trace_mirror_before_drain(s, cnt);
11139a0cec66SPaolo Bonzini 
11145e771752SSergio Lopez             s->in_drain = true;
11159a0cec66SPaolo Bonzini             bdrv_drained_begin(bs);
1116d69a879bSHanna Reitz 
1117d69a879bSHanna Reitz             /* Must be zero because we are drained */
1118d69a879bSHanna Reitz             assert(s->in_active_write_counter == 0);
1119d69a879bSHanna Reitz 
112020dca810SJohn Snow             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1121bdffb31dSPaolo Bonzini             if (cnt > 0 || mirror_flush(s) < 0) {
11229a0cec66SPaolo Bonzini                 bdrv_drained_end(bs);
11235e771752SSergio Lopez                 s->in_drain = false;
11249a0cec66SPaolo Bonzini                 continue;
11259a0cec66SPaolo Bonzini             }
11269a0cec66SPaolo Bonzini 
11279a0cec66SPaolo Bonzini             /* The two disks are in sync.  Exit and report successful
11289a0cec66SPaolo Bonzini              * completion.
11299a0cec66SPaolo Bonzini              */
11309a0cec66SPaolo Bonzini             assert(QLIST_EMPTY(&bs->tracked_requests));
11319a0cec66SPaolo Bonzini             need_drain = false;
11329a0cec66SPaolo Bonzini             break;
1133893f7ebaSPaolo Bonzini         }
1134893f7ebaSPaolo Bonzini 
113544716224SHanna Reitz         if (job_is_ready(&s->common.job) && !should_complete) {
1136018e5987SKevin Wolf             if (s->in_flight == 0 && cnt == 0) {
113744716224SHanna Reitz                 trace_mirror_before_sleep(s, cnt, job_is_ready(&s->common.job),
1138018e5987SKevin Wolf                                           BLOCK_JOB_SLICE_TIME);
1139018e5987SKevin Wolf                 job_sleep_ns(&s->common.job, BLOCK_JOB_SLICE_TIME);
1140018e5987SKevin Wolf             }
1141018e5987SKevin Wolf         } else {
1142018e5987SKevin Wolf             block_job_ratelimit_sleep(&s->common);
1143018e5987SKevin Wolf         }
114449efb1f5SDenis V. Lunev         s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1145893f7ebaSPaolo Bonzini     }
1146893f7ebaSPaolo Bonzini 
1147893f7ebaSPaolo Bonzini immediate_exit:
1148bd48bde8SPaolo Bonzini     if (s->in_flight > 0) {
1149bd48bde8SPaolo Bonzini         /* We get here only if something went wrong.  Either the job failed,
1150bd48bde8SPaolo Bonzini          * or it was cancelled prematurely so that we do not guarantee that
1151bd48bde8SPaolo Bonzini          * the target is a copy of the source.
1152bd48bde8SPaolo Bonzini          */
115308b83bffSHanna Reitz         assert(ret < 0 || job_is_cancelled(&s->common.job));
11549a0cec66SPaolo Bonzini         assert(need_drain);
1155bae8196dSPaolo Bonzini         mirror_wait_for_all_io(s);
1156bd48bde8SPaolo Bonzini     }
1157bd48bde8SPaolo Bonzini 
1158bd48bde8SPaolo Bonzini     assert(s->in_flight == 0);
11597191bf31SMarkus Armbruster     qemu_vfree(s->buf);
1160b812f671SPaolo Bonzini     g_free(s->cow_bitmap);
1161402a4741SPaolo Bonzini     g_free(s->in_flight_bitmap);
1162dc162c8eSFam Zheng     bdrv_dirty_iter_free(s->dbi);
11635a7e7a0bSStefan Hajnoczi 
11649a0cec66SPaolo Bonzini     if (need_drain) {
11655e771752SSergio Lopez         s->in_drain = true;
1166e253f4b8SKevin Wolf         bdrv_drained_begin(bs);
11679a0cec66SPaolo Bonzini     }
1168f67432a2SJohn Snow 
1169f67432a2SJohn Snow     return ret;
1170893f7ebaSPaolo Bonzini }
1171893f7ebaSPaolo Bonzini 
mirror_complete(Job * job,Error ** errp)11723453d972SKevin Wolf static void mirror_complete(Job *job, Error **errp)
1173d63ffd87SPaolo Bonzini {
11743453d972SKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1175274fcceeSMax Reitz 
117644716224SHanna Reitz     if (!job_is_ready(job)) {
11779df229c3SAlberto Garcia         error_setg(errp, "The active block job '%s' cannot be completed",
11783453d972SKevin Wolf                    job->id);
1179d63ffd87SPaolo Bonzini         return;
1180d63ffd87SPaolo Bonzini     }
1181d63ffd87SPaolo Bonzini 
118215d67298SChanglong Xie     /* block all operations on to_replace bs */
118309158f00SBenoît Canet     if (s->replaces) {
1184e12f3784SWen Congyang         s->to_replace = bdrv_find_node(s->replaces);
118509158f00SBenoît Canet         if (!s->to_replace) {
1186e12f3784SWen Congyang             error_setg(errp, "Node name '%s' not found", s->replaces);
118709158f00SBenoît Canet             return;
118809158f00SBenoît Canet         }
118909158f00SBenoît Canet 
119064631f36SVladimir Sementsov-Ogievskiy         /* TODO Translate this into child freeze system. */
119109158f00SBenoît Canet         error_setg(&s->replace_blocker,
119209158f00SBenoît Canet                    "block device is in use by block-job-complete");
119309158f00SBenoît Canet         bdrv_op_block_all(s->to_replace, s->replace_blocker);
119409158f00SBenoît Canet         bdrv_ref(s->to_replace);
119509158f00SBenoît Canet     }
119609158f00SBenoît Canet 
1197d63ffd87SPaolo Bonzini     s->should_complete = true;
119800769414SMax Reitz 
119900769414SMax Reitz     /* If the job is paused, it will be re-entered when it is resumed */
1200279ac06eSEmanuele Giuseppe Esposito     WITH_JOB_LOCK_GUARD() {
120100769414SMax Reitz         if (!job->paused) {
1202279ac06eSEmanuele Giuseppe Esposito             job_enter_cond_locked(job, NULL);
1203279ac06eSEmanuele Giuseppe Esposito         }
1204d63ffd87SPaolo Bonzini     }
120500769414SMax Reitz }
1206d63ffd87SPaolo Bonzini 
mirror_pause(Job * job)1207537c3d4fSStefan Hajnoczi static void coroutine_fn mirror_pause(Job *job)
1208565ac01fSStefan Hajnoczi {
1209da01ff7fSKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1210565ac01fSStefan Hajnoczi 
1211bae8196dSPaolo Bonzini     mirror_wait_for_all_io(s);
1212565ac01fSStefan Hajnoczi }
1213565ac01fSStefan Hajnoczi 
mirror_drained_poll(BlockJob * job)121489bd0305SKevin Wolf static bool mirror_drained_poll(BlockJob *job)
121589bd0305SKevin Wolf {
121689bd0305SKevin Wolf     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
12175e771752SSergio Lopez 
12185e771752SSergio Lopez     /* If the job isn't paused nor cancelled, we can't be sure that it won't
12195e771752SSergio Lopez      * issue more requests. We make an exception if we've reached this point
12205e771752SSergio Lopez      * from one of our own drain sections, to avoid a deadlock waiting for
12215e771752SSergio Lopez      * ourselves.
12225e771752SSergio Lopez      */
1223279ac06eSEmanuele Giuseppe Esposito     WITH_JOB_LOCK_GUARD() {
1224279ac06eSEmanuele Giuseppe Esposito         if (!s->common.job.paused && !job_is_cancelled_locked(&job->job)
1225279ac06eSEmanuele Giuseppe Esposito             && !s->in_drain) {
12265e771752SSergio Lopez             return true;
12275e771752SSergio Lopez         }
1228279ac06eSEmanuele Giuseppe Esposito     }
12295e771752SSergio Lopez 
123089bd0305SKevin Wolf     return !!s->in_flight;
123189bd0305SKevin Wolf }
123289bd0305SKevin Wolf 
mirror_cancel(Job * job,bool force)123373895f38SHanna Reitz static bool mirror_cancel(Job *job, bool force)
1234521ff8b7SVladimir Sementsov-Ogievskiy {
1235521ff8b7SVladimir Sementsov-Ogievskiy     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1236521ff8b7SVladimir Sementsov-Ogievskiy     BlockDriverState *target = blk_bs(s->target);
1237521ff8b7SVladimir Sementsov-Ogievskiy 
123873895f38SHanna Reitz     /*
123973895f38SHanna Reitz      * Before the job is READY, we treat any cancellation like a
124073895f38SHanna Reitz      * force-cancellation.
124173895f38SHanna Reitz      */
124273895f38SHanna Reitz     force = force || !job_is_ready(job);
124373895f38SHanna Reitz 
124473895f38SHanna Reitz     if (force) {
1245521ff8b7SVladimir Sementsov-Ogievskiy         bdrv_cancel_in_flight(target);
1246521ff8b7SVladimir Sementsov-Ogievskiy     }
124773895f38SHanna Reitz     return force;
124873895f38SHanna Reitz }
124973895f38SHanna Reitz 
commit_active_cancel(Job * job,bool force)125073895f38SHanna Reitz static bool commit_active_cancel(Job *job, bool force)
125173895f38SHanna Reitz {
125273895f38SHanna Reitz     /* Same as above in mirror_cancel() */
125373895f38SHanna Reitz     return force || !job_is_ready(job);
12549c785cd7SVladimir Sementsov-Ogievskiy }
1255521ff8b7SVladimir Sementsov-Ogievskiy 
mirror_change(BlockJob * job,BlockJobChangeOptions * opts,Error ** errp)12562d400d15SFiona Ebner static void mirror_change(BlockJob *job, BlockJobChangeOptions *opts,
12572d400d15SFiona Ebner                           Error **errp)
12582d400d15SFiona Ebner {
12592d400d15SFiona Ebner     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
12602d400d15SFiona Ebner     BlockJobChangeOptionsMirror *change_opts = &opts->u.mirror;
12612d400d15SFiona Ebner     MirrorCopyMode current;
12622d400d15SFiona Ebner 
12632d400d15SFiona Ebner     /*
12642d400d15SFiona Ebner      * The implementation relies on the fact that copy_mode is only written
12652d400d15SFiona Ebner      * under the BQL. Otherwise, further synchronization would be required.
12662d400d15SFiona Ebner      */
12672d400d15SFiona Ebner 
12682d400d15SFiona Ebner     GLOBAL_STATE_CODE();
12692d400d15SFiona Ebner 
12702d400d15SFiona Ebner     if (qatomic_read(&s->copy_mode) == change_opts->copy_mode) {
12712d400d15SFiona Ebner         return;
12722d400d15SFiona Ebner     }
12732d400d15SFiona Ebner 
12742d400d15SFiona Ebner     if (change_opts->copy_mode != MIRROR_COPY_MODE_WRITE_BLOCKING) {
12752d400d15SFiona Ebner         error_setg(errp, "Change to copy mode '%s' is not implemented",
12762d400d15SFiona Ebner                    MirrorCopyMode_str(change_opts->copy_mode));
12772d400d15SFiona Ebner         return;
12782d400d15SFiona Ebner     }
12792d400d15SFiona Ebner 
12802d400d15SFiona Ebner     current = qatomic_cmpxchg(&s->copy_mode, MIRROR_COPY_MODE_BACKGROUND,
12812d400d15SFiona Ebner                               change_opts->copy_mode);
12822d400d15SFiona Ebner     if (current != MIRROR_COPY_MODE_BACKGROUND) {
12832d400d15SFiona Ebner         error_setg(errp, "Expected current copy mode '%s', got '%s'",
12842d400d15SFiona Ebner                    MirrorCopyMode_str(MIRROR_COPY_MODE_BACKGROUND),
12852d400d15SFiona Ebner                    MirrorCopyMode_str(current));
12862d400d15SFiona Ebner     }
12872d400d15SFiona Ebner }
12882d400d15SFiona Ebner 
mirror_query(BlockJob * job,BlockJobInfo * info)128976cb2f24SFiona Ebner static void mirror_query(BlockJob *job, BlockJobInfo *info)
129076cb2f24SFiona Ebner {
129176cb2f24SFiona Ebner     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
129276cb2f24SFiona Ebner 
129376cb2f24SFiona Ebner     info->u.mirror = (BlockJobInfoMirror) {
129476cb2f24SFiona Ebner         .actively_synced = qatomic_read(&s->actively_synced),
129576cb2f24SFiona Ebner     };
129676cb2f24SFiona Ebner }
129776cb2f24SFiona Ebner 
12983fc4b10aSFam Zheng static const BlockJobDriver mirror_job_driver = {
129933e9e9bdSKevin Wolf     .job_driver = {
1300893f7ebaSPaolo Bonzini         .instance_size          = sizeof(MirrorBlockJob),
13018e4c8700SKevin Wolf         .job_type               = JOB_TYPE_MIRROR,
130280fa2c75SKevin Wolf         .free                   = block_job_free,
1303b15de828SKevin Wolf         .user_resume            = block_job_user_resume,
1304f67432a2SJohn Snow         .run                    = mirror_run,
1305737efc1eSJohn Snow         .prepare                = mirror_prepare,
1306737efc1eSJohn Snow         .abort                  = mirror_abort,
1307565ac01fSStefan Hajnoczi         .pause                  = mirror_pause,
1308da01ff7fSKevin Wolf         .complete               = mirror_complete,
1309521ff8b7SVladimir Sementsov-Ogievskiy         .cancel                 = mirror_cancel,
13103453d972SKevin Wolf     },
131189bd0305SKevin Wolf     .drained_poll           = mirror_drained_poll,
13122d400d15SFiona Ebner     .change                 = mirror_change,
131376cb2f24SFiona Ebner     .query                  = mirror_query,
1314893f7ebaSPaolo Bonzini };
1315893f7ebaSPaolo Bonzini 
131603544a6eSFam Zheng static const BlockJobDriver commit_active_job_driver = {
131733e9e9bdSKevin Wolf     .job_driver = {
131803544a6eSFam Zheng         .instance_size          = sizeof(MirrorBlockJob),
13198e4c8700SKevin Wolf         .job_type               = JOB_TYPE_COMMIT,
132080fa2c75SKevin Wolf         .free                   = block_job_free,
1321b15de828SKevin Wolf         .user_resume            = block_job_user_resume,
1322f67432a2SJohn Snow         .run                    = mirror_run,
1323737efc1eSJohn Snow         .prepare                = mirror_prepare,
1324737efc1eSJohn Snow         .abort                  = mirror_abort,
1325565ac01fSStefan Hajnoczi         .pause                  = mirror_pause,
1326da01ff7fSKevin Wolf         .complete               = mirror_complete,
132773895f38SHanna Reitz         .cancel                 = commit_active_cancel,
13283453d972SKevin Wolf     },
132989bd0305SKevin Wolf     .drained_poll           = mirror_drained_poll,
133003544a6eSFam Zheng };
133103544a6eSFam Zheng 
1332537c3d4fSStefan Hajnoczi static void coroutine_fn
do_sync_target_write(MirrorBlockJob * job,MirrorMethod method,uint64_t offset,uint64_t bytes,QEMUIOVector * qiov,int flags)1333537c3d4fSStefan Hajnoczi do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
1334d06107adSMax Reitz                      uint64_t offset, uint64_t bytes,
1335d06107adSMax Reitz                      QEMUIOVector *qiov, int flags)
1336d06107adSMax Reitz {
1337d06107adSMax Reitz     int ret;
1338dbdf699cSVladimir Sementsov-Ogievskiy     size_t qiov_offset = 0;
1339dbdf699cSVladimir Sementsov-Ogievskiy     int64_t bitmap_offset, bitmap_end;
1340d06107adSMax Reitz 
1341dbdf699cSVladimir Sementsov-Ogievskiy     if (!QEMU_IS_ALIGNED(offset, job->granularity) &&
1342dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_dirty_bitmap_get(job->dirty_bitmap, offset))
1343dbdf699cSVladimir Sementsov-Ogievskiy     {
1344dbdf699cSVladimir Sementsov-Ogievskiy             /*
1345dbdf699cSVladimir Sementsov-Ogievskiy              * Dirty unaligned padding: ignore it.
1346dbdf699cSVladimir Sementsov-Ogievskiy              *
1347dbdf699cSVladimir Sementsov-Ogievskiy              * Reasoning:
1348dbdf699cSVladimir Sementsov-Ogievskiy              * 1. If we copy it, we can't reset corresponding bit in
1349dbdf699cSVladimir Sementsov-Ogievskiy              *    dirty_bitmap as there may be some "dirty" bytes still not
1350dbdf699cSVladimir Sementsov-Ogievskiy              *    copied.
1351dbdf699cSVladimir Sementsov-Ogievskiy              * 2. It's already dirty, so skipping it we don't diverge mirror
1352dbdf699cSVladimir Sementsov-Ogievskiy              *    progress.
1353dbdf699cSVladimir Sementsov-Ogievskiy              *
1354dbdf699cSVladimir Sementsov-Ogievskiy              * Note, that because of this, guest write may have no contribution
1355dbdf699cSVladimir Sementsov-Ogievskiy              * into mirror converge, but that's not bad, as we have background
1356dbdf699cSVladimir Sementsov-Ogievskiy              * process of mirroring. If under some bad circumstances (high guest
1357dbdf699cSVladimir Sementsov-Ogievskiy              * IO load) background process starve, we will not converge anyway,
1358dbdf699cSVladimir Sementsov-Ogievskiy              * even if each write will contribute, as guest is not guaranteed to
1359dbdf699cSVladimir Sementsov-Ogievskiy              * rewrite the whole disk.
1360dbdf699cSVladimir Sementsov-Ogievskiy              */
1361dbdf699cSVladimir Sementsov-Ogievskiy             qiov_offset = QEMU_ALIGN_UP(offset, job->granularity) - offset;
1362dbdf699cSVladimir Sementsov-Ogievskiy             if (bytes <= qiov_offset) {
1363dbdf699cSVladimir Sementsov-Ogievskiy                 /* nothing to do after shrink */
1364dbdf699cSVladimir Sementsov-Ogievskiy                 return;
1365dbdf699cSVladimir Sementsov-Ogievskiy             }
1366dbdf699cSVladimir Sementsov-Ogievskiy             offset += qiov_offset;
1367dbdf699cSVladimir Sementsov-Ogievskiy             bytes -= qiov_offset;
1368dbdf699cSVladimir Sementsov-Ogievskiy     }
1369dbdf699cSVladimir Sementsov-Ogievskiy 
1370dbdf699cSVladimir Sementsov-Ogievskiy     if (!QEMU_IS_ALIGNED(offset + bytes, job->granularity) &&
1371dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_dirty_bitmap_get(job->dirty_bitmap, offset + bytes - 1))
1372dbdf699cSVladimir Sementsov-Ogievskiy     {
1373dbdf699cSVladimir Sementsov-Ogievskiy         uint64_t tail = (offset + bytes) % job->granularity;
1374dbdf699cSVladimir Sementsov-Ogievskiy 
1375dbdf699cSVladimir Sementsov-Ogievskiy         if (bytes <= tail) {
1376dbdf699cSVladimir Sementsov-Ogievskiy             /* nothing to do after shrink */
1377dbdf699cSVladimir Sementsov-Ogievskiy             return;
1378dbdf699cSVladimir Sementsov-Ogievskiy         }
1379dbdf699cSVladimir Sementsov-Ogievskiy         bytes -= tail;
1380dbdf699cSVladimir Sementsov-Ogievskiy     }
1381dbdf699cSVladimir Sementsov-Ogievskiy 
1382dbdf699cSVladimir Sementsov-Ogievskiy     /*
1383dbdf699cSVladimir Sementsov-Ogievskiy      * Tails are either clean or shrunk, so for bitmap resetting
1384dbdf699cSVladimir Sementsov-Ogievskiy      * we safely align the range down.
1385dbdf699cSVladimir Sementsov-Ogievskiy      */
1386dbdf699cSVladimir Sementsov-Ogievskiy     bitmap_offset = QEMU_ALIGN_UP(offset, job->granularity);
1387dbdf699cSVladimir Sementsov-Ogievskiy     bitmap_end = QEMU_ALIGN_DOWN(offset + bytes, job->granularity);
1388dbdf699cSVladimir Sementsov-Ogievskiy     if (bitmap_offset < bitmap_end) {
1389dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_reset_dirty_bitmap(job->dirty_bitmap, bitmap_offset,
1390dbdf699cSVladimir Sementsov-Ogievskiy                                 bitmap_end - bitmap_offset);
1391dbdf699cSVladimir Sementsov-Ogievskiy     }
1392d06107adSMax Reitz 
13935c511ac3SVladimir Sementsov-Ogievskiy     job_progress_increase_remaining(&job->common.job, bytes);
1394d69a879bSHanna Reitz     job->active_write_bytes_in_flight += bytes;
1395d06107adSMax Reitz 
1396d06107adSMax Reitz     switch (method) {
1397d06107adSMax Reitz     case MIRROR_METHOD_COPY:
1398dbdf699cSVladimir Sementsov-Ogievskiy         ret = blk_co_pwritev_part(job->target, offset, bytes,
1399dbdf699cSVladimir Sementsov-Ogievskiy                                   qiov, qiov_offset, flags);
1400d06107adSMax Reitz         break;
1401d06107adSMax Reitz 
1402d06107adSMax Reitz     case MIRROR_METHOD_ZERO:
1403d06107adSMax Reitz         assert(!qiov);
14045c511ac3SVladimir Sementsov-Ogievskiy         ret = blk_co_pwrite_zeroes(job->target, offset, bytes, flags);
1405d06107adSMax Reitz         break;
1406d06107adSMax Reitz 
1407d06107adSMax Reitz     case MIRROR_METHOD_DISCARD:
1408d06107adSMax Reitz         assert(!qiov);
14095c511ac3SVladimir Sementsov-Ogievskiy         ret = blk_co_pdiscard(job->target, offset, bytes);
1410d06107adSMax Reitz         break;
1411d06107adSMax Reitz 
1412d06107adSMax Reitz     default:
1413d06107adSMax Reitz         abort();
1414d06107adSMax Reitz     }
1415d06107adSMax Reitz 
1416d69a879bSHanna Reitz     job->active_write_bytes_in_flight -= bytes;
1417d06107adSMax Reitz     if (ret >= 0) {
14185c511ac3SVladimir Sementsov-Ogievskiy         job_progress_update(&job->common.job, bytes);
1419d06107adSMax Reitz     } else {
1420d06107adSMax Reitz         BlockErrorAction action;
1421d06107adSMax Reitz 
1422dbdf699cSVladimir Sementsov-Ogievskiy         /*
1423dbdf699cSVladimir Sementsov-Ogievskiy          * We failed, so we should mark dirty the whole area, aligned up.
1424dbdf699cSVladimir Sementsov-Ogievskiy          * Note that we don't care about shrunk tails if any: they were dirty
1425dbdf699cSVladimir Sementsov-Ogievskiy          * at function start, and they must be still dirty, as we've locked
1426dbdf699cSVladimir Sementsov-Ogievskiy          * the region for in-flight op.
1427dbdf699cSVladimir Sementsov-Ogievskiy          */
1428dbdf699cSVladimir Sementsov-Ogievskiy         bitmap_offset = QEMU_ALIGN_DOWN(offset, job->granularity);
1429dbdf699cSVladimir Sementsov-Ogievskiy         bitmap_end = QEMU_ALIGN_UP(offset + bytes, job->granularity);
1430dbdf699cSVladimir Sementsov-Ogievskiy         bdrv_set_dirty_bitmap(job->dirty_bitmap, bitmap_offset,
1431dbdf699cSVladimir Sementsov-Ogievskiy                               bitmap_end - bitmap_offset);
143276cb2f24SFiona Ebner         qatomic_set(&job->actively_synced, false);
1433d06107adSMax Reitz 
1434d06107adSMax Reitz         action = mirror_error_action(job, false, -ret);
1435d06107adSMax Reitz         if (action == BLOCK_ERROR_ACTION_REPORT) {
1436d06107adSMax Reitz             if (!job->ret) {
1437d06107adSMax Reitz                 job->ret = ret;
1438d06107adSMax Reitz             }
1439d06107adSMax Reitz         }
1440d06107adSMax Reitz     }
1441d06107adSMax Reitz }
1442d06107adSMax Reitz 
active_write_prepare(MirrorBlockJob * s,uint64_t offset,uint64_t bytes)1443d06107adSMax Reitz static MirrorOp *coroutine_fn active_write_prepare(MirrorBlockJob *s,
1444d06107adSMax Reitz                                                    uint64_t offset,
1445d06107adSMax Reitz                                                    uint64_t bytes)
1446d06107adSMax Reitz {
1447d06107adSMax Reitz     MirrorOp *op;
1448d06107adSMax Reitz     uint64_t start_chunk = offset / s->granularity;
1449d06107adSMax Reitz     uint64_t end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1450d06107adSMax Reitz 
1451d06107adSMax Reitz     op = g_new(MirrorOp, 1);
1452d06107adSMax Reitz     *op = (MirrorOp){
1453d06107adSMax Reitz         .s                  = s,
1454d06107adSMax Reitz         .offset             = offset,
1455d06107adSMax Reitz         .bytes              = bytes,
1456d06107adSMax Reitz         .is_active_write    = true,
1457ce8cabbdSKevin Wolf         .is_in_flight       = true,
1458ead3f1bfSVladimir Sementsov-Ogievskiy         .co                 = qemu_coroutine_self(),
1459d06107adSMax Reitz     };
1460d06107adSMax Reitz     qemu_co_queue_init(&op->waiting_requests);
1461d06107adSMax Reitz     QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
1462d06107adSMax Reitz 
1463d06107adSMax Reitz     s->in_active_write_counter++;
1464d06107adSMax Reitz 
1465d69a879bSHanna Reitz     /*
1466d69a879bSHanna Reitz      * Wait for concurrent requests affecting the area.  If there are already
1467d69a879bSHanna Reitz      * running requests that are copying off now-to-be stale data in the area,
1468d69a879bSHanna Reitz      * we must wait for them to finish before we begin writing fresh data to the
1469d69a879bSHanna Reitz      * target so that the write operations appear in the correct order.
1470d69a879bSHanna Reitz      * Note that background requests (see mirror_iteration()) in contrast only
1471d69a879bSHanna Reitz      * wait for conflicting requests at the start of the dirty area, and then
1472d69a879bSHanna Reitz      * (based on the in_flight_bitmap) truncate the area to copy so it will not
1473d69a879bSHanna Reitz      * conflict with any requests beyond that.  For active writes, however, we
1474d69a879bSHanna Reitz      * cannot truncate that area.  The request from our parent must be blocked
1475d69a879bSHanna Reitz      * until the area is copied in full.  Therefore, we must wait for the whole
1476d69a879bSHanna Reitz      * area to become free of concurrent requests.
1477d69a879bSHanna Reitz      */
1478d06107adSMax Reitz     mirror_wait_on_conflicts(op, s, offset, bytes);
1479d06107adSMax Reitz 
1480d06107adSMax Reitz     bitmap_set(s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1481d06107adSMax Reitz 
1482d06107adSMax Reitz     return op;
1483d06107adSMax Reitz }
1484d06107adSMax Reitz 
active_write_settle(MirrorOp * op)14859c93652dSKevin Wolf static void coroutine_fn GRAPH_RDLOCK active_write_settle(MirrorOp *op)
1486d06107adSMax Reitz {
1487d06107adSMax Reitz     uint64_t start_chunk = op->offset / op->s->granularity;
1488d06107adSMax Reitz     uint64_t end_chunk = DIV_ROUND_UP(op->offset + op->bytes,
1489d06107adSMax Reitz                                       op->s->granularity);
1490d06107adSMax Reitz 
149176cb2f24SFiona Ebner     if (!--op->s->in_active_write_counter &&
149276cb2f24SFiona Ebner         qatomic_read(&op->s->actively_synced)) {
1493d06107adSMax Reitz         BdrvChild *source = op->s->mirror_top_bs->backing;
1494d06107adSMax Reitz 
1495d06107adSMax Reitz         if (QLIST_FIRST(&source->bs->parents) == source &&
1496d06107adSMax Reitz             QLIST_NEXT(source, next_parent) == NULL)
1497d06107adSMax Reitz         {
1498d06107adSMax Reitz             /* Assert that we are back in sync once all active write
1499d06107adSMax Reitz              * operations are settled.
1500d06107adSMax Reitz              * Note that we can only assert this if the mirror node
1501d06107adSMax Reitz              * is the source node's only parent. */
1502d06107adSMax Reitz             assert(!bdrv_get_dirty_count(op->s->dirty_bitmap));
1503d06107adSMax Reitz         }
1504d06107adSMax Reitz     }
1505d06107adSMax Reitz     bitmap_clear(op->s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1506d06107adSMax Reitz     QTAILQ_REMOVE(&op->s->ops_in_flight, op, next);
1507d06107adSMax Reitz     qemu_co_queue_restart_all(&op->waiting_requests);
1508d06107adSMax Reitz     g_free(op);
1509d06107adSMax Reitz }
1510d06107adSMax Reitz 
1511b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
bdrv_mirror_top_preadv(BlockDriverState * bs,int64_t offset,int64_t bytes,QEMUIOVector * qiov,BdrvRequestFlags flags)1512b9b10c35SKevin Wolf bdrv_mirror_top_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
1513b9b10c35SKevin Wolf                        QEMUIOVector *qiov, BdrvRequestFlags flags)
15144ef85a9cSKevin Wolf {
15154ef85a9cSKevin Wolf     return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
15164ef85a9cSKevin Wolf }
15174ef85a9cSKevin Wolf 
should_copy_to_target(MirrorBDSOpaque * s)15187b32ad22SFiona Ebner static bool should_copy_to_target(MirrorBDSOpaque *s)
15197b32ad22SFiona Ebner {
15207b32ad22SFiona Ebner     return s->job && s->job->ret >= 0 &&
15217b32ad22SFiona Ebner         !job_is_cancelled(&s->job->common.job) &&
15222d400d15SFiona Ebner         qatomic_read(&s->job->copy_mode) == MIRROR_COPY_MODE_WRITE_BLOCKING;
15237b32ad22SFiona Ebner }
15247b32ad22SFiona Ebner 
15259a5a1c62SEmanuele Giuseppe Esposito static int coroutine_fn GRAPH_RDLOCK
bdrv_mirror_top_do_write(BlockDriverState * bs,MirrorMethod method,bool copy_to_target,uint64_t offset,uint64_t bytes,QEMUIOVector * qiov,int flags)15269a5a1c62SEmanuele Giuseppe Esposito bdrv_mirror_top_do_write(BlockDriverState *bs, MirrorMethod method,
15277b32ad22SFiona Ebner                          bool copy_to_target, uint64_t offset, uint64_t bytes,
15287b32ad22SFiona Ebner                          QEMUIOVector *qiov, int flags)
1529d06107adSMax Reitz {
1530d06107adSMax Reitz     MirrorOp *op = NULL;
1531d06107adSMax Reitz     MirrorBDSOpaque *s = bs->opaque;
1532d06107adSMax Reitz     int ret = 0;
1533d06107adSMax Reitz 
1534d06107adSMax Reitz     if (copy_to_target) {
1535d06107adSMax Reitz         op = active_write_prepare(s->job, offset, bytes);
1536d06107adSMax Reitz     }
1537d06107adSMax Reitz 
1538d06107adSMax Reitz     switch (method) {
1539d06107adSMax Reitz     case MIRROR_METHOD_COPY:
1540d06107adSMax Reitz         ret = bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1541d06107adSMax Reitz         break;
1542d06107adSMax Reitz 
1543d06107adSMax Reitz     case MIRROR_METHOD_ZERO:
1544d06107adSMax Reitz         ret = bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
1545d06107adSMax Reitz         break;
1546d06107adSMax Reitz 
1547d06107adSMax Reitz     case MIRROR_METHOD_DISCARD:
15480b9fd3f4SFam Zheng         ret = bdrv_co_pdiscard(bs->backing, offset, bytes);
1549d06107adSMax Reitz         break;
1550d06107adSMax Reitz 
1551d06107adSMax Reitz     default:
1552d06107adSMax Reitz         abort();
1553d06107adSMax Reitz     }
1554d06107adSMax Reitz 
1555058cfca5SFiona Ebner     if (!copy_to_target && s->job && s->job->dirty_bitmap) {
155676cb2f24SFiona Ebner         qatomic_set(&s->job->actively_synced, false);
1557058cfca5SFiona Ebner         bdrv_set_dirty_bitmap(s->job->dirty_bitmap, offset, bytes);
1558058cfca5SFiona Ebner     }
1559058cfca5SFiona Ebner 
1560d06107adSMax Reitz     if (ret < 0) {
1561d06107adSMax Reitz         goto out;
1562d06107adSMax Reitz     }
1563d06107adSMax Reitz 
1564d06107adSMax Reitz     if (copy_to_target) {
1565d06107adSMax Reitz         do_sync_target_write(s->job, method, offset, bytes, qiov, flags);
1566d06107adSMax Reitz     }
1567d06107adSMax Reitz 
1568d06107adSMax Reitz out:
1569d06107adSMax Reitz     if (copy_to_target) {
1570d06107adSMax Reitz         active_write_settle(op);
1571d06107adSMax Reitz     }
1572d06107adSMax Reitz     return ret;
1573d06107adSMax Reitz }
1574d06107adSMax Reitz 
1575b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
bdrv_mirror_top_pwritev(BlockDriverState * bs,int64_t offset,int64_t bytes,QEMUIOVector * qiov,BdrvRequestFlags flags)1576b9b10c35SKevin Wolf bdrv_mirror_top_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
1577b9b10c35SKevin Wolf                         QEMUIOVector *qiov, BdrvRequestFlags flags)
15784ef85a9cSKevin Wolf {
1579d06107adSMax Reitz     QEMUIOVector bounce_qiov;
1580d06107adSMax Reitz     void *bounce_buf;
1581d06107adSMax Reitz     int ret = 0;
15827b32ad22SFiona Ebner     bool copy_to_target = should_copy_to_target(bs->opaque);
1583d06107adSMax Reitz 
1584d06107adSMax Reitz     if (copy_to_target) {
1585d06107adSMax Reitz         /* The guest might concurrently modify the data to write; but
1586d06107adSMax Reitz          * the data on source and destination must match, so we have
1587d06107adSMax Reitz          * to use a bounce buffer if we are going to write to the
1588d06107adSMax Reitz          * target now. */
1589d06107adSMax Reitz         bounce_buf = qemu_blockalign(bs, bytes);
1590d06107adSMax Reitz         iov_to_buf_full(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
1591d06107adSMax Reitz 
1592d06107adSMax Reitz         qemu_iovec_init(&bounce_qiov, 1);
1593d06107adSMax Reitz         qemu_iovec_add(&bounce_qiov, bounce_buf, bytes);
1594d06107adSMax Reitz         qiov = &bounce_qiov;
1595e8b65355SStefan Hajnoczi 
1596e8b65355SStefan Hajnoczi         flags &= ~BDRV_REQ_REGISTERED_BUF;
1597d06107adSMax Reitz     }
1598d06107adSMax Reitz 
15997b32ad22SFiona Ebner     ret = bdrv_mirror_top_do_write(bs, MIRROR_METHOD_COPY, copy_to_target,
16007b32ad22SFiona Ebner                                    offset, bytes, qiov, flags);
1601d06107adSMax Reitz 
1602d06107adSMax Reitz     if (copy_to_target) {
1603d06107adSMax Reitz         qemu_iovec_destroy(&bounce_qiov);
1604d06107adSMax Reitz         qemu_vfree(bounce_buf);
1605d06107adSMax Reitz     }
1606d06107adSMax Reitz 
1607d06107adSMax Reitz     return ret;
16084ef85a9cSKevin Wolf }
16094ef85a9cSKevin Wolf 
bdrv_mirror_top_flush(BlockDriverState * bs)161088095349SEmanuele Giuseppe Esposito static int coroutine_fn GRAPH_RDLOCK bdrv_mirror_top_flush(BlockDriverState *bs)
16114ef85a9cSKevin Wolf {
1612ce960aa9SVladimir Sementsov-Ogievskiy     if (bs->backing == NULL) {
1613ce960aa9SVladimir Sementsov-Ogievskiy         /* we can be here after failed bdrv_append in mirror_start_job */
1614ce960aa9SVladimir Sementsov-Ogievskiy         return 0;
1615ce960aa9SVladimir Sementsov-Ogievskiy     }
16164ef85a9cSKevin Wolf     return bdrv_co_flush(bs->backing->bs);
16174ef85a9cSKevin Wolf }
16184ef85a9cSKevin Wolf 
1619abaf8b75SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
bdrv_mirror_top_pwrite_zeroes(BlockDriverState * bs,int64_t offset,int64_t bytes,BdrvRequestFlags flags)1620abaf8b75SKevin Wolf bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1621abaf8b75SKevin Wolf                               int64_t bytes, BdrvRequestFlags flags)
16224ef85a9cSKevin Wolf {
16237b32ad22SFiona Ebner     bool copy_to_target = should_copy_to_target(bs->opaque);
16247b32ad22SFiona Ebner     return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_ZERO, copy_to_target,
16257b32ad22SFiona Ebner                                     offset, bytes, NULL, flags);
16264ef85a9cSKevin Wolf }
16274ef85a9cSKevin Wolf 
16289a5a1c62SEmanuele Giuseppe Esposito static int coroutine_fn GRAPH_RDLOCK
bdrv_mirror_top_pdiscard(BlockDriverState * bs,int64_t offset,int64_t bytes)16299a5a1c62SEmanuele Giuseppe Esposito bdrv_mirror_top_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
16304ef85a9cSKevin Wolf {
16317b32ad22SFiona Ebner     bool copy_to_target = should_copy_to_target(bs->opaque);
16327b32ad22SFiona Ebner     return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_DISCARD, copy_to_target,
16337b32ad22SFiona Ebner                                     offset, bytes, NULL, 0);
16344ef85a9cSKevin Wolf }
16354ef85a9cSKevin Wolf 
bdrv_mirror_top_refresh_filename(BlockDriverState * bs)1636004915a9SKevin Wolf static void GRAPH_RDLOCK bdrv_mirror_top_refresh_filename(BlockDriverState *bs)
1637fd4a6493SKevin Wolf {
163818775ff3SVladimir Sementsov-Ogievskiy     if (bs->backing == NULL) {
163918775ff3SVladimir Sementsov-Ogievskiy         /* we can be here after failed bdrv_attach_child in
164018775ff3SVladimir Sementsov-Ogievskiy          * bdrv_set_backing_hd */
164118775ff3SVladimir Sementsov-Ogievskiy         return;
164218775ff3SVladimir Sementsov-Ogievskiy     }
1643fd4a6493SKevin Wolf     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1644fd4a6493SKevin Wolf             bs->backing->bs->filename);
1645fd4a6493SKevin Wolf }
1646fd4a6493SKevin Wolf 
bdrv_mirror_top_child_perm(BlockDriverState * bs,BdrvChild * c,BdrvChildRole role,BlockReopenQueue * reopen_queue,uint64_t perm,uint64_t shared,uint64_t * nperm,uint64_t * nshared)16474ef85a9cSKevin Wolf static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1648bf8e925eSMax Reitz                                        BdrvChildRole role,
1649e0995dc3SKevin Wolf                                        BlockReopenQueue *reopen_queue,
16504ef85a9cSKevin Wolf                                        uint64_t perm, uint64_t shared,
16514ef85a9cSKevin Wolf                                        uint64_t *nperm, uint64_t *nshared)
16524ef85a9cSKevin Wolf {
1653f94dc3b4SMax Reitz     MirrorBDSOpaque *s = bs->opaque;
1654f94dc3b4SMax Reitz 
1655f94dc3b4SMax Reitz     if (s->stop) {
1656f94dc3b4SMax Reitz         /*
1657f94dc3b4SMax Reitz          * If the job is to be stopped, we do not need to forward
1658f94dc3b4SMax Reitz          * anything to the real image.
1659f94dc3b4SMax Reitz          */
1660f94dc3b4SMax Reitz         *nperm = 0;
1661f94dc3b4SMax Reitz         *nshared = BLK_PERM_ALL;
1662f94dc3b4SMax Reitz         return;
1663f94dc3b4SMax Reitz     }
1664f94dc3b4SMax Reitz 
166553431b90SMax Reitz     bdrv_default_perms(bs, c, role, reopen_queue,
166653431b90SMax Reitz                        perm, shared, nperm, nshared);
16674ef85a9cSKevin Wolf 
166853431b90SMax Reitz     if (s->is_commit) {
166953431b90SMax Reitz         /*
167053431b90SMax Reitz          * For commit jobs, we cannot take CONSISTENT_READ, because
167153431b90SMax Reitz          * that permission is unshared for everything above the base
167253431b90SMax Reitz          * node (except for filters on the base node).
167353431b90SMax Reitz          * We also have to force-share the WRITE permission, or
167453431b90SMax Reitz          * otherwise we would block ourselves at the base node (if
167553431b90SMax Reitz          * writes are blocked for a node, they are also blocked for
167653431b90SMax Reitz          * its backing file).
167753431b90SMax Reitz          * (We could also share RESIZE, because it may be needed for
167853431b90SMax Reitz          * the target if its size is less than the top node's; but
167953431b90SMax Reitz          * bdrv_default_perms_for_cow() automatically shares RESIZE
168053431b90SMax Reitz          * for backing nodes if WRITE is shared, so there is no need
168153431b90SMax Reitz          * to do it here.)
168253431b90SMax Reitz          */
168353431b90SMax Reitz         *nperm &= ~BLK_PERM_CONSISTENT_READ;
168453431b90SMax Reitz         *nshared |= BLK_PERM_WRITE;
168553431b90SMax Reitz     }
16864ef85a9cSKevin Wolf }
16874ef85a9cSKevin Wolf 
16884ef85a9cSKevin Wolf /* Dummy node that provides consistent read to its users without requiring it
16894ef85a9cSKevin Wolf  * from its backing file and that allows writes on the backing file chain. */
16904ef85a9cSKevin Wolf static BlockDriver bdrv_mirror_top = {
16914ef85a9cSKevin Wolf     .format_name                = "mirror_top",
16924ef85a9cSKevin Wolf     .bdrv_co_preadv             = bdrv_mirror_top_preadv,
16934ef85a9cSKevin Wolf     .bdrv_co_pwritev            = bdrv_mirror_top_pwritev,
16944ef85a9cSKevin Wolf     .bdrv_co_pwrite_zeroes      = bdrv_mirror_top_pwrite_zeroes,
16954ef85a9cSKevin Wolf     .bdrv_co_pdiscard           = bdrv_mirror_top_pdiscard,
16964ef85a9cSKevin Wolf     .bdrv_co_flush              = bdrv_mirror_top_flush,
1697fd4a6493SKevin Wolf     .bdrv_refresh_filename      = bdrv_mirror_top_refresh_filename,
16984ef85a9cSKevin Wolf     .bdrv_child_perm            = bdrv_mirror_top_child_perm,
16996540fd15SMax Reitz 
17006540fd15SMax Reitz     .is_filter                  = true,
1701046fd84fSVladimir Sementsov-Ogievskiy     .filtered_child_is_backing  = true,
17024ef85a9cSKevin Wolf };
17034ef85a9cSKevin Wolf 
mirror_start_job(const char * job_id,BlockDriverState * bs,int creation_flags,BlockDriverState * target,const char * replaces,int64_t speed,uint32_t granularity,int64_t buf_size,BlockMirrorBackingMode backing_mode,bool zero_target,BlockdevOnError on_source_error,BlockdevOnError on_target_error,bool unmap,BlockCompletionFunc * cb,void * opaque,const BlockJobDriver * driver,bool is_none_mode,BlockDriverState * base,bool auto_complete,const char * filter_node_name,bool is_mirror,MirrorCopyMode copy_mode,Error ** errp)1704cc19f177SVladimir Sementsov-Ogievskiy static BlockJob *mirror_start_job(
1705cc19f177SVladimir Sementsov-Ogievskiy                              const char *job_id, BlockDriverState *bs,
170647970dfbSJohn Snow                              int creation_flags, BlockDriverState *target,
170747970dfbSJohn Snow                              const char *replaces, int64_t speed,
170847970dfbSJohn Snow                              uint32_t granularity, int64_t buf_size,
1709274fcceeSMax Reitz                              BlockMirrorBackingMode backing_mode,
1710cdf3bc93SMax Reitz                              bool zero_target,
171103544a6eSFam Zheng                              BlockdevOnError on_source_error,
1712b952b558SPaolo Bonzini                              BlockdevOnError on_target_error,
17130fc9f8eaSFam Zheng                              bool unmap,
1714097310b5SMarkus Armbruster                              BlockCompletionFunc *cb,
171551ccfa2dSFam Zheng                              void *opaque,
171603544a6eSFam Zheng                              const BlockJobDriver *driver,
1717b49f7eadSWen Congyang                              bool is_none_mode, BlockDriverState *base,
171851ccfa2dSFam Zheng                              bool auto_complete, const char *filter_node_name,
1719481debaaSMax Reitz                              bool is_mirror, MirrorCopyMode copy_mode,
172051ccfa2dSFam Zheng                              Error **errp)
1721893f7ebaSPaolo Bonzini {
1722893f7ebaSPaolo Bonzini     MirrorBlockJob *s;
1723429076e8SMax Reitz     MirrorBDSOpaque *bs_opaque;
17244ef85a9cSKevin Wolf     BlockDriverState *mirror_top_bs;
17254ef85a9cSKevin Wolf     bool target_is_backing;
17263f072a7fSMax Reitz     uint64_t target_perms, target_shared_perms;
1727d7086422SKevin Wolf     int ret;
1728893f7ebaSPaolo Bonzini 
17293804e3cfSKevin Wolf     GLOBAL_STATE_CODE();
17303804e3cfSKevin Wolf 
1731eee13dfeSPaolo Bonzini     if (granularity == 0) {
1732341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(target);
1733eee13dfeSPaolo Bonzini     }
1734eee13dfeSPaolo Bonzini 
173531826642SEric Blake     assert(is_power_of_2(granularity));
1736eee13dfeSPaolo Bonzini 
173748ac0a4dSWen Congyang     if (buf_size < 0) {
173848ac0a4dSWen Congyang         error_setg(errp, "Invalid parameter 'buf-size'");
1739cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
174048ac0a4dSWen Congyang     }
174148ac0a4dSWen Congyang 
174248ac0a4dSWen Congyang     if (buf_size == 0) {
174348ac0a4dSWen Congyang         buf_size = DEFAULT_MIRROR_BUF_SIZE;
174448ac0a4dSWen Congyang     }
17455bc361b8SFam Zheng 
1746ad74751fSKevin Wolf     bdrv_graph_rdlock_main_loop();
17473f072a7fSMax Reitz     if (bdrv_skip_filters(bs) == bdrv_skip_filters(target)) {
174886fae10cSKevin Wolf         error_setg(errp, "Can't mirror node into itself");
1749ad74751fSKevin Wolf         bdrv_graph_rdunlock_main_loop();
1750cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
175186fae10cSKevin Wolf     }
175286fae10cSKevin Wolf 
175353431b90SMax Reitz     target_is_backing = bdrv_chain_contains(bs, target);
1754ad74751fSKevin Wolf     bdrv_graph_rdunlock_main_loop();
175553431b90SMax Reitz 
17564ef85a9cSKevin Wolf     /* In the case of active commit, add dummy driver to provide consistent
17574ef85a9cSKevin Wolf      * reads on the top, while disabling it in the intermediate nodes, and make
17584ef85a9cSKevin Wolf      * the backing chain writable. */
17596cdbceb1SKevin Wolf     mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
17606cdbceb1SKevin Wolf                                          BDRV_O_RDWR, errp);
17614ef85a9cSKevin Wolf     if (mirror_top_bs == NULL) {
1762cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
1763893f7ebaSPaolo Bonzini     }
1764d3c8c674SKevin Wolf     if (!filter_node_name) {
1765d3c8c674SKevin Wolf         mirror_top_bs->implicit = true;
1766d3c8c674SKevin Wolf     }
1767e5182c1cSMax Reitz 
1768e5182c1cSMax Reitz     /* So that we can always drop this node */
1769e5182c1cSMax Reitz     mirror_top_bs->never_freeze = true;
1770e5182c1cSMax Reitz 
17714ef85a9cSKevin Wolf     mirror_top_bs->total_sectors = bs->total_sectors;
1772228345bfSMax Reitz     mirror_top_bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED;
177380f5c33fSKevin Wolf     mirror_top_bs->supported_zero_flags = BDRV_REQ_WRITE_UNCHANGED |
177480f5c33fSKevin Wolf                                           BDRV_REQ_NO_FALLBACK;
1775429076e8SMax Reitz     bs_opaque = g_new0(MirrorBDSOpaque, 1);
1776429076e8SMax Reitz     mirror_top_bs->opaque = bs_opaque;
1777893f7ebaSPaolo Bonzini 
177853431b90SMax Reitz     bs_opaque->is_commit = target_is_backing;
177953431b90SMax Reitz 
17804ef85a9cSKevin Wolf     bdrv_drained_begin(bs);
1781934aee14SVladimir Sementsov-Ogievskiy     ret = bdrv_append(mirror_top_bs, bs, errp);
17824ef85a9cSKevin Wolf     bdrv_drained_end(bs);
17834ef85a9cSKevin Wolf 
1784934aee14SVladimir Sementsov-Ogievskiy     if (ret < 0) {
1785b2c2832cSKevin Wolf         bdrv_unref(mirror_top_bs);
1786cc19f177SVladimir Sementsov-Ogievskiy         return NULL;
1787b2c2832cSKevin Wolf     }
1788b2c2832cSKevin Wolf 
17894ef85a9cSKevin Wolf     /* Make sure that the source is not resized while the job is running */
179075859b94SJohn Snow     s = block_job_create(job_id, driver, NULL, mirror_top_bs,
17914ef85a9cSKevin Wolf                          BLK_PERM_CONSISTENT_READ,
17924ef85a9cSKevin Wolf                          BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
179364631f36SVladimir Sementsov-Ogievskiy                          BLK_PERM_WRITE, speed,
17944ef85a9cSKevin Wolf                          creation_flags, cb, opaque, errp);
17954ef85a9cSKevin Wolf     if (!s) {
17964ef85a9cSKevin Wolf         goto fail;
17974ef85a9cSKevin Wolf     }
1798429076e8SMax Reitz 
17997a25fcd0SMax Reitz     /* The block job now has a reference to this node */
18007a25fcd0SMax Reitz     bdrv_unref(mirror_top_bs);
18017a25fcd0SMax Reitz 
18024ef85a9cSKevin Wolf     s->mirror_top_bs = mirror_top_bs;
18034ef85a9cSKevin Wolf 
18044ef85a9cSKevin Wolf     /* No resize for the target either; while the mirror is still running, a
18054ef85a9cSKevin Wolf      * consistent read isn't necessarily possible. We could possibly allow
18064ef85a9cSKevin Wolf      * writes and graph modifications, though it would likely defeat the
18074ef85a9cSKevin Wolf      * purpose of a mirror, so leave them blocked for now.
18084ef85a9cSKevin Wolf      *
18094ef85a9cSKevin Wolf      * In the case of active commit, things look a bit different, though,
18104ef85a9cSKevin Wolf      * because the target is an already populated backing file in active use.
18114ef85a9cSKevin Wolf      * We can allow anything except resize there.*/
18123f072a7fSMax Reitz 
18133f072a7fSMax Reitz     target_perms = BLK_PERM_WRITE;
18143f072a7fSMax Reitz     target_shared_perms = BLK_PERM_WRITE_UNCHANGED;
18153f072a7fSMax Reitz 
18163f072a7fSMax Reitz     if (target_is_backing) {
18173f072a7fSMax Reitz         int64_t bs_size, target_size;
18183f072a7fSMax Reitz         bs_size = bdrv_getlength(bs);
18193f072a7fSMax Reitz         if (bs_size < 0) {
18203f072a7fSMax Reitz             error_setg_errno(errp, -bs_size,
18213f072a7fSMax Reitz                              "Could not inquire top image size");
18223f072a7fSMax Reitz             goto fail;
18233f072a7fSMax Reitz         }
18243f072a7fSMax Reitz 
18253f072a7fSMax Reitz         target_size = bdrv_getlength(target);
18263f072a7fSMax Reitz         if (target_size < 0) {
18273f072a7fSMax Reitz             error_setg_errno(errp, -target_size,
18283f072a7fSMax Reitz                              "Could not inquire base image size");
18293f072a7fSMax Reitz             goto fail;
18303f072a7fSMax Reitz         }
18313f072a7fSMax Reitz 
18323f072a7fSMax Reitz         if (target_size < bs_size) {
18333f072a7fSMax Reitz             target_perms |= BLK_PERM_RESIZE;
18343f072a7fSMax Reitz         }
18353f072a7fSMax Reitz 
183664631f36SVladimir Sementsov-Ogievskiy         target_shared_perms |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE;
1837ad74751fSKevin Wolf     } else {
1838ad74751fSKevin Wolf         bdrv_graph_rdlock_main_loop();
1839ad74751fSKevin Wolf         if (bdrv_chain_contains(bs, bdrv_skip_filters(target))) {
18403f072a7fSMax Reitz             /*
18413f072a7fSMax Reitz              * We may want to allow this in the future, but it would
18423f072a7fSMax Reitz              * require taking some extra care.
18433f072a7fSMax Reitz              */
1844ad74751fSKevin Wolf             error_setg(errp, "Cannot mirror to a filter on top of a node in "
1845ad74751fSKevin Wolf                        "the source's backing chain");
1846ad74751fSKevin Wolf             bdrv_graph_rdunlock_main_loop();
18473f072a7fSMax Reitz             goto fail;
18483f072a7fSMax Reitz         }
1849ad74751fSKevin Wolf         bdrv_graph_rdunlock_main_loop();
1850ad74751fSKevin Wolf     }
18513f072a7fSMax Reitz 
1852d861ab3aSKevin Wolf     s->target = blk_new(s->common.job.aio_context,
18533f072a7fSMax Reitz                         target_perms, target_shared_perms);
1854d7086422SKevin Wolf     ret = blk_insert_bs(s->target, target, errp);
1855d7086422SKevin Wolf     if (ret < 0) {
18564ef85a9cSKevin Wolf         goto fail;
1857d7086422SKevin Wolf     }
1858045a2f82SFam Zheng     if (is_mirror) {
1859045a2f82SFam Zheng         /* XXX: Mirror target could be a NBD server of target QEMU in the case
1860045a2f82SFam Zheng          * of non-shared block migration. To allow migration completion, we
1861045a2f82SFam Zheng          * have to allow "inactivate" of the target BB.  When that happens, we
1862045a2f82SFam Zheng          * know the job is drained, and the vcpus are stopped, so no write
1863045a2f82SFam Zheng          * operation will be performed. Block layer already has assertions to
1864045a2f82SFam Zheng          * ensure that. */
1865045a2f82SFam Zheng         blk_set_force_allow_inactivate(s->target);
1866045a2f82SFam Zheng     }
18679ff7f0dfSKevin Wolf     blk_set_allow_aio_context_change(s->target, true);
1868cf312932SKevin Wolf     blk_set_disable_request_queuing(s->target, true);
1869e253f4b8SKevin Wolf 
1870ad74751fSKevin Wolf     bdrv_graph_rdlock_main_loop();
187109158f00SBenoît Canet     s->replaces = g_strdup(replaces);
1872b952b558SPaolo Bonzini     s->on_source_error = on_source_error;
1873b952b558SPaolo Bonzini     s->on_target_error = on_target_error;
187403544a6eSFam Zheng     s->is_none_mode = is_none_mode;
1875274fcceeSMax Reitz     s->backing_mode = backing_mode;
1876cdf3bc93SMax Reitz     s->zero_target = zero_target;
18772d400d15SFiona Ebner     qatomic_set(&s->copy_mode, copy_mode);
18785bc361b8SFam Zheng     s->base = base;
18793f072a7fSMax Reitz     s->base_overlay = bdrv_find_overlay(bs, base);
1880eee13dfeSPaolo Bonzini     s->granularity = granularity;
188148ac0a4dSWen Congyang     s->buf_size = ROUND_UP(buf_size, granularity);
18820fc9f8eaSFam Zheng     s->unmap = unmap;
1883b49f7eadSWen Congyang     if (auto_complete) {
1884b49f7eadSWen Congyang         s->should_complete = true;
1885b49f7eadSWen Congyang     }
1886ad74751fSKevin Wolf     bdrv_graph_rdunlock_main_loop();
1887b812f671SPaolo Bonzini 
1888058cfca5SFiona Ebner     s->dirty_bitmap = bdrv_create_dirty_bitmap(s->mirror_top_bs, granularity,
1889058cfca5SFiona Ebner                                                NULL, errp);
1890b8afb520SFam Zheng     if (!s->dirty_bitmap) {
189188f9d1b3SKevin Wolf         goto fail;
1892b8afb520SFam Zheng     }
1893058cfca5SFiona Ebner 
1894058cfca5SFiona Ebner     /*
1895058cfca5SFiona Ebner      * The dirty bitmap is set by bdrv_mirror_top_do_write() when not in active
1896058cfca5SFiona Ebner      * mode.
1897058cfca5SFiona Ebner      */
1898dbdf699cSVladimir Sementsov-Ogievskiy     bdrv_disable_dirty_bitmap(s->dirty_bitmap);
189910f3cd15SAlberto Garcia 
19006bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
190167b24427SAlberto Garcia     ret = block_job_add_bdrv(&s->common, "source", bs, 0,
190267b24427SAlberto Garcia                              BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE |
190367b24427SAlberto Garcia                              BLK_PERM_CONSISTENT_READ,
190467b24427SAlberto Garcia                              errp);
190567b24427SAlberto Garcia     if (ret < 0) {
19066bc30f19SStefan Hajnoczi         bdrv_graph_wrunlock();
190767b24427SAlberto Garcia         goto fail;
190867b24427SAlberto Garcia     }
190967b24427SAlberto Garcia 
19104ef85a9cSKevin Wolf     /* Required permissions are already taken with blk_new() */
191176d554e2SKevin Wolf     block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
191276d554e2SKevin Wolf                        &error_abort);
191376d554e2SKevin Wolf 
1914f3ede4b0SAlberto Garcia     /* In commit_active_start() all intermediate nodes disappear, so
1915f3ede4b0SAlberto Garcia      * any jobs in them must be blocked */
19164ef85a9cSKevin Wolf     if (target_is_backing) {
19173f072a7fSMax Reitz         BlockDriverState *iter, *filtered_target;
19183f072a7fSMax Reitz         uint64_t iter_shared_perms;
19193f072a7fSMax Reitz 
19203f072a7fSMax Reitz         /*
19213f072a7fSMax Reitz          * The topmost node with
19223f072a7fSMax Reitz          * bdrv_skip_filters(filtered_target) == bdrv_skip_filters(target)
19233f072a7fSMax Reitz          */
19243f072a7fSMax Reitz         filtered_target = bdrv_cow_bs(bdrv_find_overlay(bs, target));
19253f072a7fSMax Reitz 
19263f072a7fSMax Reitz         assert(bdrv_skip_filters(filtered_target) ==
19273f072a7fSMax Reitz                bdrv_skip_filters(target));
19283f072a7fSMax Reitz 
19293f072a7fSMax Reitz         /*
19303f072a7fSMax Reitz          * XXX BLK_PERM_WRITE needs to be allowed so we don't block
19314ef85a9cSKevin Wolf          * ourselves at s->base (if writes are blocked for a node, they are
19324ef85a9cSKevin Wolf          * also blocked for its backing file). The other options would be a
19333f072a7fSMax Reitz          * second filter driver above s->base (== target).
19343f072a7fSMax Reitz          */
19353f072a7fSMax Reitz         iter_shared_perms = BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE;
19363f072a7fSMax Reitz 
19373f072a7fSMax Reitz         for (iter = bdrv_filter_or_cow_bs(bs); iter != target;
19383f072a7fSMax Reitz              iter = bdrv_filter_or_cow_bs(iter))
19393f072a7fSMax Reitz         {
19403f072a7fSMax Reitz             if (iter == filtered_target) {
19413f072a7fSMax Reitz                 /*
19423f072a7fSMax Reitz                  * From here on, all nodes are filters on the base.
19433f072a7fSMax Reitz                  * This allows us to share BLK_PERM_CONSISTENT_READ.
19443f072a7fSMax Reitz                  */
19453f072a7fSMax Reitz                 iter_shared_perms |= BLK_PERM_CONSISTENT_READ;
19463f072a7fSMax Reitz             }
19473f072a7fSMax Reitz 
19484ef85a9cSKevin Wolf             ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
19493f072a7fSMax Reitz                                      iter_shared_perms, errp);
19504ef85a9cSKevin Wolf             if (ret < 0) {
19516bc30f19SStefan Hajnoczi                 bdrv_graph_wrunlock();
19524ef85a9cSKevin Wolf                 goto fail;
19534ef85a9cSKevin Wolf             }
1954f3ede4b0SAlberto Garcia         }
1955ef53dc09SAlberto Garcia 
1956ef53dc09SAlberto Garcia         if (bdrv_freeze_backing_chain(mirror_top_bs, target, errp) < 0) {
19576bc30f19SStefan Hajnoczi             bdrv_graph_wrunlock();
1958ef53dc09SAlberto Garcia             goto fail;
1959ef53dc09SAlberto Garcia         }
1960f3ede4b0SAlberto Garcia     }
19616bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
196210f3cd15SAlberto Garcia 
196312aa4082SMax Reitz     QTAILQ_INIT(&s->ops_in_flight);
196412aa4082SMax Reitz 
19655ccac6f1SJohn Snow     trace_mirror_start(bs, s, opaque);
1966da01ff7fSKevin Wolf     job_start(&s->common.job);
1967cc19f177SVladimir Sementsov-Ogievskiy 
1968cc19f177SVladimir Sementsov-Ogievskiy     return &s->common;
19694ef85a9cSKevin Wolf 
19704ef85a9cSKevin Wolf fail:
19714ef85a9cSKevin Wolf     if (s) {
19727a25fcd0SMax Reitz         /* Make sure this BDS does not go away until we have completed the graph
19737a25fcd0SMax Reitz          * changes below */
19747a25fcd0SMax Reitz         bdrv_ref(mirror_top_bs);
19757a25fcd0SMax Reitz 
19764ef85a9cSKevin Wolf         g_free(s->replaces);
19774ef85a9cSKevin Wolf         blk_unref(s->target);
1978429076e8SMax Reitz         bs_opaque->job = NULL;
1979e917e2cbSAlberto Garcia         if (s->dirty_bitmap) {
19805deb6cbdSVladimir Sementsov-Ogievskiy             bdrv_release_dirty_bitmap(s->dirty_bitmap);
1981e917e2cbSAlberto Garcia         }
19824ad35181SKevin Wolf         job_early_fail(&s->common.job);
19834ef85a9cSKevin Wolf     }
19844ef85a9cSKevin Wolf 
1985f94dc3b4SMax Reitz     bs_opaque->stop = true;
1986ccd6a379SKevin Wolf     bdrv_drained_begin(bs);
19876bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
1988ccd6a379SKevin Wolf     assert(mirror_top_bs->backing->bs == bs);
1989f94dc3b4SMax Reitz     bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
1990c1cef672SFam Zheng                              &error_abort);
1991ccd6a379SKevin Wolf     bdrv_replace_node(mirror_top_bs, bs, &error_abort);
19926bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
1993ccd6a379SKevin Wolf     bdrv_drained_end(bs);
19947a25fcd0SMax Reitz 
19957a25fcd0SMax Reitz     bdrv_unref(mirror_top_bs);
1996cc19f177SVladimir Sementsov-Ogievskiy 
1997cc19f177SVladimir Sementsov-Ogievskiy     return NULL;
1998893f7ebaSPaolo Bonzini }
199903544a6eSFam Zheng 
mirror_start(const char * job_id,BlockDriverState * bs,BlockDriverState * target,const char * replaces,int creation_flags,int64_t speed,uint32_t granularity,int64_t buf_size,MirrorSyncMode mode,BlockMirrorBackingMode backing_mode,bool zero_target,BlockdevOnError on_source_error,BlockdevOnError on_target_error,bool unmap,const char * filter_node_name,MirrorCopyMode copy_mode,Error ** errp)200071aa9867SAlberto Garcia void mirror_start(const char *job_id, BlockDriverState *bs,
200171aa9867SAlberto Garcia                   BlockDriverState *target, const char *replaces,
2002a1999b33SJohn Snow                   int creation_flags, int64_t speed,
2003a1999b33SJohn Snow                   uint32_t granularity, int64_t buf_size,
2004274fcceeSMax Reitz                   MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
2005cdf3bc93SMax Reitz                   bool zero_target,
2006274fcceeSMax Reitz                   BlockdevOnError on_source_error,
200703544a6eSFam Zheng                   BlockdevOnError on_target_error,
2008481debaaSMax Reitz                   bool unmap, const char *filter_node_name,
2009481debaaSMax Reitz                   MirrorCopyMode copy_mode, Error **errp)
201003544a6eSFam Zheng {
201103544a6eSFam Zheng     bool is_none_mode;
201203544a6eSFam Zheng     BlockDriverState *base;
201303544a6eSFam Zheng 
2014b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2015b4ad82aaSEmanuele Giuseppe Esposito 
2016c8b56501SJohn Snow     if ((mode == MIRROR_SYNC_MODE_INCREMENTAL) ||
2017c8b56501SJohn Snow         (mode == MIRROR_SYNC_MODE_BITMAP)) {
2018c8b56501SJohn Snow         error_setg(errp, "Sync mode '%s' not supported",
2019c8b56501SJohn Snow                    MirrorSyncMode_str(mode));
2020d58d8453SJohn Snow         return;
2021d58d8453SJohn Snow     }
2022ad74751fSKevin Wolf 
2023ad74751fSKevin Wolf     bdrv_graph_rdlock_main_loop();
202403544a6eSFam Zheng     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
20253f072a7fSMax Reitz     base = mode == MIRROR_SYNC_MODE_TOP ? bdrv_backing_chain_next(bs) : NULL;
2026ad74751fSKevin Wolf     bdrv_graph_rdunlock_main_loop();
2027ad74751fSKevin Wolf 
2028a1999b33SJohn Snow     mirror_start_job(job_id, bs, creation_flags, target, replaces,
2029cdf3bc93SMax Reitz                      speed, granularity, buf_size, backing_mode, zero_target,
203051ccfa2dSFam Zheng                      on_source_error, on_target_error, unmap, NULL, NULL,
20316cdbceb1SKevin Wolf                      &mirror_job_driver, is_none_mode, base, false,
2032481debaaSMax Reitz                      filter_node_name, true, copy_mode, errp);
203303544a6eSFam Zheng }
203403544a6eSFam Zheng 
commit_active_start(const char * job_id,BlockDriverState * bs,BlockDriverState * base,int creation_flags,int64_t speed,BlockdevOnError on_error,const char * filter_node_name,BlockCompletionFunc * cb,void * opaque,bool auto_complete,Error ** errp)2035cc19f177SVladimir Sementsov-Ogievskiy BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
203647970dfbSJohn Snow                               BlockDriverState *base, int creation_flags,
203747970dfbSJohn Snow                               int64_t speed, BlockdevOnError on_error,
20380db832f4SKevin Wolf                               const char *filter_node_name,
203978bbd910SFam Zheng                               BlockCompletionFunc *cb, void *opaque,
204078bbd910SFam Zheng                               bool auto_complete, Error **errp)
204103544a6eSFam Zheng {
20421ba79388SAlberto Garcia     bool base_read_only;
2043eb5becc1SVladimir Sementsov-Ogievskiy     BlockJob *job;
20444da83585SJeff Cody 
2045b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2046b4ad82aaSEmanuele Giuseppe Esposito 
20471ba79388SAlberto Garcia     base_read_only = bdrv_is_read_only(base);
20484da83585SJeff Cody 
20491ba79388SAlberto Garcia     if (base_read_only) {
20501ba79388SAlberto Garcia         if (bdrv_reopen_set_read_only(base, false, errp) < 0) {
2051cc19f177SVladimir Sementsov-Ogievskiy             return NULL;
205220a63d2cSFam Zheng         }
20531ba79388SAlberto Garcia     }
20544da83585SJeff Cody 
2055eb5becc1SVladimir Sementsov-Ogievskiy     job = mirror_start_job(
2056cc19f177SVladimir Sementsov-Ogievskiy                      job_id, bs, creation_flags, base, NULL, speed, 0, 0,
2057cdf3bc93SMax Reitz                      MIRROR_LEAVE_BACKING_CHAIN, false,
205851ccfa2dSFam Zheng                      on_error, on_error, true, cb, opaque,
20596cdbceb1SKevin Wolf                      &commit_active_job_driver, false, base, auto_complete,
2060481debaaSMax Reitz                      filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
2061eb5becc1SVladimir Sementsov-Ogievskiy                      errp);
2062eb5becc1SVladimir Sementsov-Ogievskiy     if (!job) {
20634da83585SJeff Cody         goto error_restore_flags;
20644da83585SJeff Cody     }
20654da83585SJeff Cody 
2066eb5becc1SVladimir Sementsov-Ogievskiy     return job;
20674da83585SJeff Cody 
20684da83585SJeff Cody error_restore_flags:
20694da83585SJeff Cody     /* ignore error and errp for bdrv_reopen, because we want to propagate
20704da83585SJeff Cody      * the original error */
20711ba79388SAlberto Garcia     if (base_read_only) {
20721ba79388SAlberto Garcia         bdrv_reopen_set_read_only(base, true, NULL);
20731ba79388SAlberto Garcia     }
2074cc19f177SVladimir Sementsov-Ogievskiy     return NULL;
207503544a6eSFam Zheng }
2076