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