xref: /openbmc/qemu/block/mirror.c (revision 61b9251a)
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 "trace.h"
15 #include "block/blockjob.h"
16 #include "block/block_int.h"
17 #include "sysemu/block-backend.h"
18 #include "qapi/qmp/qerror.h"
19 #include "qemu/ratelimit.h"
20 #include "qemu/bitmap.h"
21 
22 #define SLICE_TIME    100000000ULL /* ns */
23 #define MAX_IN_FLIGHT 16
24 #define DEFAULT_MIRROR_BUF_SIZE   (10 << 20)
25 
26 /* The mirroring buffer is a list of granularity-sized chunks.
27  * Free chunks are organized in a list.
28  */
29 typedef struct MirrorBuffer {
30     QSIMPLEQ_ENTRY(MirrorBuffer) next;
31 } MirrorBuffer;
32 
33 typedef struct MirrorBlockJob {
34     BlockJob common;
35     RateLimit limit;
36     BlockDriverState *target;
37     BlockDriverState *base;
38     /* The name of the graph node to replace */
39     char *replaces;
40     /* The BDS to replace */
41     BlockDriverState *to_replace;
42     /* Used to block operations on the drive-mirror-replace target */
43     Error *replace_blocker;
44     bool is_none_mode;
45     BlockdevOnError on_source_error, on_target_error;
46     bool synced;
47     bool should_complete;
48     int64_t sector_num;
49     int64_t granularity;
50     size_t buf_size;
51     int64_t bdev_length;
52     unsigned long *cow_bitmap;
53     BdrvDirtyBitmap *dirty_bitmap;
54     HBitmapIter hbi;
55     uint8_t *buf;
56     QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
57     int buf_free_count;
58 
59     unsigned long *in_flight_bitmap;
60     int in_flight;
61     int sectors_in_flight;
62     int ret;
63     bool unmap;
64     bool waiting_for_io;
65 } MirrorBlockJob;
66 
67 typedef struct MirrorOp {
68     MirrorBlockJob *s;
69     QEMUIOVector qiov;
70     int64_t sector_num;
71     int nb_sectors;
72 } MirrorOp;
73 
74 static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
75                                             int error)
76 {
77     s->synced = false;
78     if (read) {
79         return block_job_error_action(&s->common, s->common.bs,
80                                       s->on_source_error, true, error);
81     } else {
82         return block_job_error_action(&s->common, s->target,
83                                       s->on_target_error, false, error);
84     }
85 }
86 
87 static void mirror_iteration_done(MirrorOp *op, int ret)
88 {
89     MirrorBlockJob *s = op->s;
90     struct iovec *iov;
91     int64_t chunk_num;
92     int i, nb_chunks, sectors_per_chunk;
93 
94     trace_mirror_iteration_done(s, op->sector_num, op->nb_sectors, ret);
95 
96     s->in_flight--;
97     s->sectors_in_flight -= op->nb_sectors;
98     iov = op->qiov.iov;
99     for (i = 0; i < op->qiov.niov; i++) {
100         MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
101         QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
102         s->buf_free_count++;
103     }
104 
105     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
106     chunk_num = op->sector_num / sectors_per_chunk;
107     nb_chunks = op->nb_sectors / sectors_per_chunk;
108     bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
109     if (ret >= 0) {
110         if (s->cow_bitmap) {
111             bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
112         }
113         s->common.offset += (uint64_t)op->nb_sectors * BDRV_SECTOR_SIZE;
114     }
115 
116     qemu_iovec_destroy(&op->qiov);
117     g_free(op);
118 
119     if (s->waiting_for_io) {
120         qemu_coroutine_enter(s->common.co, NULL);
121     }
122 }
123 
124 static void mirror_write_complete(void *opaque, int ret)
125 {
126     MirrorOp *op = opaque;
127     MirrorBlockJob *s = op->s;
128     if (ret < 0) {
129         BlockErrorAction action;
130 
131         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);
132         action = mirror_error_action(s, false, -ret);
133         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
134             s->ret = ret;
135         }
136     }
137     mirror_iteration_done(op, ret);
138 }
139 
140 static void mirror_read_complete(void *opaque, int ret)
141 {
142     MirrorOp *op = opaque;
143     MirrorBlockJob *s = op->s;
144     if (ret < 0) {
145         BlockErrorAction action;
146 
147         bdrv_set_dirty_bitmap(s->dirty_bitmap, op->sector_num, op->nb_sectors);
148         action = mirror_error_action(s, true, -ret);
149         if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
150             s->ret = ret;
151         }
152 
153         mirror_iteration_done(op, ret);
154         return;
155     }
156     bdrv_aio_writev(s->target, op->sector_num, &op->qiov, op->nb_sectors,
157                     mirror_write_complete, op);
158 }
159 
160 static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
161 {
162     BlockDriverState *source = s->common.bs;
163     int nb_sectors, sectors_per_chunk, nb_chunks;
164     int64_t end, sector_num, next_chunk, next_sector, hbitmap_next_sector;
165     uint64_t delay_ns = 0;
166     MirrorOp *op;
167     int pnum;
168     int64_t ret;
169 
170     s->sector_num = hbitmap_iter_next(&s->hbi);
171     if (s->sector_num < 0) {
172         bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
173         s->sector_num = hbitmap_iter_next(&s->hbi);
174         trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
175         assert(s->sector_num >= 0);
176     }
177 
178     hbitmap_next_sector = s->sector_num;
179     sector_num = s->sector_num;
180     sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
181     end = s->bdev_length / BDRV_SECTOR_SIZE;
182 
183     /* Extend the QEMUIOVector to include all adjacent blocks that will
184      * be copied in this operation.
185      *
186      * We have to do this if we have no backing file yet in the destination,
187      * and the cluster size is very large.  Then we need to do COW ourselves.
188      * The first time a cluster is copied, copy it entirely.  Note that,
189      * because both the granularity and the cluster size are powers of two,
190      * the number of sectors to copy cannot exceed one cluster.
191      *
192      * We also want to extend the QEMUIOVector to include more adjacent
193      * dirty blocks if possible, to limit the number of I/O operations and
194      * run efficiently even with a small granularity.
195      */
196     nb_chunks = 0;
197     nb_sectors = 0;
198     next_sector = sector_num;
199     next_chunk = sector_num / sectors_per_chunk;
200 
201     /* Wait for I/O to this cluster (from a previous iteration) to be done.  */
202     while (test_bit(next_chunk, s->in_flight_bitmap)) {
203         trace_mirror_yield_in_flight(s, sector_num, s->in_flight);
204         s->waiting_for_io = true;
205         qemu_coroutine_yield();
206         s->waiting_for_io = false;
207     }
208 
209     do {
210         int added_sectors, added_chunks;
211 
212         if (!bdrv_get_dirty(source, s->dirty_bitmap, next_sector) ||
213             test_bit(next_chunk, s->in_flight_bitmap)) {
214             assert(nb_sectors > 0);
215             break;
216         }
217 
218         added_sectors = sectors_per_chunk;
219         if (s->cow_bitmap && !test_bit(next_chunk, s->cow_bitmap)) {
220             bdrv_round_to_clusters(s->target,
221                                    next_sector, added_sectors,
222                                    &next_sector, &added_sectors);
223 
224             /* On the first iteration, the rounding may make us copy
225              * sectors before the first dirty one.
226              */
227             if (next_sector < sector_num) {
228                 assert(nb_sectors == 0);
229                 sector_num = next_sector;
230                 next_chunk = next_sector / sectors_per_chunk;
231             }
232         }
233 
234         added_sectors = MIN(added_sectors, end - (sector_num + nb_sectors));
235         added_chunks = (added_sectors + sectors_per_chunk - 1) / sectors_per_chunk;
236 
237         /* When doing COW, it may happen that there is not enough space for
238          * a full cluster.  Wait if that is the case.
239          */
240         while (nb_chunks == 0 && s->buf_free_count < added_chunks) {
241             trace_mirror_yield_buf_busy(s, nb_chunks, s->in_flight);
242             s->waiting_for_io = true;
243             qemu_coroutine_yield();
244             s->waiting_for_io = false;
245         }
246         if (s->buf_free_count < nb_chunks + added_chunks) {
247             trace_mirror_break_buf_busy(s, nb_chunks, s->in_flight);
248             break;
249         }
250         if (IOV_MAX < nb_chunks + added_chunks) {
251             trace_mirror_break_iov_max(s, nb_chunks, added_chunks);
252             break;
253         }
254 
255         /* We have enough free space to copy these sectors.  */
256         bitmap_set(s->in_flight_bitmap, next_chunk, added_chunks);
257 
258         nb_sectors += added_sectors;
259         nb_chunks += added_chunks;
260         next_sector += added_sectors;
261         next_chunk += added_chunks;
262         if (!s->synced && s->common.speed) {
263             delay_ns = ratelimit_calculate_delay(&s->limit, added_sectors);
264         }
265     } while (delay_ns == 0 && next_sector < end);
266 
267     /* Allocate a MirrorOp that is used as an AIO callback.  */
268     op = g_new(MirrorOp, 1);
269     op->s = s;
270     op->sector_num = sector_num;
271     op->nb_sectors = nb_sectors;
272 
273     /* Now make a QEMUIOVector taking enough granularity-sized chunks
274      * from s->buf_free.
275      */
276     qemu_iovec_init(&op->qiov, nb_chunks);
277     next_sector = sector_num;
278     while (nb_chunks-- > 0) {
279         MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
280         size_t remaining = (nb_sectors * BDRV_SECTOR_SIZE) - op->qiov.size;
281 
282         QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
283         s->buf_free_count--;
284         qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
285 
286         /* Advance the HBitmapIter in parallel, so that we do not examine
287          * the same sector twice.
288          */
289         if (next_sector > hbitmap_next_sector
290             && bdrv_get_dirty(source, s->dirty_bitmap, next_sector)) {
291             hbitmap_next_sector = hbitmap_iter_next(&s->hbi);
292         }
293 
294         next_sector += sectors_per_chunk;
295     }
296 
297     bdrv_reset_dirty_bitmap(s->dirty_bitmap, sector_num, nb_sectors);
298 
299     /* Copy the dirty cluster.  */
300     s->in_flight++;
301     s->sectors_in_flight += nb_sectors;
302     trace_mirror_one_iteration(s, sector_num, nb_sectors);
303 
304     ret = bdrv_get_block_status_above(source, NULL, sector_num,
305                                       nb_sectors, &pnum);
306     if (ret < 0 || pnum < nb_sectors ||
307             (ret & BDRV_BLOCK_DATA && !(ret & BDRV_BLOCK_ZERO))) {
308         bdrv_aio_readv(source, sector_num, &op->qiov, nb_sectors,
309                        mirror_read_complete, op);
310     } else if (ret & BDRV_BLOCK_ZERO) {
311         bdrv_aio_write_zeroes(s->target, sector_num, op->nb_sectors,
312                               s->unmap ? BDRV_REQ_MAY_UNMAP : 0,
313                               mirror_write_complete, op);
314     } else {
315         assert(!(ret & BDRV_BLOCK_DATA));
316         bdrv_aio_discard(s->target, sector_num, op->nb_sectors,
317                          mirror_write_complete, op);
318     }
319     return delay_ns;
320 }
321 
322 static void mirror_free_init(MirrorBlockJob *s)
323 {
324     int granularity = s->granularity;
325     size_t buf_size = s->buf_size;
326     uint8_t *buf = s->buf;
327 
328     assert(s->buf_free_count == 0);
329     QSIMPLEQ_INIT(&s->buf_free);
330     while (buf_size != 0) {
331         MirrorBuffer *cur = (MirrorBuffer *)buf;
332         QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
333         s->buf_free_count++;
334         buf_size -= granularity;
335         buf += granularity;
336     }
337 }
338 
339 static void mirror_drain(MirrorBlockJob *s)
340 {
341     while (s->in_flight > 0) {
342         s->waiting_for_io = true;
343         qemu_coroutine_yield();
344         s->waiting_for_io = false;
345     }
346 }
347 
348 typedef struct {
349     int ret;
350 } MirrorExitData;
351 
352 static void mirror_exit(BlockJob *job, void *opaque)
353 {
354     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
355     MirrorExitData *data = opaque;
356     AioContext *replace_aio_context = NULL;
357     BlockDriverState *src = s->common.bs;
358 
359     /* Make sure that the source BDS doesn't go away before we called
360      * block_job_completed(). */
361     bdrv_ref(src);
362 
363     if (s->to_replace) {
364         replace_aio_context = bdrv_get_aio_context(s->to_replace);
365         aio_context_acquire(replace_aio_context);
366     }
367 
368     if (s->should_complete && data->ret == 0) {
369         BlockDriverState *to_replace = s->common.bs;
370         if (s->to_replace) {
371             to_replace = s->to_replace;
372         }
373         if (bdrv_get_flags(s->target) != bdrv_get_flags(to_replace)) {
374             bdrv_reopen(s->target, bdrv_get_flags(to_replace), NULL);
375         }
376         bdrv_replace_in_backing_chain(to_replace, s->target);
377     }
378     if (s->to_replace) {
379         bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
380         error_free(s->replace_blocker);
381         bdrv_unref(s->to_replace);
382     }
383     if (replace_aio_context) {
384         aio_context_release(replace_aio_context);
385     }
386     g_free(s->replaces);
387     bdrv_op_unblock_all(s->target, s->common.blocker);
388     bdrv_unref(s->target);
389     block_job_completed(&s->common, data->ret);
390     g_free(data);
391     bdrv_unref(src);
392 }
393 
394 static void coroutine_fn mirror_run(void *opaque)
395 {
396     MirrorBlockJob *s = opaque;
397     MirrorExitData *data;
398     BlockDriverState *bs = s->common.bs;
399     int64_t sector_num, end, length;
400     uint64_t last_pause_ns;
401     BlockDriverInfo bdi;
402     char backing_filename[2]; /* we only need 2 characters because we are only
403                                  checking for a NULL string */
404     int ret = 0;
405     int n;
406 
407     if (block_job_is_cancelled(&s->common)) {
408         goto immediate_exit;
409     }
410 
411     s->bdev_length = bdrv_getlength(bs);
412     if (s->bdev_length < 0) {
413         ret = s->bdev_length;
414         goto immediate_exit;
415     } else if (s->bdev_length == 0) {
416         /* Report BLOCK_JOB_READY and wait for complete. */
417         block_job_event_ready(&s->common);
418         s->synced = true;
419         while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
420             block_job_yield(&s->common);
421         }
422         s->common.cancelled = false;
423         goto immediate_exit;
424     }
425 
426     length = DIV_ROUND_UP(s->bdev_length, s->granularity);
427     s->in_flight_bitmap = bitmap_new(length);
428 
429     /* If we have no backing file yet in the destination, we cannot let
430      * the destination do COW.  Instead, we copy sectors around the
431      * dirty data if needed.  We need a bitmap to do that.
432      */
433     bdrv_get_backing_filename(s->target, backing_filename,
434                               sizeof(backing_filename));
435     if (backing_filename[0] && !s->target->backing) {
436         ret = bdrv_get_info(s->target, &bdi);
437         if (ret < 0) {
438             goto immediate_exit;
439         }
440         if (s->granularity < bdi.cluster_size) {
441             s->buf_size = MAX(s->buf_size, bdi.cluster_size);
442             s->cow_bitmap = bitmap_new(length);
443         }
444     }
445 
446     end = s->bdev_length / BDRV_SECTOR_SIZE;
447     s->buf = qemu_try_blockalign(bs, s->buf_size);
448     if (s->buf == NULL) {
449         ret = -ENOMEM;
450         goto immediate_exit;
451     }
452 
453     mirror_free_init(s);
454 
455     last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
456     if (!s->is_none_mode) {
457         /* First part, loop on the sectors and initialize the dirty bitmap.  */
458         BlockDriverState *base = s->base;
459         bool mark_all_dirty = s->base == NULL && !bdrv_has_zero_init(s->target);
460 
461         for (sector_num = 0; sector_num < end; ) {
462             /* Just to make sure we are not exceeding int limit. */
463             int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,
464                                  end - sector_num);
465             int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
466 
467             if (now - last_pause_ns > SLICE_TIME) {
468                 last_pause_ns = now;
469                 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, 0);
470             }
471 
472             if (block_job_is_cancelled(&s->common)) {
473                 goto immediate_exit;
474             }
475 
476             ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);
477 
478             if (ret < 0) {
479                 goto immediate_exit;
480             }
481 
482             assert(n > 0);
483             if (ret == 1 || mark_all_dirty) {
484                 bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);
485             }
486             sector_num += n;
487         }
488     }
489 
490     bdrv_dirty_iter_init(s->dirty_bitmap, &s->hbi);
491     for (;;) {
492         uint64_t delay_ns = 0;
493         int64_t cnt;
494         bool should_complete;
495 
496         if (s->ret < 0) {
497             ret = s->ret;
498             goto immediate_exit;
499         }
500 
501         cnt = bdrv_get_dirty_count(s->dirty_bitmap);
502         /* s->common.offset contains the number of bytes already processed so
503          * far, cnt is the number of dirty sectors remaining and
504          * s->sectors_in_flight is the number of sectors currently being
505          * processed; together those are the current total operation length */
506         s->common.len = s->common.offset +
507                         (cnt + s->sectors_in_flight) * BDRV_SECTOR_SIZE;
508 
509         /* Note that even when no rate limit is applied we need to yield
510          * periodically with no pending I/O so that bdrv_drain_all() returns.
511          * We do so every SLICE_TIME nanoseconds, or when there is an error,
512          * or when the source is clean, whichever comes first.
513          */
514         if (qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - last_pause_ns < SLICE_TIME &&
515             s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
516             if (s->in_flight == MAX_IN_FLIGHT || s->buf_free_count == 0 ||
517                 (cnt == 0 && s->in_flight > 0)) {
518                 trace_mirror_yield(s, s->in_flight, s->buf_free_count, cnt);
519                 s->waiting_for_io = true;
520                 qemu_coroutine_yield();
521                 s->waiting_for_io = false;
522                 continue;
523             } else if (cnt != 0) {
524                 delay_ns = mirror_iteration(s);
525             }
526         }
527 
528         should_complete = false;
529         if (s->in_flight == 0 && cnt == 0) {
530             trace_mirror_before_flush(s);
531             ret = bdrv_flush(s->target);
532             if (ret < 0) {
533                 if (mirror_error_action(s, false, -ret) ==
534                     BLOCK_ERROR_ACTION_REPORT) {
535                     goto immediate_exit;
536                 }
537             } else {
538                 /* We're out of the streaming phase.  From now on, if the job
539                  * is cancelled we will actually complete all pending I/O and
540                  * report completion.  This way, block-job-cancel will leave
541                  * the target in a consistent state.
542                  */
543                 if (!s->synced) {
544                     block_job_event_ready(&s->common);
545                     s->synced = true;
546                 }
547 
548                 should_complete = s->should_complete ||
549                     block_job_is_cancelled(&s->common);
550                 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
551             }
552         }
553 
554         if (cnt == 0 && should_complete) {
555             /* The dirty bitmap is not updated while operations are pending.
556              * If we're about to exit, wait for pending operations before
557              * calling bdrv_get_dirty_count(bs), or we may exit while the
558              * source has dirty data to copy!
559              *
560              * Note that I/O can be submitted by the guest while
561              * mirror_populate runs.
562              */
563             trace_mirror_before_drain(s, cnt);
564             bdrv_drain(bs);
565             cnt = bdrv_get_dirty_count(s->dirty_bitmap);
566         }
567 
568         ret = 0;
569         trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
570         if (!s->synced) {
571             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
572             if (block_job_is_cancelled(&s->common)) {
573                 break;
574             }
575         } else if (!should_complete) {
576             delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
577             block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
578         } else if (cnt == 0) {
579             /* The two disks are in sync.  Exit and report successful
580              * completion.
581              */
582             assert(QLIST_EMPTY(&bs->tracked_requests));
583             s->common.cancelled = false;
584             break;
585         }
586         last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
587     }
588 
589 immediate_exit:
590     if (s->in_flight > 0) {
591         /* We get here only if something went wrong.  Either the job failed,
592          * or it was cancelled prematurely so that we do not guarantee that
593          * the target is a copy of the source.
594          */
595         assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));
596         mirror_drain(s);
597     }
598 
599     assert(s->in_flight == 0);
600     qemu_vfree(s->buf);
601     g_free(s->cow_bitmap);
602     g_free(s->in_flight_bitmap);
603     bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);
604     if (s->target->blk) {
605         blk_iostatus_disable(s->target->blk);
606     }
607 
608     data = g_malloc(sizeof(*data));
609     data->ret = ret;
610     block_job_defer_to_main_loop(&s->common, mirror_exit, data);
611 }
612 
613 static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)
614 {
615     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
616 
617     if (speed < 0) {
618         error_setg(errp, QERR_INVALID_PARAMETER, "speed");
619         return;
620     }
621     ratelimit_set_speed(&s->limit, speed / BDRV_SECTOR_SIZE, SLICE_TIME);
622 }
623 
624 static void mirror_iostatus_reset(BlockJob *job)
625 {
626     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
627 
628     if (s->target->blk) {
629         blk_iostatus_reset(s->target->blk);
630     }
631 }
632 
633 static void mirror_complete(BlockJob *job, Error **errp)
634 {
635     MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
636     Error *local_err = NULL;
637     int ret;
638 
639     ret = bdrv_open_backing_file(s->target, NULL, &local_err);
640     if (ret < 0) {
641         error_propagate(errp, local_err);
642         return;
643     }
644     if (!s->synced) {
645         error_setg(errp, QERR_BLOCK_JOB_NOT_READY, job->id);
646         return;
647     }
648 
649     /* check the target bs is not blocked and block all operations on it */
650     if (s->replaces) {
651         AioContext *replace_aio_context;
652 
653         s->to_replace = bdrv_find_node(s->replaces);
654         if (!s->to_replace) {
655             error_setg(errp, "Node name '%s' not found", s->replaces);
656             return;
657         }
658 
659         replace_aio_context = bdrv_get_aio_context(s->to_replace);
660         aio_context_acquire(replace_aio_context);
661 
662         error_setg(&s->replace_blocker,
663                    "block device is in use by block-job-complete");
664         bdrv_op_block_all(s->to_replace, s->replace_blocker);
665         bdrv_ref(s->to_replace);
666 
667         aio_context_release(replace_aio_context);
668     }
669 
670     s->should_complete = true;
671     block_job_enter(&s->common);
672 }
673 
674 static const BlockJobDriver mirror_job_driver = {
675     .instance_size = sizeof(MirrorBlockJob),
676     .job_type      = BLOCK_JOB_TYPE_MIRROR,
677     .set_speed     = mirror_set_speed,
678     .iostatus_reset= mirror_iostatus_reset,
679     .complete      = mirror_complete,
680 };
681 
682 static const BlockJobDriver commit_active_job_driver = {
683     .instance_size = sizeof(MirrorBlockJob),
684     .job_type      = BLOCK_JOB_TYPE_COMMIT,
685     .set_speed     = mirror_set_speed,
686     .iostatus_reset
687                    = mirror_iostatus_reset,
688     .complete      = mirror_complete,
689 };
690 
691 static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,
692                              const char *replaces,
693                              int64_t speed, uint32_t granularity,
694                              int64_t buf_size,
695                              BlockdevOnError on_source_error,
696                              BlockdevOnError on_target_error,
697                              bool unmap,
698                              BlockCompletionFunc *cb,
699                              void *opaque, Error **errp,
700                              const BlockJobDriver *driver,
701                              bool is_none_mode, BlockDriverState *base)
702 {
703     MirrorBlockJob *s;
704 
705     if (granularity == 0) {
706         granularity = bdrv_get_default_bitmap_granularity(target);
707     }
708 
709     assert ((granularity & (granularity - 1)) == 0);
710 
711     if ((on_source_error == BLOCKDEV_ON_ERROR_STOP ||
712          on_source_error == BLOCKDEV_ON_ERROR_ENOSPC) &&
713         (!bs->blk || !blk_iostatus_is_enabled(bs->blk))) {
714         error_setg(errp, QERR_INVALID_PARAMETER, "on-source-error");
715         return;
716     }
717 
718     if (buf_size < 0) {
719         error_setg(errp, "Invalid parameter 'buf-size'");
720         return;
721     }
722 
723     if (buf_size == 0) {
724         buf_size = DEFAULT_MIRROR_BUF_SIZE;
725     }
726 
727     s = block_job_create(driver, bs, speed, cb, opaque, errp);
728     if (!s) {
729         return;
730     }
731 
732     s->replaces = g_strdup(replaces);
733     s->on_source_error = on_source_error;
734     s->on_target_error = on_target_error;
735     s->target = target;
736     s->is_none_mode = is_none_mode;
737     s->base = base;
738     s->granularity = granularity;
739     s->buf_size = ROUND_UP(buf_size, granularity);
740     s->unmap = unmap;
741 
742     s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
743     if (!s->dirty_bitmap) {
744         g_free(s->replaces);
745         block_job_unref(&s->common);
746         return;
747     }
748 
749     bdrv_op_block_all(s->target, s->common.blocker);
750 
751     bdrv_set_enable_write_cache(s->target, true);
752     if (s->target->blk) {
753         blk_set_on_error(s->target->blk, on_target_error, on_target_error);
754         blk_iostatus_enable(s->target->blk);
755     }
756     s->common.co = qemu_coroutine_create(mirror_run);
757     trace_mirror_start(bs, s, s->common.co, opaque);
758     qemu_coroutine_enter(s->common.co, s);
759 }
760 
761 void mirror_start(BlockDriverState *bs, BlockDriverState *target,
762                   const char *replaces,
763                   int64_t speed, uint32_t granularity, int64_t buf_size,
764                   MirrorSyncMode mode, BlockdevOnError on_source_error,
765                   BlockdevOnError on_target_error,
766                   bool unmap,
767                   BlockCompletionFunc *cb,
768                   void *opaque, Error **errp)
769 {
770     bool is_none_mode;
771     BlockDriverState *base;
772 
773     if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
774         error_setg(errp, "Sync mode 'incremental' not supported");
775         return;
776     }
777     is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
778     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
779     mirror_start_job(bs, target, replaces,
780                      speed, granularity, buf_size,
781                      on_source_error, on_target_error, unmap, cb, opaque, errp,
782                      &mirror_job_driver, is_none_mode, base);
783 }
784 
785 void commit_active_start(BlockDriverState *bs, BlockDriverState *base,
786                          int64_t speed,
787                          BlockdevOnError on_error,
788                          BlockCompletionFunc *cb,
789                          void *opaque, Error **errp)
790 {
791     int64_t length, base_length;
792     int orig_base_flags;
793     int ret;
794     Error *local_err = NULL;
795 
796     orig_base_flags = bdrv_get_flags(base);
797 
798     if (bdrv_reopen(base, bs->open_flags, errp)) {
799         return;
800     }
801 
802     length = bdrv_getlength(bs);
803     if (length < 0) {
804         error_setg_errno(errp, -length,
805                          "Unable to determine length of %s", bs->filename);
806         goto error_restore_flags;
807     }
808 
809     base_length = bdrv_getlength(base);
810     if (base_length < 0) {
811         error_setg_errno(errp, -base_length,
812                          "Unable to determine length of %s", base->filename);
813         goto error_restore_flags;
814     }
815 
816     if (length > base_length) {
817         ret = bdrv_truncate(base, length);
818         if (ret < 0) {
819             error_setg_errno(errp, -ret,
820                             "Top image %s is larger than base image %s, and "
821                              "resize of base image failed",
822                              bs->filename, base->filename);
823             goto error_restore_flags;
824         }
825     }
826 
827     bdrv_ref(base);
828     mirror_start_job(bs, base, NULL, speed, 0, 0,
829                      on_error, on_error, false, cb, opaque, &local_err,
830                      &commit_active_job_driver, false, base);
831     if (local_err) {
832         error_propagate(errp, local_err);
833         goto error_restore_flags;
834     }
835 
836     return;
837 
838 error_restore_flags:
839     /* ignore error and errp for bdrv_reopen, because we want to propagate
840      * the original error */
841     bdrv_reopen(base, orig_base_flags, NULL);
842     return;
843 }
844