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