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