xref: /qemu/block/mirror.c (revision ab27c3b5)
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"
2340365552SKevin Wolf #include "qemu/error-report.h"
24893f7ebaSPaolo Bonzini 
25893f7ebaSPaolo Bonzini #define SLICE_TIME    100000000ULL /* ns */
26402a4741SPaolo Bonzini #define MAX_IN_FLIGHT 16
2748ac0a4dSWen Congyang #define DEFAULT_MIRROR_BUF_SIZE   (10 << 20)
28402a4741SPaolo Bonzini 
29402a4741SPaolo Bonzini /* The mirroring buffer is a list of granularity-sized chunks.
30402a4741SPaolo Bonzini  * Free chunks are organized in a list.
31402a4741SPaolo Bonzini  */
32402a4741SPaolo Bonzini typedef struct MirrorBuffer {
33402a4741SPaolo Bonzini     QSIMPLEQ_ENTRY(MirrorBuffer) next;
34402a4741SPaolo Bonzini } MirrorBuffer;
35893f7ebaSPaolo Bonzini 
36893f7ebaSPaolo Bonzini typedef struct MirrorBlockJob {
37893f7ebaSPaolo Bonzini     BlockJob common;
38893f7ebaSPaolo Bonzini     RateLimit limit;
39893f7ebaSPaolo Bonzini     BlockDriverState *target;
405bc361b8SFam Zheng     BlockDriverState *base;
4109158f00SBenoît Canet     /* The name of the graph node to replace */
4209158f00SBenoît Canet     char *replaces;
4309158f00SBenoît Canet     /* The BDS to replace */
4409158f00SBenoît Canet     BlockDriverState *to_replace;
4509158f00SBenoît Canet     /* Used to block operations on the drive-mirror-replace target */
4609158f00SBenoît Canet     Error *replace_blocker;
4703544a6eSFam Zheng     bool is_none_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) {
83b952b558SPaolo Bonzini         return block_job_error_action(&s->common, s->common.bs,
84b952b558SPaolo Bonzini                                       s->on_source_error, true, error);
85b952b558SPaolo Bonzini     } else {
86b952b558SPaolo Bonzini         return block_job_error_action(&s->common, s->target,
87b952b558SPaolo Bonzini                                       s->on_target_error, 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     }
160bd48bde8SPaolo Bonzini     bdrv_aio_writev(s->target, op->sector_num, &op->qiov, op->nb_sectors,
161bd48bde8SPaolo Bonzini                     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) {
189e5b43573SFam Zheng         bdrv_round_to_clusters(s->target, *sector_num, *nb_sectors,
190e5b43573SFam Zheng                                &align_sector_num, &align_nb_sectors);
1918f0720ecSPaolo Bonzini     }
1928f0720ecSPaolo Bonzini 
193e5b43573SFam Zheng     if (align_nb_sectors > max_sectors) {
194e5b43573SFam Zheng         align_nb_sectors = max_sectors;
195e5b43573SFam Zheng         if (need_cow) {
196e5b43573SFam Zheng             align_nb_sectors = QEMU_ALIGN_DOWN(align_nb_sectors,
197e5b43573SFam Zheng                                                s->target_cluster_sectors);
198e5b43573SFam Zheng         }
199e5b43573SFam Zheng     }
2004150ae60SFam Zheng     /* Clipping may result in align_nb_sectors unaligned to chunk boundary, but
2014150ae60SFam Zheng      * that doesn't matter because it's already the end of source image. */
2024150ae60SFam Zheng     mirror_clip_sectors(s, align_sector_num, &align_nb_sectors);
203402a4741SPaolo Bonzini 
204e5b43573SFam Zheng     ret = align_sector_num + align_nb_sectors - (*sector_num + *nb_sectors);
205e5b43573SFam Zheng     *sector_num = align_sector_num;
206e5b43573SFam Zheng     *nb_sectors = align_nb_sectors;
207e5b43573SFam Zheng     assert(ret >= 0);
208e5b43573SFam Zheng     return ret;
209e5b43573SFam Zheng }
210e5b43573SFam Zheng 
21121cd917fSFam Zheng static inline void mirror_wait_for_io(MirrorBlockJob *s)
21221cd917fSFam Zheng {
21321cd917fSFam Zheng     assert(!s->waiting_for_io);
21421cd917fSFam Zheng     s->waiting_for_io = true;
21521cd917fSFam Zheng     qemu_coroutine_yield();
21621cd917fSFam Zheng     s->waiting_for_io = false;
21721cd917fSFam Zheng }
21821cd917fSFam Zheng 
219e5b43573SFam Zheng /* Submit async read while handling COW.
220e5b43573SFam Zheng  * Returns: nb_sectors if no alignment is necessary, or
221e5b43573SFam Zheng  *          (new_end - sector_num) if tail is rounded up or down due to
222e5b43573SFam Zheng  *          alignment or buffer limit.
223402a4741SPaolo Bonzini  */
224e5b43573SFam Zheng static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,
225e5b43573SFam Zheng                           int nb_sectors)
226e5b43573SFam Zheng {
227e5b43573SFam Zheng     BlockDriverState *source = s->common.bs;
228e5b43573SFam Zheng     int sectors_per_chunk, nb_chunks;
229e5b43573SFam Zheng     int ret = nb_sectors;
230e5b43573SFam Zheng     MirrorOp *op;
231402a4741SPaolo Bonzini 
232e5b43573SFam Zheng     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
233e5b43573SFam Zheng 
234e5b43573SFam Zheng     /* We can only handle as much as buf_size at a time. */
235e5b43573SFam Zheng     nb_sectors = MIN(s->buf_size >> BDRV_SECTOR_BITS, nb_sectors);
236e5b43573SFam Zheng     assert(nb_sectors);
237e5b43573SFam Zheng 
238e5b43573SFam Zheng     if (s->cow_bitmap) {
239e5b43573SFam Zheng         ret += mirror_cow_align(s, &sector_num, &nb_sectors);
240e5b43573SFam Zheng     }
241e5b43573SFam Zheng     assert(nb_sectors << BDRV_SECTOR_BITS <= s->buf_size);
242e5b43573SFam Zheng     /* The sector range must meet granularity because:
243e5b43573SFam Zheng      * 1) Caller passes in aligned values;
244e5b43573SFam Zheng      * 2) mirror_cow_align is used only when target cluster is larger. */
245e5b43573SFam Zheng     assert(!(sector_num % sectors_per_chunk));
2464150ae60SFam Zheng     nb_chunks = DIV_ROUND_UP(nb_sectors, sectors_per_chunk);
247e5b43573SFam Zheng 
248e5b43573SFam Zheng     while (s->buf_free_count < nb_chunks) {
249402a4741SPaolo Bonzini         trace_mirror_yield_in_flight(s, sector_num, s->in_flight);
25021cd917fSFam Zheng         mirror_wait_for_io(s);
251b812f671SPaolo Bonzini     }
252b812f671SPaolo Bonzini 
253bd48bde8SPaolo Bonzini     /* Allocate a MirrorOp that is used as an AIO callback.  */
254c84b3192SPaolo Bonzini     op = g_new(MirrorOp, 1);
255bd48bde8SPaolo Bonzini     op->s = s;
256bd48bde8SPaolo Bonzini     op->sector_num = sector_num;
257bd48bde8SPaolo Bonzini     op->nb_sectors = nb_sectors;
258402a4741SPaolo Bonzini 
259402a4741SPaolo Bonzini     /* Now make a QEMUIOVector taking enough granularity-sized chunks
260402a4741SPaolo Bonzini      * from s->buf_free.
261402a4741SPaolo Bonzini      */
262402a4741SPaolo Bonzini     qemu_iovec_init(&op->qiov, nb_chunks);
263402a4741SPaolo Bonzini     while (nb_chunks-- > 0) {
264402a4741SPaolo Bonzini         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
265e5b43573SFam Zheng         size_t remaining = nb_sectors * BDRV_SECTOR_SIZE - op->qiov.size;
2665a0f6fd5SKevin Wolf 
267402a4741SPaolo Bonzini         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
268402a4741SPaolo Bonzini         s->buf_free_count--;
2695a0f6fd5SKevin Wolf         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
270402a4741SPaolo Bonzini     }
271402a4741SPaolo Bonzini 
272893f7ebaSPaolo Bonzini     /* Copy the dirty cluster.  */
273bd48bde8SPaolo Bonzini     s->in_flight++;
274b21c7652SMax Reitz     s->sectors_in_flight += nb_sectors;
275b812f671SPaolo Bonzini     trace_mirror_one_iteration(s, sector_num, nb_sectors);
276dcfb3bebSFam Zheng 
277bd48bde8SPaolo Bonzini     bdrv_aio_readv(source, sector_num, &op->qiov, nb_sectors,
278bd48bde8SPaolo Bonzini                    mirror_read_complete, op);
279e5b43573SFam Zheng     return ret;
280e5b43573SFam Zheng }
281e5b43573SFam Zheng 
282e5b43573SFam Zheng static void mirror_do_zero_or_discard(MirrorBlockJob *s,
283e5b43573SFam Zheng                                       int64_t sector_num,
284e5b43573SFam Zheng                                       int nb_sectors,
285e5b43573SFam Zheng                                       bool is_discard)
286e5b43573SFam Zheng {
287e5b43573SFam Zheng     MirrorOp *op;
288e5b43573SFam Zheng 
289e5b43573SFam Zheng     /* Allocate a MirrorOp that is used as an AIO callback. The qiov is zeroed
290e5b43573SFam Zheng      * so the freeing in mirror_iteration_done is nop. */
291e5b43573SFam Zheng     op = g_new0(MirrorOp, 1);
292e5b43573SFam Zheng     op->s = s;
293e5b43573SFam Zheng     op->sector_num = sector_num;
294e5b43573SFam Zheng     op->nb_sectors = nb_sectors;
295e5b43573SFam Zheng 
296e5b43573SFam Zheng     s->in_flight++;
297e5b43573SFam Zheng     s->sectors_in_flight += nb_sectors;
298e5b43573SFam Zheng     if (is_discard) {
299e5b43573SFam Zheng         bdrv_aio_discard(s->target, sector_num, op->nb_sectors,
300e5b43573SFam Zheng                          mirror_write_complete, op);
301e5b43573SFam Zheng     } else {
302dcfb3bebSFam Zheng         bdrv_aio_write_zeroes(s->target, sector_num, op->nb_sectors,
303dcfb3bebSFam Zheng                               s->unmap ? BDRV_REQ_MAY_UNMAP : 0,
304dcfb3bebSFam Zheng                               mirror_write_complete, op);
305e5b43573SFam Zheng     }
306e5b43573SFam Zheng }
307e5b43573SFam Zheng 
308e5b43573SFam Zheng static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
309e5b43573SFam Zheng {
310e5b43573SFam Zheng     BlockDriverState *source = s->common.bs;
3119c83625bSMax Reitz     int64_t sector_num, first_chunk;
312e5b43573SFam Zheng     uint64_t delay_ns = 0;
313e5b43573SFam Zheng     /* At least the first dirty chunk is mirrored in one iteration. */
314e5b43573SFam Zheng     int nb_chunks = 1;
315e5b43573SFam Zheng     int64_t end = s->bdev_length / BDRV_SECTOR_SIZE;
316e5b43573SFam Zheng     int sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
317e5b43573SFam Zheng 
318e5b43573SFam Zheng     sector_num = hbitmap_iter_next(&s->hbi);
319e5b43573SFam Zheng     if (sector_num < 0) {
320e5b43573SFam Zheng         bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
321e5b43573SFam Zheng         sector_num = hbitmap_iter_next(&s->hbi);
322e5b43573SFam Zheng         trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
323e5b43573SFam Zheng         assert(sector_num >= 0);
324e5b43573SFam Zheng     }
325e5b43573SFam Zheng 
3269c83625bSMax Reitz     first_chunk = sector_num / sectors_per_chunk;
3279c83625bSMax Reitz     while (test_bit(first_chunk, s->in_flight_bitmap)) {
3289c83625bSMax Reitz         trace_mirror_yield_in_flight(s, first_chunk, s->in_flight);
3299c83625bSMax Reitz         mirror_wait_for_io(s);
3309c83625bSMax Reitz     }
3319c83625bSMax Reitz 
332e5b43573SFam Zheng     /* Find the number of consective dirty chunks following the first dirty
333e5b43573SFam Zheng      * one, and wait for in flight requests in them. */
334e5b43573SFam Zheng     while (nb_chunks * sectors_per_chunk < (s->buf_size >> BDRV_SECTOR_BITS)) {
335e5b43573SFam Zheng         int64_t hbitmap_next;
336e5b43573SFam Zheng         int64_t next_sector = sector_num + nb_chunks * sectors_per_chunk;
337e5b43573SFam Zheng         int64_t next_chunk = next_sector / sectors_per_chunk;
338e5b43573SFam Zheng         if (next_sector >= end ||
339e5b43573SFam Zheng             !bdrv_get_dirty(source, s->dirty_bitmap, next_sector)) {
340e5b43573SFam Zheng             break;
341e5b43573SFam Zheng         }
342e5b43573SFam Zheng         if (test_bit(next_chunk, s->in_flight_bitmap)) {
343e5b43573SFam Zheng             break;
344e5b43573SFam Zheng         }
3459c83625bSMax Reitz 
346e5b43573SFam Zheng         hbitmap_next = hbitmap_iter_next(&s->hbi);
347f27a2742SMax Reitz         if (hbitmap_next > next_sector || hbitmap_next < 0) {
348f27a2742SMax Reitz             /* The bitmap iterator's cache is stale, refresh it */
349f27a2742SMax Reitz             bdrv_set_dirty_iter(&s->hbi, next_sector);
350f27a2742SMax Reitz             hbitmap_next = hbitmap_iter_next(&s->hbi);
351f27a2742SMax Reitz         }
352e5b43573SFam Zheng         assert(hbitmap_next == next_sector);
353e5b43573SFam Zheng         nb_chunks++;
354e5b43573SFam Zheng     }
355e5b43573SFam Zheng 
356e5b43573SFam Zheng     /* Clear dirty bits before querying the block status, because
357e5b43573SFam Zheng      * calling bdrv_get_block_status_above could yield - if some blocks are
358e5b43573SFam Zheng      * marked dirty in this window, we need to know.
359e5b43573SFam Zheng      */
360e5b43573SFam Zheng     bdrv_reset_dirty_bitmap(s->dirty_bitmap, sector_num,
361e5b43573SFam Zheng                             nb_chunks * sectors_per_chunk);
362e5b43573SFam Zheng     bitmap_set(s->in_flight_bitmap, sector_num / sectors_per_chunk, nb_chunks);
363e5b43573SFam Zheng     while (nb_chunks > 0 && sector_num < end) {
364e5b43573SFam Zheng         int ret;
365e5b43573SFam Zheng         int io_sectors;
366e5b43573SFam Zheng         BlockDriverState *file;
367e5b43573SFam Zheng         enum MirrorMethod {
368e5b43573SFam Zheng             MIRROR_METHOD_COPY,
369e5b43573SFam Zheng             MIRROR_METHOD_ZERO,
370e5b43573SFam Zheng             MIRROR_METHOD_DISCARD
371e5b43573SFam Zheng         } mirror_method = MIRROR_METHOD_COPY;
372e5b43573SFam Zheng 
373e5b43573SFam Zheng         assert(!(sector_num % sectors_per_chunk));
374e5b43573SFam Zheng         ret = bdrv_get_block_status_above(source, NULL, sector_num,
375e5b43573SFam Zheng                                           nb_chunks * sectors_per_chunk,
376e5b43573SFam Zheng                                           &io_sectors, &file);
377e5b43573SFam Zheng         if (ret < 0) {
378e5b43573SFam Zheng             io_sectors = nb_chunks * sectors_per_chunk;
379e5b43573SFam Zheng         }
380e5b43573SFam Zheng 
381e5b43573SFam Zheng         io_sectors -= io_sectors % sectors_per_chunk;
382e5b43573SFam Zheng         if (io_sectors < sectors_per_chunk) {
383e5b43573SFam Zheng             io_sectors = sectors_per_chunk;
384e5b43573SFam Zheng         } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
385e5b43573SFam Zheng             int64_t target_sector_num;
386e5b43573SFam Zheng             int target_nb_sectors;
387e5b43573SFam Zheng             bdrv_round_to_clusters(s->target, sector_num, io_sectors,
388e5b43573SFam Zheng                                    &target_sector_num, &target_nb_sectors);
389e5b43573SFam Zheng             if (target_sector_num == sector_num &&
390e5b43573SFam Zheng                 target_nb_sectors == io_sectors) {
391e5b43573SFam Zheng                 mirror_method = ret & BDRV_BLOCK_ZERO ?
392e5b43573SFam Zheng                                     MIRROR_METHOD_ZERO :
393e5b43573SFam Zheng                                     MIRROR_METHOD_DISCARD;
394e5b43573SFam Zheng             }
395e5b43573SFam Zheng         }
396e5b43573SFam Zheng 
3974150ae60SFam Zheng         mirror_clip_sectors(s, sector_num, &io_sectors);
398e5b43573SFam Zheng         switch (mirror_method) {
399e5b43573SFam Zheng         case MIRROR_METHOD_COPY:
400e5b43573SFam Zheng             io_sectors = mirror_do_read(s, sector_num, io_sectors);
401e5b43573SFam Zheng             break;
402e5b43573SFam Zheng         case MIRROR_METHOD_ZERO:
403e5b43573SFam Zheng             mirror_do_zero_or_discard(s, sector_num, io_sectors, false);
404e5b43573SFam Zheng             break;
405e5b43573SFam Zheng         case MIRROR_METHOD_DISCARD:
406e5b43573SFam Zheng             mirror_do_zero_or_discard(s, sector_num, io_sectors, true);
407e5b43573SFam Zheng             break;
408e5b43573SFam Zheng         default:
409e5b43573SFam Zheng             abort();
410e5b43573SFam Zheng         }
411e5b43573SFam Zheng         assert(io_sectors);
412e5b43573SFam Zheng         sector_num += io_sectors;
4134150ae60SFam Zheng         nb_chunks -= DIV_ROUND_UP(io_sectors, sectors_per_chunk);
414e5b43573SFam Zheng         delay_ns += ratelimit_calculate_delay(&s->limit, io_sectors);
415dcfb3bebSFam Zheng     }
416cc8c9d6cSPaolo Bonzini     return delay_ns;
417893f7ebaSPaolo Bonzini }
418b952b558SPaolo Bonzini 
419402a4741SPaolo Bonzini static void mirror_free_init(MirrorBlockJob *s)
420402a4741SPaolo Bonzini {
421402a4741SPaolo Bonzini     int granularity = s->granularity;
422402a4741SPaolo Bonzini     size_t buf_size = s->buf_size;
423402a4741SPaolo Bonzini     uint8_t *buf = s->buf;
424402a4741SPaolo Bonzini 
425402a4741SPaolo Bonzini     assert(s->buf_free_count == 0);
426402a4741SPaolo Bonzini     QSIMPLEQ_INIT(&s->buf_free);
427402a4741SPaolo Bonzini     while (buf_size != 0) {
428402a4741SPaolo Bonzini         MirrorBuffer *cur = (MirrorBuffer *)buf;
429402a4741SPaolo Bonzini         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
430402a4741SPaolo Bonzini         s->buf_free_count++;
431402a4741SPaolo Bonzini         buf_size -= granularity;
432402a4741SPaolo Bonzini         buf += granularity;
433402a4741SPaolo Bonzini     }
434402a4741SPaolo Bonzini }
435402a4741SPaolo Bonzini 
436bd48bde8SPaolo Bonzini static void mirror_drain(MirrorBlockJob *s)
437bd48bde8SPaolo Bonzini {
438bd48bde8SPaolo Bonzini     while (s->in_flight > 0) {
43921cd917fSFam Zheng         mirror_wait_for_io(s);
440bd48bde8SPaolo Bonzini     }
441893f7ebaSPaolo Bonzini }
442893f7ebaSPaolo Bonzini 
4435a7e7a0bSStefan Hajnoczi typedef struct {
4445a7e7a0bSStefan Hajnoczi     int ret;
4455a7e7a0bSStefan Hajnoczi } MirrorExitData;
4465a7e7a0bSStefan Hajnoczi 
4475a7e7a0bSStefan Hajnoczi static void mirror_exit(BlockJob *job, void *opaque)
4485a7e7a0bSStefan Hajnoczi {
4495a7e7a0bSStefan Hajnoczi     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
4505a7e7a0bSStefan Hajnoczi     MirrorExitData *data = opaque;
4515a7e7a0bSStefan Hajnoczi     AioContext *replace_aio_context = NULL;
4523f09bfbcSKevin Wolf     BlockDriverState *src = s->common.bs;
4533f09bfbcSKevin Wolf 
4543f09bfbcSKevin Wolf     /* Make sure that the source BDS doesn't go away before we called
4553f09bfbcSKevin Wolf      * block_job_completed(). */
4563f09bfbcSKevin Wolf     bdrv_ref(src);
4575a7e7a0bSStefan Hajnoczi 
4585a7e7a0bSStefan Hajnoczi     if (s->to_replace) {
4595a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(s->to_replace);
4605a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
4615a7e7a0bSStefan Hajnoczi     }
4625a7e7a0bSStefan Hajnoczi 
4635a7e7a0bSStefan Hajnoczi     if (s->should_complete && data->ret == 0) {
4645a7e7a0bSStefan Hajnoczi         BlockDriverState *to_replace = s->common.bs;
4655a7e7a0bSStefan Hajnoczi         if (s->to_replace) {
4665a7e7a0bSStefan Hajnoczi             to_replace = s->to_replace;
4675a7e7a0bSStefan Hajnoczi         }
46840365552SKevin Wolf 
46940365552SKevin Wolf         /* This was checked in mirror_start_job(), but meanwhile one of the
47040365552SKevin Wolf          * nodes could have been newly attached to a BlockBackend. */
47140365552SKevin Wolf         if (to_replace->blk && s->target->blk) {
47240365552SKevin Wolf             error_report("block job: Can't create node with two BlockBackends");
47340365552SKevin Wolf             data->ret = -EINVAL;
47440365552SKevin Wolf             goto out;
47540365552SKevin Wolf         }
47640365552SKevin Wolf 
4775a7e7a0bSStefan Hajnoczi         if (bdrv_get_flags(s->target) != bdrv_get_flags(to_replace)) {
4785a7e7a0bSStefan Hajnoczi             bdrv_reopen(s->target, bdrv_get_flags(to_replace), NULL);
4795a7e7a0bSStefan Hajnoczi         }
4803f09bfbcSKevin Wolf         bdrv_replace_in_backing_chain(to_replace, s->target);
4815a7e7a0bSStefan Hajnoczi     }
48240365552SKevin Wolf 
48340365552SKevin Wolf out:
4845a7e7a0bSStefan Hajnoczi     if (s->to_replace) {
4855a7e7a0bSStefan Hajnoczi         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
4865a7e7a0bSStefan Hajnoczi         error_free(s->replace_blocker);
4875a7e7a0bSStefan Hajnoczi         bdrv_unref(s->to_replace);
4885a7e7a0bSStefan Hajnoczi     }
4895a7e7a0bSStefan Hajnoczi     if (replace_aio_context) {
4905a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
4915a7e7a0bSStefan Hajnoczi     }
4925a7e7a0bSStefan Hajnoczi     g_free(s->replaces);
49310f3cd15SAlberto Garcia     bdrv_op_unblock_all(s->target, s->common.blocker);
4945a7e7a0bSStefan Hajnoczi     bdrv_unref(s->target);
4955a7e7a0bSStefan Hajnoczi     block_job_completed(&s->common, data->ret);
4965a7e7a0bSStefan Hajnoczi     g_free(data);
497176c3699SFam Zheng     bdrv_drained_end(src);
498*ab27c3b5SFam Zheng     if (qemu_get_aio_context() == bdrv_get_aio_context(src)) {
499*ab27c3b5SFam Zheng         aio_enable_external(iohandler_get_aio_context());
500*ab27c3b5SFam Zheng     }
5013f09bfbcSKevin Wolf     bdrv_unref(src);
5025a7e7a0bSStefan Hajnoczi }
5035a7e7a0bSStefan Hajnoczi 
504893f7ebaSPaolo Bonzini static void coroutine_fn mirror_run(void *opaque)
505893f7ebaSPaolo Bonzini {
506893f7ebaSPaolo Bonzini     MirrorBlockJob *s = opaque;
5075a7e7a0bSStefan Hajnoczi     MirrorExitData *data;
508893f7ebaSPaolo Bonzini     BlockDriverState *bs = s->common.bs;
50999900697SFam Zheng     int64_t sector_num, end, length;
510bd48bde8SPaolo Bonzini     uint64_t last_pause_ns;
511b812f671SPaolo Bonzini     BlockDriverInfo bdi;
5121d33936eSJeff Cody     char backing_filename[2]; /* we only need 2 characters because we are only
5131d33936eSJeff Cody                                  checking for a NULL string */
514893f7ebaSPaolo Bonzini     int ret = 0;
515893f7ebaSPaolo Bonzini     int n;
516e5b43573SFam Zheng     int target_cluster_size = BDRV_SECTOR_SIZE;
517893f7ebaSPaolo Bonzini 
518893f7ebaSPaolo Bonzini     if (block_job_is_cancelled(&s->common)) {
519893f7ebaSPaolo Bonzini         goto immediate_exit;
520893f7ebaSPaolo Bonzini     }
521893f7ebaSPaolo Bonzini 
522b21c7652SMax Reitz     s->bdev_length = bdrv_getlength(bs);
523b21c7652SMax Reitz     if (s->bdev_length < 0) {
524b21c7652SMax Reitz         ret = s->bdev_length;
525373df5b1SFam Zheng         goto immediate_exit;
526b21c7652SMax Reitz     } else if (s->bdev_length == 0) {
5279e48b025SFam Zheng         /* Report BLOCK_JOB_READY and wait for complete. */
5289e48b025SFam Zheng         block_job_event_ready(&s->common);
5299e48b025SFam Zheng         s->synced = true;
5309e48b025SFam Zheng         while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
5319e48b025SFam Zheng             block_job_yield(&s->common);
5329e48b025SFam Zheng         }
5339e48b025SFam Zheng         s->common.cancelled = false;
5349e48b025SFam Zheng         goto immediate_exit;
535893f7ebaSPaolo Bonzini     }
536893f7ebaSPaolo Bonzini 
537b21c7652SMax Reitz     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
538402a4741SPaolo Bonzini     s->in_flight_bitmap = bitmap_new(length);
539402a4741SPaolo Bonzini 
540b812f671SPaolo Bonzini     /* If we have no backing file yet in the destination, we cannot let
541b812f671SPaolo Bonzini      * the destination do COW.  Instead, we copy sectors around the
542b812f671SPaolo Bonzini      * dirty data if needed.  We need a bitmap to do that.
543b812f671SPaolo Bonzini      */
544b812f671SPaolo Bonzini     bdrv_get_backing_filename(s->target, backing_filename,
545b812f671SPaolo Bonzini                               sizeof(backing_filename));
546e5b43573SFam Zheng     if (!bdrv_get_info(s->target, &bdi) && bdi.cluster_size) {
547e5b43573SFam Zheng         target_cluster_size = bdi.cluster_size;
548c3cc95bdSFam Zheng     }
549e5b43573SFam Zheng     if (backing_filename[0] && !s->target->backing
550e5b43573SFam Zheng         && s->granularity < target_cluster_size) {
551e5b43573SFam Zheng         s->buf_size = MAX(s->buf_size, target_cluster_size);
552b812f671SPaolo Bonzini         s->cow_bitmap = bitmap_new(length);
553b812f671SPaolo Bonzini     }
554e5b43573SFam Zheng     s->target_cluster_sectors = target_cluster_size >> BDRV_SECTOR_BITS;
555e5b43573SFam Zheng     s->max_iov = MIN(s->common.bs->bl.max_iov, s->target->bl.max_iov);
556b812f671SPaolo Bonzini 
557b21c7652SMax Reitz     end = s->bdev_length / BDRV_SECTOR_SIZE;
5587504edf4SKevin Wolf     s->buf = qemu_try_blockalign(bs, s->buf_size);
5597504edf4SKevin Wolf     if (s->buf == NULL) {
5607504edf4SKevin Wolf         ret = -ENOMEM;
5617504edf4SKevin Wolf         goto immediate_exit;
5627504edf4SKevin Wolf     }
5637504edf4SKevin Wolf 
564402a4741SPaolo Bonzini     mirror_free_init(s);
565893f7ebaSPaolo Bonzini 
5664c0cbd6fSFam Zheng     last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
56703544a6eSFam Zheng     if (!s->is_none_mode) {
568893f7ebaSPaolo Bonzini         /* First part, loop on the sectors and initialize the dirty bitmap.  */
5695bc361b8SFam Zheng         BlockDriverState *base = s->base;
5705279efebSJeff Cody         bool mark_all_dirty = s->base == NULL && !bdrv_has_zero_init(s->target);
5715279efebSJeff Cody 
572893f7ebaSPaolo Bonzini         for (sector_num = 0; sector_num < end; ) {
57399900697SFam Zheng             /* Just to make sure we are not exceeding int limit. */
57499900697SFam Zheng             int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,
57599900697SFam Zheng                                  end - sector_num);
5764c0cbd6fSFam Zheng             int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
5774c0cbd6fSFam Zheng 
5784c0cbd6fSFam Zheng             if (now - last_pause_ns > SLICE_TIME) {
5794c0cbd6fSFam Zheng                 last_pause_ns = now;
5804c0cbd6fSFam Zheng                 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, 0);
5814c0cbd6fSFam Zheng             }
5824c0cbd6fSFam Zheng 
5834c0cbd6fSFam Zheng             if (block_job_is_cancelled(&s->common)) {
5844c0cbd6fSFam Zheng                 goto immediate_exit;
5854c0cbd6fSFam Zheng             }
5864c0cbd6fSFam Zheng 
58799900697SFam Zheng             ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);
588893f7ebaSPaolo Bonzini 
589893f7ebaSPaolo Bonzini             if (ret < 0) {
590893f7ebaSPaolo Bonzini                 goto immediate_exit;
591893f7ebaSPaolo Bonzini             }
592893f7ebaSPaolo Bonzini 
593893f7ebaSPaolo Bonzini             assert(n > 0);
5945279efebSJeff Cody             if (ret == 1 || mark_all_dirty) {
59520dca810SJohn Snow                 bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);
596893f7ebaSPaolo Bonzini             }
59799900697SFam Zheng             sector_num += n;
598893f7ebaSPaolo Bonzini         }
599893f7ebaSPaolo Bonzini     }
600893f7ebaSPaolo Bonzini 
60120dca810SJohn Snow     bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
602893f7ebaSPaolo Bonzini     for (;;) {
603cc8c9d6cSPaolo Bonzini         uint64_t delay_ns = 0;
604893f7ebaSPaolo Bonzini         int64_t cnt;
605893f7ebaSPaolo Bonzini         bool should_complete;
606893f7ebaSPaolo Bonzini 
607bd48bde8SPaolo Bonzini         if (s->ret < 0) {
608bd48bde8SPaolo Bonzini             ret = s->ret;
609893f7ebaSPaolo Bonzini             goto immediate_exit;
610893f7ebaSPaolo Bonzini         }
611bd48bde8SPaolo Bonzini 
61220dca810SJohn Snow         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
613b21c7652SMax Reitz         /* s->common.offset contains the number of bytes already processed so
614b21c7652SMax Reitz          * far, cnt is the number of dirty sectors remaining and
615b21c7652SMax Reitz          * s->sectors_in_flight is the number of sectors currently being
616b21c7652SMax Reitz          * processed; together those are the current total operation length */
617b21c7652SMax Reitz         s->common.len = s->common.offset +
618b21c7652SMax Reitz                         (cnt + s->sectors_in_flight) * BDRV_SECTOR_SIZE;
619bd48bde8SPaolo Bonzini 
620bd48bde8SPaolo Bonzini         /* Note that even when no rate limit is applied we need to yield
621a7282330SFam Zheng          * periodically with no pending I/O so that bdrv_drain_all() returns.
622bd48bde8SPaolo Bonzini          * We do so every SLICE_TIME nanoseconds, or when there is an error,
623bd48bde8SPaolo Bonzini          * or when the source is clean, whichever comes first.
624bd48bde8SPaolo Bonzini          */
625bc72ad67SAlex Bligh         if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - last_pause_ns < SLICE_TIME &&
626bd48bde8SPaolo Bonzini             s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
627402a4741SPaolo Bonzini             if (s->in_flight == MAX_IN_FLIGHT || s->buf_free_count == 0 ||
628402a4741SPaolo Bonzini                 (cnt == 0 && s->in_flight > 0)) {
629402a4741SPaolo Bonzini                 trace_mirror_yield(s, s->in_flight, s->buf_free_count, cnt);
63021cd917fSFam Zheng                 mirror_wait_for_io(s);
631bd48bde8SPaolo Bonzini                 continue;
632bd48bde8SPaolo Bonzini             } else if (cnt != 0) {
633cc8c9d6cSPaolo Bonzini                 delay_ns = mirror_iteration(s);
634893f7ebaSPaolo Bonzini             }
635cc8c9d6cSPaolo Bonzini         }
636893f7ebaSPaolo Bonzini 
637893f7ebaSPaolo Bonzini         should_complete = false;
638bd48bde8SPaolo Bonzini         if (s->in_flight == 0 && cnt == 0) {
639893f7ebaSPaolo Bonzini             trace_mirror_before_flush(s);
640893f7ebaSPaolo Bonzini             ret = bdrv_flush(s->target);
641893f7ebaSPaolo Bonzini             if (ret < 0) {
642a589569fSWenchao Xia                 if (mirror_error_action(s, false, -ret) ==
643a589569fSWenchao Xia                     BLOCK_ERROR_ACTION_REPORT) {
644893f7ebaSPaolo Bonzini                     goto immediate_exit;
645893f7ebaSPaolo Bonzini                 }
646b952b558SPaolo Bonzini             } else {
647893f7ebaSPaolo Bonzini                 /* We're out of the streaming phase.  From now on, if the job
648893f7ebaSPaolo Bonzini                  * is cancelled we will actually complete all pending I/O and
649893f7ebaSPaolo Bonzini                  * report completion.  This way, block-job-cancel will leave
650893f7ebaSPaolo Bonzini                  * the target in a consistent state.
651893f7ebaSPaolo Bonzini                  */
652d63ffd87SPaolo Bonzini                 if (!s->synced) {
653bcada37bSWenchao Xia                     block_job_event_ready(&s->common);
654d63ffd87SPaolo Bonzini                     s->synced = true;
655d63ffd87SPaolo Bonzini                 }
656d63ffd87SPaolo Bonzini 
657d63ffd87SPaolo Bonzini                 should_complete = s->should_complete ||
658d63ffd87SPaolo Bonzini                     block_job_is_cancelled(&s->common);
65920dca810SJohn Snow                 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
660893f7ebaSPaolo Bonzini             }
661b952b558SPaolo Bonzini         }
662893f7ebaSPaolo Bonzini 
663893f7ebaSPaolo Bonzini         if (cnt == 0 && should_complete) {
664893f7ebaSPaolo Bonzini             /* The dirty bitmap is not updated while operations are pending.
665893f7ebaSPaolo Bonzini              * If we're about to exit, wait for pending operations before
666893f7ebaSPaolo Bonzini              * calling bdrv_get_dirty_count(bs), or we may exit while the
667893f7ebaSPaolo Bonzini              * source has dirty data to copy!
668893f7ebaSPaolo Bonzini              *
669893f7ebaSPaolo Bonzini              * Note that I/O can be submitted by the guest while
670893f7ebaSPaolo Bonzini              * mirror_populate runs.
671893f7ebaSPaolo Bonzini              */
672893f7ebaSPaolo Bonzini             trace_mirror_before_drain(s, cnt);
67339bf92ddSFam Zheng             bdrv_co_drain(bs);
67420dca810SJohn Snow             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
675893f7ebaSPaolo Bonzini         }
676893f7ebaSPaolo Bonzini 
677893f7ebaSPaolo Bonzini         ret = 0;
678cc8c9d6cSPaolo Bonzini         trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
679d63ffd87SPaolo Bonzini         if (!s->synced) {
6807483d1e5SAlex Bligh             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
681893f7ebaSPaolo Bonzini             if (block_job_is_cancelled(&s->common)) {
682893f7ebaSPaolo Bonzini                 break;
683893f7ebaSPaolo Bonzini             }
684893f7ebaSPaolo Bonzini         } else if (!should_complete) {
685bd48bde8SPaolo Bonzini             delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
6867483d1e5SAlex Bligh             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
687893f7ebaSPaolo Bonzini         } else if (cnt == 0) {
688893f7ebaSPaolo Bonzini             /* The two disks are in sync.  Exit and report successful
689893f7ebaSPaolo Bonzini              * completion.
690893f7ebaSPaolo Bonzini              */
691893f7ebaSPaolo Bonzini             assert(QLIST_EMPTY(&bs->tracked_requests));
692893f7ebaSPaolo Bonzini             s->common.cancelled = false;
693893f7ebaSPaolo Bonzini             break;
694893f7ebaSPaolo Bonzini         }
695bc72ad67SAlex Bligh         last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
696893f7ebaSPaolo Bonzini     }
697893f7ebaSPaolo Bonzini 
698893f7ebaSPaolo Bonzini immediate_exit:
699bd48bde8SPaolo Bonzini     if (s->in_flight > 0) {
700bd48bde8SPaolo Bonzini         /* We get here only if something went wrong.  Either the job failed,
701bd48bde8SPaolo Bonzini          * or it was cancelled prematurely so that we do not guarantee that
702bd48bde8SPaolo Bonzini          * the target is a copy of the source.
703bd48bde8SPaolo Bonzini          */
704bd48bde8SPaolo Bonzini         assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));
705bd48bde8SPaolo Bonzini         mirror_drain(s);
706bd48bde8SPaolo Bonzini     }
707bd48bde8SPaolo Bonzini 
708bd48bde8SPaolo Bonzini     assert(s->in_flight == 0);
7097191bf31SMarkus Armbruster     qemu_vfree(s->buf);
710b812f671SPaolo Bonzini     g_free(s->cow_bitmap);
711402a4741SPaolo Bonzini     g_free(s->in_flight_bitmap);
712e4654d2dSFam Zheng     bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);
713373340b2SMax Reitz     if (s->target->blk) {
714373340b2SMax Reitz         blk_iostatus_disable(s->target->blk);
715373340b2SMax Reitz     }
7165a7e7a0bSStefan Hajnoczi 
7175a7e7a0bSStefan Hajnoczi     data = g_malloc(sizeof(*data));
7185a7e7a0bSStefan Hajnoczi     data->ret = ret;
719176c3699SFam Zheng     /* Before we switch to target in mirror_exit, make sure data doesn't
720176c3699SFam Zheng      * change. */
721176c3699SFam Zheng     bdrv_drained_begin(s->common.bs);
722*ab27c3b5SFam Zheng     if (qemu_get_aio_context() == bdrv_get_aio_context(bs)) {
723*ab27c3b5SFam Zheng         /* FIXME: virtio host notifiers run on iohandler_ctx, therefore the
724*ab27c3b5SFam Zheng          * above bdrv_drained_end isn't enough to quiesce it. This is ugly, we
725*ab27c3b5SFam Zheng          * need a block layer API change to achieve this. */
726*ab27c3b5SFam Zheng         aio_disable_external(iohandler_get_aio_context());
727*ab27c3b5SFam Zheng     }
7285a7e7a0bSStefan Hajnoczi     block_job_defer_to_main_loop(&s->common, mirror_exit, data);
729893f7ebaSPaolo Bonzini }
730893f7ebaSPaolo Bonzini 
731893f7ebaSPaolo Bonzini static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)
732893f7ebaSPaolo Bonzini {
733893f7ebaSPaolo Bonzini     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
734893f7ebaSPaolo Bonzini 
735893f7ebaSPaolo Bonzini     if (speed < 0) {
736c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER, "speed");
737893f7ebaSPaolo Bonzini         return;
738893f7ebaSPaolo Bonzini     }
739893f7ebaSPaolo Bonzini     ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
740893f7ebaSPaolo Bonzini }
741893f7ebaSPaolo Bonzini 
742b952b558SPaolo Bonzini static void mirror_iostatus_reset(BlockJob *job)
743b952b558SPaolo Bonzini {
744b952b558SPaolo Bonzini     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
745b952b558SPaolo Bonzini 
746373340b2SMax Reitz     if (s->target->blk) {
747373340b2SMax Reitz         blk_iostatus_reset(s->target->blk);
748373340b2SMax Reitz     }
749b952b558SPaolo Bonzini }
750b952b558SPaolo Bonzini 
751d63ffd87SPaolo Bonzini static void mirror_complete(BlockJob *job, Error **errp)
752d63ffd87SPaolo Bonzini {
753d63ffd87SPaolo Bonzini     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
75434b5d2c6SMax Reitz     Error *local_err = NULL;
755d63ffd87SPaolo Bonzini     int ret;
756d63ffd87SPaolo Bonzini 
757d9b7b057SKevin Wolf     ret = bdrv_open_backing_file(s->target, NULL, "backing", &local_err);
758d63ffd87SPaolo Bonzini     if (ret < 0) {
75934b5d2c6SMax Reitz         error_propagate(errp, local_err);
760d63ffd87SPaolo Bonzini         return;
761d63ffd87SPaolo Bonzini     }
762d63ffd87SPaolo Bonzini     if (!s->synced) {
7638ccb9569SKevin Wolf         error_setg(errp, QERR_BLOCK_JOB_NOT_READY, job->id);
764d63ffd87SPaolo Bonzini         return;
765d63ffd87SPaolo Bonzini     }
766d63ffd87SPaolo Bonzini 
76709158f00SBenoît Canet     /* check the target bs is not blocked and block all operations on it */
76809158f00SBenoît Canet     if (s->replaces) {
7695a7e7a0bSStefan Hajnoczi         AioContext *replace_aio_context;
7705a7e7a0bSStefan Hajnoczi 
771e12f3784SWen Congyang         s->to_replace = bdrv_find_node(s->replaces);
77209158f00SBenoît Canet         if (!s->to_replace) {
773e12f3784SWen Congyang             error_setg(errp, "Node name '%s' not found", s->replaces);
77409158f00SBenoît Canet             return;
77509158f00SBenoît Canet         }
77609158f00SBenoît Canet 
7775a7e7a0bSStefan Hajnoczi         replace_aio_context = bdrv_get_aio_context(s->to_replace);
7785a7e7a0bSStefan Hajnoczi         aio_context_acquire(replace_aio_context);
7795a7e7a0bSStefan Hajnoczi 
78009158f00SBenoît Canet         error_setg(&s->replace_blocker,
78109158f00SBenoît Canet                    "block device is in use by block-job-complete");
78209158f00SBenoît Canet         bdrv_op_block_all(s->to_replace, s->replace_blocker);
78309158f00SBenoît Canet         bdrv_ref(s->to_replace);
7845a7e7a0bSStefan Hajnoczi 
7855a7e7a0bSStefan Hajnoczi         aio_context_release(replace_aio_context);
78609158f00SBenoît Canet     }
78709158f00SBenoît Canet 
788d63ffd87SPaolo Bonzini     s->should_complete = true;
789751ebd76SFam Zheng     block_job_enter(&s->common);
790d63ffd87SPaolo Bonzini }
791d63ffd87SPaolo Bonzini 
7923fc4b10aSFam Zheng static const BlockJobDriver mirror_job_driver = {
793893f7ebaSPaolo Bonzini     .instance_size = sizeof(MirrorBlockJob),
79479e14bf7SFam Zheng     .job_type      = BLOCK_JOB_TYPE_MIRROR,
795893f7ebaSPaolo Bonzini     .set_speed     = mirror_set_speed,
796b952b558SPaolo Bonzini     .iostatus_reset= mirror_iostatus_reset,
797d63ffd87SPaolo Bonzini     .complete      = mirror_complete,
798893f7ebaSPaolo Bonzini };
799893f7ebaSPaolo Bonzini 
80003544a6eSFam Zheng static const BlockJobDriver commit_active_job_driver = {
80103544a6eSFam Zheng     .instance_size = sizeof(MirrorBlockJob),
80203544a6eSFam Zheng     .job_type      = BLOCK_JOB_TYPE_COMMIT,
80303544a6eSFam Zheng     .set_speed     = mirror_set_speed,
80403544a6eSFam Zheng     .iostatus_reset
80503544a6eSFam Zheng                    = mirror_iostatus_reset,
80603544a6eSFam Zheng     .complete      = mirror_complete,
80703544a6eSFam Zheng };
80803544a6eSFam Zheng 
80903544a6eSFam Zheng static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,
81009158f00SBenoît Canet                              const char *replaces,
8115fba6c0eSJohn Snow                              int64_t speed, uint32_t granularity,
81203544a6eSFam Zheng                              int64_t buf_size,
81303544a6eSFam Zheng                              BlockdevOnError on_source_error,
814b952b558SPaolo Bonzini                              BlockdevOnError on_target_error,
8150fc9f8eaSFam Zheng                              bool unmap,
816097310b5SMarkus Armbruster                              BlockCompletionFunc *cb,
81703544a6eSFam Zheng                              void *opaque, Error **errp,
81803544a6eSFam Zheng                              const BlockJobDriver *driver,
81903544a6eSFam Zheng                              bool is_none_mode, BlockDriverState *base)
820893f7ebaSPaolo Bonzini {
821893f7ebaSPaolo Bonzini     MirrorBlockJob *s;
82240365552SKevin Wolf     BlockDriverState *replaced_bs;
823893f7ebaSPaolo Bonzini 
824eee13dfeSPaolo Bonzini     if (granularity == 0) {
825341ebc2fSJohn Snow         granularity = bdrv_get_default_bitmap_granularity(target);
826eee13dfeSPaolo Bonzini     }
827eee13dfeSPaolo Bonzini 
828eee13dfeSPaolo Bonzini     assert ((granularity & (granularity - 1)) == 0);
829eee13dfeSPaolo Bonzini 
830b952b558SPaolo Bonzini     if ((on_source_error == BLOCKDEV_ON_ERROR_STOP ||
831b952b558SPaolo Bonzini          on_source_error == BLOCKDEV_ON_ERROR_ENOSPC) &&
832373340b2SMax Reitz         (!bs->blk || !blk_iostatus_is_enabled(bs->blk))) {
833c6bd8c70SMarkus Armbruster         error_setg(errp, QERR_INVALID_PARAMETER, "on-source-error");
834b952b558SPaolo Bonzini         return;
835b952b558SPaolo Bonzini     }
836b952b558SPaolo Bonzini 
83748ac0a4dSWen Congyang     if (buf_size < 0) {
83848ac0a4dSWen Congyang         error_setg(errp, "Invalid parameter 'buf-size'");
83948ac0a4dSWen Congyang         return;
84048ac0a4dSWen Congyang     }
84148ac0a4dSWen Congyang 
84248ac0a4dSWen Congyang     if (buf_size == 0) {
84348ac0a4dSWen Congyang         buf_size = DEFAULT_MIRROR_BUF_SIZE;
84448ac0a4dSWen Congyang     }
8455bc361b8SFam Zheng 
84640365552SKevin Wolf     /* We can't support this case as long as the block layer can't handle
84740365552SKevin Wolf      * multiple BlockBackends per BlockDriverState. */
84840365552SKevin Wolf     if (replaces) {
84940365552SKevin Wolf         replaced_bs = bdrv_lookup_bs(replaces, replaces, errp);
85040365552SKevin Wolf         if (replaced_bs == NULL) {
85140365552SKevin Wolf             return;
85240365552SKevin Wolf         }
85340365552SKevin Wolf     } else {
85440365552SKevin Wolf         replaced_bs = bs;
85540365552SKevin Wolf     }
85640365552SKevin Wolf     if (replaced_bs->blk && target->blk) {
85740365552SKevin Wolf         error_setg(errp, "Can't create node with two BlockBackends");
85840365552SKevin Wolf         return;
85940365552SKevin Wolf     }
86040365552SKevin Wolf 
86103544a6eSFam Zheng     s = block_job_create(driver, bs, speed, cb, opaque, errp);
862893f7ebaSPaolo Bonzini     if (!s) {
863893f7ebaSPaolo Bonzini         return;
864893f7ebaSPaolo Bonzini     }
865893f7ebaSPaolo Bonzini 
86609158f00SBenoît Canet     s->replaces = g_strdup(replaces);
867b952b558SPaolo Bonzini     s->on_source_error = on_source_error;
868b952b558SPaolo Bonzini     s->on_target_error = on_target_error;
869893f7ebaSPaolo Bonzini     s->target = target;
87003544a6eSFam Zheng     s->is_none_mode = is_none_mode;
8715bc361b8SFam Zheng     s->base = base;
872eee13dfeSPaolo Bonzini     s->granularity = granularity;
87348ac0a4dSWen Congyang     s->buf_size = ROUND_UP(buf_size, granularity);
8740fc9f8eaSFam Zheng     s->unmap = unmap;
875b812f671SPaolo Bonzini 
8760db6e54aSFam Zheng     s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
877b8afb520SFam Zheng     if (!s->dirty_bitmap) {
87897031164STing Wang         g_free(s->replaces);
87918930ba3SFam Zheng         block_job_unref(&s->common);
880b8afb520SFam Zheng         return;
881b8afb520SFam Zheng     }
88210f3cd15SAlberto Garcia 
88310f3cd15SAlberto Garcia     bdrv_op_block_all(s->target, s->common.blocker);
88410f3cd15SAlberto Garcia 
885373340b2SMax Reitz     if (s->target->blk) {
886373340b2SMax Reitz         blk_set_on_error(s->target->blk, on_target_error, on_target_error);
887373340b2SMax Reitz         blk_iostatus_enable(s->target->blk);
888373340b2SMax Reitz     }
889893f7ebaSPaolo Bonzini     s->common.co = qemu_coroutine_create(mirror_run);
890893f7ebaSPaolo Bonzini     trace_mirror_start(bs, s, s->common.co, opaque);
891893f7ebaSPaolo Bonzini     qemu_coroutine_enter(s->common.co, s);
892893f7ebaSPaolo Bonzini }
89303544a6eSFam Zheng 
89403544a6eSFam Zheng void mirror_start(BlockDriverState *bs, BlockDriverState *target,
89509158f00SBenoît Canet                   const char *replaces,
8965fba6c0eSJohn Snow                   int64_t speed, uint32_t granularity, int64_t buf_size,
89703544a6eSFam Zheng                   MirrorSyncMode mode, BlockdevOnError on_source_error,
89803544a6eSFam Zheng                   BlockdevOnError on_target_error,
8990fc9f8eaSFam Zheng                   bool unmap,
900097310b5SMarkus Armbruster                   BlockCompletionFunc *cb,
90103544a6eSFam Zheng                   void *opaque, Error **errp)
90203544a6eSFam Zheng {
90303544a6eSFam Zheng     bool is_none_mode;
90403544a6eSFam Zheng     BlockDriverState *base;
90503544a6eSFam Zheng 
9064b80ab2bSJohn Snow     if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
9074b80ab2bSJohn Snow         error_setg(errp, "Sync mode 'incremental' not supported");
908d58d8453SJohn Snow         return;
909d58d8453SJohn Snow     }
91003544a6eSFam Zheng     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
911760e0063SKevin Wolf     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
91209158f00SBenoît Canet     mirror_start_job(bs, target, replaces,
91309158f00SBenoît Canet                      speed, granularity, buf_size,
9140fc9f8eaSFam Zheng                      on_source_error, on_target_error, unmap, cb, opaque, errp,
91503544a6eSFam Zheng                      &mirror_job_driver, is_none_mode, base);
91603544a6eSFam Zheng }
91703544a6eSFam Zheng 
91803544a6eSFam Zheng void commit_active_start(BlockDriverState *bs, BlockDriverState *base,
91903544a6eSFam Zheng                          int64_t speed,
92003544a6eSFam Zheng                          BlockdevOnError on_error,
921097310b5SMarkus Armbruster                          BlockCompletionFunc *cb,
92203544a6eSFam Zheng                          void *opaque, Error **errp)
92303544a6eSFam Zheng {
9244da83585SJeff Cody     int64_t length, base_length;
9254da83585SJeff Cody     int orig_base_flags;
92639a611a3SJeff Cody     int ret;
927cc67f4d1SJeff Cody     Error *local_err = NULL;
9284da83585SJeff Cody 
9294da83585SJeff Cody     orig_base_flags = bdrv_get_flags(base);
9304da83585SJeff Cody 
93120a63d2cSFam Zheng     if (bdrv_reopen(base, bs->open_flags, errp)) {
93220a63d2cSFam Zheng         return;
93320a63d2cSFam Zheng     }
9344da83585SJeff Cody 
9354da83585SJeff Cody     length = bdrv_getlength(bs);
9364da83585SJeff Cody     if (length < 0) {
93739a611a3SJeff Cody         error_setg_errno(errp, -length,
93839a611a3SJeff Cody                          "Unable to determine length of %s", bs->filename);
9394da83585SJeff Cody         goto error_restore_flags;
9404da83585SJeff Cody     }
9414da83585SJeff Cody 
9424da83585SJeff Cody     base_length = bdrv_getlength(base);
9434da83585SJeff Cody     if (base_length < 0) {
94439a611a3SJeff Cody         error_setg_errno(errp, -base_length,
94539a611a3SJeff Cody                          "Unable to determine length of %s", base->filename);
9464da83585SJeff Cody         goto error_restore_flags;
9474da83585SJeff Cody     }
9484da83585SJeff Cody 
9494da83585SJeff Cody     if (length > base_length) {
95039a611a3SJeff Cody         ret = bdrv_truncate(base, length);
95139a611a3SJeff Cody         if (ret < 0) {
95239a611a3SJeff Cody             error_setg_errno(errp, -ret,
95339a611a3SJeff Cody                             "Top image %s is larger than base image %s, and "
9544da83585SJeff Cody                              "resize of base image failed",
9554da83585SJeff Cody                              bs->filename, base->filename);
9564da83585SJeff Cody             goto error_restore_flags;
9574da83585SJeff Cody         }
9584da83585SJeff Cody     }
9594da83585SJeff Cody 
96020a63d2cSFam Zheng     bdrv_ref(base);
96109158f00SBenoît Canet     mirror_start_job(bs, base, NULL, speed, 0, 0,
9620fc9f8eaSFam Zheng                      on_error, on_error, false, cb, opaque, &local_err,
96303544a6eSFam Zheng                      &commit_active_job_driver, false, base);
9640fb6395cSMarkus Armbruster     if (local_err) {
965cc67f4d1SJeff Cody         error_propagate(errp, local_err);
9664da83585SJeff Cody         goto error_restore_flags;
9674da83585SJeff Cody     }
9684da83585SJeff Cody 
9694da83585SJeff Cody     return;
9704da83585SJeff Cody 
9714da83585SJeff Cody error_restore_flags:
9724da83585SJeff Cody     /* ignore error and errp for bdrv_reopen, because we want to propagate
9734da83585SJeff Cody      * the original error */
9744da83585SJeff Cody     bdrv_reopen(base, orig_base_flags, NULL);
9754da83585SJeff Cody     return;
97603544a6eSFam Zheng }
977