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