xref: /openbmc/qemu/block/mirror.c (revision 438c78da)
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 "qemu/cutils.h"
16 #include "qemu/coroutine.h"
17 #include "qemu/range.h"
18 #include "trace.h"
19 #include "block/blockjob_int.h"
20 #include "block/block_int.h"
21 #include "sysemu/block-backend.h"
22 #include "qapi/error.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qemu/ratelimit.h"
25 #include "qemu/bitmap.h"
26 
27 #define MAX_IN_FLIGHT 16
28 #define MAX_IO_BYTES (1 << 20) /* 1 Mb */
29 #define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
30 
31 /* The mirroring buffer is a list of granularity-sized chunks.
32  * Free chunks are organized in a list.
33  */
34 typedef struct MirrorBuffer {
35     QSIMPLEQ_ENTRY(MirrorBuffer) next;
36 } MirrorBuffer;
37 
38 typedef struct MirrorOp MirrorOp;
39 
40 typedef struct MirrorBlockJob {
41     BlockJob common;
42     BlockBackend *target;
43     BlockDriverState *mirror_top_bs;
44     BlockDriverState *base;
45 
46     /* The name of the graph node to replace */
47     char *replaces;
48     /* The BDS to replace */
49     BlockDriverState *to_replace;
50     /* Used to block operations on the drive-mirror-replace target */
51     Error *replace_blocker;
52     bool is_none_mode;
53     BlockMirrorBackingMode backing_mode;
54     MirrorCopyMode copy_mode;
55     BlockdevOnError on_source_error, on_target_error;
56     bool synced;
57     /* Set when the target is synced (dirty bitmap is clean, nothing
58      * in flight) and the job is running in active mode */
59     bool actively_synced;
60     bool should_complete;
61     int64_t granularity;
62     size_t buf_size;
63     int64_t bdev_length;
64     unsigned long *cow_bitmap;
65     BdrvDirtyBitmap *dirty_bitmap;
66     BdrvDirtyBitmapIter *dbi;
67     uint8_t *buf;
68     QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
69     int buf_free_count;
70 
71     uint64_t last_pause_ns;
72     unsigned long *in_flight_bitmap;
73     int in_flight;
74     int64_t bytes_in_flight;
75     QTAILQ_HEAD(MirrorOpList, MirrorOp) ops_in_flight;
76     int ret;
77     bool unmap;
78     int target_cluster_size;
79     int max_iov;
80     bool initial_zeroing_ongoing;
81     int in_active_write_counter;
82     bool prepared;
83 } MirrorBlockJob;
84 
85 typedef struct MirrorBDSOpaque {
86     MirrorBlockJob *job;
87 } MirrorBDSOpaque;
88 
89 struct MirrorOp {
90     MirrorBlockJob *s;
91     QEMUIOVector qiov;
92     int64_t offset;
93     uint64_t bytes;
94 
95     /* The pointee is set by mirror_co_read(), mirror_co_zero(), and
96      * mirror_co_discard() before yielding for the first time */
97     int64_t *bytes_handled;
98 
99     bool is_pseudo_op;
100     bool is_active_write;
101     CoQueue waiting_requests;
102 
103     QTAILQ_ENTRY(MirrorOp) next;
104 };
105 
106 typedef enum MirrorMethod {
107     MIRROR_METHOD_COPY,
108     MIRROR_METHOD_ZERO,
109     MIRROR_METHOD_DISCARD,
110 } MirrorMethod;
111 
112 static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
113                                             int error)
114 {
115     s->synced = false;
116     s->actively_synced = false;
117     if (read) {
118         return block_job_error_action(&s->common, s->on_source_error,
119                                       true, error);
120     } else {
121         return block_job_error_action(&s->common, s->on_target_error,
122                                       false, error);
123     }
124 }
125 
126 static void coroutine_fn mirror_wait_on_conflicts(MirrorOp *self,
127                                                   MirrorBlockJob *s,
128                                                   uint64_t offset,
129                                                   uint64_t bytes)
130 {
131     uint64_t self_start_chunk = offset / s->granularity;
132     uint64_t self_end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
133     uint64_t self_nb_chunks = self_end_chunk - self_start_chunk;
134 
135     while (find_next_bit(s->in_flight_bitmap, self_end_chunk,
136                          self_start_chunk) < self_end_chunk &&
137            s->ret >= 0)
138     {
139         MirrorOp *op;
140 
141         QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
142             uint64_t op_start_chunk = op->offset / s->granularity;
143             uint64_t op_nb_chunks = DIV_ROUND_UP(op->offset + op->bytes,
144                                                  s->granularity) -
145                                     op_start_chunk;
146 
147             if (op == self) {
148                 continue;
149             }
150 
151             if (ranges_overlap(self_start_chunk, self_nb_chunks,
152                                op_start_chunk, op_nb_chunks))
153             {
154                 qemu_co_queue_wait(&op->waiting_requests, NULL);
155                 break;
156             }
157         }
158     }
159 }
160 
161 static void coroutine_fn mirror_iteration_done(MirrorOp *op, int ret)
162 {
163     MirrorBlockJob *s = op->s;
164     struct iovec *iov;
165     int64_t chunk_num;
166     int i, nb_chunks;
167 
168     trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
169 
170     s->in_flight--;
171     s->bytes_in_flight -= op->bytes;
172     iov = op->qiov.iov;
173     for (i = 0; i < op->qiov.niov; i++) {
174         MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
175         QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
176         s->buf_free_count++;
177     }
178 
179     chunk_num = op->offset / s->granularity;
180     nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
181 
182     bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
183     QTAILQ_REMOVE(&s->ops_in_flight, op, next);
184     if (ret >= 0) {
185         if (s->cow_bitmap) {
186             bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
187         }
188         if (!s->initial_zeroing_ongoing) {
189             job_progress_update(&s->common.job, op->bytes);
190         }
191     }
192     qemu_iovec_destroy(&op->qiov);
193 
194     qemu_co_queue_restart_all(&op->waiting_requests);
195     g_free(op);
196 }
197 
198 static void coroutine_fn mirror_write_complete(MirrorOp *op, int ret)
199 {
200     MirrorBlockJob *s = op->s;
201 
202     aio_context_acquire(blk_get_aio_context(s->common.blk));
203     if (ret < 0) {
204         BlockErrorAction action;
205 
206         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
207         action = mirror_error_action(s, false, -ret);
208         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
209             s->ret = ret;
210         }
211     }
212     mirror_iteration_done(op, ret);
213     aio_context_release(blk_get_aio_context(s->common.blk));
214 }
215 
216 static void coroutine_fn mirror_read_complete(MirrorOp *op, int ret)
217 {
218     MirrorBlockJob *s = op->s;
219 
220     aio_context_acquire(blk_get_aio_context(s->common.blk));
221     if (ret < 0) {
222         BlockErrorAction action;
223 
224         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
225         action = mirror_error_action(s, true, -ret);
226         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
227             s->ret = ret;
228         }
229 
230         mirror_iteration_done(op, ret);
231     } else {
232         ret = blk_co_pwritev(s->target, op->offset,
233                              op->qiov.size, &op->qiov, 0);
234         mirror_write_complete(op, ret);
235     }
236     aio_context_release(blk_get_aio_context(s->common.blk));
237 }
238 
239 /* Clip bytes relative to offset to not exceed end-of-file */
240 static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
241                                         int64_t offset,
242                                         int64_t bytes)
243 {
244     return MIN(bytes, s->bdev_length - offset);
245 }
246 
247 /* Round offset and/or bytes to target cluster if COW is needed, and
248  * return the offset of the adjusted tail against original. */
249 static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
250                             uint64_t *bytes)
251 {
252     bool need_cow;
253     int ret = 0;
254     int64_t align_offset = *offset;
255     int64_t align_bytes = *bytes;
256     int max_bytes = s->granularity * s->max_iov;
257 
258     need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
259     need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
260                           s->cow_bitmap);
261     if (need_cow) {
262         bdrv_round_to_clusters(blk_bs(s->target), *offset, *bytes,
263                                &align_offset, &align_bytes);
264     }
265 
266     if (align_bytes > max_bytes) {
267         align_bytes = max_bytes;
268         if (need_cow) {
269             align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
270         }
271     }
272     /* Clipping may result in align_bytes unaligned to chunk boundary, but
273      * that doesn't matter because it's already the end of source image. */
274     align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
275 
276     ret = align_offset + align_bytes - (*offset + *bytes);
277     *offset = align_offset;
278     *bytes = align_bytes;
279     assert(ret >= 0);
280     return ret;
281 }
282 
283 static inline void mirror_wait_for_any_operation(MirrorBlockJob *s, bool active)
284 {
285     MirrorOp *op;
286 
287     QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
288         /* Do not wait on pseudo ops, because it may in turn wait on
289          * some other operation to start, which may in fact be the
290          * caller of this function.  Since there is only one pseudo op
291          * at any given time, we will always find some real operation
292          * to wait on. */
293         if (!op->is_pseudo_op && op->is_active_write == active) {
294             qemu_co_queue_wait(&op->waiting_requests, NULL);
295             return;
296         }
297     }
298     abort();
299 }
300 
301 static inline void mirror_wait_for_free_in_flight_slot(MirrorBlockJob *s)
302 {
303     /* Only non-active operations use up in-flight slots */
304     mirror_wait_for_any_operation(s, false);
305 }
306 
307 /* Perform a mirror copy operation.
308  *
309  * *op->bytes_handled is set to the number of bytes copied after and
310  * including offset, excluding any bytes copied prior to offset due
311  * to alignment.  This will be op->bytes if no alignment is necessary,
312  * or (new_end - op->offset) if the tail is rounded up or down due to
313  * alignment or buffer limit.
314  */
315 static void coroutine_fn mirror_co_read(void *opaque)
316 {
317     MirrorOp *op = opaque;
318     MirrorBlockJob *s = op->s;
319     int nb_chunks;
320     uint64_t ret;
321     uint64_t max_bytes;
322 
323     max_bytes = s->granularity * s->max_iov;
324 
325     /* We can only handle as much as buf_size at a time. */
326     op->bytes = MIN(s->buf_size, MIN(max_bytes, op->bytes));
327     assert(op->bytes);
328     assert(op->bytes < BDRV_REQUEST_MAX_BYTES);
329     *op->bytes_handled = op->bytes;
330 
331     if (s->cow_bitmap) {
332         *op->bytes_handled += mirror_cow_align(s, &op->offset, &op->bytes);
333     }
334     /* Cannot exceed BDRV_REQUEST_MAX_BYTES + INT_MAX */
335     assert(*op->bytes_handled <= UINT_MAX);
336     assert(op->bytes <= s->buf_size);
337     /* The offset is granularity-aligned because:
338      * 1) Caller passes in aligned values;
339      * 2) mirror_cow_align is used only when target cluster is larger. */
340     assert(QEMU_IS_ALIGNED(op->offset, s->granularity));
341     /* The range is sector-aligned, since bdrv_getlength() rounds up. */
342     assert(QEMU_IS_ALIGNED(op->bytes, BDRV_SECTOR_SIZE));
343     nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
344 
345     while (s->buf_free_count < nb_chunks) {
346         trace_mirror_yield_in_flight(s, op->offset, s->in_flight);
347         mirror_wait_for_free_in_flight_slot(s);
348     }
349 
350     /* Now make a QEMUIOVector taking enough granularity-sized chunks
351      * from s->buf_free.
352      */
353     qemu_iovec_init(&op->qiov, nb_chunks);
354     while (nb_chunks-- > 0) {
355         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
356         size_t remaining = op->bytes - op->qiov.size;
357 
358         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
359         s->buf_free_count--;
360         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
361     }
362 
363     /* Copy the dirty cluster.  */
364     s->in_flight++;
365     s->bytes_in_flight += op->bytes;
366     trace_mirror_one_iteration(s, op->offset, op->bytes);
367 
368     ret = bdrv_co_preadv(s->mirror_top_bs->backing, op->offset, op->bytes,
369                          &op->qiov, 0);
370     mirror_read_complete(op, ret);
371 }
372 
373 static void coroutine_fn mirror_co_zero(void *opaque)
374 {
375     MirrorOp *op = opaque;
376     int ret;
377 
378     op->s->in_flight++;
379     op->s->bytes_in_flight += op->bytes;
380     *op->bytes_handled = op->bytes;
381 
382     ret = blk_co_pwrite_zeroes(op->s->target, op->offset, op->bytes,
383                                op->s->unmap ? BDRV_REQ_MAY_UNMAP : 0);
384     mirror_write_complete(op, ret);
385 }
386 
387 static void coroutine_fn mirror_co_discard(void *opaque)
388 {
389     MirrorOp *op = opaque;
390     int ret;
391 
392     op->s->in_flight++;
393     op->s->bytes_in_flight += op->bytes;
394     *op->bytes_handled = op->bytes;
395 
396     ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes);
397     mirror_write_complete(op, ret);
398 }
399 
400 static unsigned mirror_perform(MirrorBlockJob *s, int64_t offset,
401                                unsigned bytes, MirrorMethod mirror_method)
402 {
403     MirrorOp *op;
404     Coroutine *co;
405     int64_t bytes_handled = -1;
406 
407     op = g_new(MirrorOp, 1);
408     *op = (MirrorOp){
409         .s              = s,
410         .offset         = offset,
411         .bytes          = bytes,
412         .bytes_handled  = &bytes_handled,
413     };
414     qemu_co_queue_init(&op->waiting_requests);
415 
416     switch (mirror_method) {
417     case MIRROR_METHOD_COPY:
418         co = qemu_coroutine_create(mirror_co_read, op);
419         break;
420     case MIRROR_METHOD_ZERO:
421         co = qemu_coroutine_create(mirror_co_zero, op);
422         break;
423     case MIRROR_METHOD_DISCARD:
424         co = qemu_coroutine_create(mirror_co_discard, op);
425         break;
426     default:
427         abort();
428     }
429 
430     QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
431     qemu_coroutine_enter(co);
432     /* At this point, ownership of op has been moved to the coroutine
433      * and the object may already be freed */
434 
435     /* Assert that this value has been set */
436     assert(bytes_handled >= 0);
437 
438     /* Same assertion as in mirror_co_read() (and for mirror_co_read()
439      * and mirror_co_discard(), bytes_handled == op->bytes, which
440      * is the @bytes parameter given to this function) */
441     assert(bytes_handled <= UINT_MAX);
442     return bytes_handled;
443 }
444 
445 static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
446 {
447     BlockDriverState *source = s->mirror_top_bs->backing->bs;
448     MirrorOp *pseudo_op;
449     int64_t offset;
450     uint64_t delay_ns = 0, ret = 0;
451     /* At least the first dirty chunk is mirrored in one iteration. */
452     int nb_chunks = 1;
453     bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
454     int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
455 
456     bdrv_dirty_bitmap_lock(s->dirty_bitmap);
457     offset = bdrv_dirty_iter_next(s->dbi);
458     if (offset < 0) {
459         bdrv_set_dirty_iter(s->dbi, 0);
460         offset = bdrv_dirty_iter_next(s->dbi);
461         trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
462         assert(offset >= 0);
463     }
464     bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
465 
466     mirror_wait_on_conflicts(NULL, s, offset, 1);
467 
468     job_pause_point(&s->common.job);
469 
470     /* Find the number of consective dirty chunks following the first dirty
471      * one, and wait for in flight requests in them. */
472     bdrv_dirty_bitmap_lock(s->dirty_bitmap);
473     while (nb_chunks * s->granularity < s->buf_size) {
474         int64_t next_dirty;
475         int64_t next_offset = offset + nb_chunks * s->granularity;
476         int64_t next_chunk = next_offset / s->granularity;
477         if (next_offset >= s->bdev_length ||
478             !bdrv_get_dirty_locked(source, s->dirty_bitmap, next_offset)) {
479             break;
480         }
481         if (test_bit(next_chunk, s->in_flight_bitmap)) {
482             break;
483         }
484 
485         next_dirty = bdrv_dirty_iter_next(s->dbi);
486         if (next_dirty > next_offset || next_dirty < 0) {
487             /* The bitmap iterator's cache is stale, refresh it */
488             bdrv_set_dirty_iter(s->dbi, next_offset);
489             next_dirty = bdrv_dirty_iter_next(s->dbi);
490         }
491         assert(next_dirty == next_offset);
492         nb_chunks++;
493     }
494 
495     /* Clear dirty bits before querying the block status, because
496      * calling bdrv_block_status_above could yield - if some blocks are
497      * marked dirty in this window, we need to know.
498      */
499     bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
500                                    nb_chunks * s->granularity);
501     bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
502 
503     /* Before claiming an area in the in-flight bitmap, we have to
504      * create a MirrorOp for it so that conflicting requests can wait
505      * for it.  mirror_perform() will create the real MirrorOps later,
506      * for now we just create a pseudo operation that will wake up all
507      * conflicting requests once all real operations have been
508      * launched. */
509     pseudo_op = g_new(MirrorOp, 1);
510     *pseudo_op = (MirrorOp){
511         .offset         = offset,
512         .bytes          = nb_chunks * s->granularity,
513         .is_pseudo_op   = true,
514     };
515     qemu_co_queue_init(&pseudo_op->waiting_requests);
516     QTAILQ_INSERT_TAIL(&s->ops_in_flight, pseudo_op, next);
517 
518     bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
519     while (nb_chunks > 0 && offset < s->bdev_length) {
520         int ret;
521         int64_t io_bytes;
522         int64_t io_bytes_acct;
523         MirrorMethod mirror_method = MIRROR_METHOD_COPY;
524 
525         assert(!(offset % s->granularity));
526         ret = bdrv_block_status_above(source, NULL, offset,
527                                       nb_chunks * s->granularity,
528                                       &io_bytes, NULL, NULL);
529         if (ret < 0) {
530             io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
531         } else if (ret & BDRV_BLOCK_DATA) {
532             io_bytes = MIN(io_bytes, max_io_bytes);
533         }
534 
535         io_bytes -= io_bytes % s->granularity;
536         if (io_bytes < s->granularity) {
537             io_bytes = s->granularity;
538         } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
539             int64_t target_offset;
540             int64_t target_bytes;
541             bdrv_round_to_clusters(blk_bs(s->target), offset, io_bytes,
542                                    &target_offset, &target_bytes);
543             if (target_offset == offset &&
544                 target_bytes == io_bytes) {
545                 mirror_method = ret & BDRV_BLOCK_ZERO ?
546                                     MIRROR_METHOD_ZERO :
547                                     MIRROR_METHOD_DISCARD;
548             }
549         }
550 
551         while (s->in_flight >= MAX_IN_FLIGHT) {
552             trace_mirror_yield_in_flight(s, offset, s->in_flight);
553             mirror_wait_for_free_in_flight_slot(s);
554         }
555 
556         if (s->ret < 0) {
557             ret = 0;
558             goto fail;
559         }
560 
561         io_bytes = mirror_clip_bytes(s, offset, io_bytes);
562         io_bytes = mirror_perform(s, offset, io_bytes, mirror_method);
563         if (mirror_method != MIRROR_METHOD_COPY && write_zeroes_ok) {
564             io_bytes_acct = 0;
565         } else {
566             io_bytes_acct = io_bytes;
567         }
568         assert(io_bytes);
569         offset += io_bytes;
570         nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
571         delay_ns = block_job_ratelimit_get_delay(&s->common, io_bytes_acct);
572     }
573 
574     ret = delay_ns;
575 fail:
576     QTAILQ_REMOVE(&s->ops_in_flight, pseudo_op, next);
577     qemu_co_queue_restart_all(&pseudo_op->waiting_requests);
578     g_free(pseudo_op);
579 
580     return ret;
581 }
582 
583 static void mirror_free_init(MirrorBlockJob *s)
584 {
585     int granularity = s->granularity;
586     size_t buf_size = s->buf_size;
587     uint8_t *buf = s->buf;
588 
589     assert(s->buf_free_count == 0);
590     QSIMPLEQ_INIT(&s->buf_free);
591     while (buf_size != 0) {
592         MirrorBuffer *cur = (MirrorBuffer *)buf;
593         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
594         s->buf_free_count++;
595         buf_size -= granularity;
596         buf += granularity;
597     }
598 }
599 
600 /* This is also used for the .pause callback. There is no matching
601  * mirror_resume() because mirror_run() will begin iterating again
602  * when the job is resumed.
603  */
604 static void mirror_wait_for_all_io(MirrorBlockJob *s)
605 {
606     while (s->in_flight > 0) {
607         mirror_wait_for_free_in_flight_slot(s);
608     }
609 }
610 
611 /**
612  * mirror_exit_common: handle both abort() and prepare() cases.
613  * for .prepare, returns 0 on success and -errno on failure.
614  * for .abort cases, denoted by abort = true, MUST return 0.
615  */
616 static int mirror_exit_common(Job *job)
617 {
618     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
619     BlockJob *bjob = &s->common;
620     MirrorBDSOpaque *bs_opaque = s->mirror_top_bs->opaque;
621     AioContext *replace_aio_context = NULL;
622     BlockDriverState *src = s->mirror_top_bs->backing->bs;
623     BlockDriverState *target_bs = blk_bs(s->target);
624     BlockDriverState *mirror_top_bs = s->mirror_top_bs;
625     Error *local_err = NULL;
626     bool abort = job->ret < 0;
627     int ret = 0;
628 
629     if (s->prepared) {
630         return 0;
631     }
632     s->prepared = true;
633 
634     bdrv_release_dirty_bitmap(src, s->dirty_bitmap);
635 
636     /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
637      * before we can call bdrv_drained_end */
638     bdrv_ref(src);
639     bdrv_ref(mirror_top_bs);
640     bdrv_ref(target_bs);
641 
642     /* Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
643      * inserting target_bs at s->to_replace, where we might not be able to get
644      * these permissions.
645      *
646      * Note that blk_unref() alone doesn't necessarily drop permissions because
647      * we might be running nested inside mirror_drain(), which takes an extra
648      * reference, so use an explicit blk_set_perm() first. */
649     blk_set_perm(s->target, 0, BLK_PERM_ALL, &error_abort);
650     blk_unref(s->target);
651     s->target = NULL;
652 
653     /* We don't access the source any more. Dropping any WRITE/RESIZE is
654      * required before it could become a backing file of target_bs. */
655     bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
656                             &error_abort);
657     if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
658         BlockDriverState *backing = s->is_none_mode ? src : s->base;
659         if (backing_bs(target_bs) != backing) {
660             bdrv_set_backing_hd(target_bs, backing, &local_err);
661             if (local_err) {
662                 error_report_err(local_err);
663                 ret = -EPERM;
664             }
665         }
666     }
667 
668     if (s->to_replace) {
669         replace_aio_context = bdrv_get_aio_context(s->to_replace);
670         aio_context_acquire(replace_aio_context);
671     }
672 
673     if (s->should_complete && !abort) {
674         BlockDriverState *to_replace = s->to_replace ?: src;
675 
676         if (bdrv_get_flags(target_bs) != bdrv_get_flags(to_replace)) {
677             bdrv_reopen(target_bs, bdrv_get_flags(to_replace), NULL);
678         }
679 
680         /* The mirror job has no requests in flight any more, but we need to
681          * drain potential other users of the BDS before changing the graph. */
682         bdrv_drained_begin(target_bs);
683         bdrv_replace_node(to_replace, target_bs, &local_err);
684         bdrv_drained_end(target_bs);
685         if (local_err) {
686             error_report_err(local_err);
687             ret = -EPERM;
688         }
689     }
690     if (s->to_replace) {
691         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
692         error_free(s->replace_blocker);
693         bdrv_unref(s->to_replace);
694     }
695     if (replace_aio_context) {
696         aio_context_release(replace_aio_context);
697     }
698     g_free(s->replaces);
699     bdrv_unref(target_bs);
700 
701     /* Remove the mirror filter driver from the graph. Before this, get rid of
702      * the blockers on the intermediate nodes so that the resulting state is
703      * valid. Also give up permissions on mirror_top_bs->backing, which might
704      * block the removal. */
705     block_job_remove_all_bdrv(bjob);
706     bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
707                             &error_abort);
708     bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
709 
710     /* We just changed the BDS the job BB refers to (with either or both of the
711      * bdrv_replace_node() calls), so switch the BB back so the cleanup does
712      * the right thing. We don't need any permissions any more now. */
713     blk_remove_bs(bjob->blk);
714     blk_set_perm(bjob->blk, 0, BLK_PERM_ALL, &error_abort);
715     blk_insert_bs(bjob->blk, mirror_top_bs, &error_abort);
716 
717     bs_opaque->job = NULL;
718 
719     bdrv_drained_end(src);
720     bdrv_unref(mirror_top_bs);
721     bdrv_unref(src);
722 
723     return ret;
724 }
725 
726 static int mirror_prepare(Job *job)
727 {
728     return mirror_exit_common(job);
729 }
730 
731 static void mirror_abort(Job *job)
732 {
733     int ret = mirror_exit_common(job);
734     assert(ret == 0);
735 }
736 
737 static void mirror_throttle(MirrorBlockJob *s)
738 {
739     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
740 
741     if (now - s->last_pause_ns > BLOCK_JOB_SLICE_TIME) {
742         s->last_pause_ns = now;
743         job_sleep_ns(&s->common.job, 0);
744     } else {
745         job_pause_point(&s->common.job);
746     }
747 }
748 
749 static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
750 {
751     int64_t offset;
752     BlockDriverState *base = s->base;
753     BlockDriverState *bs = s->mirror_top_bs->backing->bs;
754     BlockDriverState *target_bs = blk_bs(s->target);
755     int ret;
756     int64_t count;
757 
758     if (base == NULL && !bdrv_has_zero_init(target_bs)) {
759         if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
760             bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
761             return 0;
762         }
763 
764         s->initial_zeroing_ongoing = true;
765         for (offset = 0; offset < s->bdev_length; ) {
766             int bytes = MIN(s->bdev_length - offset,
767                             QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
768 
769             mirror_throttle(s);
770 
771             if (job_is_cancelled(&s->common.job)) {
772                 s->initial_zeroing_ongoing = false;
773                 return 0;
774             }
775 
776             if (s->in_flight >= MAX_IN_FLIGHT) {
777                 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
778                                    s->in_flight);
779                 mirror_wait_for_free_in_flight_slot(s);
780                 continue;
781             }
782 
783             mirror_perform(s, offset, bytes, MIRROR_METHOD_ZERO);
784             offset += bytes;
785         }
786 
787         mirror_wait_for_all_io(s);
788         s->initial_zeroing_ongoing = false;
789     }
790 
791     /* First part, loop on the sectors and initialize the dirty bitmap.  */
792     for (offset = 0; offset < s->bdev_length; ) {
793         /* Just to make sure we are not exceeding int limit. */
794         int bytes = MIN(s->bdev_length - offset,
795                         QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
796 
797         mirror_throttle(s);
798 
799         if (job_is_cancelled(&s->common.job)) {
800             return 0;
801         }
802 
803         ret = bdrv_is_allocated_above(bs, base, offset, bytes, &count);
804         if (ret < 0) {
805             return ret;
806         }
807 
808         assert(count);
809         if (ret == 1) {
810             bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
811         }
812         offset += count;
813     }
814     return 0;
815 }
816 
817 /* Called when going out of the streaming phase to flush the bulk of the
818  * data to the medium, or just before completing.
819  */
820 static int mirror_flush(MirrorBlockJob *s)
821 {
822     int ret = blk_flush(s->target);
823     if (ret < 0) {
824         if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
825             s->ret = ret;
826         }
827     }
828     return ret;
829 }
830 
831 static int coroutine_fn mirror_run(Job *job, Error **errp)
832 {
833     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
834     BlockDriverState *bs = s->mirror_top_bs->backing->bs;
835     BlockDriverState *target_bs = blk_bs(s->target);
836     bool need_drain = true;
837     int64_t length;
838     BlockDriverInfo bdi;
839     char backing_filename[2]; /* we only need 2 characters because we are only
840                                  checking for a NULL string */
841     int ret = 0;
842 
843     if (job_is_cancelled(&s->common.job)) {
844         goto immediate_exit;
845     }
846 
847     s->bdev_length = bdrv_getlength(bs);
848     if (s->bdev_length < 0) {
849         ret = s->bdev_length;
850         goto immediate_exit;
851     }
852 
853     /* Active commit must resize the base image if its size differs from the
854      * active layer. */
855     if (s->base == blk_bs(s->target)) {
856         int64_t base_length;
857 
858         base_length = blk_getlength(s->target);
859         if (base_length < 0) {
860             ret = base_length;
861             goto immediate_exit;
862         }
863 
864         if (s->bdev_length > base_length) {
865             ret = blk_truncate(s->target, s->bdev_length, PREALLOC_MODE_OFF,
866                                NULL);
867             if (ret < 0) {
868                 goto immediate_exit;
869             }
870         }
871     }
872 
873     if (s->bdev_length == 0) {
874         /* Transition to the READY state and wait for complete. */
875         job_transition_to_ready(&s->common.job);
876         s->synced = true;
877         s->actively_synced = true;
878         while (!job_is_cancelled(&s->common.job) && !s->should_complete) {
879             job_yield(&s->common.job);
880         }
881         s->common.job.cancelled = false;
882         goto immediate_exit;
883     }
884 
885     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
886     s->in_flight_bitmap = bitmap_new(length);
887 
888     /* If we have no backing file yet in the destination, we cannot let
889      * the destination do COW.  Instead, we copy sectors around the
890      * dirty data if needed.  We need a bitmap to do that.
891      */
892     bdrv_get_backing_filename(target_bs, backing_filename,
893                               sizeof(backing_filename));
894     if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
895         s->target_cluster_size = bdi.cluster_size;
896     } else {
897         s->target_cluster_size = BDRV_SECTOR_SIZE;
898     }
899     if (backing_filename[0] && !target_bs->backing &&
900         s->granularity < s->target_cluster_size) {
901         s->buf_size = MAX(s->buf_size, s->target_cluster_size);
902         s->cow_bitmap = bitmap_new(length);
903     }
904     s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
905 
906     s->buf = qemu_try_blockalign(bs, s->buf_size);
907     if (s->buf == NULL) {
908         ret = -ENOMEM;
909         goto immediate_exit;
910     }
911 
912     mirror_free_init(s);
913 
914     s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
915     if (!s->is_none_mode) {
916         ret = mirror_dirty_init(s);
917         if (ret < 0 || job_is_cancelled(&s->common.job)) {
918             goto immediate_exit;
919         }
920     }
921 
922     assert(!s->dbi);
923     s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
924     for (;;) {
925         uint64_t delay_ns = 0;
926         int64_t cnt, delta;
927         bool should_complete;
928 
929         /* Do not start passive operations while there are active
930          * writes in progress */
931         while (s->in_active_write_counter) {
932             mirror_wait_for_any_operation(s, true);
933         }
934 
935         if (s->ret < 0) {
936             ret = s->ret;
937             goto immediate_exit;
938         }
939 
940         job_pause_point(&s->common.job);
941 
942         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
943         /* cnt is the number of dirty bytes remaining and s->bytes_in_flight is
944          * the number of bytes currently being processed; together those are
945          * the current remaining operation length */
946         job_progress_set_remaining(&s->common.job, s->bytes_in_flight + cnt);
947 
948         /* Note that even when no rate limit is applied we need to yield
949          * periodically with no pending I/O so that bdrv_drain_all() returns.
950          * We do so every BLKOCK_JOB_SLICE_TIME nanoseconds, or when there is
951          * an error, or when the source is clean, whichever comes first. */
952         delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
953         if (delta < BLOCK_JOB_SLICE_TIME &&
954             s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
955             if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
956                 (cnt == 0 && s->in_flight > 0)) {
957                 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
958                 mirror_wait_for_free_in_flight_slot(s);
959                 continue;
960             } else if (cnt != 0) {
961                 delay_ns = mirror_iteration(s);
962             }
963         }
964 
965         should_complete = false;
966         if (s->in_flight == 0 && cnt == 0) {
967             trace_mirror_before_flush(s);
968             if (!s->synced) {
969                 if (mirror_flush(s) < 0) {
970                     /* Go check s->ret.  */
971                     continue;
972                 }
973                 /* We're out of the streaming phase.  From now on, if the job
974                  * is cancelled we will actually complete all pending I/O and
975                  * report completion.  This way, block-job-cancel will leave
976                  * the target in a consistent state.
977                  */
978                 job_transition_to_ready(&s->common.job);
979                 s->synced = true;
980                 if (s->copy_mode != MIRROR_COPY_MODE_BACKGROUND) {
981                     s->actively_synced = true;
982                 }
983             }
984 
985             should_complete = s->should_complete ||
986                 job_is_cancelled(&s->common.job);
987             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
988         }
989 
990         if (cnt == 0 && should_complete) {
991             /* The dirty bitmap is not updated while operations are pending.
992              * If we're about to exit, wait for pending operations before
993              * calling bdrv_get_dirty_count(bs), or we may exit while the
994              * source has dirty data to copy!
995              *
996              * Note that I/O can be submitted by the guest while
997              * mirror_populate runs, so pause it now.  Before deciding
998              * whether to switch to target check one last time if I/O has
999              * come in the meanwhile, and if not flush the data to disk.
1000              */
1001             trace_mirror_before_drain(s, cnt);
1002 
1003             bdrv_drained_begin(bs);
1004             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1005             if (cnt > 0 || mirror_flush(s) < 0) {
1006                 bdrv_drained_end(bs);
1007                 continue;
1008             }
1009 
1010             /* The two disks are in sync.  Exit and report successful
1011              * completion.
1012              */
1013             assert(QLIST_EMPTY(&bs->tracked_requests));
1014             s->common.job.cancelled = false;
1015             need_drain = false;
1016             break;
1017         }
1018 
1019         ret = 0;
1020 
1021         if (s->synced && !should_complete) {
1022             delay_ns = (s->in_flight == 0 &&
1023                         cnt == 0 ? BLOCK_JOB_SLICE_TIME : 0);
1024         }
1025         trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
1026         job_sleep_ns(&s->common.job, delay_ns);
1027         if (job_is_cancelled(&s->common.job) &&
1028             (!s->synced || s->common.job.force_cancel))
1029         {
1030             break;
1031         }
1032         s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1033     }
1034 
1035 immediate_exit:
1036     if (s->in_flight > 0) {
1037         /* We get here only if something went wrong.  Either the job failed,
1038          * or it was cancelled prematurely so that we do not guarantee that
1039          * the target is a copy of the source.
1040          */
1041         assert(ret < 0 || ((s->common.job.force_cancel || !s->synced) &&
1042                job_is_cancelled(&s->common.job)));
1043         assert(need_drain);
1044         mirror_wait_for_all_io(s);
1045     }
1046 
1047     assert(s->in_flight == 0);
1048     qemu_vfree(s->buf);
1049     g_free(s->cow_bitmap);
1050     g_free(s->in_flight_bitmap);
1051     bdrv_dirty_iter_free(s->dbi);
1052 
1053     if (need_drain) {
1054         bdrv_drained_begin(bs);
1055     }
1056 
1057     return ret;
1058 }
1059 
1060 static void mirror_complete(Job *job, Error **errp)
1061 {
1062     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1063     BlockDriverState *target;
1064 
1065     target = blk_bs(s->target);
1066 
1067     if (!s->synced) {
1068         error_setg(errp, "The active block job '%s' cannot be completed",
1069                    job->id);
1070         return;
1071     }
1072 
1073     if (s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
1074         int ret;
1075 
1076         assert(!target->backing);
1077         ret = bdrv_open_backing_file(target, NULL, "backing", errp);
1078         if (ret < 0) {
1079             return;
1080         }
1081     }
1082 
1083     /* block all operations on to_replace bs */
1084     if (s->replaces) {
1085         AioContext *replace_aio_context;
1086 
1087         s->to_replace = bdrv_find_node(s->replaces);
1088         if (!s->to_replace) {
1089             error_setg(errp, "Node name '%s' not found", s->replaces);
1090             return;
1091         }
1092 
1093         replace_aio_context = bdrv_get_aio_context(s->to_replace);
1094         aio_context_acquire(replace_aio_context);
1095 
1096         /* TODO Translate this into permission system. Current definition of
1097          * GRAPH_MOD would require to request it for the parents; they might
1098          * not even be BlockDriverStates, however, so a BdrvChild can't address
1099          * them. May need redefinition of GRAPH_MOD. */
1100         error_setg(&s->replace_blocker,
1101                    "block device is in use by block-job-complete");
1102         bdrv_op_block_all(s->to_replace, s->replace_blocker);
1103         bdrv_ref(s->to_replace);
1104 
1105         aio_context_release(replace_aio_context);
1106     }
1107 
1108     s->should_complete = true;
1109     job_enter(job);
1110 }
1111 
1112 static void mirror_pause(Job *job)
1113 {
1114     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1115 
1116     mirror_wait_for_all_io(s);
1117 }
1118 
1119 static bool mirror_drained_poll(BlockJob *job)
1120 {
1121     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1122     return !!s->in_flight;
1123 }
1124 
1125 static void mirror_attached_aio_context(BlockJob *job, AioContext *new_context)
1126 {
1127     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1128 
1129     blk_set_aio_context(s->target, new_context);
1130 }
1131 
1132 static void mirror_drain(BlockJob *job)
1133 {
1134     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1135 
1136     /* Need to keep a reference in case blk_drain triggers execution
1137      * of mirror_complete...
1138      */
1139     if (s->target) {
1140         BlockBackend *target = s->target;
1141         blk_ref(target);
1142         blk_drain(target);
1143         blk_unref(target);
1144     }
1145 }
1146 
1147 static const BlockJobDriver mirror_job_driver = {
1148     .job_driver = {
1149         .instance_size          = sizeof(MirrorBlockJob),
1150         .job_type               = JOB_TYPE_MIRROR,
1151         .free                   = block_job_free,
1152         .user_resume            = block_job_user_resume,
1153         .drain                  = block_job_drain,
1154         .run                    = mirror_run,
1155         .prepare                = mirror_prepare,
1156         .abort                  = mirror_abort,
1157         .pause                  = mirror_pause,
1158         .complete               = mirror_complete,
1159     },
1160     .drained_poll           = mirror_drained_poll,
1161     .attached_aio_context   = mirror_attached_aio_context,
1162     .drain                  = mirror_drain,
1163 };
1164 
1165 static const BlockJobDriver commit_active_job_driver = {
1166     .job_driver = {
1167         .instance_size          = sizeof(MirrorBlockJob),
1168         .job_type               = JOB_TYPE_COMMIT,
1169         .free                   = block_job_free,
1170         .user_resume            = block_job_user_resume,
1171         .drain                  = block_job_drain,
1172         .run                    = mirror_run,
1173         .prepare                = mirror_prepare,
1174         .abort                  = mirror_abort,
1175         .pause                  = mirror_pause,
1176         .complete               = mirror_complete,
1177     },
1178     .drained_poll           = mirror_drained_poll,
1179     .attached_aio_context   = mirror_attached_aio_context,
1180     .drain                  = mirror_drain,
1181 };
1182 
1183 static void do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
1184                                  uint64_t offset, uint64_t bytes,
1185                                  QEMUIOVector *qiov, int flags)
1186 {
1187     BdrvDirtyBitmapIter *iter;
1188     QEMUIOVector target_qiov;
1189     uint64_t dirty_offset;
1190     int dirty_bytes;
1191 
1192     if (qiov) {
1193         qemu_iovec_init(&target_qiov, qiov->niov);
1194     }
1195 
1196     iter = bdrv_dirty_iter_new(job->dirty_bitmap);
1197     bdrv_set_dirty_iter(iter, offset);
1198 
1199     while (true) {
1200         bool valid_area;
1201         int ret;
1202 
1203         bdrv_dirty_bitmap_lock(job->dirty_bitmap);
1204         valid_area = bdrv_dirty_iter_next_area(iter, offset + bytes,
1205                                                &dirty_offset, &dirty_bytes);
1206         if (!valid_area) {
1207             bdrv_dirty_bitmap_unlock(job->dirty_bitmap);
1208             break;
1209         }
1210 
1211         bdrv_reset_dirty_bitmap_locked(job->dirty_bitmap,
1212                                        dirty_offset, dirty_bytes);
1213         bdrv_dirty_bitmap_unlock(job->dirty_bitmap);
1214 
1215         job_progress_increase_remaining(&job->common.job, dirty_bytes);
1216 
1217         assert(dirty_offset - offset <= SIZE_MAX);
1218         if (qiov) {
1219             qemu_iovec_reset(&target_qiov);
1220             qemu_iovec_concat(&target_qiov, qiov,
1221                               dirty_offset - offset, dirty_bytes);
1222         }
1223 
1224         switch (method) {
1225         case MIRROR_METHOD_COPY:
1226             ret = blk_co_pwritev(job->target, dirty_offset, dirty_bytes,
1227                                  qiov ? &target_qiov : NULL, flags);
1228             break;
1229 
1230         case MIRROR_METHOD_ZERO:
1231             assert(!qiov);
1232             ret = blk_co_pwrite_zeroes(job->target, dirty_offset, dirty_bytes,
1233                                        flags);
1234             break;
1235 
1236         case MIRROR_METHOD_DISCARD:
1237             assert(!qiov);
1238             ret = blk_co_pdiscard(job->target, dirty_offset, dirty_bytes);
1239             break;
1240 
1241         default:
1242             abort();
1243         }
1244 
1245         if (ret >= 0) {
1246             job_progress_update(&job->common.job, dirty_bytes);
1247         } else {
1248             BlockErrorAction action;
1249 
1250             bdrv_set_dirty_bitmap(job->dirty_bitmap, dirty_offset, dirty_bytes);
1251             job->actively_synced = false;
1252 
1253             action = mirror_error_action(job, false, -ret);
1254             if (action == BLOCK_ERROR_ACTION_REPORT) {
1255                 if (!job->ret) {
1256                     job->ret = ret;
1257                 }
1258                 break;
1259             }
1260         }
1261     }
1262 
1263     bdrv_dirty_iter_free(iter);
1264     if (qiov) {
1265         qemu_iovec_destroy(&target_qiov);
1266     }
1267 }
1268 
1269 static MirrorOp *coroutine_fn active_write_prepare(MirrorBlockJob *s,
1270                                                    uint64_t offset,
1271                                                    uint64_t bytes)
1272 {
1273     MirrorOp *op;
1274     uint64_t start_chunk = offset / s->granularity;
1275     uint64_t end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1276 
1277     op = g_new(MirrorOp, 1);
1278     *op = (MirrorOp){
1279         .s                  = s,
1280         .offset             = offset,
1281         .bytes              = bytes,
1282         .is_active_write    = true,
1283     };
1284     qemu_co_queue_init(&op->waiting_requests);
1285     QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
1286 
1287     s->in_active_write_counter++;
1288 
1289     mirror_wait_on_conflicts(op, s, offset, bytes);
1290 
1291     bitmap_set(s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1292 
1293     return op;
1294 }
1295 
1296 static void coroutine_fn active_write_settle(MirrorOp *op)
1297 {
1298     uint64_t start_chunk = op->offset / op->s->granularity;
1299     uint64_t end_chunk = DIV_ROUND_UP(op->offset + op->bytes,
1300                                       op->s->granularity);
1301 
1302     if (!--op->s->in_active_write_counter && op->s->actively_synced) {
1303         BdrvChild *source = op->s->mirror_top_bs->backing;
1304 
1305         if (QLIST_FIRST(&source->bs->parents) == source &&
1306             QLIST_NEXT(source, next_parent) == NULL)
1307         {
1308             /* Assert that we are back in sync once all active write
1309              * operations are settled.
1310              * Note that we can only assert this if the mirror node
1311              * is the source node's only parent. */
1312             assert(!bdrv_get_dirty_count(op->s->dirty_bitmap));
1313         }
1314     }
1315     bitmap_clear(op->s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1316     QTAILQ_REMOVE(&op->s->ops_in_flight, op, next);
1317     qemu_co_queue_restart_all(&op->waiting_requests);
1318     g_free(op);
1319 }
1320 
1321 static int coroutine_fn bdrv_mirror_top_preadv(BlockDriverState *bs,
1322     uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1323 {
1324     return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
1325 }
1326 
1327 static int coroutine_fn bdrv_mirror_top_do_write(BlockDriverState *bs,
1328     MirrorMethod method, uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
1329     int flags)
1330 {
1331     MirrorOp *op = NULL;
1332     MirrorBDSOpaque *s = bs->opaque;
1333     int ret = 0;
1334     bool copy_to_target;
1335 
1336     copy_to_target = s->job->ret >= 0 &&
1337                      s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1338 
1339     if (copy_to_target) {
1340         op = active_write_prepare(s->job, offset, bytes);
1341     }
1342 
1343     switch (method) {
1344     case MIRROR_METHOD_COPY:
1345         ret = bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1346         break;
1347 
1348     case MIRROR_METHOD_ZERO:
1349         ret = bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
1350         break;
1351 
1352     case MIRROR_METHOD_DISCARD:
1353         ret = bdrv_co_pdiscard(bs->backing, offset, bytes);
1354         break;
1355 
1356     default:
1357         abort();
1358     }
1359 
1360     if (ret < 0) {
1361         goto out;
1362     }
1363 
1364     if (copy_to_target) {
1365         do_sync_target_write(s->job, method, offset, bytes, qiov, flags);
1366     }
1367 
1368 out:
1369     if (copy_to_target) {
1370         active_write_settle(op);
1371     }
1372     return ret;
1373 }
1374 
1375 static int coroutine_fn bdrv_mirror_top_pwritev(BlockDriverState *bs,
1376     uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1377 {
1378     MirrorBDSOpaque *s = bs->opaque;
1379     QEMUIOVector bounce_qiov;
1380     void *bounce_buf;
1381     int ret = 0;
1382     bool copy_to_target;
1383 
1384     copy_to_target = s->job->ret >= 0 &&
1385                      s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1386 
1387     if (copy_to_target) {
1388         /* The guest might concurrently modify the data to write; but
1389          * the data on source and destination must match, so we have
1390          * to use a bounce buffer if we are going to write to the
1391          * target now. */
1392         bounce_buf = qemu_blockalign(bs, bytes);
1393         iov_to_buf_full(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
1394 
1395         qemu_iovec_init(&bounce_qiov, 1);
1396         qemu_iovec_add(&bounce_qiov, bounce_buf, bytes);
1397         qiov = &bounce_qiov;
1398     }
1399 
1400     ret = bdrv_mirror_top_do_write(bs, MIRROR_METHOD_COPY, offset, bytes, qiov,
1401                                    flags);
1402 
1403     if (copy_to_target) {
1404         qemu_iovec_destroy(&bounce_qiov);
1405         qemu_vfree(bounce_buf);
1406     }
1407 
1408     return ret;
1409 }
1410 
1411 static int coroutine_fn bdrv_mirror_top_flush(BlockDriverState *bs)
1412 {
1413     if (bs->backing == NULL) {
1414         /* we can be here after failed bdrv_append in mirror_start_job */
1415         return 0;
1416     }
1417     return bdrv_co_flush(bs->backing->bs);
1418 }
1419 
1420 static int coroutine_fn bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs,
1421     int64_t offset, int bytes, BdrvRequestFlags flags)
1422 {
1423     return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_ZERO, offset, bytes, NULL,
1424                                     flags);
1425 }
1426 
1427 static int coroutine_fn bdrv_mirror_top_pdiscard(BlockDriverState *bs,
1428     int64_t offset, int bytes)
1429 {
1430     return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_DISCARD, offset, bytes,
1431                                     NULL, 0);
1432 }
1433 
1434 static void bdrv_mirror_top_refresh_filename(BlockDriverState *bs, QDict *opts)
1435 {
1436     if (bs->backing == NULL) {
1437         /* we can be here after failed bdrv_attach_child in
1438          * bdrv_set_backing_hd */
1439         return;
1440     }
1441     bdrv_refresh_filename(bs->backing->bs);
1442     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1443             bs->backing->bs->filename);
1444 }
1445 
1446 static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1447                                        const BdrvChildRole *role,
1448                                        BlockReopenQueue *reopen_queue,
1449                                        uint64_t perm, uint64_t shared,
1450                                        uint64_t *nperm, uint64_t *nshared)
1451 {
1452     /* Must be able to forward guest writes to the real image */
1453     *nperm = 0;
1454     if (perm & BLK_PERM_WRITE) {
1455         *nperm |= BLK_PERM_WRITE;
1456     }
1457 
1458     *nshared = BLK_PERM_ALL;
1459 }
1460 
1461 /* Dummy node that provides consistent read to its users without requiring it
1462  * from its backing file and that allows writes on the backing file chain. */
1463 static BlockDriver bdrv_mirror_top = {
1464     .format_name                = "mirror_top",
1465     .bdrv_co_preadv             = bdrv_mirror_top_preadv,
1466     .bdrv_co_pwritev            = bdrv_mirror_top_pwritev,
1467     .bdrv_co_pwrite_zeroes      = bdrv_mirror_top_pwrite_zeroes,
1468     .bdrv_co_pdiscard           = bdrv_mirror_top_pdiscard,
1469     .bdrv_co_flush              = bdrv_mirror_top_flush,
1470     .bdrv_co_block_status       = bdrv_co_block_status_from_backing,
1471     .bdrv_refresh_filename      = bdrv_mirror_top_refresh_filename,
1472     .bdrv_child_perm            = bdrv_mirror_top_child_perm,
1473 };
1474 
1475 static void mirror_start_job(const char *job_id, BlockDriverState *bs,
1476                              int creation_flags, BlockDriverState *target,
1477                              const char *replaces, int64_t speed,
1478                              uint32_t granularity, int64_t buf_size,
1479                              BlockMirrorBackingMode backing_mode,
1480                              BlockdevOnError on_source_error,
1481                              BlockdevOnError on_target_error,
1482                              bool unmap,
1483                              BlockCompletionFunc *cb,
1484                              void *opaque,
1485                              const BlockJobDriver *driver,
1486                              bool is_none_mode, BlockDriverState *base,
1487                              bool auto_complete, const char *filter_node_name,
1488                              bool is_mirror, MirrorCopyMode copy_mode,
1489                              Error **errp)
1490 {
1491     MirrorBlockJob *s;
1492     MirrorBDSOpaque *bs_opaque;
1493     BlockDriverState *mirror_top_bs;
1494     bool target_graph_mod;
1495     bool target_is_backing;
1496     Error *local_err = NULL;
1497     int ret;
1498 
1499     if (granularity == 0) {
1500         granularity = bdrv_get_default_bitmap_granularity(target);
1501     }
1502 
1503     assert(is_power_of_2(granularity));
1504 
1505     if (buf_size < 0) {
1506         error_setg(errp, "Invalid parameter 'buf-size'");
1507         return;
1508     }
1509 
1510     if (buf_size == 0) {
1511         buf_size = DEFAULT_MIRROR_BUF_SIZE;
1512     }
1513 
1514     if (bs == target) {
1515         error_setg(errp, "Can't mirror node into itself");
1516         return;
1517     }
1518 
1519     /* In the case of active commit, add dummy driver to provide consistent
1520      * reads on the top, while disabling it in the intermediate nodes, and make
1521      * the backing chain writable. */
1522     mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
1523                                          BDRV_O_RDWR, errp);
1524     if (mirror_top_bs == NULL) {
1525         return;
1526     }
1527     if (!filter_node_name) {
1528         mirror_top_bs->implicit = true;
1529     }
1530     mirror_top_bs->total_sectors = bs->total_sectors;
1531     mirror_top_bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED;
1532     mirror_top_bs->supported_zero_flags = BDRV_REQ_WRITE_UNCHANGED;
1533     bs_opaque = g_new0(MirrorBDSOpaque, 1);
1534     mirror_top_bs->opaque = bs_opaque;
1535     bdrv_set_aio_context(mirror_top_bs, bdrv_get_aio_context(bs));
1536 
1537     /* bdrv_append takes ownership of the mirror_top_bs reference, need to keep
1538      * it alive until block_job_create() succeeds even if bs has no parent. */
1539     bdrv_ref(mirror_top_bs);
1540     bdrv_drained_begin(bs);
1541     bdrv_append(mirror_top_bs, bs, &local_err);
1542     bdrv_drained_end(bs);
1543 
1544     if (local_err) {
1545         bdrv_unref(mirror_top_bs);
1546         error_propagate(errp, local_err);
1547         return;
1548     }
1549 
1550     /* Make sure that the source is not resized while the job is running */
1551     s = block_job_create(job_id, driver, NULL, mirror_top_bs,
1552                          BLK_PERM_CONSISTENT_READ,
1553                          BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1554                          BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD, speed,
1555                          creation_flags, cb, opaque, errp);
1556     if (!s) {
1557         goto fail;
1558     }
1559     bs_opaque->job = s;
1560 
1561     /* The block job now has a reference to this node */
1562     bdrv_unref(mirror_top_bs);
1563 
1564     s->mirror_top_bs = mirror_top_bs;
1565 
1566     /* No resize for the target either; while the mirror is still running, a
1567      * consistent read isn't necessarily possible. We could possibly allow
1568      * writes and graph modifications, though it would likely defeat the
1569      * purpose of a mirror, so leave them blocked for now.
1570      *
1571      * In the case of active commit, things look a bit different, though,
1572      * because the target is an already populated backing file in active use.
1573      * We can allow anything except resize there.*/
1574     target_is_backing = bdrv_chain_contains(bs, target);
1575     target_graph_mod = (backing_mode != MIRROR_LEAVE_BACKING_CHAIN);
1576     s->target = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE |
1577                         (target_graph_mod ? BLK_PERM_GRAPH_MOD : 0),
1578                         BLK_PERM_WRITE_UNCHANGED |
1579                         (target_is_backing ? BLK_PERM_CONSISTENT_READ |
1580                                              BLK_PERM_WRITE |
1581                                              BLK_PERM_GRAPH_MOD : 0));
1582     ret = blk_insert_bs(s->target, target, errp);
1583     if (ret < 0) {
1584         goto fail;
1585     }
1586     if (is_mirror) {
1587         /* XXX: Mirror target could be a NBD server of target QEMU in the case
1588          * of non-shared block migration. To allow migration completion, we
1589          * have to allow "inactivate" of the target BB.  When that happens, we
1590          * know the job is drained, and the vcpus are stopped, so no write
1591          * operation will be performed. Block layer already has assertions to
1592          * ensure that. */
1593         blk_set_force_allow_inactivate(s->target);
1594     }
1595 
1596     s->replaces = g_strdup(replaces);
1597     s->on_source_error = on_source_error;
1598     s->on_target_error = on_target_error;
1599     s->is_none_mode = is_none_mode;
1600     s->backing_mode = backing_mode;
1601     s->copy_mode = copy_mode;
1602     s->base = base;
1603     s->granularity = granularity;
1604     s->buf_size = ROUND_UP(buf_size, granularity);
1605     s->unmap = unmap;
1606     if (auto_complete) {
1607         s->should_complete = true;
1608     }
1609 
1610     s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
1611     if (!s->dirty_bitmap) {
1612         goto fail;
1613     }
1614 
1615     /* Required permissions are already taken with blk_new() */
1616     block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
1617                        &error_abort);
1618 
1619     /* In commit_active_start() all intermediate nodes disappear, so
1620      * any jobs in them must be blocked */
1621     if (target_is_backing) {
1622         BlockDriverState *iter;
1623         for (iter = backing_bs(bs); iter != target; iter = backing_bs(iter)) {
1624             /* XXX BLK_PERM_WRITE needs to be allowed so we don't block
1625              * ourselves at s->base (if writes are blocked for a node, they are
1626              * also blocked for its backing file). The other options would be a
1627              * second filter driver above s->base (== target). */
1628             ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
1629                                      BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE,
1630                                      errp);
1631             if (ret < 0) {
1632                 goto fail;
1633             }
1634         }
1635     }
1636 
1637     QTAILQ_INIT(&s->ops_in_flight);
1638 
1639     trace_mirror_start(bs, s, opaque);
1640     job_start(&s->common.job);
1641     return;
1642 
1643 fail:
1644     if (s) {
1645         /* Make sure this BDS does not go away until we have completed the graph
1646          * changes below */
1647         bdrv_ref(mirror_top_bs);
1648 
1649         g_free(s->replaces);
1650         blk_unref(s->target);
1651         bs_opaque->job = NULL;
1652         job_early_fail(&s->common.job);
1653     }
1654 
1655     bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
1656                             &error_abort);
1657     bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
1658 
1659     bdrv_unref(mirror_top_bs);
1660 }
1661 
1662 void mirror_start(const char *job_id, BlockDriverState *bs,
1663                   BlockDriverState *target, const char *replaces,
1664                   int creation_flags, int64_t speed,
1665                   uint32_t granularity, int64_t buf_size,
1666                   MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
1667                   BlockdevOnError on_source_error,
1668                   BlockdevOnError on_target_error,
1669                   bool unmap, const char *filter_node_name,
1670                   MirrorCopyMode copy_mode, Error **errp)
1671 {
1672     bool is_none_mode;
1673     BlockDriverState *base;
1674 
1675     if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
1676         error_setg(errp, "Sync mode 'incremental' not supported");
1677         return;
1678     }
1679     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
1680     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
1681     mirror_start_job(job_id, bs, creation_flags, target, replaces,
1682                      speed, granularity, buf_size, backing_mode,
1683                      on_source_error, on_target_error, unmap, NULL, NULL,
1684                      &mirror_job_driver, is_none_mode, base, false,
1685                      filter_node_name, true, copy_mode, errp);
1686 }
1687 
1688 void commit_active_start(const char *job_id, BlockDriverState *bs,
1689                          BlockDriverState *base, int creation_flags,
1690                          int64_t speed, BlockdevOnError on_error,
1691                          const char *filter_node_name,
1692                          BlockCompletionFunc *cb, void *opaque,
1693                          bool auto_complete, Error **errp)
1694 {
1695     int orig_base_flags;
1696     Error *local_err = NULL;
1697 
1698     orig_base_flags = bdrv_get_flags(base);
1699 
1700     if (bdrv_reopen(base, bs->open_flags, errp)) {
1701         return;
1702     }
1703 
1704     mirror_start_job(job_id, bs, creation_flags, base, NULL, speed, 0, 0,
1705                      MIRROR_LEAVE_BACKING_CHAIN,
1706                      on_error, on_error, true, cb, opaque,
1707                      &commit_active_job_driver, false, base, auto_complete,
1708                      filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
1709                      &local_err);
1710     if (local_err) {
1711         error_propagate(errp, local_err);
1712         goto error_restore_flags;
1713     }
1714 
1715     return;
1716 
1717 error_restore_flags:
1718     /* ignore error and errp for bdrv_reopen, because we want to propagate
1719      * the original error */
1720     bdrv_reopen(base, orig_base_flags, NULL);
1721     return;
1722 }
1723