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