xref: /openbmc/qemu/block/mirror.c (revision daa76aa416b1e18ab1fac650ff53d966d8f21f68)
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, NULL);
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: nb_sectors if no alignment is necessary, or
222  *          (new_end - sector_num) if tail is rounded up or down due to
223  *          alignment or buffer limit.
224  */
225 static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,
226                           int nb_sectors)
227 {
228     BlockBackend *source = s->common.blk;
229     int sectors_per_chunk, nb_chunks;
230     int ret = nb_sectors;
231     MirrorOp *op;
232 
233     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
234 
235     /* We can only handle as much as buf_size at a time. */
236     nb_sectors = MIN(s->buf_size >> BDRV_SECTOR_BITS, nb_sectors);
237     assert(nb_sectors);
238 
239     if (s->cow_bitmap) {
240         ret += mirror_cow_align(s, &sector_num, &nb_sectors);
241     }
242     assert(nb_sectors << BDRV_SECTOR_BITS <= s->buf_size);
243     /* The sector range must meet granularity because:
244      * 1) Caller passes in aligned values;
245      * 2) mirror_cow_align is used only when target cluster is larger. */
246     assert(!(sector_num % sectors_per_chunk));
247     nb_chunks = DIV_ROUND_UP(nb_sectors, sectors_per_chunk);
248 
249     while (s->buf_free_count < nb_chunks) {
250         trace_mirror_yield_in_flight(s, sector_num, s->in_flight);
251         mirror_wait_for_io(s);
252     }
253 
254     /* Allocate a MirrorOp that is used as an AIO callback.  */
255     op = g_new(MirrorOp, 1);
256     op->s = s;
257     op->sector_num = sector_num;
258     op->nb_sectors = nb_sectors;
259 
260     /* Now make a QEMUIOVector taking enough granularity-sized chunks
261      * from s->buf_free.
262      */
263     qemu_iovec_init(&op->qiov, nb_chunks);
264     while (nb_chunks-- > 0) {
265         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
266         size_t remaining = nb_sectors * BDRV_SECTOR_SIZE - op->qiov.size;
267 
268         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
269         s->buf_free_count--;
270         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
271     }
272 
273     /* Copy the dirty cluster.  */
274     s->in_flight++;
275     s->sectors_in_flight += nb_sectors;
276     trace_mirror_one_iteration(s, sector_num, nb_sectors);
277 
278     blk_aio_preadv(source, sector_num * BDRV_SECTOR_SIZE, &op->qiov, 0,
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_sectors_to_clusters(blk_bs(s->target), sector_num,
390                                            io_sectors,  &target_sector_num,
391                                            &target_nb_sectors);
392             if (target_sector_num == sector_num &&
393                 target_nb_sectors == io_sectors) {
394                 mirror_method = ret & BDRV_BLOCK_ZERO ?
395                                     MIRROR_METHOD_ZERO :
396                                     MIRROR_METHOD_DISCARD;
397             }
398         }
399 
400         mirror_clip_sectors(s, sector_num, &io_sectors);
401         switch (mirror_method) {
402         case MIRROR_METHOD_COPY:
403             io_sectors = mirror_do_read(s, sector_num, io_sectors);
404             break;
405         case MIRROR_METHOD_ZERO:
406             mirror_do_zero_or_discard(s, sector_num, io_sectors, false);
407             break;
408         case MIRROR_METHOD_DISCARD:
409             mirror_do_zero_or_discard(s, sector_num, io_sectors, true);
410             break;
411         default:
412             abort();
413         }
414         assert(io_sectors);
415         sector_num += io_sectors;
416         nb_chunks -= DIV_ROUND_UP(io_sectors, sectors_per_chunk);
417         delay_ns += ratelimit_calculate_delay(&s->limit, io_sectors);
418     }
419     return delay_ns;
420 }
421 
422 static void mirror_free_init(MirrorBlockJob *s)
423 {
424     int granularity = s->granularity;
425     size_t buf_size = s->buf_size;
426     uint8_t *buf = s->buf;
427 
428     assert(s->buf_free_count == 0);
429     QSIMPLEQ_INIT(&s->buf_free);
430     while (buf_size != 0) {
431         MirrorBuffer *cur = (MirrorBuffer *)buf;
432         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
433         s->buf_free_count++;
434         buf_size -= granularity;
435         buf += granularity;
436     }
437 }
438 
439 static void mirror_drain(MirrorBlockJob *s)
440 {
441     while (s->in_flight > 0) {
442         mirror_wait_for_io(s);
443     }
444 }
445 
446 typedef struct {
447     int ret;
448 } MirrorExitData;
449 
450 static void mirror_exit(BlockJob *job, void *opaque)
451 {
452     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
453     MirrorExitData *data = opaque;
454     AioContext *replace_aio_context = NULL;
455     BlockDriverState *src = blk_bs(s->common.blk);
456     BlockDriverState *target_bs = blk_bs(s->target);
457 
458     /* Make sure that the source BDS doesn't go away before we called
459      * block_job_completed(). */
460     bdrv_ref(src);
461 
462     if (s->to_replace) {
463         replace_aio_context = bdrv_get_aio_context(s->to_replace);
464         aio_context_acquire(replace_aio_context);
465     }
466 
467     if (s->should_complete && data->ret == 0) {
468         BlockDriverState *to_replace = src;
469         if (s->to_replace) {
470             to_replace = s->to_replace;
471         }
472 
473         if (bdrv_get_flags(target_bs) != bdrv_get_flags(to_replace)) {
474             bdrv_reopen(target_bs, bdrv_get_flags(to_replace), NULL);
475         }
476 
477         /* The mirror job has no requests in flight any more, but we need to
478          * drain potential other users of the BDS before changing the graph. */
479         bdrv_drained_begin(target_bs);
480         bdrv_replace_in_backing_chain(to_replace, target_bs);
481         bdrv_drained_end(target_bs);
482 
483         /* We just changed the BDS the job BB refers to */
484         blk_remove_bs(job->blk);
485         blk_insert_bs(job->blk, src);
486     }
487     if (s->to_replace) {
488         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
489         error_free(s->replace_blocker);
490         bdrv_unref(s->to_replace);
491     }
492     if (replace_aio_context) {
493         aio_context_release(replace_aio_context);
494     }
495     g_free(s->replaces);
496     bdrv_op_unblock_all(target_bs, s->common.blocker);
497     blk_unref(s->target);
498     block_job_completed(&s->common, data->ret);
499     g_free(data);
500     bdrv_drained_end(src);
501     if (qemu_get_aio_context() == bdrv_get_aio_context(src)) {
502         aio_enable_external(iohandler_get_aio_context());
503     }
504     bdrv_unref(src);
505 }
506 
507 static void coroutine_fn mirror_run(void *opaque)
508 {
509     MirrorBlockJob *s = opaque;
510     MirrorExitData *data;
511     BlockDriverState *bs = blk_bs(s->common.blk);
512     BlockDriverState *target_bs = blk_bs(s->target);
513     int64_t sector_num, end, length;
514     uint64_t last_pause_ns;
515     BlockDriverInfo bdi;
516     char backing_filename[2]; /* we only need 2 characters because we are only
517                                  checking for a NULL string */
518     int ret = 0;
519     int n;
520     int target_cluster_size = BDRV_SECTOR_SIZE;
521 
522     if (block_job_is_cancelled(&s->common)) {
523         goto immediate_exit;
524     }
525 
526     s->bdev_length = bdrv_getlength(bs);
527     if (s->bdev_length < 0) {
528         ret = s->bdev_length;
529         goto immediate_exit;
530     } else if (s->bdev_length == 0) {
531         /* Report BLOCK_JOB_READY and wait for complete. */
532         block_job_event_ready(&s->common);
533         s->synced = true;
534         while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
535             block_job_yield(&s->common);
536         }
537         s->common.cancelled = false;
538         goto immediate_exit;
539     }
540 
541     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
542     s->in_flight_bitmap = bitmap_new(length);
543 
544     /* If we have no backing file yet in the destination, we cannot let
545      * the destination do COW.  Instead, we copy sectors around the
546      * dirty data if needed.  We need a bitmap to do that.
547      */
548     bdrv_get_backing_filename(target_bs, backing_filename,
549                               sizeof(backing_filename));
550     if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
551         target_cluster_size = bdi.cluster_size;
552     }
553     if (backing_filename[0] && !target_bs->backing
554         && s->granularity < target_cluster_size) {
555         s->buf_size = MAX(s->buf_size, target_cluster_size);
556         s->cow_bitmap = bitmap_new(length);
557     }
558     s->target_cluster_sectors = target_cluster_size >> BDRV_SECTOR_BITS;
559     s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
560 
561     end = s->bdev_length / BDRV_SECTOR_SIZE;
562     s->buf = qemu_try_blockalign(bs, s->buf_size);
563     if (s->buf == NULL) {
564         ret = -ENOMEM;
565         goto immediate_exit;
566     }
567 
568     mirror_free_init(s);
569 
570     last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
571     if (!s->is_none_mode) {
572         /* First part, loop on the sectors and initialize the dirty bitmap.  */
573         BlockDriverState *base = s->base;
574         bool mark_all_dirty = s->base == NULL && !bdrv_has_zero_init(target_bs);
575 
576         for (sector_num = 0; sector_num < end; ) {
577             /* Just to make sure we are not exceeding int limit. */
578             int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,
579                                  end - sector_num);
580             int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
581 
582             if (now - last_pause_ns > SLICE_TIME) {
583                 last_pause_ns = now;
584                 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, 0);
585             }
586 
587             if (block_job_is_cancelled(&s->common)) {
588                 goto immediate_exit;
589             }
590 
591             ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);
592 
593             if (ret < 0) {
594                 goto immediate_exit;
595             }
596 
597             assert(n > 0);
598             if (ret == 1 || mark_all_dirty) {
599                 bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);
600             }
601             sector_num += n;
602         }
603     }
604 
605     bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
606     for (;;) {
607         uint64_t delay_ns = 0;
608         int64_t cnt;
609         bool should_complete;
610 
611         if (s->ret < 0) {
612             ret = s->ret;
613             goto immediate_exit;
614         }
615 
616         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
617         /* s->common.offset contains the number of bytes already processed so
618          * far, cnt is the number of dirty sectors remaining and
619          * s->sectors_in_flight is the number of sectors currently being
620          * processed; together those are the current total operation length */
621         s->common.len = s->common.offset +
622                         (cnt + s->sectors_in_flight) * BDRV_SECTOR_SIZE;
623 
624         /* Note that even when no rate limit is applied we need to yield
625          * periodically with no pending I/O so that bdrv_drain_all() returns.
626          * We do so every SLICE_TIME nanoseconds, or when there is an error,
627          * or when the source is clean, whichever comes first.
628          */
629         if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - last_pause_ns < SLICE_TIME &&
630             s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
631             if (s->in_flight == MAX_IN_FLIGHT || s->buf_free_count == 0 ||
632                 (cnt == 0 && s->in_flight > 0)) {
633                 trace_mirror_yield(s, s->in_flight, s->buf_free_count, cnt);
634                 mirror_wait_for_io(s);
635                 continue;
636             } else if (cnt != 0) {
637                 delay_ns = mirror_iteration(s);
638             }
639         }
640 
641         should_complete = false;
642         if (s->in_flight == 0 && cnt == 0) {
643             trace_mirror_before_flush(s);
644             ret = blk_flush(s->target);
645             if (ret < 0) {
646                 if (mirror_error_action(s, false, -ret) ==
647                     BLOCK_ERROR_ACTION_REPORT) {
648                     goto immediate_exit;
649                 }
650             } else {
651                 /* We're out of the streaming phase.  From now on, if the job
652                  * is cancelled we will actually complete all pending I/O and
653                  * report completion.  This way, block-job-cancel will leave
654                  * the target in a consistent state.
655                  */
656                 if (!s->synced) {
657                     block_job_event_ready(&s->common);
658                     s->synced = true;
659                 }
660 
661                 should_complete = s->should_complete ||
662                     block_job_is_cancelled(&s->common);
663                 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
664             }
665         }
666 
667         if (cnt == 0 && should_complete) {
668             /* The dirty bitmap is not updated while operations are pending.
669              * If we're about to exit, wait for pending operations before
670              * calling bdrv_get_dirty_count(bs), or we may exit while the
671              * source has dirty data to copy!
672              *
673              * Note that I/O can be submitted by the guest while
674              * mirror_populate runs.
675              */
676             trace_mirror_before_drain(s, cnt);
677             bdrv_co_drain(bs);
678             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
679         }
680 
681         ret = 0;
682         trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
683         if (!s->synced) {
684             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
685             if (block_job_is_cancelled(&s->common)) {
686                 break;
687             }
688         } else if (!should_complete) {
689             delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
690             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
691         } else if (cnt == 0) {
692             /* The two disks are in sync.  Exit and report successful
693              * completion.
694              */
695             assert(QLIST_EMPTY(&bs->tracked_requests));
696             s->common.cancelled = false;
697             break;
698         }
699         last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
700     }
701 
702 immediate_exit:
703     if (s->in_flight > 0) {
704         /* We get here only if something went wrong.  Either the job failed,
705          * or it was cancelled prematurely so that we do not guarantee that
706          * the target is a copy of the source.
707          */
708         assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));
709         mirror_drain(s);
710     }
711 
712     assert(s->in_flight == 0);
713     qemu_vfree(s->buf);
714     g_free(s->cow_bitmap);
715     g_free(s->in_flight_bitmap);
716     bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);
717 
718     data = g_malloc(sizeof(*data));
719     data->ret = ret;
720     /* Before we switch to target in mirror_exit, make sure data doesn't
721      * change. */
722     bdrv_drained_begin(bs);
723     if (qemu_get_aio_context() == bdrv_get_aio_context(bs)) {
724         /* FIXME: virtio host notifiers run on iohandler_ctx, therefore the
725          * above bdrv_drained_end isn't enough to quiesce it. This is ugly, we
726          * need a block layer API change to achieve this. */
727         aio_disable_external(iohandler_get_aio_context());
728     }
729     block_job_defer_to_main_loop(&s->common, mirror_exit, data);
730 }
731 
732 static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)
733 {
734     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
735 
736     if (speed < 0) {
737         error_setg(errp, QERR_INVALID_PARAMETER, "speed");
738         return;
739     }
740     ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
741 }
742 
743 static void mirror_complete(BlockJob *job, Error **errp)
744 {
745     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
746     BlockDriverState *src, *target;
747 
748     src = blk_bs(job->blk);
749     target = blk_bs(s->target);
750 
751     if (!s->synced) {
752         error_setg(errp, QERR_BLOCK_JOB_NOT_READY, job->id);
753         return;
754     }
755 
756     if (s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
757         int ret;
758 
759         assert(!target->backing);
760         ret = bdrv_open_backing_file(target, NULL, "backing", errp);
761         if (ret < 0) {
762             return;
763         }
764     }
765 
766     /* check the target bs is not blocked and block all operations on it */
767     if (s->replaces) {
768         AioContext *replace_aio_context;
769 
770         s->to_replace = bdrv_find_node(s->replaces);
771         if (!s->to_replace) {
772             error_setg(errp, "Node name '%s' not found", s->replaces);
773             return;
774         }
775 
776         replace_aio_context = bdrv_get_aio_context(s->to_replace);
777         aio_context_acquire(replace_aio_context);
778 
779         error_setg(&s->replace_blocker,
780                    "block device is in use by block-job-complete");
781         bdrv_op_block_all(s->to_replace, s->replace_blocker);
782         bdrv_ref(s->to_replace);
783 
784         aio_context_release(replace_aio_context);
785     }
786 
787     if (s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
788         BlockDriverState *backing = s->is_none_mode ? src : s->base;
789         if (backing_bs(target) != backing) {
790             bdrv_set_backing_hd(target, backing);
791         }
792     }
793 
794     s->should_complete = true;
795     block_job_enter(&s->common);
796 }
797 
798 static const BlockJobDriver mirror_job_driver = {
799     .instance_size = sizeof(MirrorBlockJob),
800     .job_type      = BLOCK_JOB_TYPE_MIRROR,
801     .set_speed     = mirror_set_speed,
802     .complete      = mirror_complete,
803 };
804 
805 static const BlockJobDriver commit_active_job_driver = {
806     .instance_size = sizeof(MirrorBlockJob),
807     .job_type      = BLOCK_JOB_TYPE_COMMIT,
808     .set_speed     = mirror_set_speed,
809     .complete      = mirror_complete,
810 };
811 
812 static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,
813                              const char *replaces,
814                              int64_t speed, uint32_t granularity,
815                              int64_t buf_size,
816                              BlockMirrorBackingMode backing_mode,
817                              BlockdevOnError on_source_error,
818                              BlockdevOnError on_target_error,
819                              bool unmap,
820                              BlockCompletionFunc *cb,
821                              void *opaque, Error **errp,
822                              const BlockJobDriver *driver,
823                              bool is_none_mode, BlockDriverState *base)
824 {
825     MirrorBlockJob *s;
826 
827     if (granularity == 0) {
828         granularity = bdrv_get_default_bitmap_granularity(target);
829     }
830 
831     assert ((granularity & (granularity - 1)) == 0);
832 
833     if (buf_size < 0) {
834         error_setg(errp, "Invalid parameter 'buf-size'");
835         return;
836     }
837 
838     if (buf_size == 0) {
839         buf_size = DEFAULT_MIRROR_BUF_SIZE;
840     }
841 
842     s = block_job_create(driver, bs, speed, cb, opaque, errp);
843     if (!s) {
844         return;
845     }
846 
847     s->target = blk_new();
848     blk_insert_bs(s->target, target);
849 
850     s->replaces = g_strdup(replaces);
851     s->on_source_error = on_source_error;
852     s->on_target_error = on_target_error;
853     s->is_none_mode = is_none_mode;
854     s->backing_mode = backing_mode;
855     s->base = base;
856     s->granularity = granularity;
857     s->buf_size = ROUND_UP(buf_size, granularity);
858     s->unmap = unmap;
859 
860     s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
861     if (!s->dirty_bitmap) {
862         g_free(s->replaces);
863         blk_unref(s->target);
864         block_job_unref(&s->common);
865         return;
866     }
867 
868     bdrv_op_block_all(target, s->common.blocker);
869 
870     s->common.co = qemu_coroutine_create(mirror_run);
871     trace_mirror_start(bs, s, s->common.co, opaque);
872     qemu_coroutine_enter(s->common.co, s);
873 }
874 
875 void mirror_start(BlockDriverState *bs, BlockDriverState *target,
876                   const char *replaces,
877                   int64_t speed, uint32_t granularity, int64_t buf_size,
878                   MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
879                   BlockdevOnError on_source_error,
880                   BlockdevOnError on_target_error,
881                   bool unmap,
882                   BlockCompletionFunc *cb,
883                   void *opaque, Error **errp)
884 {
885     bool is_none_mode;
886     BlockDriverState *base;
887 
888     if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
889         error_setg(errp, "Sync mode 'incremental' not supported");
890         return;
891     }
892     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
893     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
894     mirror_start_job(bs, target, replaces,
895                      speed, granularity, buf_size, backing_mode,
896                      on_source_error, on_target_error, unmap, cb, opaque, errp,
897                      &mirror_job_driver, is_none_mode, base);
898 }
899 
900 void commit_active_start(BlockDriverState *bs, BlockDriverState *base,
901                          int64_t speed,
902                          BlockdevOnError on_error,
903                          BlockCompletionFunc *cb,
904                          void *opaque, Error **errp)
905 {
906     int64_t length, base_length;
907     int orig_base_flags;
908     int ret;
909     Error *local_err = NULL;
910 
911     orig_base_flags = bdrv_get_flags(base);
912 
913     if (bdrv_reopen(base, bs->open_flags, errp)) {
914         return;
915     }
916 
917     length = bdrv_getlength(bs);
918     if (length < 0) {
919         error_setg_errno(errp, -length,
920                          "Unable to determine length of %s", bs->filename);
921         goto error_restore_flags;
922     }
923 
924     base_length = bdrv_getlength(base);
925     if (base_length < 0) {
926         error_setg_errno(errp, -base_length,
927                          "Unable to determine length of %s", base->filename);
928         goto error_restore_flags;
929     }
930 
931     if (length > base_length) {
932         ret = bdrv_truncate(base, length);
933         if (ret < 0) {
934             error_setg_errno(errp, -ret,
935                             "Top image %s is larger than base image %s, and "
936                              "resize of base image failed",
937                              bs->filename, base->filename);
938             goto error_restore_flags;
939         }
940     }
941 
942     mirror_start_job(bs, base, NULL, speed, 0, 0, MIRROR_LEAVE_BACKING_CHAIN,
943                      on_error, on_error, false, cb, opaque, &local_err,
944                      &commit_active_job_driver, false, base);
945     if (local_err) {
946         error_propagate(errp, local_err);
947         goto error_restore_flags;
948     }
949 
950     return;
951 
952 error_restore_flags:
953     /* ignore error and errp for bdrv_reopen, because we want to propagate
954      * the original error */
955     bdrv_reopen(base, orig_base_flags, NULL);
956     return;
957 }
958