xref: /qemu/block/mirror.c (revision 52ea63de)
1 /*
2  * Image mirroring
3  *
4  * Copyright Red Hat, Inc. 2012
5  *
6  * Authors:
7  *  Paolo Bonzini  <pbonzini@redhat.com>
8  *
9  * This work is licensed under the terms of the GNU LGPL, version 2 or later.
10  * See the COPYING.LIB file in the top-level directory.
11  *
12  */
13 
14 #include "qemu/osdep.h"
15 #include "trace.h"
16 #include "block/blockjob.h"
17 #include "block/block_int.h"
18 #include "sysemu/block-backend.h"
19 #include "qapi/error.h"
20 #include "qapi/qmp/qerror.h"
21 #include "qemu/ratelimit.h"
22 #include "qemu/bitmap.h"
23 
24 #define SLICE_TIME    100000000ULL /* ns */
25 #define MAX_IN_FLIGHT 16
26 #define DEFAULT_MIRROR_BUF_SIZE   (10 << 20)
27 
28 /* The mirroring buffer is a list of granularity-sized chunks.
29  * Free chunks are organized in a list.
30  */
31 typedef struct MirrorBuffer {
32     QSIMPLEQ_ENTRY(MirrorBuffer) next;
33 } MirrorBuffer;
34 
35 typedef struct MirrorBlockJob {
36     BlockJob common;
37     RateLimit limit;
38     BlockBackend *target;
39     BlockDriverState *base;
40     /* The name of the graph node to replace */
41     char *replaces;
42     /* The BDS to replace */
43     BlockDriverState *to_replace;
44     /* Used to block operations on the drive-mirror-replace target */
45     Error *replace_blocker;
46     bool is_none_mode;
47     BlockdevOnError on_source_error, on_target_error;
48     bool synced;
49     bool should_complete;
50     int64_t granularity;
51     size_t buf_size;
52     int64_t bdev_length;
53     unsigned long *cow_bitmap;
54     BdrvDirtyBitmap *dirty_bitmap;
55     HBitmapIter hbi;
56     uint8_t *buf;
57     QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
58     int buf_free_count;
59 
60     unsigned long *in_flight_bitmap;
61     int in_flight;
62     int sectors_in_flight;
63     int ret;
64     bool unmap;
65     bool waiting_for_io;
66     int target_cluster_sectors;
67     int max_iov;
68 } MirrorBlockJob;
69 
70 typedef struct MirrorOp {
71     MirrorBlockJob *s;
72     QEMUIOVector qiov;
73     int64_t sector_num;
74     int nb_sectors;
75 } MirrorOp;
76 
77 static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
78                                             int error)
79 {
80     s->synced = false;
81     if (read) {
82         return block_job_error_action(&s->common, s->on_source_error,
83                                       true, error);
84     } else {
85         return block_job_error_action(&s->common, s->on_target_error,
86                                       false, error);
87     }
88 }
89 
90 static void mirror_iteration_done(MirrorOp *op, int ret)
91 {
92     MirrorBlockJob *s = op->s;
93     struct iovec *iov;
94     int64_t chunk_num;
95     int i, nb_chunks, sectors_per_chunk;
96 
97     trace_mirror_iteration_done(s, op->sector_num, op->nb_sectors, ret);
98 
99     s->in_flight--;
100     s->sectors_in_flight -= op->nb_sectors;
101     iov = op->qiov.iov;
102     for (i = 0; i < op->qiov.niov; i++) {
103         MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
104         QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
105         s->buf_free_count++;
106     }
107 
108     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
109     chunk_num = op->sector_num / sectors_per_chunk;
110     nb_chunks = DIV_ROUND_UP(op->nb_sectors, sectors_per_chunk);
111     bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
112     if (ret >= 0) {
113         if (s->cow_bitmap) {
114             bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
115         }
116         s->common.offset += (uint64_t)op->nb_sectors * BDRV_SECTOR_SIZE;
117     }
118 
119     qemu_iovec_destroy(&op->qiov);
120     g_free(op);
121 
122     if (s->waiting_for_io) {
123         qemu_coroutine_enter(s->common.co, NULL);
124     }
125 }
126 
127 static void mirror_write_complete(void *opaque, int ret)
128 {
129     MirrorOp *op = opaque;
130     MirrorBlockJob *s = op->s;
131     if (ret < 0) {
132         BlockErrorAction action;
133 
134         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);
135         action = mirror_error_action(s, false, -ret);
136         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
137             s->ret = ret;
138         }
139     }
140     mirror_iteration_done(op, ret);
141 }
142 
143 static void mirror_read_complete(void *opaque, int ret)
144 {
145     MirrorOp *op = opaque;
146     MirrorBlockJob *s = op->s;
147     if (ret < 0) {
148         BlockErrorAction action;
149 
150         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);
151         action = mirror_error_action(s, true, -ret);
152         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
153             s->ret = ret;
154         }
155 
156         mirror_iteration_done(op, ret);
157         return;
158     }
159     blk_aio_pwritev(s->target, op->sector_num * BDRV_SECTOR_SIZE, &op->qiov,
160                     op->nb_sectors * BDRV_SECTOR_SIZE,
161                     mirror_write_complete, op);
162 }
163 
164 static inline void mirror_clip_sectors(MirrorBlockJob *s,
165                                        int64_t sector_num,
166                                        int *nb_sectors)
167 {
168     *nb_sectors = MIN(*nb_sectors,
169                       s->bdev_length / BDRV_SECTOR_SIZE - sector_num);
170 }
171 
172 /* Round sector_num and/or nb_sectors to target cluster if COW is needed, and
173  * return the offset of the adjusted tail sector against original. */
174 static int mirror_cow_align(MirrorBlockJob *s,
175                             int64_t *sector_num,
176                             int *nb_sectors)
177 {
178     bool need_cow;
179     int ret = 0;
180     int chunk_sectors = s->granularity >> BDRV_SECTOR_BITS;
181     int64_t align_sector_num = *sector_num;
182     int align_nb_sectors = *nb_sectors;
183     int max_sectors = chunk_sectors * s->max_iov;
184 
185     need_cow = !test_bit(*sector_num / chunk_sectors, s->cow_bitmap);
186     need_cow |= !test_bit((*sector_num + *nb_sectors - 1) / chunk_sectors,
187                           s->cow_bitmap);
188     if (need_cow) {
189         bdrv_round_to_clusters(blk_bs(s->target), *sector_num, *nb_sectors,
190                                &align_sector_num, &align_nb_sectors);
191     }
192 
193     if (align_nb_sectors > max_sectors) {
194         align_nb_sectors = max_sectors;
195         if (need_cow) {
196             align_nb_sectors = QEMU_ALIGN_DOWN(align_nb_sectors,
197                                                s->target_cluster_sectors);
198         }
199     }
200     /* Clipping may result in align_nb_sectors unaligned to chunk boundary, but
201      * that doesn't matter because it's already the end of source image. */
202     mirror_clip_sectors(s, align_sector_num, &align_nb_sectors);
203 
204     ret = align_sector_num + align_nb_sectors - (*sector_num + *nb_sectors);
205     *sector_num = align_sector_num;
206     *nb_sectors = align_nb_sectors;
207     assert(ret >= 0);
208     return ret;
209 }
210 
211 static inline void mirror_wait_for_io(MirrorBlockJob *s)
212 {
213     assert(!s->waiting_for_io);
214     s->waiting_for_io = true;
215     qemu_coroutine_yield();
216     s->waiting_for_io = false;
217 }
218 
219 /* Submit async read while handling COW.
220  * Returns: nb_sectors if no alignment is necessary, or
221  *          (new_end - sector_num) if tail is rounded up or down due to
222  *          alignment or buffer limit.
223  */
224 static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,
225                           int nb_sectors)
226 {
227     BlockBackend *source = s->common.blk;
228     int sectors_per_chunk, nb_chunks;
229     int ret = nb_sectors;
230     MirrorOp *op;
231 
232     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
233 
234     /* We can only handle as much as buf_size at a time. */
235     nb_sectors = MIN(s->buf_size >> BDRV_SECTOR_BITS, nb_sectors);
236     assert(nb_sectors);
237 
238     if (s->cow_bitmap) {
239         ret += mirror_cow_align(s, &sector_num, &nb_sectors);
240     }
241     assert(nb_sectors << BDRV_SECTOR_BITS <= s->buf_size);
242     /* The sector range must meet granularity because:
243      * 1) Caller passes in aligned values;
244      * 2) mirror_cow_align is used only when target cluster is larger. */
245     assert(!(sector_num % sectors_per_chunk));
246     nb_chunks = DIV_ROUND_UP(nb_sectors, sectors_per_chunk);
247 
248     while (s->buf_free_count < nb_chunks) {
249         trace_mirror_yield_in_flight(s, sector_num, s->in_flight);
250         mirror_wait_for_io(s);
251     }
252 
253     /* Allocate a MirrorOp that is used as an AIO callback.  */
254     op = g_new(MirrorOp, 1);
255     op->s = s;
256     op->sector_num = sector_num;
257     op->nb_sectors = nb_sectors;
258 
259     /* Now make a QEMUIOVector taking enough granularity-sized chunks
260      * from s->buf_free.
261      */
262     qemu_iovec_init(&op->qiov, nb_chunks);
263     while (nb_chunks-- > 0) {
264         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
265         size_t remaining = nb_sectors * BDRV_SECTOR_SIZE - op->qiov.size;
266 
267         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
268         s->buf_free_count--;
269         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
270     }
271 
272     /* Copy the dirty cluster.  */
273     s->in_flight++;
274     s->sectors_in_flight += nb_sectors;
275     trace_mirror_one_iteration(s, sector_num, nb_sectors);
276 
277     blk_aio_preadv(source, sector_num * BDRV_SECTOR_SIZE, &op->qiov,
278                    nb_sectors * BDRV_SECTOR_SIZE,
279                    mirror_read_complete, op);
280     return ret;
281 }
282 
283 static void mirror_do_zero_or_discard(MirrorBlockJob *s,
284                                       int64_t sector_num,
285                                       int nb_sectors,
286                                       bool is_discard)
287 {
288     MirrorOp *op;
289 
290     /* Allocate a MirrorOp that is used as an AIO callback. The qiov is zeroed
291      * so the freeing in mirror_iteration_done is nop. */
292     op = g_new0(MirrorOp, 1);
293     op->s = s;
294     op->sector_num = sector_num;
295     op->nb_sectors = nb_sectors;
296 
297     s->in_flight++;
298     s->sectors_in_flight += nb_sectors;
299     if (is_discard) {
300         blk_aio_discard(s->target, sector_num, op->nb_sectors,
301                         mirror_write_complete, op);
302     } else {
303         blk_aio_pwrite_zeroes(s->target, sector_num * BDRV_SECTOR_SIZE,
304                               op->nb_sectors * BDRV_SECTOR_SIZE,
305                               s->unmap ? BDRV_REQ_MAY_UNMAP : 0,
306                               mirror_write_complete, op);
307     }
308 }
309 
310 static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
311 {
312     BlockDriverState *source = blk_bs(s->common.blk);
313     int64_t sector_num, first_chunk;
314     uint64_t delay_ns = 0;
315     /* At least the first dirty chunk is mirrored in one iteration. */
316     int nb_chunks = 1;
317     int64_t end = s->bdev_length / BDRV_SECTOR_SIZE;
318     int sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
319 
320     sector_num = hbitmap_iter_next(&s->hbi);
321     if (sector_num < 0) {
322         bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
323         sector_num = hbitmap_iter_next(&s->hbi);
324         trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
325         assert(sector_num >= 0);
326     }
327 
328     first_chunk = sector_num / sectors_per_chunk;
329     while (test_bit(first_chunk, s->in_flight_bitmap)) {
330         trace_mirror_yield_in_flight(s, first_chunk, s->in_flight);
331         mirror_wait_for_io(s);
332     }
333 
334     /* Find the number of consective dirty chunks following the first dirty
335      * one, and wait for in flight requests in them. */
336     while (nb_chunks * sectors_per_chunk < (s->buf_size >> BDRV_SECTOR_BITS)) {
337         int64_t hbitmap_next;
338         int64_t next_sector = sector_num + nb_chunks * sectors_per_chunk;
339         int64_t next_chunk = next_sector / sectors_per_chunk;
340         if (next_sector >= end ||
341             !bdrv_get_dirty(source, s->dirty_bitmap, next_sector)) {
342             break;
343         }
344         if (test_bit(next_chunk, s->in_flight_bitmap)) {
345             break;
346         }
347 
348         hbitmap_next = hbitmap_iter_next(&s->hbi);
349         if (hbitmap_next > next_sector || hbitmap_next < 0) {
350             /* The bitmap iterator's cache is stale, refresh it */
351             bdrv_set_dirty_iter(&s->hbi, next_sector);
352             hbitmap_next = hbitmap_iter_next(&s->hbi);
353         }
354         assert(hbitmap_next == next_sector);
355         nb_chunks++;
356     }
357 
358     /* Clear dirty bits before querying the block status, because
359      * calling bdrv_get_block_status_above could yield - if some blocks are
360      * marked dirty in this window, we need to know.
361      */
362     bdrv_reset_dirty_bitmap(s->dirty_bitmap, sector_num,
363                             nb_chunks * sectors_per_chunk);
364     bitmap_set(s->in_flight_bitmap, sector_num / sectors_per_chunk, nb_chunks);
365     while (nb_chunks > 0 && sector_num < end) {
366         int ret;
367         int io_sectors;
368         BlockDriverState *file;
369         enum MirrorMethod {
370             MIRROR_METHOD_COPY,
371             MIRROR_METHOD_ZERO,
372             MIRROR_METHOD_DISCARD
373         } mirror_method = MIRROR_METHOD_COPY;
374 
375         assert(!(sector_num % sectors_per_chunk));
376         ret = bdrv_get_block_status_above(source, NULL, sector_num,
377                                           nb_chunks * sectors_per_chunk,
378                                           &io_sectors, &file);
379         if (ret < 0) {
380             io_sectors = nb_chunks * sectors_per_chunk;
381         }
382 
383         io_sectors -= io_sectors % sectors_per_chunk;
384         if (io_sectors < sectors_per_chunk) {
385             io_sectors = sectors_per_chunk;
386         } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
387             int64_t target_sector_num;
388             int target_nb_sectors;
389             bdrv_round_to_clusters(blk_bs(s->target), sector_num, io_sectors,
390                                    &target_sector_num, &target_nb_sectors);
391             if (target_sector_num == sector_num &&
392                 target_nb_sectors == io_sectors) {
393                 mirror_method = ret & BDRV_BLOCK_ZERO ?
394                                     MIRROR_METHOD_ZERO :
395                                     MIRROR_METHOD_DISCARD;
396             }
397         }
398 
399         mirror_clip_sectors(s, sector_num, &io_sectors);
400         switch (mirror_method) {
401         case MIRROR_METHOD_COPY:
402             io_sectors = mirror_do_read(s, sector_num, io_sectors);
403             break;
404         case MIRROR_METHOD_ZERO:
405             mirror_do_zero_or_discard(s, sector_num, io_sectors, false);
406             break;
407         case MIRROR_METHOD_DISCARD:
408             mirror_do_zero_or_discard(s, sector_num, io_sectors, true);
409             break;
410         default:
411             abort();
412         }
413         assert(io_sectors);
414         sector_num += io_sectors;
415         nb_chunks -= DIV_ROUND_UP(io_sectors, sectors_per_chunk);
416         delay_ns += ratelimit_calculate_delay(&s->limit, io_sectors);
417     }
418     return delay_ns;
419 }
420 
421 static void mirror_free_init(MirrorBlockJob *s)
422 {
423     int granularity = s->granularity;
424     size_t buf_size = s->buf_size;
425     uint8_t *buf = s->buf;
426 
427     assert(s->buf_free_count == 0);
428     QSIMPLEQ_INIT(&s->buf_free);
429     while (buf_size != 0) {
430         MirrorBuffer *cur = (MirrorBuffer *)buf;
431         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
432         s->buf_free_count++;
433         buf_size -= granularity;
434         buf += granularity;
435     }
436 }
437 
438 static void mirror_drain(MirrorBlockJob *s)
439 {
440     while (s->in_flight > 0) {
441         mirror_wait_for_io(s);
442     }
443 }
444 
445 typedef struct {
446     int ret;
447 } MirrorExitData;
448 
449 static void mirror_exit(BlockJob *job, void *opaque)
450 {
451     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
452     MirrorExitData *data = opaque;
453     AioContext *replace_aio_context = NULL;
454     BlockDriverState *src = blk_bs(s->common.blk);
455     BlockDriverState *target_bs = blk_bs(s->target);
456 
457     /* Make sure that the source BDS doesn't go away before we called
458      * block_job_completed(). */
459     bdrv_ref(src);
460 
461     if (s->to_replace) {
462         replace_aio_context = bdrv_get_aio_context(s->to_replace);
463         aio_context_acquire(replace_aio_context);
464     }
465 
466     if (s->should_complete && data->ret == 0) {
467         BlockDriverState *to_replace = src;
468         if (s->to_replace) {
469             to_replace = s->to_replace;
470         }
471 
472         if (bdrv_get_flags(target_bs) != bdrv_get_flags(to_replace)) {
473             bdrv_reopen(target_bs, bdrv_get_flags(to_replace), NULL);
474         }
475 
476         /* The mirror job has no requests in flight any more, but we need to
477          * drain potential other users of the BDS before changing the graph. */
478         bdrv_drained_begin(target_bs);
479         bdrv_replace_in_backing_chain(to_replace, target_bs);
480         bdrv_drained_end(target_bs);
481 
482         /* We just changed the BDS the job BB refers to */
483         blk_remove_bs(job->blk);
484         blk_insert_bs(job->blk, src);
485     }
486     if (s->to_replace) {
487         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
488         error_free(s->replace_blocker);
489         bdrv_unref(s->to_replace);
490     }
491     if (replace_aio_context) {
492         aio_context_release(replace_aio_context);
493     }
494     g_free(s->replaces);
495     bdrv_op_unblock_all(target_bs, s->common.blocker);
496     blk_unref(s->target);
497     block_job_completed(&s->common, data->ret);
498     g_free(data);
499     bdrv_drained_end(src);
500     if (qemu_get_aio_context() == bdrv_get_aio_context(src)) {
501         aio_enable_external(iohandler_get_aio_context());
502     }
503     bdrv_unref(src);
504 }
505 
506 static void coroutine_fn mirror_run(void *opaque)
507 {
508     MirrorBlockJob *s = opaque;
509     MirrorExitData *data;
510     BlockDriverState *bs = blk_bs(s->common.blk);
511     BlockDriverState *target_bs = blk_bs(s->target);
512     int64_t sector_num, end, length;
513     uint64_t last_pause_ns;
514     BlockDriverInfo bdi;
515     char backing_filename[2]; /* we only need 2 characters because we are only
516                                  checking for a NULL string */
517     int ret = 0;
518     int n;
519     int target_cluster_size = BDRV_SECTOR_SIZE;
520 
521     if (block_job_is_cancelled(&s->common)) {
522         goto immediate_exit;
523     }
524 
525     s->bdev_length = bdrv_getlength(bs);
526     if (s->bdev_length < 0) {
527         ret = s->bdev_length;
528         goto immediate_exit;
529     } else if (s->bdev_length == 0) {
530         /* Report BLOCK_JOB_READY and wait for complete. */
531         block_job_event_ready(&s->common);
532         s->synced = true;
533         while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
534             block_job_yield(&s->common);
535         }
536         s->common.cancelled = false;
537         goto immediate_exit;
538     }
539 
540     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
541     s->in_flight_bitmap = bitmap_new(length);
542 
543     /* If we have no backing file yet in the destination, we cannot let
544      * the destination do COW.  Instead, we copy sectors around the
545      * dirty data if needed.  We need a bitmap to do that.
546      */
547     bdrv_get_backing_filename(target_bs, backing_filename,
548                               sizeof(backing_filename));
549     if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
550         target_cluster_size = bdi.cluster_size;
551     }
552     if (backing_filename[0] && !target_bs->backing
553         && s->granularity < target_cluster_size) {
554         s->buf_size = MAX(s->buf_size, target_cluster_size);
555         s->cow_bitmap = bitmap_new(length);
556     }
557     s->target_cluster_sectors = target_cluster_size >> BDRV_SECTOR_BITS;
558     s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
559 
560     end = s->bdev_length / BDRV_SECTOR_SIZE;
561     s->buf = qemu_try_blockalign(bs, s->buf_size);
562     if (s->buf == NULL) {
563         ret = -ENOMEM;
564         goto immediate_exit;
565     }
566 
567     mirror_free_init(s);
568 
569     last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
570     if (!s->is_none_mode) {
571         /* First part, loop on the sectors and initialize the dirty bitmap.  */
572         BlockDriverState *base = s->base;
573         bool mark_all_dirty = s->base == NULL && !bdrv_has_zero_init(target_bs);
574 
575         for (sector_num = 0; sector_num < end; ) {
576             /* Just to make sure we are not exceeding int limit. */
577             int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,
578                                  end - sector_num);
579             int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
580 
581             if (now - last_pause_ns > SLICE_TIME) {
582                 last_pause_ns = now;
583                 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, 0);
584             }
585 
586             if (block_job_is_cancelled(&s->common)) {
587                 goto immediate_exit;
588             }
589 
590             ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);
591 
592             if (ret < 0) {
593                 goto immediate_exit;
594             }
595 
596             assert(n > 0);
597             if (ret == 1 || mark_all_dirty) {
598                 bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);
599             }
600             sector_num += n;
601         }
602     }
603 
604     bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
605     for (;;) {
606         uint64_t delay_ns = 0;
607         int64_t cnt;
608         bool should_complete;
609 
610         if (s->ret < 0) {
611             ret = s->ret;
612             goto immediate_exit;
613         }
614 
615         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
616         /* s->common.offset contains the number of bytes already processed so
617          * far, cnt is the number of dirty sectors remaining and
618          * s->sectors_in_flight is the number of sectors currently being
619          * processed; together those are the current total operation length */
620         s->common.len = s->common.offset +
621                         (cnt + s->sectors_in_flight) * BDRV_SECTOR_SIZE;
622 
623         /* Note that even when no rate limit is applied we need to yield
624          * periodically with no pending I/O so that bdrv_drain_all() returns.
625          * We do so every SLICE_TIME nanoseconds, or when there is an error,
626          * or when the source is clean, whichever comes first.
627          */
628         if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - last_pause_ns < SLICE_TIME &&
629             s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
630             if (s->in_flight == MAX_IN_FLIGHT || s->buf_free_count == 0 ||
631                 (cnt == 0 && s->in_flight > 0)) {
632                 trace_mirror_yield(s, s->in_flight, s->buf_free_count, cnt);
633                 mirror_wait_for_io(s);
634                 continue;
635             } else if (cnt != 0) {
636                 delay_ns = mirror_iteration(s);
637             }
638         }
639 
640         should_complete = false;
641         if (s->in_flight == 0 && cnt == 0) {
642             trace_mirror_before_flush(s);
643             ret = blk_flush(s->target);
644             if (ret < 0) {
645                 if (mirror_error_action(s, false, -ret) ==
646                     BLOCK_ERROR_ACTION_REPORT) {
647                     goto immediate_exit;
648                 }
649             } else {
650                 /* We're out of the streaming phase.  From now on, if the job
651                  * is cancelled we will actually complete all pending I/O and
652                  * report completion.  This way, block-job-cancel will leave
653                  * the target in a consistent state.
654                  */
655                 if (!s->synced) {
656                     block_job_event_ready(&s->common);
657                     s->synced = true;
658                 }
659 
660                 should_complete = s->should_complete ||
661                     block_job_is_cancelled(&s->common);
662                 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
663             }
664         }
665 
666         if (cnt == 0 && should_complete) {
667             /* The dirty bitmap is not updated while operations are pending.
668              * If we're about to exit, wait for pending operations before
669              * calling bdrv_get_dirty_count(bs), or we may exit while the
670              * source has dirty data to copy!
671              *
672              * Note that I/O can be submitted by the guest while
673              * mirror_populate runs.
674              */
675             trace_mirror_before_drain(s, cnt);
676             bdrv_co_drain(bs);
677             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
678         }
679 
680         ret = 0;
681         trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
682         if (!s->synced) {
683             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
684             if (block_job_is_cancelled(&s->common)) {
685                 break;
686             }
687         } else if (!should_complete) {
688             delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
689             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
690         } else if (cnt == 0) {
691             /* The two disks are in sync.  Exit and report successful
692              * completion.
693              */
694             assert(QLIST_EMPTY(&bs->tracked_requests));
695             s->common.cancelled = false;
696             break;
697         }
698         last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
699     }
700 
701 immediate_exit:
702     if (s->in_flight > 0) {
703         /* We get here only if something went wrong.  Either the job failed,
704          * or it was cancelled prematurely so that we do not guarantee that
705          * the target is a copy of the source.
706          */
707         assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));
708         mirror_drain(s);
709     }
710 
711     assert(s->in_flight == 0);
712     qemu_vfree(s->buf);
713     g_free(s->cow_bitmap);
714     g_free(s->in_flight_bitmap);
715     bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);
716 
717     data = g_malloc(sizeof(*data));
718     data->ret = ret;
719     /* Before we switch to target in mirror_exit, make sure data doesn't
720      * change. */
721     bdrv_drained_begin(bs);
722     if (qemu_get_aio_context() == bdrv_get_aio_context(bs)) {
723         /* FIXME: virtio host notifiers run on iohandler_ctx, therefore the
724          * above bdrv_drained_end isn't enough to quiesce it. This is ugly, we
725          * need a block layer API change to achieve this. */
726         aio_disable_external(iohandler_get_aio_context());
727     }
728     block_job_defer_to_main_loop(&s->common, mirror_exit, data);
729 }
730 
731 static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)
732 {
733     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
734 
735     if (speed < 0) {
736         error_setg(errp, QERR_INVALID_PARAMETER, "speed");
737         return;
738     }
739     ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
740 }
741 
742 static void mirror_complete(BlockJob *job, Error **errp)
743 {
744     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
745     Error *local_err = NULL;
746     int ret;
747 
748     ret = bdrv_open_backing_file(blk_bs(s->target), NULL, "backing",
749                                  &local_err);
750     if (ret < 0) {
751         error_propagate(errp, local_err);
752         return;
753     }
754     if (!s->synced) {
755         error_setg(errp, QERR_BLOCK_JOB_NOT_READY, job->id);
756         return;
757     }
758 
759     /* check the target bs is not blocked and block all operations on it */
760     if (s->replaces) {
761         AioContext *replace_aio_context;
762 
763         s->to_replace = bdrv_find_node(s->replaces);
764         if (!s->to_replace) {
765             error_setg(errp, "Node name '%s' not found", s->replaces);
766             return;
767         }
768 
769         replace_aio_context = bdrv_get_aio_context(s->to_replace);
770         aio_context_acquire(replace_aio_context);
771 
772         error_setg(&s->replace_blocker,
773                    "block device is in use by block-job-complete");
774         bdrv_op_block_all(s->to_replace, s->replace_blocker);
775         bdrv_ref(s->to_replace);
776 
777         aio_context_release(replace_aio_context);
778     }
779 
780     s->should_complete = true;
781     block_job_enter(&s->common);
782 }
783 
784 static const BlockJobDriver mirror_job_driver = {
785     .instance_size = sizeof(MirrorBlockJob),
786     .job_type      = BLOCK_JOB_TYPE_MIRROR,
787     .set_speed     = mirror_set_speed,
788     .complete      = mirror_complete,
789 };
790 
791 static const BlockJobDriver commit_active_job_driver = {
792     .instance_size = sizeof(MirrorBlockJob),
793     .job_type      = BLOCK_JOB_TYPE_COMMIT,
794     .set_speed     = mirror_set_speed,
795     .complete      = mirror_complete,
796 };
797 
798 static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,
799                              const char *replaces,
800                              int64_t speed, uint32_t granularity,
801                              int64_t buf_size,
802                              BlockdevOnError on_source_error,
803                              BlockdevOnError on_target_error,
804                              bool unmap,
805                              BlockCompletionFunc *cb,
806                              void *opaque, Error **errp,
807                              const BlockJobDriver *driver,
808                              bool is_none_mode, BlockDriverState *base)
809 {
810     MirrorBlockJob *s;
811 
812     if (granularity == 0) {
813         granularity = bdrv_get_default_bitmap_granularity(target);
814     }
815 
816     assert ((granularity & (granularity - 1)) == 0);
817 
818     if (buf_size < 0) {
819         error_setg(errp, "Invalid parameter 'buf-size'");
820         return;
821     }
822 
823     if (buf_size == 0) {
824         buf_size = DEFAULT_MIRROR_BUF_SIZE;
825     }
826 
827     s = block_job_create(driver, bs, speed, cb, opaque, errp);
828     if (!s) {
829         return;
830     }
831 
832     s->target = blk_new();
833     blk_insert_bs(s->target, target);
834 
835     s->replaces = g_strdup(replaces);
836     s->on_source_error = on_source_error;
837     s->on_target_error = on_target_error;
838     s->is_none_mode = is_none_mode;
839     s->base = base;
840     s->granularity = granularity;
841     s->buf_size = ROUND_UP(buf_size, granularity);
842     s->unmap = unmap;
843 
844     s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
845     if (!s->dirty_bitmap) {
846         g_free(s->replaces);
847         blk_unref(s->target);
848         block_job_unref(&s->common);
849         return;
850     }
851 
852     bdrv_op_block_all(target, s->common.blocker);
853 
854     s->common.co = qemu_coroutine_create(mirror_run);
855     trace_mirror_start(bs, s, s->common.co, opaque);
856     qemu_coroutine_enter(s->common.co, s);
857 }
858 
859 void mirror_start(BlockDriverState *bs, BlockDriverState *target,
860                   const char *replaces,
861                   int64_t speed, uint32_t granularity, int64_t buf_size,
862                   MirrorSyncMode mode, BlockdevOnError on_source_error,
863                   BlockdevOnError on_target_error,
864                   bool unmap,
865                   BlockCompletionFunc *cb,
866                   void *opaque, Error **errp)
867 {
868     bool is_none_mode;
869     BlockDriverState *base;
870 
871     if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
872         error_setg(errp, "Sync mode 'incremental' not supported");
873         return;
874     }
875     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
876     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
877     mirror_start_job(bs, target, replaces,
878                      speed, granularity, buf_size,
879                      on_source_error, on_target_error, unmap, cb, opaque, errp,
880                      &mirror_job_driver, is_none_mode, base);
881 }
882 
883 void commit_active_start(BlockDriverState *bs, BlockDriverState *base,
884                          int64_t speed,
885                          BlockdevOnError on_error,
886                          BlockCompletionFunc *cb,
887                          void *opaque, Error **errp)
888 {
889     int64_t length, base_length;
890     int orig_base_flags;
891     int ret;
892     Error *local_err = NULL;
893 
894     orig_base_flags = bdrv_get_flags(base);
895 
896     if (bdrv_reopen(base, bs->open_flags, errp)) {
897         return;
898     }
899 
900     length = bdrv_getlength(bs);
901     if (length < 0) {
902         error_setg_errno(errp, -length,
903                          "Unable to determine length of %s", bs->filename);
904         goto error_restore_flags;
905     }
906 
907     base_length = bdrv_getlength(base);
908     if (base_length < 0) {
909         error_setg_errno(errp, -base_length,
910                          "Unable to determine length of %s", base->filename);
911         goto error_restore_flags;
912     }
913 
914     if (length > base_length) {
915         ret = bdrv_truncate(base, length);
916         if (ret < 0) {
917             error_setg_errno(errp, -ret,
918                             "Top image %s is larger than base image %s, and "
919                              "resize of base image failed",
920                              bs->filename, base->filename);
921             goto error_restore_flags;
922         }
923     }
924 
925     mirror_start_job(bs, base, NULL, speed, 0, 0,
926                      on_error, on_error, false, cb, opaque, &local_err,
927                      &commit_active_job_driver, false, base);
928     if (local_err) {
929         error_propagate(errp, local_err);
930         goto error_restore_flags;
931     }
932 
933     return;
934 
935 error_restore_flags:
936     /* ignore error and errp for bdrv_reopen, because we want to propagate
937      * the original error */
938     bdrv_reopen(base, orig_base_flags, NULL);
939     return;
940 }
941