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