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