xref: /qemu/block/mirror.c (revision 274fccee2bf63702b34e3923b1e50a49147a7918)
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"
15893f7ebaSPaolo Bonzini #include "trace.h"
16737e150eSPaolo Bonzini #include "block/blockjob.h"
17737e150eSPaolo Bonzini #include "block/block_int.h"
18373340b2SMax Reitz #include "sysemu/block-backend.h"
19da34e65cSMarkus Armbruster #include "qapi/error.h"
20cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
21893f7ebaSPaolo Bonzini #include "qemu/ratelimit.h"
22b812f671SPaolo Bonzini #include "qemu/bitmap.h"
23893f7ebaSPaolo Bonzini 
24893f7ebaSPaolo Bonzini #define SLICE_TIME    100000000ULL /* ns */
25402a4741SPaolo Bonzini #define MAX_IN_FLIGHT 16
2648ac0a4dSWen Congyang #define DEFAULT_MIRROR_BUF_SIZE   (10 << 20)
27402a4741SPaolo Bonzini 
28402a4741SPaolo Bonzini /* The mirroring buffer is a list of granularity-sized chunks.
29402a4741SPaolo Bonzini  * Free chunks are organized in a list.
30402a4741SPaolo Bonzini  */
31402a4741SPaolo Bonzini typedef struct MirrorBuffer {
32402a4741SPaolo Bonzini     QSIMPLEQ_ENTRY(MirrorBuffer) next;
33402a4741SPaolo Bonzini } MirrorBuffer;
34893f7ebaSPaolo Bonzini 
35893f7ebaSPaolo Bonzini typedef struct MirrorBlockJob {
36893f7ebaSPaolo Bonzini     BlockJob common;
37893f7ebaSPaolo Bonzini     RateLimit limit;
38e253f4b8SKevin Wolf     BlockBackend *target;
395bc361b8SFam Zheng     BlockDriverState *base;
4009158f00SBenoît Canet     /* The name of the graph node to replace */
4109158f00SBenoît Canet     char *replaces;
4209158f00SBenoît Canet     /* The BDS to replace */
4309158f00SBenoît Canet     BlockDriverState *to_replace;
4409158f00SBenoît Canet     /* Used to block operations on the drive-mirror-replace target */
4509158f00SBenoît Canet     Error *replace_blocker;
4603544a6eSFam Zheng     bool is_none_mode;
47*274fcceeSMax Reitz     BlockMirrorBackingMode backing_mode;
48b952b558SPaolo Bonzini     BlockdevOnError on_source_error, on_target_error;
49d63ffd87SPaolo Bonzini     bool synced;
50d63ffd87SPaolo Bonzini     bool should_complete;
51eee13dfeSPaolo Bonzini     int64_t granularity;
52b812f671SPaolo Bonzini     size_t buf_size;
53b21c7652SMax Reitz     int64_t bdev_length;
54b812f671SPaolo Bonzini     unsigned long *cow_bitmap;
55e4654d2dSFam Zheng     BdrvDirtyBitmap *dirty_bitmap;
568f0720ecSPaolo Bonzini     HBitmapIter hbi;
57893f7ebaSPaolo Bonzini     uint8_t *buf;
58402a4741SPaolo Bonzini     QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
59402a4741SPaolo Bonzini     int buf_free_count;
60bd48bde8SPaolo Bonzini 
61402a4741SPaolo Bonzini     unsigned long *in_flight_bitmap;
62bd48bde8SPaolo Bonzini     int in_flight;
63b21c7652SMax Reitz     int sectors_in_flight;
64bd48bde8SPaolo Bonzini     int ret;
650fc9f8eaSFam Zheng     bool unmap;
66e424aff5SKevin Wolf     bool waiting_for_io;
67e5b43573SFam Zheng     int target_cluster_sectors;
68e5b43573SFam Zheng     int max_iov;
69893f7ebaSPaolo Bonzini } MirrorBlockJob;
70893f7ebaSPaolo Bonzini 
71bd48bde8SPaolo Bonzini typedef struct MirrorOp {
72bd48bde8SPaolo Bonzini     MirrorBlockJob *s;
73bd48bde8SPaolo Bonzini     QEMUIOVector qiov;
74bd48bde8SPaolo Bonzini     int64_t sector_num;
75bd48bde8SPaolo Bonzini     int nb_sectors;
76bd48bde8SPaolo Bonzini } MirrorOp;
77bd48bde8SPaolo Bonzini 
78b952b558SPaolo Bonzini static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
79b952b558SPaolo Bonzini                                             int error)
80b952b558SPaolo Bonzini {
81b952b558SPaolo Bonzini     s->synced = false;
82b952b558SPaolo Bonzini     if (read) {
8381e254dcSKevin Wolf         return block_job_error_action(&s->common, s->on_source_error,
8481e254dcSKevin Wolf                                       true, error);
85b952b558SPaolo Bonzini     } else {
8681e254dcSKevin Wolf         return block_job_error_action(&s->common, s->on_target_error,
8781e254dcSKevin Wolf                                       false, error);
88b952b558SPaolo Bonzini     }
89b952b558SPaolo Bonzini }
90b952b558SPaolo Bonzini 
91bd48bde8SPaolo Bonzini static void mirror_iteration_done(MirrorOp *op, int ret)
92bd48bde8SPaolo Bonzini {
93bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
94402a4741SPaolo Bonzini     struct iovec *iov;
95bd48bde8SPaolo Bonzini     int64_t chunk_num;
96402a4741SPaolo Bonzini     int i, nb_chunks, sectors_per_chunk;
97bd48bde8SPaolo Bonzini 
98bd48bde8SPaolo Bonzini     trace_mirror_iteration_done(s, op->sector_num, op->nb_sectors, ret);
99bd48bde8SPaolo Bonzini 
100bd48bde8SPaolo Bonzini     s->in_flight--;
101b21c7652SMax Reitz     s->sectors_in_flight -= op->nb_sectors;
102402a4741SPaolo Bonzini     iov = op->qiov.iov;
103402a4741SPaolo Bonzini     for (i = 0; i < op->qiov.niov; i++) {
104402a4741SPaolo Bonzini         MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
105402a4741SPaolo Bonzini         QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
106402a4741SPaolo Bonzini         s->buf_free_count++;
107402a4741SPaolo Bonzini     }
108402a4741SPaolo Bonzini 
109bd48bde8SPaolo Bonzini     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
110bd48bde8SPaolo Bonzini     chunk_num = op->sector_num / sectors_per_chunk;
1114150ae60SFam Zheng     nb_chunks = DIV_ROUND_UP(op->nb_sectors, sectors_per_chunk);
112402a4741SPaolo Bonzini     bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
113b21c7652SMax Reitz     if (ret >= 0) {
114b21c7652SMax Reitz         if (s->cow_bitmap) {
115bd48bde8SPaolo Bonzini             bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
116bd48bde8SPaolo Bonzini         }
117b21c7652SMax Reitz         s->common.offset += (uint64_t)op->nb_sectors * BDRV_SECTOR_SIZE;
118b21c7652SMax Reitz     }
119bd48bde8SPaolo Bonzini 
1206df3bf8eSZhang Min     qemu_iovec_destroy(&op->qiov);
121c84b3192SPaolo Bonzini     g_free(op);
1227b770c72SStefan Hajnoczi 
123e424aff5SKevin Wolf     if (s->waiting_for_io) {
124bd48bde8SPaolo Bonzini         qemu_coroutine_enter(s->common.co, NULL);
125bd48bde8SPaolo Bonzini     }
1267b770c72SStefan Hajnoczi }
127bd48bde8SPaolo Bonzini 
128bd48bde8SPaolo Bonzini static void mirror_write_complete(void *opaque, int ret)
129bd48bde8SPaolo Bonzini {
130bd48bde8SPaolo Bonzini     MirrorOp *op = opaque;
131bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
132bd48bde8SPaolo Bonzini     if (ret < 0) {
133bd48bde8SPaolo Bonzini         BlockErrorAction action;
134bd48bde8SPaolo Bonzini 
13520dca810SJohn Snow         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);
136bd48bde8SPaolo Bonzini         action = mirror_error_action(s, false, -ret);
137a589569fSWenchao Xia         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
138bd48bde8SPaolo Bonzini             s->ret = ret;
139bd48bde8SPaolo Bonzini         }
140bd48bde8SPaolo Bonzini     }
141bd48bde8SPaolo Bonzini     mirror_iteration_done(op, ret);
142bd48bde8SPaolo Bonzini }
143bd48bde8SPaolo Bonzini 
144bd48bde8SPaolo Bonzini static void mirror_read_complete(void *opaque, int ret)
145bd48bde8SPaolo Bonzini {
146bd48bde8SPaolo Bonzini     MirrorOp *op = opaque;
147bd48bde8SPaolo Bonzini     MirrorBlockJob *s = op->s;
148bd48bde8SPaolo Bonzini     if (ret < 0) {
149bd48bde8SPaolo Bonzini         BlockErrorAction action;
150bd48bde8SPaolo Bonzini 
15120dca810SJohn Snow         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);
152bd48bde8SPaolo Bonzini         action = mirror_error_action(s, true, -ret);
153a589569fSWenchao Xia         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
154bd48bde8SPaolo Bonzini             s->ret = ret;
155bd48bde8SPaolo Bonzini         }
156bd48bde8SPaolo Bonzini 
157bd48bde8SPaolo Bonzini         mirror_iteration_done(op, ret);
158bd48bde8SPaolo Bonzini         return;
159bd48bde8SPaolo Bonzini     }
160e253f4b8SKevin Wolf     blk_aio_pwritev(s->target, op->sector_num * BDRV_SECTOR_SIZE, &op->qiov,
16173698c30SEric Blake                     0, mirror_write_complete, op);
162bd48bde8SPaolo Bonzini }
163bd48bde8SPaolo Bonzini 
1644150ae60SFam Zheng static inline void mirror_clip_sectors(MirrorBlockJob *s,
1654150ae60SFam Zheng                                        int64_t sector_num,
1664150ae60SFam Zheng                                        int *nb_sectors)
1674150ae60SFam Zheng {
1684150ae60SFam Zheng     *nb_sectors = MIN(*nb_sectors,
1694150ae60SFam Zheng                       s->bdev_length / BDRV_SECTOR_SIZE - sector_num);
1704150ae60SFam Zheng }
1714150ae60SFam Zheng 
172e5b43573SFam Zheng /* Round sector_num and/or nb_sectors to target cluster if COW is needed, and
173e5b43573SFam Zheng  * return the offset of the adjusted tail sector against original. */
174e5b43573SFam Zheng static int mirror_cow_align(MirrorBlockJob *s,
175e5b43573SFam Zheng                             int64_t *sector_num,
176e5b43573SFam Zheng                             int *nb_sectors)
177893f7ebaSPaolo Bonzini {
178e5b43573SFam Zheng     bool need_cow;
179e5b43573SFam Zheng     int ret = 0;
180e5b43573SFam Zheng     int chunk_sectors = s->granularity >> BDRV_SECTOR_BITS;
181e5b43573SFam Zheng     int64_t align_sector_num = *sector_num;
182e5b43573SFam Zheng     int align_nb_sectors = *nb_sectors;
183e5b43573SFam Zheng     int max_sectors = chunk_sectors * s->max_iov;
184893f7ebaSPaolo Bonzini 
185e5b43573SFam Zheng     need_cow = !test_bit(*sector_num / chunk_sectors, s->cow_bitmap);
186e5b43573SFam Zheng     need_cow |= !test_bit((*sector_num + *nb_sectors - 1) / chunk_sectors,
187e5b43573SFam Zheng                           s->cow_bitmap);
188e5b43573SFam Zheng     if (need_cow) {
189244483e6SKevin Wolf         bdrv_round_sectors_to_clusters(blk_bs(s->target), *sector_num,
190244483e6SKevin Wolf                                        *nb_sectors, &align_sector_num,
191244483e6SKevin Wolf                                        &align_nb_sectors);
1928f0720ecSPaolo Bonzini     }
1938f0720ecSPaolo Bonzini 
194e5b43573SFam Zheng     if (align_nb_sectors > max_sectors) {
195e5b43573SFam Zheng         align_nb_sectors = max_sectors;
196e5b43573SFam Zheng         if (need_cow) {
197e5b43573SFam Zheng             align_nb_sectors = QEMU_ALIGN_DOWN(align_nb_sectors,
198e5b43573SFam Zheng                                                s->target_cluster_sectors);
199e5b43573SFam Zheng         }
200e5b43573SFam Zheng     }
2014150ae60SFam Zheng     /* Clipping may result in align_nb_sectors unaligned to chunk boundary, but
2024150ae60SFam Zheng      * that doesn't matter because it's already the end of source image. */
2034150ae60SFam Zheng     mirror_clip_sectors(s, align_sector_num, &align_nb_sectors);
204402a4741SPaolo Bonzini 
205e5b43573SFam Zheng     ret = align_sector_num + align_nb_sectors - (*sector_num + *nb_sectors);
206e5b43573SFam Zheng     *sector_num = align_sector_num;
207e5b43573SFam Zheng     *nb_sectors = align_nb_sectors;
208e5b43573SFam Zheng     assert(ret >= 0);
209e5b43573SFam Zheng     return ret;
210e5b43573SFam Zheng }
211e5b43573SFam Zheng 
21221cd917fSFam Zheng static inline void mirror_wait_for_io(MirrorBlockJob *s)
21321cd917fSFam Zheng {
21421cd917fSFam Zheng     assert(!s->waiting_for_io);
21521cd917fSFam Zheng     s->waiting_for_io = true;
21621cd917fSFam Zheng     qemu_coroutine_yield();
21721cd917fSFam Zheng     s->waiting_for_io = false;
21821cd917fSFam Zheng }
21921cd917fSFam Zheng 
220e5b43573SFam Zheng /* Submit async read while handling COW.
221e5b43573SFam Zheng  * Returns: nb_sectors if no alignment is necessary, or
222e5b43573SFam Zheng  *          (new_end - sector_num) if tail is rounded up or down due to
223e5b43573SFam Zheng  *          alignment or buffer limit.
224402a4741SPaolo Bonzini  */
225e5b43573SFam Zheng static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,
226e5b43573SFam Zheng                           int nb_sectors)
227e5b43573SFam Zheng {
228e253f4b8SKevin Wolf     BlockBackend *source = s->common.blk;
229e5b43573SFam Zheng     int sectors_per_chunk, nb_chunks;
230e5b43573SFam Zheng     int ret = nb_sectors;
231e5b43573SFam Zheng     MirrorOp *op;
232402a4741SPaolo Bonzini 
233e5b43573SFam Zheng     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
234e5b43573SFam Zheng 
235e5b43573SFam Zheng     /* We can only handle as much as buf_size at a time. */
236e5b43573SFam Zheng     nb_sectors = MIN(s->buf_size >> BDRV_SECTOR_BITS, nb_sectors);
237e5b43573SFam Zheng     assert(nb_sectors);
238e5b43573SFam Zheng 
239e5b43573SFam Zheng     if (s->cow_bitmap) {
240e5b43573SFam Zheng         ret += mirror_cow_align(s, &sector_num, &nb_sectors);
241e5b43573SFam Zheng     }
242e5b43573SFam Zheng     assert(nb_sectors << BDRV_SECTOR_BITS <= s->buf_size);
243e5b43573SFam Zheng     /* The sector range must meet granularity because:
244e5b43573SFam Zheng      * 1) Caller passes in aligned values;
245e5b43573SFam Zheng      * 2) mirror_cow_align is used only when target cluster is larger. */
246e5b43573SFam Zheng     assert(!(sector_num % sectors_per_chunk));
2474150ae60SFam Zheng     nb_chunks = DIV_ROUND_UP(nb_sectors, sectors_per_chunk);
248e5b43573SFam Zheng 
249e5b43573SFam Zheng     while (s->buf_free_count < nb_chunks) {
250402a4741SPaolo Bonzini         trace_mirror_yield_in_flight(s, sector_num, s->in_flight);
25121cd917fSFam Zheng         mirror_wait_for_io(s);
252b812f671SPaolo Bonzini     }
253b812f671SPaolo Bonzini 
254bd48bde8SPaolo Bonzini     /* Allocate a MirrorOp that is used as an AIO callback.  */
255c84b3192SPaolo Bonzini     op = g_new(MirrorOp, 1);
256bd48bde8SPaolo Bonzini     op->s = s;
257bd48bde8SPaolo Bonzini     op->sector_num = sector_num;
258bd48bde8SPaolo Bonzini     op->nb_sectors = nb_sectors;
259402a4741SPaolo Bonzini 
260402a4741SPaolo Bonzini     /* Now make a QEMUIOVector taking enough granularity-sized chunks
261402a4741SPaolo Bonzini      * from s->buf_free.
262402a4741SPaolo Bonzini      */
263402a4741SPaolo Bonzini     qemu_iovec_init(&op->qiov, nb_chunks);
264402a4741SPaolo Bonzini     while (nb_chunks-- > 0) {
265402a4741SPaolo Bonzini         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
266e5b43573SFam Zheng         size_t remaining = nb_sectors * BDRV_SECTOR_SIZE - op->qiov.size;
2675a0f6fd5SKevin Wolf 
268402a4741SPaolo Bonzini         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
269402a4741SPaolo Bonzini         s->buf_free_count--;
2705a0f6fd5SKevin Wolf         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
271402a4741SPaolo Bonzini     }
272402a4741SPaolo Bonzini 
273893f7ebaSPaolo Bonzini     /* Copy the dirty cluster.  */
274bd48bde8SPaolo Bonzini     s->in_flight++;
275b21c7652SMax Reitz     s->sectors_in_flight += nb_sectors;
276b812f671SPaolo Bonzini     trace_mirror_one_iteration(s, sector_num, nb_sectors);
277dcfb3bebSFam Zheng 
27873698c30SEric Blake     blk_aio_preadv(source, sector_num * BDRV_SECTOR_SIZE, &op->qiov, 0,
279bd48bde8SPaolo Bonzini                    mirror_read_complete, op);
280e5b43573SFam Zheng     return ret;
281e5b43573SFam Zheng }
282e5b43573SFam Zheng 
283e5b43573SFam Zheng static void mirror_do_zero_or_discard(MirrorBlockJob *s,
284e5b43573SFam Zheng                                       int64_t sector_num,
285e5b43573SFam Zheng                                       int nb_sectors,
286e5b43573SFam Zheng                                       bool is_discard)
287e5b43573SFam Zheng {
288e5b43573SFam Zheng     MirrorOp *op;
289e5b43573SFam Zheng 
290e5b43573SFam Zheng     /* Allocate a MirrorOp that is used as an AIO callback. The qiov is zeroed
291e5b43573SFam Zheng      * so the freeing in mirror_iteration_done is nop. */
292e5b43573SFam Zheng     op = g_new0(MirrorOp, 1);
293e5b43573SFam Zheng     op->s = s;
294e5b43573SFam Zheng     op->sector_num = sector_num;
295e5b43573SFam Zheng     op->nb_sectors = nb_sectors;
296e5b43573SFam Zheng 
297e5b43573SFam Zheng     s->in_flight++;
298e5b43573SFam Zheng     s->sectors_in_flight += nb_sectors;
299e5b43573SFam Zheng     if (is_discard) {
300e253f4b8SKevin Wolf         blk_aio_discard(s->target, sector_num, op->nb_sectors,
301e5b43573SFam Zheng                         mirror_write_complete, op);
302e5b43573SFam Zheng     } else {
303e253f4b8SKevin Wolf         blk_aio_pwrite_zeroes(s->target, sector_num * BDRV_SECTOR_SIZE,
304e253f4b8SKevin Wolf                               op->nb_sectors * BDRV_SECTOR_SIZE,
305dcfb3bebSFam Zheng                               s->unmap ? BDRV_REQ_MAY_UNMAP : 0,
306dcfb3bebSFam Zheng                               mirror_write_complete, op);
307e5b43573SFam Zheng     }
308e5b43573SFam Zheng }
309e5b43573SFam Zheng 
310e5b43573SFam Zheng static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
311e5b43573SFam Zheng {
312e253f4b8SKevin Wolf     BlockDriverState *source = blk_bs(s->common.blk);
3139c83625bSMax Reitz     int64_t sector_num, first_chunk;
314e5b43573SFam Zheng     uint64_t delay_ns = 0;
315e5b43573SFam Zheng     /* At least the first dirty chunk is mirrored in one iteration. */
316e5b43573SFam Zheng     int nb_chunks = 1;
317e5b43573SFam Zheng     int64_t end = s->bdev_length / BDRV_SECTOR_SIZE;
318e5b43573SFam Zheng     int sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
319e5b43573SFam Zheng 
320e5b43573SFam Zheng     sector_num = hbitmap_iter_next(&s->hbi);
321e5b43573SFam Zheng     if (sector_num < 0) {
322e5b43573SFam Zheng         bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
323e5b43573SFam Zheng         sector_num = hbitmap_iter_next(&s->hbi);
324e5b43573SFam Zheng         trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
325e5b43573SFam Zheng         assert(sector_num >= 0);
326e5b43573SFam Zheng     }
327e5b43573SFam Zheng 
3289c83625bSMax Reitz     first_chunk = sector_num / sectors_per_chunk;
3299c83625bSMax Reitz     while (test_bit(first_chunk, s->in_flight_bitmap)) {
3309c83625bSMax Reitz         trace_mirror_yield_in_flight(s, first_chunk, s->in_flight);
3319c83625bSMax Reitz         mirror_wait_for_io(s);
3329c83625bSMax Reitz     }
3339c83625bSMax Reitz 
334e5b43573SFam Zheng     /* Find the number of consective dirty chunks following the first dirty
335e5b43573SFam Zheng      * one, and wait for in flight requests in them. */
336e5b43573SFam Zheng     while (nb_chunks * sectors_per_chunk < (s->buf_size >> BDRV_SECTOR_BITS)) {
337e5b43573SFam Zheng         int64_t hbitmap_next;
338e5b43573SFam Zheng         int64_t next_sector = sector_num + nb_chunks * sectors_per_chunk;
339e5b43573SFam Zheng         int64_t next_chunk = next_sector / sectors_per_chunk;
340e5b43573SFam Zheng         if (next_sector >= end ||
341e5b43573SFam Zheng             !bdrv_get_dirty(source, s->dirty_bitmap, next_sector)) {
342e5b43573SFam Zheng             break;
343e5b43573SFam Zheng         }
344e5b43573SFam Zheng         if (test_bit(next_chunk, s->in_flight_bitmap)) {
345e5b43573SFam Zheng             break;
346e5b43573SFam Zheng         }
3479c83625bSMax Reitz 
348e5b43573SFam Zheng         hbitmap_next = hbitmap_iter_next(&s->hbi);
349f27a2742SMax Reitz         if (hbitmap_next > next_sector || hbitmap_next < 0) {
350f27a2742SMax Reitz             /* The bitmap iterator's cache is stale, refresh it */
351f27a2742SMax Reitz             bdrv_set_dirty_iter(&s->hbi, next_sector);
352f27a2742SMax Reitz             hbitmap_next = hbitmap_iter_next(&s->hbi);
353f27a2742SMax Reitz         }
354e5b43573SFam Zheng         assert(hbitmap_next == next_sector);
355e5b43573SFam Zheng         nb_chunks++;
356e5b43573SFam Zheng     }
357e5b43573SFam Zheng 
358e5b43573SFam Zheng     /* Clear dirty bits before querying the block status, because
359e5b43573SFam Zheng      * calling bdrv_get_block_status_above could yield - if some blocks are
360e5b43573SFam Zheng      * marked dirty in this window, we need to know.
361e5b43573SFam Zheng      */
362e5b43573SFam Zheng     bdrv_reset_dirty_bitmap(s->dirty_bitmap, sector_num,
363e5b43573SFam Zheng                             nb_chunks * sectors_per_chunk);
364e5b43573SFam Zheng     bitmap_set(s->in_flight_bitmap, sector_num / sectors_per_chunk, nb_chunks);
365e5b43573SFam Zheng     while (nb_chunks > 0 && sector_num < end) {
366e5b43573SFam Zheng         int ret;
367e5b43573SFam Zheng         int io_sectors;
368e5b43573SFam Zheng         BlockDriverState *file;
369e5b43573SFam Zheng         enum MirrorMethod {
370e5b43573SFam Zheng             MIRROR_METHOD_COPY,
371e5b43573SFam Zheng             MIRROR_METHOD_ZERO,
372e5b43573SFam Zheng             MIRROR_METHOD_DISCARD
373e5b43573SFam Zheng         } mirror_method = MIRROR_METHOD_COPY;
374e5b43573SFam Zheng 
375e5b43573SFam Zheng         assert(!(sector_num % sectors_per_chunk));
376e5b43573SFam Zheng         ret = bdrv_get_block_status_above(source, NULL, sector_num,
377e5b43573SFam Zheng                                           nb_chunks * sectors_per_chunk,
378e5b43573SFam Zheng                                           &io_sectors, &file);
379e5b43573SFam Zheng         if (ret < 0) {
380e5b43573SFam Zheng             io_sectors = nb_chunks * sectors_per_chunk;
381e5b43573SFam Zheng         }
382e5b43573SFam Zheng 
383e5b43573SFam Zheng         io_sectors -= io_sectors % sectors_per_chunk;
384e5b43573SFam Zheng         if (io_sectors < sectors_per_chunk) {
385e5b43573SFam Zheng             io_sectors = sectors_per_chunk;
386e5b43573SFam Zheng         } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
387e5b43573SFam Zheng             int64_t target_sector_num;
388e5b43573SFam Zheng             int target_nb_sectors;
389244483e6SKevin Wolf             bdrv_round_sectors_to_clusters(blk_bs(s->target), sector_num,
390244483e6SKevin Wolf                                            io_sectors,  &target_sector_num,
391244483e6SKevin Wolf                                            &target_nb_sectors);
392e5b43573SFam Zheng             if (target_sector_num == sector_num &&
393e5b43573SFam Zheng                 target_nb_sectors == io_sectors) {
394e5b43573SFam Zheng                 mirror_method = ret & BDRV_BLOCK_ZERO ?
395e5b43573SFam Zheng                                     MIRROR_METHOD_ZERO :
396e5b43573SFam Zheng                                     MIRROR_METHOD_DISCARD;
397e5b43573SFam Zheng             }
398e5b43573SFam Zheng         }
399e5b43573SFam Zheng 
4004150ae60SFam Zheng         mirror_clip_sectors(s, sector_num, &io_sectors);
401e5b43573SFam Zheng         switch (mirror_method) {
402e5b43573SFam Zheng         case MIRROR_METHOD_COPY:
403e5b43573SFam Zheng             io_sectors = mirror_do_read(s, sector_num, io_sectors);
404e5b43573SFam Zheng             break;
405e5b43573SFam Zheng         case MIRROR_METHOD_ZERO:
406e5b43573SFam Zheng             mirror_do_zero_or_discard(s, sector_num, io_sectors, false);
407e5b43573SFam Zheng             break;
408e5b43573SFam Zheng         case MIRROR_METHOD_DISCARD:
409e5b43573SFam Zheng             mirror_do_zero_or_discard(s, sector_num, io_sectors, true);
410e5b43573SFam Zheng             break;
411e5b43573SFam Zheng         default:
412e5b43573SFam Zheng             abort();
413e5b43573SFam Zheng         }
414e5b43573SFam Zheng         assert(io_sectors);
415e5b43573SFam Zheng         sector_num += io_sectors;
4164150ae60SFam Zheng         nb_chunks -= DIV_ROUND_UP(io_sectors, sectors_per_chunk);
417e5b43573SFam Zheng         delay_ns += ratelimit_calculate_delay(&s->limit, io_sectors);
418dcfb3bebSFam Zheng     }
419cc8c9d6cSPaolo Bonzini     return delay_ns;
420893f7ebaSPaolo Bonzini }
421b952b558SPaolo Bonzini 
422402a4741SPaolo Bonzini static void mirror_free_init(MirrorBlockJob *s)
423402a4741SPaolo Bonzini {
424402a4741SPaolo Bonzini     int granularity = s->granularity;
425402a4741SPaolo Bonzini     size_t buf_size = s->buf_size;
426402a4741SPaolo Bonzini     uint8_t *buf = s->buf;
427402a4741SPaolo Bonzini 
428402a4741SPaolo Bonzini     assert(s->buf_free_count == 0);
429402a4741SPaolo Bonzini     QSIMPLEQ_INIT(&s->buf_free);
430402a4741SPaolo Bonzini     while (buf_size != 0) {
431402a4741SPaolo Bonzini         MirrorBuffer *cur = (MirrorBuffer *)buf;
432402a4741SPaolo Bonzini         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
433402a4741SPaolo Bonzini         s->buf_free_count++;
434402a4741SPaolo Bonzini         buf_size -= granularity;
435402a4741SPaolo Bonzini         buf += granularity;
436402a4741SPaolo Bonzini     }
437402a4741SPaolo Bonzini }
438402a4741SPaolo Bonzini 
439bd48bde8SPaolo Bonzini static void mirror_drain(MirrorBlockJob *s)
440bd48bde8SPaolo Bonzini {
441bd48bde8SPaolo Bonzini     while (s->in_flight > 0) {
44221cd917fSFam Zheng         mirror_wait_for_io(s);
443bd48bde8SPaolo Bonzini     }
444893f7ebaSPaolo Bonzini }
445893f7ebaSPaolo Bonzini 
4465a7e7a0bSStefan Hajnoczi typedef struct {
4475a7e7a0bSStefan Hajnoczi     int ret;
4485a7e7a0bSStefan Hajnoczi } MirrorExitData;
4495a7e7a0bSStefan Hajnoczi 
4505a7e7a0bSStefan Hajnoczi static void mirror_exit(BlockJob *job, void *opaque)
4515a7e7a0bSStefan Hajnoczi {
4525a7e7a0bSStefan Hajnoczi     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
4535a7e7a0bSStefan Hajnoczi     MirrorExitData *data = opaque;
4545a7e7a0bSStefan Hajnoczi     AioContext *replace_aio_context = NULL;
455e253f4b8SKevin Wolf     BlockDriverState *src = blk_bs(s->common.blk);
456e253f4b8SKevin Wolf     BlockDriverState *target_bs = blk_bs(s->target);
4573f09bfbcSKevin Wolf 
4583f09bfbcSKevin Wolf     /* Make sure that the source BDS doesn't go away before we called
4593f09bfbcSKevin Wolf      * block_job_completed(). */
4603f09bfbcSKevin Wolf     bdrv_ref(src);
4615a7e7a0bSStefan Hajnoczi 
4625a7e7a0bSStefan Hajnoczi     if (s->to_replace) {
4635a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(s->to_replace);
4645a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
4655a7e7a0bSStefan Hajnoczi     }
4665a7e7a0bSStefan Hajnoczi 
4675a7e7a0bSStefan Hajnoczi     if (s->should_complete && data->ret == 0) {
468e253f4b8SKevin Wolf         BlockDriverState *to_replace = src;
4695a7e7a0bSStefan Hajnoczi         if (s->to_replace) {
4705a7e7a0bSStefan Hajnoczi             to_replace = s->to_replace;
4715a7e7a0bSStefan Hajnoczi         }
47240365552SKevin Wolf 
473e253f4b8SKevin Wolf         if (bdrv_get_flags(target_bs) != bdrv_get_flags(to_replace)) {
474e253f4b8SKevin Wolf             bdrv_reopen(target_bs, bdrv_get_flags(to_replace), NULL);
4755a7e7a0bSStefan Hajnoczi         }
476b8804815SKevin Wolf 
477b8804815SKevin Wolf         /* The mirror job has no requests in flight any more, but we need to
478b8804815SKevin Wolf          * drain potential other users of the BDS before changing the graph. */
479e253f4b8SKevin Wolf         bdrv_drained_begin(target_bs);
480e253f4b8SKevin Wolf         bdrv_replace_in_backing_chain(to_replace, target_bs);
481e253f4b8SKevin Wolf         bdrv_drained_end(target_bs);
482b8804815SKevin Wolf 
483b6d2e599SKevin Wolf         /* We just changed the BDS the job BB refers to */
484b6d2e599SKevin Wolf         blk_remove_bs(job->blk);
485b6d2e599SKevin Wolf         blk_insert_bs(job->blk, src);
4865a7e7a0bSStefan Hajnoczi     }
4875a7e7a0bSStefan Hajnoczi     if (s->to_replace) {
4885a7e7a0bSStefan Hajnoczi         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
4895a7e7a0bSStefan Hajnoczi         error_free(s->replace_blocker);
4905a7e7a0bSStefan Hajnoczi         bdrv_unref(s->to_replace);
4915a7e7a0bSStefan Hajnoczi     }
4925a7e7a0bSStefan Hajnoczi     if (replace_aio_context) {
4935a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
4945a7e7a0bSStefan Hajnoczi     }
4955a7e7a0bSStefan Hajnoczi     g_free(s->replaces);
496e253f4b8SKevin Wolf     bdrv_op_unblock_all(target_bs, s->common.blocker);
497e253f4b8SKevin Wolf     blk_unref(s->target);
4985a7e7a0bSStefan Hajnoczi     block_job_completed(&s->common, data->ret);
4995a7e7a0bSStefan Hajnoczi     g_free(data);
500176c3699SFam Zheng     bdrv_drained_end(src);
501ab27c3b5SFam Zheng     if (qemu_get_aio_context() == bdrv_get_aio_context(src)) {
502ab27c3b5SFam Zheng         aio_enable_external(iohandler_get_aio_context());
503ab27c3b5SFam Zheng     }
5043f09bfbcSKevin Wolf     bdrv_unref(src);
5055a7e7a0bSStefan Hajnoczi }
5065a7e7a0bSStefan Hajnoczi 
507893f7ebaSPaolo Bonzini static void coroutine_fn mirror_run(void *opaque)
508893f7ebaSPaolo Bonzini {
509893f7ebaSPaolo Bonzini     MirrorBlockJob *s = opaque;
5105a7e7a0bSStefan Hajnoczi     MirrorExitData *data;
511e253f4b8SKevin Wolf     BlockDriverState *bs = blk_bs(s->common.blk);
512e253f4b8SKevin Wolf     BlockDriverState *target_bs = blk_bs(s->target);
51399900697SFam Zheng     int64_t sector_num, end, length;
514bd48bde8SPaolo Bonzini     uint64_t last_pause_ns;
515b812f671SPaolo Bonzini     BlockDriverInfo bdi;
5161d33936eSJeff Cody     char backing_filename[2]; /* we only need 2 characters because we are only
5171d33936eSJeff Cody                                  checking for a NULL string */
518893f7ebaSPaolo Bonzini     int ret = 0;
519893f7ebaSPaolo Bonzini     int n;
520e5b43573SFam Zheng     int target_cluster_size = BDRV_SECTOR_SIZE;
521893f7ebaSPaolo Bonzini 
522893f7ebaSPaolo Bonzini     if (block_job_is_cancelled(&s->common)) {
523893f7ebaSPaolo Bonzini         goto immediate_exit;
524893f7ebaSPaolo Bonzini     }
525893f7ebaSPaolo Bonzini 
526b21c7652SMax Reitz     s->bdev_length = bdrv_getlength(bs);
527b21c7652SMax Reitz     if (s->bdev_length < 0) {
528b21c7652SMax Reitz         ret = s->bdev_length;
529373df5b1SFam Zheng         goto immediate_exit;
530b21c7652SMax Reitz     } else if (s->bdev_length == 0) {
5319e48b025SFam Zheng         /* Report BLOCK_JOB_READY and wait for complete. */
5329e48b025SFam Zheng         block_job_event_ready(&s->common);
5339e48b025SFam Zheng         s->synced = true;
5349e48b025SFam Zheng         while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
5359e48b025SFam Zheng             block_job_yield(&s->common);
5369e48b025SFam Zheng         }
5379e48b025SFam Zheng         s->common.cancelled = false;
5389e48b025SFam Zheng         goto immediate_exit;
539893f7ebaSPaolo Bonzini     }
540893f7ebaSPaolo Bonzini 
541b21c7652SMax Reitz     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
542402a4741SPaolo Bonzini     s->in_flight_bitmap = bitmap_new(length);
543402a4741SPaolo Bonzini 
544b812f671SPaolo Bonzini     /* If we have no backing file yet in the destination, we cannot let
545b812f671SPaolo Bonzini      * the destination do COW.  Instead, we copy sectors around the
546b812f671SPaolo Bonzini      * dirty data if needed.  We need a bitmap to do that.
547b812f671SPaolo Bonzini      */
548e253f4b8SKevin Wolf     bdrv_get_backing_filename(target_bs, backing_filename,
549b812f671SPaolo Bonzini                               sizeof(backing_filename));
550e253f4b8SKevin Wolf     if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
551e5b43573SFam Zheng         target_cluster_size = bdi.cluster_size;
552c3cc95bdSFam Zheng     }
553e253f4b8SKevin Wolf     if (backing_filename[0] && !target_bs->backing
554e5b43573SFam Zheng         && s->granularity < target_cluster_size) {
555e5b43573SFam Zheng         s->buf_size = MAX(s->buf_size, target_cluster_size);
556b812f671SPaolo Bonzini         s->cow_bitmap = bitmap_new(length);
557b812f671SPaolo Bonzini     }
558e5b43573SFam Zheng     s->target_cluster_sectors = target_cluster_size >> BDRV_SECTOR_BITS;
559e253f4b8SKevin Wolf     s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
560b812f671SPaolo Bonzini 
561b21c7652SMax Reitz     end = s->bdev_length / BDRV_SECTOR_SIZE;
5627504edf4SKevin Wolf     s->buf = qemu_try_blockalign(bs, s->buf_size);
5637504edf4SKevin Wolf     if (s->buf == NULL) {
5647504edf4SKevin Wolf         ret = -ENOMEM;
5657504edf4SKevin Wolf         goto immediate_exit;
5667504edf4SKevin Wolf     }
5677504edf4SKevin Wolf 
568402a4741SPaolo Bonzini     mirror_free_init(s);
569893f7ebaSPaolo Bonzini 
5704c0cbd6fSFam Zheng     last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
57103544a6eSFam Zheng     if (!s->is_none_mode) {
572893f7ebaSPaolo Bonzini         /* First part, loop on the sectors and initialize the dirty bitmap.  */
5735bc361b8SFam Zheng         BlockDriverState *base = s->base;
574e253f4b8SKevin Wolf         bool mark_all_dirty = s->base == NULL && !bdrv_has_zero_init(target_bs);
5755279efebSJeff Cody 
576893f7ebaSPaolo Bonzini         for (sector_num = 0; sector_num < end; ) {
57799900697SFam Zheng             /* Just to make sure we are not exceeding int limit. */
57899900697SFam Zheng             int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,
57999900697SFam Zheng                                  end - sector_num);
5804c0cbd6fSFam Zheng             int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
5814c0cbd6fSFam Zheng 
5824c0cbd6fSFam Zheng             if (now - last_pause_ns > SLICE_TIME) {
5834c0cbd6fSFam Zheng                 last_pause_ns = now;
5844c0cbd6fSFam Zheng                 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, 0);
5854c0cbd6fSFam Zheng             }
5864c0cbd6fSFam Zheng 
5874c0cbd6fSFam Zheng             if (block_job_is_cancelled(&s->common)) {
5884c0cbd6fSFam Zheng                 goto immediate_exit;
5894c0cbd6fSFam Zheng             }
5904c0cbd6fSFam Zheng 
59199900697SFam Zheng             ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);
592893f7ebaSPaolo Bonzini 
593893f7ebaSPaolo Bonzini             if (ret < 0) {
594893f7ebaSPaolo Bonzini                 goto immediate_exit;
595893f7ebaSPaolo Bonzini             }
596893f7ebaSPaolo Bonzini 
597893f7ebaSPaolo Bonzini             assert(n > 0);
5985279efebSJeff Cody             if (ret == 1 || mark_all_dirty) {
59920dca810SJohn Snow                 bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);
600893f7ebaSPaolo Bonzini             }
60199900697SFam Zheng             sector_num += n;
602893f7ebaSPaolo Bonzini         }
603893f7ebaSPaolo Bonzini     }
604893f7ebaSPaolo Bonzini 
60520dca810SJohn Snow     bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
606893f7ebaSPaolo Bonzini     for (;;) {
607cc8c9d6cSPaolo Bonzini         uint64_t delay_ns = 0;
608893f7ebaSPaolo Bonzini         int64_t cnt;
609893f7ebaSPaolo Bonzini         bool should_complete;
610893f7ebaSPaolo Bonzini 
611bd48bde8SPaolo Bonzini         if (s->ret < 0) {
612bd48bde8SPaolo Bonzini             ret = s->ret;
613893f7ebaSPaolo Bonzini             goto immediate_exit;
614893f7ebaSPaolo Bonzini         }
615bd48bde8SPaolo Bonzini 
61620dca810SJohn Snow         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
617b21c7652SMax Reitz         /* s->common.offset contains the number of bytes already processed so
618b21c7652SMax Reitz          * far, cnt is the number of dirty sectors remaining and
619b21c7652SMax Reitz          * s->sectors_in_flight is the number of sectors currently being
620b21c7652SMax Reitz          * processed; together those are the current total operation length */
621b21c7652SMax Reitz         s->common.len = s->common.offset +
622b21c7652SMax Reitz                         (cnt + s->sectors_in_flight) * BDRV_SECTOR_SIZE;
623bd48bde8SPaolo Bonzini 
624bd48bde8SPaolo Bonzini         /* Note that even when no rate limit is applied we need to yield
625a7282330SFam Zheng          * periodically with no pending I/O so that bdrv_drain_all() returns.
626bd48bde8SPaolo Bonzini          * We do so every SLICE_TIME nanoseconds, or when there is an error,
627bd48bde8SPaolo Bonzini          * or when the source is clean, whichever comes first.
628bd48bde8SPaolo Bonzini          */
629bc72ad67SAlex Bligh         if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - last_pause_ns < SLICE_TIME &&
630bd48bde8SPaolo Bonzini             s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
631402a4741SPaolo Bonzini             if (s->in_flight == MAX_IN_FLIGHT || s->buf_free_count == 0 ||
632402a4741SPaolo Bonzini                 (cnt == 0 && s->in_flight > 0)) {
633402a4741SPaolo Bonzini                 trace_mirror_yield(s, s->in_flight, s->buf_free_count, cnt);
63421cd917fSFam Zheng                 mirror_wait_for_io(s);
635bd48bde8SPaolo Bonzini                 continue;
636bd48bde8SPaolo Bonzini             } else if (cnt != 0) {
637cc8c9d6cSPaolo Bonzini                 delay_ns = mirror_iteration(s);
638893f7ebaSPaolo Bonzini             }
639cc8c9d6cSPaolo Bonzini         }
640893f7ebaSPaolo Bonzini 
641893f7ebaSPaolo Bonzini         should_complete = false;
642bd48bde8SPaolo Bonzini         if (s->in_flight == 0 && cnt == 0) {
643893f7ebaSPaolo Bonzini             trace_mirror_before_flush(s);
644e253f4b8SKevin Wolf             ret = blk_flush(s->target);
645893f7ebaSPaolo Bonzini             if (ret < 0) {
646a589569fSWenchao Xia                 if (mirror_error_action(s, false, -ret) ==
647a589569fSWenchao Xia                     BLOCK_ERROR_ACTION_REPORT) {
648893f7ebaSPaolo Bonzini                     goto immediate_exit;
649893f7ebaSPaolo Bonzini                 }
650b952b558SPaolo Bonzini             } else {
651893f7ebaSPaolo Bonzini                 /* We're out of the streaming phase.  From now on, if the job
652893f7ebaSPaolo Bonzini                  * is cancelled we will actually complete all pending I/O and
653893f7ebaSPaolo Bonzini                  * report completion.  This way, block-job-cancel will leave
654893f7ebaSPaolo Bonzini                  * the target in a consistent state.
655893f7ebaSPaolo Bonzini                  */
656d63ffd87SPaolo Bonzini                 if (!s->synced) {
657bcada37bSWenchao Xia                     block_job_event_ready(&s->common);
658d63ffd87SPaolo Bonzini                     s->synced = true;
659d63ffd87SPaolo Bonzini                 }
660d63ffd87SPaolo Bonzini 
661d63ffd87SPaolo Bonzini                 should_complete = s->should_complete ||
662d63ffd87SPaolo Bonzini                     block_job_is_cancelled(&s->common);
66320dca810SJohn Snow                 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
664893f7ebaSPaolo Bonzini             }
665b952b558SPaolo Bonzini         }
666893f7ebaSPaolo Bonzini 
667893f7ebaSPaolo Bonzini         if (cnt == 0 && should_complete) {
668893f7ebaSPaolo Bonzini             /* The dirty bitmap is not updated while operations are pending.
669893f7ebaSPaolo Bonzini              * If we're about to exit, wait for pending operations before
670893f7ebaSPaolo Bonzini              * calling bdrv_get_dirty_count(bs), or we may exit while the
671893f7ebaSPaolo Bonzini              * source has dirty data to copy!
672893f7ebaSPaolo Bonzini              *
673893f7ebaSPaolo Bonzini              * Note that I/O can be submitted by the guest while
674893f7ebaSPaolo Bonzini              * mirror_populate runs.
675893f7ebaSPaolo Bonzini              */
676893f7ebaSPaolo Bonzini             trace_mirror_before_drain(s, cnt);
67739bf92ddSFam Zheng             bdrv_co_drain(bs);
67820dca810SJohn Snow             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
679893f7ebaSPaolo Bonzini         }
680893f7ebaSPaolo Bonzini 
681893f7ebaSPaolo Bonzini         ret = 0;
682cc8c9d6cSPaolo Bonzini         trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
683d63ffd87SPaolo Bonzini         if (!s->synced) {
6847483d1e5SAlex Bligh             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
685893f7ebaSPaolo Bonzini             if (block_job_is_cancelled(&s->common)) {
686893f7ebaSPaolo Bonzini                 break;
687893f7ebaSPaolo Bonzini             }
688893f7ebaSPaolo Bonzini         } else if (!should_complete) {
689bd48bde8SPaolo Bonzini             delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
6907483d1e5SAlex Bligh             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
691893f7ebaSPaolo Bonzini         } else if (cnt == 0) {
692893f7ebaSPaolo Bonzini             /* The two disks are in sync.  Exit and report successful
693893f7ebaSPaolo Bonzini              * completion.
694893f7ebaSPaolo Bonzini              */
695893f7ebaSPaolo Bonzini             assert(QLIST_EMPTY(&bs->tracked_requests));
696893f7ebaSPaolo Bonzini             s->common.cancelled = false;
697893f7ebaSPaolo Bonzini             break;
698893f7ebaSPaolo Bonzini         }
699bc72ad67SAlex Bligh         last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
700893f7ebaSPaolo Bonzini     }
701893f7ebaSPaolo Bonzini 
702893f7ebaSPaolo Bonzini immediate_exit:
703bd48bde8SPaolo Bonzini     if (s->in_flight > 0) {
704bd48bde8SPaolo Bonzini         /* We get here only if something went wrong.  Either the job failed,
705bd48bde8SPaolo Bonzini          * or it was cancelled prematurely so that we do not guarantee that
706bd48bde8SPaolo Bonzini          * the target is a copy of the source.
707bd48bde8SPaolo Bonzini          */
708bd48bde8SPaolo Bonzini         assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));
709bd48bde8SPaolo Bonzini         mirror_drain(s);
710bd48bde8SPaolo Bonzini     }
711bd48bde8SPaolo Bonzini 
712bd48bde8SPaolo Bonzini     assert(s->in_flight == 0);
7137191bf31SMarkus Armbruster     qemu_vfree(s->buf);
714b812f671SPaolo Bonzini     g_free(s->cow_bitmap);
715402a4741SPaolo Bonzini     g_free(s->in_flight_bitmap);
716e4654d2dSFam Zheng     bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);
7175a7e7a0bSStefan Hajnoczi 
7185a7e7a0bSStefan Hajnoczi     data = g_malloc(sizeof(*data));
7195a7e7a0bSStefan Hajnoczi     data->ret = ret;
720176c3699SFam Zheng     /* Before we switch to target in mirror_exit, make sure data doesn't
721176c3699SFam Zheng      * change. */
722e253f4b8SKevin Wolf     bdrv_drained_begin(bs);
723ab27c3b5SFam Zheng     if (qemu_get_aio_context() == bdrv_get_aio_context(bs)) {
724ab27c3b5SFam Zheng         /* FIXME: virtio host notifiers run on iohandler_ctx, therefore the
725ab27c3b5SFam Zheng          * above bdrv_drained_end isn't enough to quiesce it. This is ugly, we
726ab27c3b5SFam Zheng          * need a block layer API change to achieve this. */
727ab27c3b5SFam Zheng         aio_disable_external(iohandler_get_aio_context());
728ab27c3b5SFam Zheng     }
7295a7e7a0bSStefan Hajnoczi     block_job_defer_to_main_loop(&s->common, mirror_exit, data);
730893f7ebaSPaolo Bonzini }
731893f7ebaSPaolo Bonzini 
732893f7ebaSPaolo Bonzini static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)
733893f7ebaSPaolo Bonzini {
734893f7ebaSPaolo Bonzini     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
735893f7ebaSPaolo Bonzini 
736893f7ebaSPaolo Bonzini     if (speed < 0) {
737c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER, "speed");
738893f7ebaSPaolo Bonzini         return;
739893f7ebaSPaolo Bonzini     }
740893f7ebaSPaolo Bonzini     ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
741893f7ebaSPaolo Bonzini }
742893f7ebaSPaolo Bonzini 
743d63ffd87SPaolo Bonzini static void mirror_complete(BlockJob *job, Error **errp)
744d63ffd87SPaolo Bonzini {
745d63ffd87SPaolo Bonzini     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
746*274fcceeSMax Reitz     BlockDriverState *src, *target;
747d63ffd87SPaolo Bonzini 
748*274fcceeSMax Reitz     src = blk_bs(job->blk);
749*274fcceeSMax Reitz     target = blk_bs(s->target);
750*274fcceeSMax Reitz 
751d63ffd87SPaolo Bonzini     if (!s->synced) {
7528ccb9569SKevin Wolf         error_setg(errp, QERR_BLOCK_JOB_NOT_READY, job->id);
753d63ffd87SPaolo Bonzini         return;
754d63ffd87SPaolo Bonzini     }
755d63ffd87SPaolo Bonzini 
756*274fcceeSMax Reitz     if (s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
757*274fcceeSMax Reitz         int ret;
758*274fcceeSMax Reitz 
759*274fcceeSMax Reitz         assert(!target->backing);
760*274fcceeSMax Reitz         ret = bdrv_open_backing_file(target, NULL, "backing", errp);
761*274fcceeSMax Reitz         if (ret < 0) {
762*274fcceeSMax Reitz             return;
763*274fcceeSMax Reitz         }
764*274fcceeSMax Reitz     }
765*274fcceeSMax Reitz 
76609158f00SBenoît Canet     /* check the target bs is not blocked and block all operations on it */
76709158f00SBenoît Canet     if (s->replaces) {
7685a7e7a0bSStefan Hajnoczi         AioContext *replace_aio_context;
7695a7e7a0bSStefan Hajnoczi 
770e12f3784SWen Congyang         s->to_replace = bdrv_find_node(s->replaces);
77109158f00SBenoît Canet         if (!s->to_replace) {
772e12f3784SWen Congyang             error_setg(errp, "Node name '%s' not found", s->replaces);
77309158f00SBenoît Canet             return;
77409158f00SBenoît Canet         }
77509158f00SBenoît Canet 
7765a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(s->to_replace);
7775a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
7785a7e7a0bSStefan Hajnoczi 
77909158f00SBenoît Canet         error_setg(&s->replace_blocker,
78009158f00SBenoît Canet                    "block device is in use by block-job-complete");
78109158f00SBenoît Canet         bdrv_op_block_all(s->to_replace, s->replace_blocker);
78209158f00SBenoît Canet         bdrv_ref(s->to_replace);
7835a7e7a0bSStefan Hajnoczi 
7845a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
78509158f00SBenoît Canet     }
78609158f00SBenoît Canet 
787*274fcceeSMax Reitz     if (s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
788*274fcceeSMax Reitz         BlockDriverState *backing = s->is_none_mode ? src : s->base;
789*274fcceeSMax Reitz         if (backing_bs(target) != backing) {
790*274fcceeSMax Reitz             bdrv_set_backing_hd(target, backing);
791*274fcceeSMax Reitz         }
792*274fcceeSMax Reitz     }
793*274fcceeSMax Reitz 
794d63ffd87SPaolo Bonzini     s->should_complete = true;
795751ebd76SFam Zheng     block_job_enter(&s->common);
796d63ffd87SPaolo Bonzini }
797d63ffd87SPaolo Bonzini 
7983fc4b10aSFam Zheng static const BlockJobDriver mirror_job_driver = {
799893f7ebaSPaolo Bonzini     .instance_size = sizeof(MirrorBlockJob),
80079e14bf7SFam Zheng     .job_type      = BLOCK_JOB_TYPE_MIRROR,
801893f7ebaSPaolo Bonzini     .set_speed     = mirror_set_speed,
802d63ffd87SPaolo Bonzini     .complete      = mirror_complete,
803893f7ebaSPaolo Bonzini };
804893f7ebaSPaolo Bonzini 
80503544a6eSFam Zheng static const BlockJobDriver commit_active_job_driver = {
80603544a6eSFam Zheng     .instance_size = sizeof(MirrorBlockJob),
80703544a6eSFam Zheng     .job_type      = BLOCK_JOB_TYPE_COMMIT,
80803544a6eSFam Zheng     .set_speed     = mirror_set_speed,
80903544a6eSFam Zheng     .complete      = mirror_complete,
81003544a6eSFam Zheng };
81103544a6eSFam Zheng 
81203544a6eSFam Zheng static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,
81309158f00SBenoît Canet                              const char *replaces,
8145fba6c0eSJohn Snow                              int64_t speed, uint32_t granularity,
81503544a6eSFam Zheng                              int64_t buf_size,
816*274fcceeSMax Reitz                              BlockMirrorBackingMode backing_mode,
81703544a6eSFam Zheng                              BlockdevOnError on_source_error,
818b952b558SPaolo Bonzini                              BlockdevOnError on_target_error,
8190fc9f8eaSFam Zheng                              bool unmap,
820097310b5SMarkus Armbruster                              BlockCompletionFunc *cb,
82103544a6eSFam Zheng                              void *opaque, Error **errp,
82203544a6eSFam Zheng                              const BlockJobDriver *driver,
82303544a6eSFam Zheng                              bool is_none_mode, BlockDriverState *base)
824893f7ebaSPaolo Bonzini {
825893f7ebaSPaolo Bonzini     MirrorBlockJob *s;
826893f7ebaSPaolo Bonzini 
827eee13dfeSPaolo Bonzini     if (granularity == 0) {
828341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(target);
829eee13dfeSPaolo Bonzini     }
830eee13dfeSPaolo Bonzini 
831eee13dfeSPaolo Bonzini     assert ((granularity & (granularity - 1)) == 0);
832eee13dfeSPaolo Bonzini 
83348ac0a4dSWen Congyang     if (buf_size < 0) {
83448ac0a4dSWen Congyang         error_setg(errp, "Invalid parameter 'buf-size'");
83548ac0a4dSWen Congyang         return;
83648ac0a4dSWen Congyang     }
83748ac0a4dSWen Congyang 
83848ac0a4dSWen Congyang     if (buf_size == 0) {
83948ac0a4dSWen Congyang         buf_size = DEFAULT_MIRROR_BUF_SIZE;
84048ac0a4dSWen Congyang     }
8415bc361b8SFam Zheng 
84203544a6eSFam Zheng     s = block_job_create(driver, bs, speed, cb, opaque, errp);
843893f7ebaSPaolo Bonzini     if (!s) {
844893f7ebaSPaolo Bonzini         return;
845893f7ebaSPaolo Bonzini     }
846893f7ebaSPaolo Bonzini 
847e253f4b8SKevin Wolf     s->target = blk_new();
848e253f4b8SKevin Wolf     blk_insert_bs(s->target, target);
849e253f4b8SKevin Wolf 
85009158f00SBenoît Canet     s->replaces = g_strdup(replaces);
851b952b558SPaolo Bonzini     s->on_source_error = on_source_error;
852b952b558SPaolo Bonzini     s->on_target_error = on_target_error;
85303544a6eSFam Zheng     s->is_none_mode = is_none_mode;
854*274fcceeSMax Reitz     s->backing_mode = backing_mode;
8555bc361b8SFam Zheng     s->base = base;
856eee13dfeSPaolo Bonzini     s->granularity = granularity;
85748ac0a4dSWen Congyang     s->buf_size = ROUND_UP(buf_size, granularity);
8580fc9f8eaSFam Zheng     s->unmap = unmap;
859b812f671SPaolo Bonzini 
8600db6e54aSFam Zheng     s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
861b8afb520SFam Zheng     if (!s->dirty_bitmap) {
86297031164STing Wang         g_free(s->replaces);
863e253f4b8SKevin Wolf         blk_unref(s->target);
86418930ba3SFam Zheng         block_job_unref(&s->common);
865b8afb520SFam Zheng         return;
866b8afb520SFam Zheng     }
86710f3cd15SAlberto Garcia 
868e253f4b8SKevin Wolf     bdrv_op_block_all(target, s->common.blocker);
86910f3cd15SAlberto Garcia 
870893f7ebaSPaolo Bonzini     s->common.co = qemu_coroutine_create(mirror_run);
871893f7ebaSPaolo Bonzini     trace_mirror_start(bs, s, s->common.co, opaque);
872893f7ebaSPaolo Bonzini     qemu_coroutine_enter(s->common.co, s);
873893f7ebaSPaolo Bonzini }
87403544a6eSFam Zheng 
87503544a6eSFam Zheng void mirror_start(BlockDriverState *bs, BlockDriverState *target,
87609158f00SBenoît Canet                   const char *replaces,
8775fba6c0eSJohn Snow                   int64_t speed, uint32_t granularity, int64_t buf_size,
878*274fcceeSMax Reitz                   MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
879*274fcceeSMax Reitz                   BlockdevOnError on_source_error,
88003544a6eSFam Zheng                   BlockdevOnError on_target_error,
8810fc9f8eaSFam Zheng                   bool unmap,
882097310b5SMarkus Armbruster                   BlockCompletionFunc *cb,
88303544a6eSFam Zheng                   void *opaque, Error **errp)
88403544a6eSFam Zheng {
88503544a6eSFam Zheng     bool is_none_mode;
88603544a6eSFam Zheng     BlockDriverState *base;
88703544a6eSFam Zheng 
8884b80ab2bSJohn Snow     if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
8894b80ab2bSJohn Snow         error_setg(errp, "Sync mode 'incremental' not supported");
890d58d8453SJohn Snow         return;
891d58d8453SJohn Snow     }
89203544a6eSFam Zheng     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
893760e0063SKevin Wolf     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
89409158f00SBenoît Canet     mirror_start_job(bs, target, replaces,
895*274fcceeSMax Reitz                      speed, granularity, buf_size, backing_mode,
8960fc9f8eaSFam Zheng                      on_source_error, on_target_error, unmap, cb, opaque, errp,
89703544a6eSFam Zheng                      &mirror_job_driver, is_none_mode, base);
89803544a6eSFam Zheng }
89903544a6eSFam Zheng 
90003544a6eSFam Zheng void commit_active_start(BlockDriverState *bs, BlockDriverState *base,
90103544a6eSFam Zheng                          int64_t speed,
90203544a6eSFam Zheng                          BlockdevOnError on_error,
903097310b5SMarkus Armbruster                          BlockCompletionFunc *cb,
90403544a6eSFam Zheng                          void *opaque, Error **errp)
90503544a6eSFam Zheng {
9064da83585SJeff Cody     int64_t length, base_length;
9074da83585SJeff Cody     int orig_base_flags;
90839a611a3SJeff Cody     int ret;
909cc67f4d1SJeff Cody     Error *local_err = NULL;
9104da83585SJeff Cody 
9114da83585SJeff Cody     orig_base_flags = bdrv_get_flags(base);
9124da83585SJeff Cody 
91320a63d2cSFam Zheng     if (bdrv_reopen(base, bs->open_flags, errp)) {
91420a63d2cSFam Zheng         return;
91520a63d2cSFam Zheng     }
9164da83585SJeff Cody 
9174da83585SJeff Cody     length = bdrv_getlength(bs);
9184da83585SJeff Cody     if (length < 0) {
91939a611a3SJeff Cody         error_setg_errno(errp, -length,
92039a611a3SJeff Cody                          "Unable to determine length of %s", bs->filename);
9214da83585SJeff Cody         goto error_restore_flags;
9224da83585SJeff Cody     }
9234da83585SJeff Cody 
9244da83585SJeff Cody     base_length = bdrv_getlength(base);
9254da83585SJeff Cody     if (base_length < 0) {
92639a611a3SJeff Cody         error_setg_errno(errp, -base_length,
92739a611a3SJeff Cody                          "Unable to determine length of %s", base->filename);
9284da83585SJeff Cody         goto error_restore_flags;
9294da83585SJeff Cody     }
9304da83585SJeff Cody 
9314da83585SJeff Cody     if (length > base_length) {
93239a611a3SJeff Cody         ret = bdrv_truncate(base, length);
93339a611a3SJeff Cody         if (ret < 0) {
93439a611a3SJeff Cody             error_setg_errno(errp, -ret,
93539a611a3SJeff Cody                             "Top image %s is larger than base image %s, and "
9364da83585SJeff Cody                              "resize of base image failed",
9374da83585SJeff Cody                              bs->filename, base->filename);
9384da83585SJeff Cody             goto error_restore_flags;
9394da83585SJeff Cody         }
9404da83585SJeff Cody     }
9414da83585SJeff Cody 
942*274fcceeSMax Reitz     mirror_start_job(bs, base, NULL, speed, 0, 0, MIRROR_LEAVE_BACKING_CHAIN,
9430fc9f8eaSFam Zheng                      on_error, on_error, false, cb, opaque, &local_err,
94403544a6eSFam Zheng                      &commit_active_job_driver, false, base);
9450fb6395cSMarkus Armbruster     if (local_err) {
946cc67f4d1SJeff Cody         error_propagate(errp, local_err);
9474da83585SJeff Cody         goto error_restore_flags;
9484da83585SJeff Cody     }
9494da83585SJeff Cody 
9504da83585SJeff Cody     return;
9514da83585SJeff Cody 
9524da83585SJeff Cody error_restore_flags:
9534da83585SJeff Cody     /* ignore error and errp for bdrv_reopen, because we want to propagate
9544da83585SJeff Cody      * the original error */
9554da83585SJeff Cody     bdrv_reopen(base, orig_base_flags, NULL);
9564da83585SJeff Cody     return;
95703544a6eSFam Zheng }
958