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