]> git.proxmox.com Git - mirror_qemu.git/blame - block/mirror.c
mirror: Update signature of mirror_clip_sectors()
[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"
fd4a6493 15#include "qemu/cutils.h"
893f7eba 16#include "trace.h"
c87621ea 17#include "block/blockjob_int.h"
737e150e 18#include "block/block_int.h"
373340b2 19#include "sysemu/block-backend.h"
da34e65c 20#include "qapi/error.h"
cc7a8ea7 21#include "qapi/qmp/qerror.h"
893f7eba 22#include "qemu/ratelimit.h"
b812f671 23#include "qemu/bitmap.h"
893f7eba 24
402a4741
PB
25#define SLICE_TIME 100000000ULL /* ns */
26#define MAX_IN_FLIGHT 16
b436982f
EB
27#define MAX_IO_BYTES (1 << 20) /* 1 Mb */
28#define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
402a4741
PB
29
30/* The mirroring buffer is a list of granularity-sized chunks.
31 * Free chunks are organized in a list.
32 */
33typedef struct MirrorBuffer {
34 QSIMPLEQ_ENTRY(MirrorBuffer) next;
35} MirrorBuffer;
893f7eba
PB
36
37typedef struct MirrorBlockJob {
38 BlockJob common;
39 RateLimit limit;
e253f4b8 40 BlockBackend *target;
4ef85a9c
KW
41 BlockDriverState *mirror_top_bs;
42 BlockDriverState *source;
5bc361b8 43 BlockDriverState *base;
4ef85a9c 44
09158f00
BC
45 /* The name of the graph node to replace */
46 char *replaces;
47 /* The BDS to replace */
48 BlockDriverState *to_replace;
49 /* Used to block operations on the drive-mirror-replace target */
50 Error *replace_blocker;
03544a6e 51 bool is_none_mode;
274fccee 52 BlockMirrorBackingMode backing_mode;
b952b558 53 BlockdevOnError on_source_error, on_target_error;
d63ffd87
PB
54 bool synced;
55 bool should_complete;
eee13dfe 56 int64_t granularity;
b812f671 57 size_t buf_size;
b21c7652 58 int64_t bdev_length;
b812f671 59 unsigned long *cow_bitmap;
e4654d2d 60 BdrvDirtyBitmap *dirty_bitmap;
dc162c8e 61 BdrvDirtyBitmapIter *dbi;
893f7eba 62 uint8_t *buf;
402a4741
PB
63 QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
64 int buf_free_count;
bd48bde8 65
49efb1f5 66 uint64_t last_pause_ns;
402a4741 67 unsigned long *in_flight_bitmap;
bd48bde8 68 int in_flight;
b436982f 69 int64_t bytes_in_flight;
bd48bde8 70 int ret;
0fc9f8ea 71 bool unmap;
e424aff5 72 bool waiting_for_io;
b436982f 73 int target_cluster_size;
e5b43573 74 int max_iov;
90ab48eb 75 bool initial_zeroing_ongoing;
893f7eba
PB
76} MirrorBlockJob;
77
bd48bde8
PB
78typedef struct MirrorOp {
79 MirrorBlockJob *s;
80 QEMUIOVector qiov;
b436982f
EB
81 int64_t offset;
82 uint64_t bytes;
bd48bde8
PB
83} MirrorOp;
84
b952b558
PB
85static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
86 int error)
87{
88 s->synced = false;
89 if (read) {
81e254dc
KW
90 return block_job_error_action(&s->common, s->on_source_error,
91 true, error);
b952b558 92 } else {
81e254dc
KW
93 return block_job_error_action(&s->common, s->on_target_error,
94 false, error);
b952b558
PB
95 }
96}
97
bd48bde8
PB
98static void mirror_iteration_done(MirrorOp *op, int ret)
99{
100 MirrorBlockJob *s = op->s;
402a4741 101 struct iovec *iov;
bd48bde8 102 int64_t chunk_num;
b436982f 103 int i, nb_chunks;
bd48bde8 104
b436982f 105 trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
bd48bde8
PB
106
107 s->in_flight--;
b436982f 108 s->bytes_in_flight -= op->bytes;
402a4741
PB
109 iov = op->qiov.iov;
110 for (i = 0; i < op->qiov.niov; i++) {
111 MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
112 QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
113 s->buf_free_count++;
114 }
115
b436982f
EB
116 chunk_num = op->offset / s->granularity;
117 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
402a4741 118 bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
b21c7652
HR
119 if (ret >= 0) {
120 if (s->cow_bitmap) {
121 bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
122 }
90ab48eb 123 if (!s->initial_zeroing_ongoing) {
b436982f 124 s->common.offset += op->bytes;
90ab48eb 125 }
bd48bde8 126 }
6df3bf8e 127 qemu_iovec_destroy(&op->qiov);
c84b3192 128 g_free(op);
7b770c72 129
e424aff5 130 if (s->waiting_for_io) {
0b8b8753 131 qemu_coroutine_enter(s->common.co);
7b770c72 132 }
bd48bde8
PB
133}
134
135static void mirror_write_complete(void *opaque, int ret)
136{
137 MirrorOp *op = opaque;
138 MirrorBlockJob *s = op->s;
b9e413dd
PB
139
140 aio_context_acquire(blk_get_aio_context(s->common.blk));
bd48bde8 141 if (ret < 0) {
bd48bde8
PB
142 BlockErrorAction action;
143
b436982f
EB
144 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset >> BDRV_SECTOR_BITS,
145 op->bytes >> BDRV_SECTOR_BITS);
bd48bde8 146 action = mirror_error_action(s, false, -ret);
a589569f 147 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
bd48bde8
PB
148 s->ret = ret;
149 }
150 }
151 mirror_iteration_done(op, ret);
b9e413dd 152 aio_context_release(blk_get_aio_context(s->common.blk));
bd48bde8
PB
153}
154
155static void mirror_read_complete(void *opaque, int ret)
156{
157 MirrorOp *op = opaque;
158 MirrorBlockJob *s = op->s;
b9e413dd
PB
159
160 aio_context_acquire(blk_get_aio_context(s->common.blk));
bd48bde8 161 if (ret < 0) {
bd48bde8
PB
162 BlockErrorAction action;
163
b436982f
EB
164 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset >> BDRV_SECTOR_BITS,
165 op->bytes >> BDRV_SECTOR_BITS);
bd48bde8 166 action = mirror_error_action(s, true, -ret);
a589569f 167 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
bd48bde8
PB
168 s->ret = ret;
169 }
170
171 mirror_iteration_done(op, ret);
b9e413dd 172 } else {
b436982f 173 blk_aio_pwritev(s->target, op->offset, &op->qiov,
b9e413dd 174 0, mirror_write_complete, op);
bd48bde8 175 }
b9e413dd 176 aio_context_release(blk_get_aio_context(s->common.blk));
bd48bde8
PB
177}
178
931e5260
EB
179static inline int mirror_clip_sectors(MirrorBlockJob *s,
180 int64_t sector_num,
181 int nb_sectors)
4150ae60 182{
931e5260
EB
183 return MIN(nb_sectors,
184 s->bdev_length / BDRV_SECTOR_SIZE - sector_num);
4150ae60
FZ
185}
186
e5b43573
FZ
187/* Round sector_num and/or nb_sectors to target cluster if COW is needed, and
188 * return the offset of the adjusted tail sector against original. */
189static int mirror_cow_align(MirrorBlockJob *s,
190 int64_t *sector_num,
191 int *nb_sectors)
893f7eba 192{
e5b43573
FZ
193 bool need_cow;
194 int ret = 0;
195 int chunk_sectors = s->granularity >> BDRV_SECTOR_BITS;
196 int64_t align_sector_num = *sector_num;
197 int align_nb_sectors = *nb_sectors;
198 int max_sectors = chunk_sectors * s->max_iov;
199
200 need_cow = !test_bit(*sector_num / chunk_sectors, s->cow_bitmap);
201 need_cow |= !test_bit((*sector_num + *nb_sectors - 1) / chunk_sectors,
202 s->cow_bitmap);
203 if (need_cow) {
244483e6
KW
204 bdrv_round_sectors_to_clusters(blk_bs(s->target), *sector_num,
205 *nb_sectors, &align_sector_num,
206 &align_nb_sectors);
e5b43573 207 }
3515727f 208
e5b43573
FZ
209 if (align_nb_sectors > max_sectors) {
210 align_nb_sectors = max_sectors;
211 if (need_cow) {
212 align_nb_sectors = QEMU_ALIGN_DOWN(align_nb_sectors,
b436982f
EB
213 s->target_cluster_size >>
214 BDRV_SECTOR_BITS);
e5b43573 215 }
8f0720ec 216 }
4150ae60
FZ
217 /* Clipping may result in align_nb_sectors unaligned to chunk boundary, but
218 * that doesn't matter because it's already the end of source image. */
931e5260
EB
219 align_nb_sectors = mirror_clip_sectors(s, align_sector_num,
220 align_nb_sectors);
8f0720ec 221
e5b43573
FZ
222 ret = align_sector_num + align_nb_sectors - (*sector_num + *nb_sectors);
223 *sector_num = align_sector_num;
224 *nb_sectors = align_nb_sectors;
225 assert(ret >= 0);
226 return ret;
227}
228
21cd917f
FZ
229static inline void mirror_wait_for_io(MirrorBlockJob *s)
230{
231 assert(!s->waiting_for_io);
232 s->waiting_for_io = true;
233 qemu_coroutine_yield();
234 s->waiting_for_io = false;
235}
236
e5b43573 237/* Submit async read while handling COW.
17612955
JS
238 * Returns: The number of sectors copied after and including sector_num,
239 * excluding any sectors copied prior to sector_num due to alignment.
240 * This will be nb_sectors if no alignment is necessary, or
e5b43573
FZ
241 * (new_end - sector_num) if tail is rounded up or down due to
242 * alignment or buffer limit.
243 */
244static int mirror_do_read(MirrorBlockJob *s, int64_t sector_num,
245 int nb_sectors)
246{
e253f4b8 247 BlockBackend *source = s->common.blk;
e5b43573 248 int sectors_per_chunk, nb_chunks;
17612955 249 int ret;
e5b43573 250 MirrorOp *op;
e4808881 251 int max_sectors;
e5b43573 252
884fea4e 253 sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
e4808881 254 max_sectors = sectors_per_chunk * s->max_iov;
402a4741 255
e5b43573
FZ
256 /* We can only handle as much as buf_size at a time. */
257 nb_sectors = MIN(s->buf_size >> BDRV_SECTOR_BITS, nb_sectors);
e4808881 258 nb_sectors = MIN(max_sectors, nb_sectors);
e5b43573 259 assert(nb_sectors);
17612955 260 ret = nb_sectors;
402a4741 261
e5b43573
FZ
262 if (s->cow_bitmap) {
263 ret += mirror_cow_align(s, &sector_num, &nb_sectors);
264 }
265 assert(nb_sectors << BDRV_SECTOR_BITS <= s->buf_size);
266 /* The sector range must meet granularity because:
267 * 1) Caller passes in aligned values;
268 * 2) mirror_cow_align is used only when target cluster is larger. */
e5b43573 269 assert(!(sector_num % sectors_per_chunk));
4150ae60 270 nb_chunks = DIV_ROUND_UP(nb_sectors, sectors_per_chunk);
e5b43573
FZ
271
272 while (s->buf_free_count < nb_chunks) {
5cb1a49e
EB
273 trace_mirror_yield_in_flight(s, sector_num * BDRV_SECTOR_SIZE,
274 s->in_flight);
21cd917f 275 mirror_wait_for_io(s);
b812f671
PB
276 }
277
bd48bde8 278 /* Allocate a MirrorOp that is used as an AIO callback. */
c84b3192 279 op = g_new(MirrorOp, 1);
bd48bde8 280 op->s = s;
b436982f
EB
281 op->offset = sector_num * BDRV_SECTOR_SIZE;
282 op->bytes = nb_sectors * BDRV_SECTOR_SIZE;
402a4741
PB
283
284 /* Now make a QEMUIOVector taking enough granularity-sized chunks
285 * from s->buf_free.
286 */
287 qemu_iovec_init(&op->qiov, nb_chunks);
402a4741
PB
288 while (nb_chunks-- > 0) {
289 MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
e5b43573 290 size_t remaining = nb_sectors * BDRV_SECTOR_SIZE - op->qiov.size;
5a0f6fd5 291
402a4741
PB
292 QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
293 s->buf_free_count--;
5a0f6fd5 294 qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
402a4741 295 }
bd48bde8 296
893f7eba 297 /* Copy the dirty cluster. */
bd48bde8 298 s->in_flight++;
b436982f 299 s->bytes_in_flight += nb_sectors * BDRV_SECTOR_SIZE;
5cb1a49e
EB
300 trace_mirror_one_iteration(s, sector_num * BDRV_SECTOR_SIZE,
301 nb_sectors * BDRV_SECTOR_SIZE);
dcfb3beb 302
73698c30 303 blk_aio_preadv(source, sector_num * BDRV_SECTOR_SIZE, &op->qiov, 0,
e5b43573
FZ
304 mirror_read_complete, op);
305 return ret;
306}
307
308static void mirror_do_zero_or_discard(MirrorBlockJob *s,
e6f24193
EB
309 int64_t offset,
310 uint64_t bytes,
e5b43573
FZ
311 bool is_discard)
312{
313 MirrorOp *op;
314
315 /* Allocate a MirrorOp that is used as an AIO callback. The qiov is zeroed
316 * so the freeing in mirror_iteration_done is nop. */
317 op = g_new0(MirrorOp, 1);
318 op->s = s;
e6f24193
EB
319 op->offset = offset;
320 op->bytes = bytes;
e5b43573
FZ
321
322 s->in_flight++;
e6f24193 323 s->bytes_in_flight += bytes;
e5b43573 324 if (is_discard) {
e6f24193 325 blk_aio_pdiscard(s->target, offset,
b436982f 326 op->bytes, mirror_write_complete, op);
e5b43573 327 } else {
e6f24193 328 blk_aio_pwrite_zeroes(s->target, offset,
b436982f 329 op->bytes, s->unmap ? BDRV_REQ_MAY_UNMAP : 0,
dcfb3beb 330 mirror_write_complete, op);
e5b43573
FZ
331 }
332}
333
334static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
335{
4ef85a9c 336 BlockDriverState *source = s->source;
9c83625b 337 int64_t sector_num, first_chunk;
e5b43573
FZ
338 uint64_t delay_ns = 0;
339 /* At least the first dirty chunk is mirrored in one iteration. */
340 int nb_chunks = 1;
341 int64_t end = s->bdev_length / BDRV_SECTOR_SIZE;
342 int sectors_per_chunk = s->granularity >> BDRV_SECTOR_BITS;
4b5004d9 343 bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
b436982f 344 int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
e5b43573 345
b64bd51e 346 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
dc162c8e 347 sector_num = bdrv_dirty_iter_next(s->dbi);
e5b43573 348 if (sector_num < 0) {
dc162c8e
FZ
349 bdrv_set_dirty_iter(s->dbi, 0);
350 sector_num = bdrv_dirty_iter_next(s->dbi);
5cb1a49e
EB
351 trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap) *
352 BDRV_SECTOR_SIZE);
e5b43573
FZ
353 assert(sector_num >= 0);
354 }
b64bd51e 355 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
e5b43573 356
9c83625b
HR
357 first_chunk = sector_num / sectors_per_chunk;
358 while (test_bit(first_chunk, s->in_flight_bitmap)) {
5cb1a49e
EB
359 trace_mirror_yield_in_flight(s, sector_num * BDRV_SECTOR_SIZE,
360 s->in_flight);
9c83625b
HR
361 mirror_wait_for_io(s);
362 }
363
565ac01f
SH
364 block_job_pause_point(&s->common);
365
e5b43573
FZ
366 /* Find the number of consective dirty chunks following the first dirty
367 * one, and wait for in flight requests in them. */
b64bd51e 368 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
e5b43573 369 while (nb_chunks * sectors_per_chunk < (s->buf_size >> BDRV_SECTOR_BITS)) {
dc162c8e 370 int64_t next_dirty;
e5b43573
FZ
371 int64_t next_sector = sector_num + nb_chunks * sectors_per_chunk;
372 int64_t next_chunk = next_sector / sectors_per_chunk;
373 if (next_sector >= end ||
b64bd51e 374 !bdrv_get_dirty_locked(source, s->dirty_bitmap, next_sector)) {
e5b43573
FZ
375 break;
376 }
377 if (test_bit(next_chunk, s->in_flight_bitmap)) {
9c83625b 378 break;
e5b43573 379 }
9c83625b 380
dc162c8e
FZ
381 next_dirty = bdrv_dirty_iter_next(s->dbi);
382 if (next_dirty > next_sector || next_dirty < 0) {
f27a2742 383 /* The bitmap iterator's cache is stale, refresh it */
dc162c8e
FZ
384 bdrv_set_dirty_iter(s->dbi, next_sector);
385 next_dirty = bdrv_dirty_iter_next(s->dbi);
f27a2742 386 }
dc162c8e 387 assert(next_dirty == next_sector);
9c83625b 388 nb_chunks++;
e5b43573
FZ
389 }
390
391 /* Clear dirty bits before querying the block status, because
392 * calling bdrv_get_block_status_above could yield - if some blocks are
393 * marked dirty in this window, we need to know.
394 */
b64bd51e
PB
395 bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, sector_num,
396 nb_chunks * sectors_per_chunk);
397 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
398
e5b43573
FZ
399 bitmap_set(s->in_flight_bitmap, sector_num / sectors_per_chunk, nb_chunks);
400 while (nb_chunks > 0 && sector_num < end) {
39c11580 401 int64_t ret;
f3e4ce4a
EB
402 int io_sectors;
403 int64_t io_bytes_acct;
e5b43573
FZ
404 BlockDriverState *file;
405 enum MirrorMethod {
406 MIRROR_METHOD_COPY,
407 MIRROR_METHOD_ZERO,
408 MIRROR_METHOD_DISCARD
409 } mirror_method = MIRROR_METHOD_COPY;
410
411 assert(!(sector_num % sectors_per_chunk));
412 ret = bdrv_get_block_status_above(source, NULL, sector_num,
413 nb_chunks * sectors_per_chunk,
414 &io_sectors, &file);
415 if (ret < 0) {
b436982f
EB
416 io_sectors = MIN(nb_chunks * sectors_per_chunk,
417 max_io_bytes >> BDRV_SECTOR_BITS);
0965a41e 418 } else if (ret & BDRV_BLOCK_DATA) {
b436982f 419 io_sectors = MIN(io_sectors, max_io_bytes >> BDRV_SECTOR_BITS);
e5b43573
FZ
420 }
421
422 io_sectors -= io_sectors % sectors_per_chunk;
423 if (io_sectors < sectors_per_chunk) {
424 io_sectors = sectors_per_chunk;
425 } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
426 int64_t target_sector_num;
427 int target_nb_sectors;
244483e6
KW
428 bdrv_round_sectors_to_clusters(blk_bs(s->target), sector_num,
429 io_sectors, &target_sector_num,
430 &target_nb_sectors);
e5b43573
FZ
431 if (target_sector_num == sector_num &&
432 target_nb_sectors == io_sectors) {
433 mirror_method = ret & BDRV_BLOCK_ZERO ?
434 MIRROR_METHOD_ZERO :
435 MIRROR_METHOD_DISCARD;
436 }
437 }
438
cf56a3c6 439 while (s->in_flight >= MAX_IN_FLIGHT) {
5cb1a49e
EB
440 trace_mirror_yield_in_flight(s, sector_num * BDRV_SECTOR_SIZE,
441 s->in_flight);
cf56a3c6
DL
442 mirror_wait_for_io(s);
443 }
444
dbaa7b57
VSO
445 if (s->ret < 0) {
446 return 0;
447 }
448
931e5260 449 io_sectors = mirror_clip_sectors(s, sector_num, io_sectors);
e5b43573
FZ
450 switch (mirror_method) {
451 case MIRROR_METHOD_COPY:
452 io_sectors = mirror_do_read(s, sector_num, io_sectors);
f3e4ce4a 453 io_bytes_acct = io_sectors * BDRV_SECTOR_SIZE;
e5b43573
FZ
454 break;
455 case MIRROR_METHOD_ZERO:
e5b43573 456 case MIRROR_METHOD_DISCARD:
e6f24193
EB
457 mirror_do_zero_or_discard(s, sector_num * BDRV_SECTOR_SIZE,
458 io_sectors * BDRV_SECTOR_SIZE,
4b5004d9
DL
459 mirror_method == MIRROR_METHOD_DISCARD);
460 if (write_zeroes_ok) {
f3e4ce4a 461 io_bytes_acct = 0;
4b5004d9 462 } else {
f3e4ce4a 463 io_bytes_acct = io_sectors * BDRV_SECTOR_SIZE;
4b5004d9 464 }
e5b43573
FZ
465 break;
466 default:
467 abort();
468 }
469 assert(io_sectors);
470 sector_num += io_sectors;
4150ae60 471 nb_chunks -= DIV_ROUND_UP(io_sectors, sectors_per_chunk);
f14a39cc 472 if (s->common.speed) {
f3e4ce4a 473 delay_ns = ratelimit_calculate_delay(&s->limit, io_bytes_acct);
f14a39cc 474 }
dcfb3beb 475 }
cc8c9d6c 476 return delay_ns;
bd48bde8 477}
b952b558 478
402a4741
PB
479static void mirror_free_init(MirrorBlockJob *s)
480{
481 int granularity = s->granularity;
482 size_t buf_size = s->buf_size;
483 uint8_t *buf = s->buf;
484
485 assert(s->buf_free_count == 0);
486 QSIMPLEQ_INIT(&s->buf_free);
487 while (buf_size != 0) {
488 MirrorBuffer *cur = (MirrorBuffer *)buf;
489 QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
490 s->buf_free_count++;
491 buf_size -= granularity;
492 buf += granularity;
493 }
494}
495
bae8196d
PB
496/* This is also used for the .pause callback. There is no matching
497 * mirror_resume() because mirror_run() will begin iterating again
498 * when the job is resumed.
499 */
500static void mirror_wait_for_all_io(MirrorBlockJob *s)
bd48bde8
PB
501{
502 while (s->in_flight > 0) {
21cd917f 503 mirror_wait_for_io(s);
bd48bde8 504 }
893f7eba
PB
505}
506
5a7e7a0b
SH
507typedef struct {
508 int ret;
509} MirrorExitData;
510
511static void mirror_exit(BlockJob *job, void *opaque)
512{
513 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
514 MirrorExitData *data = opaque;
515 AioContext *replace_aio_context = NULL;
4ef85a9c 516 BlockDriverState *src = s->source;
e253f4b8 517 BlockDriverState *target_bs = blk_bs(s->target);
4ef85a9c 518 BlockDriverState *mirror_top_bs = s->mirror_top_bs;
12fa4af6 519 Error *local_err = NULL;
3f09bfbc 520
2119882c
PB
521 bdrv_release_dirty_bitmap(src, s->dirty_bitmap);
522
3f09bfbc
KW
523 /* Make sure that the source BDS doesn't go away before we called
524 * block_job_completed(). */
525 bdrv_ref(src);
4ef85a9c 526 bdrv_ref(mirror_top_bs);
7d9fcb39
KW
527 bdrv_ref(target_bs);
528
529 /* Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
530 * inserting target_bs at s->to_replace, where we might not be able to get
63c8ef28
KW
531 * these permissions.
532 *
533 * Note that blk_unref() alone doesn't necessarily drop permissions because
534 * we might be running nested inside mirror_drain(), which takes an extra
535 * reference, so use an explicit blk_set_perm() first. */
536 blk_set_perm(s->target, 0, BLK_PERM_ALL, &error_abort);
7d9fcb39
KW
537 blk_unref(s->target);
538 s->target = NULL;
4ef85a9c
KW
539
540 /* We don't access the source any more. Dropping any WRITE/RESIZE is
541 * required before it could become a backing file of target_bs. */
542 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
543 &error_abort);
544 if (s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
545 BlockDriverState *backing = s->is_none_mode ? src : s->base;
546 if (backing_bs(target_bs) != backing) {
12fa4af6
KW
547 bdrv_set_backing_hd(target_bs, backing, &local_err);
548 if (local_err) {
549 error_report_err(local_err);
550 data->ret = -EPERM;
551 }
4ef85a9c
KW
552 }
553 }
5a7e7a0b
SH
554
555 if (s->to_replace) {
556 replace_aio_context = bdrv_get_aio_context(s->to_replace);
557 aio_context_acquire(replace_aio_context);
558 }
559
560 if (s->should_complete && data->ret == 0) {
e253f4b8 561 BlockDriverState *to_replace = src;
5a7e7a0b
SH
562 if (s->to_replace) {
563 to_replace = s->to_replace;
564 }
40365552 565
e253f4b8
KW
566 if (bdrv_get_flags(target_bs) != bdrv_get_flags(to_replace)) {
567 bdrv_reopen(target_bs, bdrv_get_flags(to_replace), NULL);
5a7e7a0b 568 }
b8804815
KW
569
570 /* The mirror job has no requests in flight any more, but we need to
571 * drain potential other users of the BDS before changing the graph. */
e253f4b8 572 bdrv_drained_begin(target_bs);
5fe31c25 573 bdrv_replace_node(to_replace, target_bs, &local_err);
e253f4b8 574 bdrv_drained_end(target_bs);
5fe31c25
KW
575 if (local_err) {
576 error_report_err(local_err);
577 data->ret = -EPERM;
578 }
5a7e7a0b
SH
579 }
580 if (s->to_replace) {
581 bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
582 error_free(s->replace_blocker);
583 bdrv_unref(s->to_replace);
584 }
585 if (replace_aio_context) {
586 aio_context_release(replace_aio_context);
587 }
588 g_free(s->replaces);
7d9fcb39 589 bdrv_unref(target_bs);
4ef85a9c
KW
590
591 /* Remove the mirror filter driver from the graph. Before this, get rid of
592 * the blockers on the intermediate nodes so that the resulting state is
0bf74767
KW
593 * valid. Also give up permissions on mirror_top_bs->backing, which might
594 * block the removal. */
4ef85a9c 595 block_job_remove_all_bdrv(job);
c1cef672
FZ
596 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
597 &error_abort);
5fe31c25 598 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
4ef85a9c
KW
599
600 /* We just changed the BDS the job BB refers to (with either or both of the
5fe31c25
KW
601 * bdrv_replace_node() calls), so switch the BB back so the cleanup does
602 * the right thing. We don't need any permissions any more now. */
4ef85a9c
KW
603 blk_remove_bs(job->blk);
604 blk_set_perm(job->blk, 0, BLK_PERM_ALL, &error_abort);
605 blk_insert_bs(job->blk, mirror_top_bs, &error_abort);
606
5a7e7a0b 607 block_job_completed(&s->common, data->ret);
4ef85a9c 608
5a7e7a0b 609 g_free(data);
176c3699 610 bdrv_drained_end(src);
4ef85a9c 611 bdrv_unref(mirror_top_bs);
3f09bfbc 612 bdrv_unref(src);
5a7e7a0b
SH
613}
614
49efb1f5
DL
615static void mirror_throttle(MirrorBlockJob *s)
616{
617 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
618
619 if (now - s->last_pause_ns > SLICE_TIME) {
620 s->last_pause_ns = now;
621 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, 0);
622 } else {
623 block_job_pause_point(&s->common);
624 }
625}
626
c0b363ad
DL
627static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
628{
629 int64_t sector_num, end;
630 BlockDriverState *base = s->base;
4ef85a9c 631 BlockDriverState *bs = s->source;
c0b363ad 632 BlockDriverState *target_bs = blk_bs(s->target);
c0b363ad
DL
633 int ret, n;
634
635 end = s->bdev_length / BDRV_SECTOR_SIZE;
636
b7d5062c 637 if (base == NULL && !bdrv_has_zero_init(target_bs)) {
c7c2769c
DL
638 if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
639 bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, end);
640 return 0;
641 }
642
90ab48eb 643 s->initial_zeroing_ongoing = true;
c7c2769c
DL
644 for (sector_num = 0; sector_num < end; ) {
645 int nb_sectors = MIN(end - sector_num,
646 QEMU_ALIGN_DOWN(INT_MAX, s->granularity) >> BDRV_SECTOR_BITS);
647
648 mirror_throttle(s);
649
650 if (block_job_is_cancelled(&s->common)) {
90ab48eb 651 s->initial_zeroing_ongoing = false;
c7c2769c
DL
652 return 0;
653 }
654
655 if (s->in_flight >= MAX_IN_FLIGHT) {
67adf4b3
EB
656 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
657 s->in_flight);
c7c2769c
DL
658 mirror_wait_for_io(s);
659 continue;
660 }
661
e6f24193
EB
662 mirror_do_zero_or_discard(s, sector_num * BDRV_SECTOR_SIZE,
663 nb_sectors * BDRV_SECTOR_SIZE, false);
c7c2769c
DL
664 sector_num += nb_sectors;
665 }
666
bae8196d 667 mirror_wait_for_all_io(s);
90ab48eb 668 s->initial_zeroing_ongoing = false;
b7d5062c
DL
669 }
670
c0b363ad
DL
671 /* First part, loop on the sectors and initialize the dirty bitmap. */
672 for (sector_num = 0; sector_num < end; ) {
673 /* Just to make sure we are not exceeding int limit. */
674 int nb_sectors = MIN(INT_MAX >> BDRV_SECTOR_BITS,
675 end - sector_num);
676
677 mirror_throttle(s);
678
679 if (block_job_is_cancelled(&s->common)) {
680 return 0;
681 }
682
683 ret = bdrv_is_allocated_above(bs, base, sector_num, nb_sectors, &n);
684 if (ret < 0) {
685 return ret;
686 }
687
688 assert(n > 0);
b7d5062c 689 if (ret == 1) {
c0b363ad
DL
690 bdrv_set_dirty_bitmap(s->dirty_bitmap, sector_num, n);
691 }
692 sector_num += n;
693 }
694 return 0;
695}
696
bdffb31d
PB
697/* Called when going out of the streaming phase to flush the bulk of the
698 * data to the medium, or just before completing.
699 */
700static int mirror_flush(MirrorBlockJob *s)
701{
702 int ret = blk_flush(s->target);
703 if (ret < 0) {
704 if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
705 s->ret = ret;
706 }
707 }
708 return ret;
709}
710
893f7eba
PB
711static void coroutine_fn mirror_run(void *opaque)
712{
713 MirrorBlockJob *s = opaque;
5a7e7a0b 714 MirrorExitData *data;
4ef85a9c 715 BlockDriverState *bs = s->source;
e253f4b8 716 BlockDriverState *target_bs = blk_bs(s->target);
9a0cec66 717 bool need_drain = true;
c0b363ad 718 int64_t length;
b812f671 719 BlockDriverInfo bdi;
1d33936e
JC
720 char backing_filename[2]; /* we only need 2 characters because we are only
721 checking for a NULL string */
893f7eba 722 int ret = 0;
893f7eba
PB
723
724 if (block_job_is_cancelled(&s->common)) {
725 goto immediate_exit;
726 }
727
b21c7652
HR
728 s->bdev_length = bdrv_getlength(bs);
729 if (s->bdev_length < 0) {
730 ret = s->bdev_length;
373df5b1 731 goto immediate_exit;
becc347e
KW
732 }
733
734 /* Active commit must resize the base image if its size differs from the
735 * active layer. */
736 if (s->base == blk_bs(s->target)) {
737 int64_t base_length;
738
739 base_length = blk_getlength(s->target);
740 if (base_length < 0) {
741 ret = base_length;
742 goto immediate_exit;
743 }
744
745 if (s->bdev_length > base_length) {
ed3d2ec9 746 ret = blk_truncate(s->target, s->bdev_length, NULL);
becc347e
KW
747 if (ret < 0) {
748 goto immediate_exit;
749 }
750 }
751 }
752
753 if (s->bdev_length == 0) {
9e48b025
FZ
754 /* Report BLOCK_JOB_READY and wait for complete. */
755 block_job_event_ready(&s->common);
756 s->synced = true;
757 while (!block_job_is_cancelled(&s->common) && !s->should_complete) {
758 block_job_yield(&s->common);
759 }
760 s->common.cancelled = false;
761 goto immediate_exit;
893f7eba
PB
762 }
763
b21c7652 764 length = DIV_ROUND_UP(s->bdev_length, s->granularity);
402a4741
PB
765 s->in_flight_bitmap = bitmap_new(length);
766
b812f671
PB
767 /* If we have no backing file yet in the destination, we cannot let
768 * the destination do COW. Instead, we copy sectors around the
769 * dirty data if needed. We need a bitmap to do that.
770 */
e253f4b8 771 bdrv_get_backing_filename(target_bs, backing_filename,
b812f671 772 sizeof(backing_filename));
e253f4b8 773 if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
b436982f
EB
774 s->target_cluster_size = bdi.cluster_size;
775 } else {
776 s->target_cluster_size = BDRV_SECTOR_SIZE;
e5b43573 777 }
b436982f
EB
778 if (backing_filename[0] && !target_bs->backing &&
779 s->granularity < s->target_cluster_size) {
780 s->buf_size = MAX(s->buf_size, s->target_cluster_size);
e5b43573 781 s->cow_bitmap = bitmap_new(length);
b812f671 782 }
e253f4b8 783 s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
b812f671 784
7504edf4
KW
785 s->buf = qemu_try_blockalign(bs, s->buf_size);
786 if (s->buf == NULL) {
787 ret = -ENOMEM;
788 goto immediate_exit;
789 }
790
402a4741 791 mirror_free_init(s);
893f7eba 792
49efb1f5 793 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
03544a6e 794 if (!s->is_none_mode) {
c0b363ad
DL
795 ret = mirror_dirty_init(s);
796 if (ret < 0 || block_job_is_cancelled(&s->common)) {
797 goto immediate_exit;
893f7eba
PB
798 }
799 }
800
dc162c8e
FZ
801 assert(!s->dbi);
802 s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap, 0);
893f7eba 803 for (;;) {
cc8c9d6c 804 uint64_t delay_ns = 0;
49efb1f5 805 int64_t cnt, delta;
893f7eba
PB
806 bool should_complete;
807
bd48bde8
PB
808 if (s->ret < 0) {
809 ret = s->ret;
810 goto immediate_exit;
811 }
812
565ac01f
SH
813 block_job_pause_point(&s->common);
814
20dca810 815 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
b21c7652
HR
816 /* s->common.offset contains the number of bytes already processed so
817 * far, cnt is the number of dirty sectors remaining and
b436982f 818 * s->bytes_in_flight is the number of bytes currently being
b21c7652 819 * processed; together those are the current total operation length */
b436982f
EB
820 s->common.len = s->common.offset + s->bytes_in_flight +
821 cnt * BDRV_SECTOR_SIZE;
bd48bde8
PB
822
823 /* Note that even when no rate limit is applied we need to yield
a7282330 824 * periodically with no pending I/O so that bdrv_drain_all() returns.
bd48bde8
PB
825 * We do so every SLICE_TIME nanoseconds, or when there is an error,
826 * or when the source is clean, whichever comes first.
827 */
49efb1f5
DL
828 delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
829 if (delta < SLICE_TIME &&
bd48bde8 830 s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
cf56a3c6 831 if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
402a4741 832 (cnt == 0 && s->in_flight > 0)) {
5cb1a49e
EB
833 trace_mirror_yield(s, cnt * BDRV_SECTOR_SIZE,
834 s->buf_free_count, s->in_flight);
21cd917f 835 mirror_wait_for_io(s);
bd48bde8
PB
836 continue;
837 } else if (cnt != 0) {
cc8c9d6c 838 delay_ns = mirror_iteration(s);
893f7eba 839 }
893f7eba
PB
840 }
841
842 should_complete = false;
bd48bde8 843 if (s->in_flight == 0 && cnt == 0) {
893f7eba 844 trace_mirror_before_flush(s);
bdffb31d
PB
845 if (!s->synced) {
846 if (mirror_flush(s) < 0) {
847 /* Go check s->ret. */
848 continue;
b952b558 849 }
b952b558
PB
850 /* We're out of the streaming phase. From now on, if the job
851 * is cancelled we will actually complete all pending I/O and
852 * report completion. This way, block-job-cancel will leave
853 * the target in a consistent state.
854 */
bdffb31d
PB
855 block_job_event_ready(&s->common);
856 s->synced = true;
d63ffd87 857 }
bdffb31d
PB
858
859 should_complete = s->should_complete ||
860 block_job_is_cancelled(&s->common);
861 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
893f7eba
PB
862 }
863
864 if (cnt == 0 && should_complete) {
865 /* The dirty bitmap is not updated while operations are pending.
866 * If we're about to exit, wait for pending operations before
867 * calling bdrv_get_dirty_count(bs), or we may exit while the
868 * source has dirty data to copy!
869 *
870 * Note that I/O can be submitted by the guest while
9a0cec66
PB
871 * mirror_populate runs, so pause it now. Before deciding
872 * whether to switch to target check one last time if I/O has
873 * come in the meanwhile, and if not flush the data to disk.
893f7eba 874 */
5cb1a49e 875 trace_mirror_before_drain(s, cnt * BDRV_SECTOR_SIZE);
9a0cec66
PB
876
877 bdrv_drained_begin(bs);
20dca810 878 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
bdffb31d 879 if (cnt > 0 || mirror_flush(s) < 0) {
9a0cec66
PB
880 bdrv_drained_end(bs);
881 continue;
882 }
883
884 /* The two disks are in sync. Exit and report successful
885 * completion.
886 */
887 assert(QLIST_EMPTY(&bs->tracked_requests));
888 s->common.cancelled = false;
889 need_drain = false;
890 break;
893f7eba
PB
891 }
892
893 ret = 0;
5cb1a49e
EB
894 trace_mirror_before_sleep(s, cnt * BDRV_SECTOR_SIZE,
895 s->synced, delay_ns);
d63ffd87 896 if (!s->synced) {
7483d1e5 897 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
893f7eba
PB
898 if (block_job_is_cancelled(&s->common)) {
899 break;
900 }
901 } else if (!should_complete) {
bd48bde8 902 delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);
7483d1e5 903 block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);
893f7eba 904 }
49efb1f5 905 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
893f7eba
PB
906 }
907
908immediate_exit:
bd48bde8
PB
909 if (s->in_flight > 0) {
910 /* We get here only if something went wrong. Either the job failed,
911 * or it was cancelled prematurely so that we do not guarantee that
912 * the target is a copy of the source.
913 */
914 assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));
9a0cec66 915 assert(need_drain);
bae8196d 916 mirror_wait_for_all_io(s);
bd48bde8
PB
917 }
918
919 assert(s->in_flight == 0);
7191bf31 920 qemu_vfree(s->buf);
b812f671 921 g_free(s->cow_bitmap);
402a4741 922 g_free(s->in_flight_bitmap);
dc162c8e 923 bdrv_dirty_iter_free(s->dbi);
5a7e7a0b
SH
924
925 data = g_malloc(sizeof(*data));
926 data->ret = ret;
9a0cec66
PB
927
928 if (need_drain) {
929 bdrv_drained_begin(bs);
930 }
5a7e7a0b 931 block_job_defer_to_main_loop(&s->common, mirror_exit, data);
893f7eba
PB
932}
933
934static void mirror_set_speed(BlockJob *job, int64_t speed, Error **errp)
935{
936 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
937
938 if (speed < 0) {
c6bd8c70 939 error_setg(errp, QERR_INVALID_PARAMETER, "speed");
893f7eba
PB
940 return;
941 }
f3e4ce4a 942 ratelimit_set_speed(&s->limit, speed, SLICE_TIME);
893f7eba
PB
943}
944
d63ffd87
PB
945static void mirror_complete(BlockJob *job, Error **errp)
946{
947 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
4ef85a9c 948 BlockDriverState *target;
274fccee 949
274fccee 950 target = blk_bs(s->target);
d63ffd87 951
d63ffd87 952 if (!s->synced) {
9df229c3
AG
953 error_setg(errp, "The active block job '%s' cannot be completed",
954 job->id);
d63ffd87
PB
955 return;
956 }
957
274fccee
HR
958 if (s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
959 int ret;
960
961 assert(!target->backing);
962 ret = bdrv_open_backing_file(target, NULL, "backing", errp);
963 if (ret < 0) {
964 return;
965 }
966 }
967
15d67298 968 /* block all operations on to_replace bs */
09158f00 969 if (s->replaces) {
5a7e7a0b
SH
970 AioContext *replace_aio_context;
971
e12f3784 972 s->to_replace = bdrv_find_node(s->replaces);
09158f00 973 if (!s->to_replace) {
e12f3784 974 error_setg(errp, "Node name '%s' not found", s->replaces);
09158f00
BC
975 return;
976 }
977
5a7e7a0b
SH
978 replace_aio_context = bdrv_get_aio_context(s->to_replace);
979 aio_context_acquire(replace_aio_context);
980
4ef85a9c
KW
981 /* TODO Translate this into permission system. Current definition of
982 * GRAPH_MOD would require to request it for the parents; they might
983 * not even be BlockDriverStates, however, so a BdrvChild can't address
984 * them. May need redefinition of GRAPH_MOD. */
09158f00
BC
985 error_setg(&s->replace_blocker,
986 "block device is in use by block-job-complete");
987 bdrv_op_block_all(s->to_replace, s->replace_blocker);
988 bdrv_ref(s->to_replace);
5a7e7a0b
SH
989
990 aio_context_release(replace_aio_context);
09158f00
BC
991 }
992
d63ffd87 993 s->should_complete = true;
751ebd76 994 block_job_enter(&s->common);
d63ffd87
PB
995}
996
bae8196d 997static void mirror_pause(BlockJob *job)
565ac01f
SH
998{
999 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1000
bae8196d 1001 mirror_wait_for_all_io(s);
565ac01f
SH
1002}
1003
1004static void mirror_attached_aio_context(BlockJob *job, AioContext *new_context)
1005{
1006 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1007
1008 blk_set_aio_context(s->target, new_context);
1009}
1010
bae8196d
PB
1011static void mirror_drain(BlockJob *job)
1012{
1013 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1014
1015 /* Need to keep a reference in case blk_drain triggers execution
1016 * of mirror_complete...
1017 */
1018 if (s->target) {
1019 BlockBackend *target = s->target;
1020 blk_ref(target);
1021 blk_drain(target);
1022 blk_unref(target);
1023 }
1024}
1025
3fc4b10a 1026static const BlockJobDriver mirror_job_driver = {
565ac01f
SH
1027 .instance_size = sizeof(MirrorBlockJob),
1028 .job_type = BLOCK_JOB_TYPE_MIRROR,
1029 .set_speed = mirror_set_speed,
a7815a76 1030 .start = mirror_run,
565ac01f
SH
1031 .complete = mirror_complete,
1032 .pause = mirror_pause,
1033 .attached_aio_context = mirror_attached_aio_context,
bae8196d 1034 .drain = mirror_drain,
893f7eba
PB
1035};
1036
03544a6e 1037static const BlockJobDriver commit_active_job_driver = {
565ac01f
SH
1038 .instance_size = sizeof(MirrorBlockJob),
1039 .job_type = BLOCK_JOB_TYPE_COMMIT,
1040 .set_speed = mirror_set_speed,
a7815a76 1041 .start = mirror_run,
565ac01f
SH
1042 .complete = mirror_complete,
1043 .pause = mirror_pause,
1044 .attached_aio_context = mirror_attached_aio_context,
bae8196d 1045 .drain = mirror_drain,
03544a6e
FZ
1046};
1047
4ef85a9c
KW
1048static int coroutine_fn bdrv_mirror_top_preadv(BlockDriverState *bs,
1049 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1050{
1051 return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
1052}
1053
1054static int coroutine_fn bdrv_mirror_top_pwritev(BlockDriverState *bs,
1055 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1056{
1057 return bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1058}
1059
1060static int coroutine_fn bdrv_mirror_top_flush(BlockDriverState *bs)
1061{
1062 return bdrv_co_flush(bs->backing->bs);
1063}
1064
1065static int64_t coroutine_fn bdrv_mirror_top_get_block_status(
1066 BlockDriverState *bs, int64_t sector_num, int nb_sectors, int *pnum,
1067 BlockDriverState **file)
1068{
1069 *pnum = nb_sectors;
1070 *file = bs->backing->bs;
d5254033 1071 return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID |
4ef85a9c
KW
1072 (sector_num << BDRV_SECTOR_BITS);
1073}
1074
1075static int coroutine_fn bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs,
f5a5ca79 1076 int64_t offset, int bytes, BdrvRequestFlags flags)
4ef85a9c 1077{
f5a5ca79 1078 return bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
4ef85a9c
KW
1079}
1080
1081static int coroutine_fn bdrv_mirror_top_pdiscard(BlockDriverState *bs,
f5a5ca79 1082 int64_t offset, int bytes)
4ef85a9c 1083{
f5a5ca79 1084 return bdrv_co_pdiscard(bs->backing->bs, offset, bytes);
4ef85a9c
KW
1085}
1086
fd4a6493
KW
1087static void bdrv_mirror_top_refresh_filename(BlockDriverState *bs, QDict *opts)
1088{
1089 bdrv_refresh_filename(bs->backing->bs);
1090 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1091 bs->backing->bs->filename);
1092}
1093
4ef85a9c
KW
1094static void bdrv_mirror_top_close(BlockDriverState *bs)
1095{
1096}
1097
1098static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1099 const BdrvChildRole *role,
1100 uint64_t perm, uint64_t shared,
1101 uint64_t *nperm, uint64_t *nshared)
1102{
1103 /* Must be able to forward guest writes to the real image */
1104 *nperm = 0;
1105 if (perm & BLK_PERM_WRITE) {
1106 *nperm |= BLK_PERM_WRITE;
1107 }
1108
1109 *nshared = BLK_PERM_ALL;
1110}
1111
1112/* Dummy node that provides consistent read to its users without requiring it
1113 * from its backing file and that allows writes on the backing file chain. */
1114static BlockDriver bdrv_mirror_top = {
1115 .format_name = "mirror_top",
1116 .bdrv_co_preadv = bdrv_mirror_top_preadv,
1117 .bdrv_co_pwritev = bdrv_mirror_top_pwritev,
1118 .bdrv_co_pwrite_zeroes = bdrv_mirror_top_pwrite_zeroes,
1119 .bdrv_co_pdiscard = bdrv_mirror_top_pdiscard,
1120 .bdrv_co_flush = bdrv_mirror_top_flush,
1121 .bdrv_co_get_block_status = bdrv_mirror_top_get_block_status,
fd4a6493 1122 .bdrv_refresh_filename = bdrv_mirror_top_refresh_filename,
4ef85a9c
KW
1123 .bdrv_close = bdrv_mirror_top_close,
1124 .bdrv_child_perm = bdrv_mirror_top_child_perm,
1125};
1126
71aa9867 1127static void mirror_start_job(const char *job_id, BlockDriverState *bs,
47970dfb
JS
1128 int creation_flags, BlockDriverState *target,
1129 const char *replaces, int64_t speed,
1130 uint32_t granularity, int64_t buf_size,
274fccee 1131 BlockMirrorBackingMode backing_mode,
09158f00
BC
1132 BlockdevOnError on_source_error,
1133 BlockdevOnError on_target_error,
0fc9f8ea 1134 bool unmap,
097310b5 1135 BlockCompletionFunc *cb,
51ccfa2d 1136 void *opaque,
09158f00 1137 const BlockJobDriver *driver,
b49f7ead 1138 bool is_none_mode, BlockDriverState *base,
51ccfa2d
FZ
1139 bool auto_complete, const char *filter_node_name,
1140 Error **errp)
893f7eba
PB
1141{
1142 MirrorBlockJob *s;
4ef85a9c
KW
1143 BlockDriverState *mirror_top_bs;
1144 bool target_graph_mod;
1145 bool target_is_backing;
b2c2832c 1146 Error *local_err = NULL;
d7086422 1147 int ret;
893f7eba 1148
eee13dfe 1149 if (granularity == 0) {
341ebc2f 1150 granularity = bdrv_get_default_bitmap_granularity(target);
eee13dfe
PB
1151 }
1152
1153 assert ((granularity & (granularity - 1)) == 0);
b436982f
EB
1154 /* Granularity must be large enough for sector-based dirty bitmap */
1155 assert(granularity >= BDRV_SECTOR_SIZE);
eee13dfe 1156
48ac0a4d
WC
1157 if (buf_size < 0) {
1158 error_setg(errp, "Invalid parameter 'buf-size'");
1159 return;
1160 }
1161
1162 if (buf_size == 0) {
1163 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1164 }
5bc361b8 1165
4ef85a9c
KW
1166 /* In the case of active commit, add dummy driver to provide consistent
1167 * reads on the top, while disabling it in the intermediate nodes, and make
1168 * the backing chain writable. */
6cdbceb1
KW
1169 mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
1170 BDRV_O_RDWR, errp);
4ef85a9c
KW
1171 if (mirror_top_bs == NULL) {
1172 return;
1173 }
1174 mirror_top_bs->total_sectors = bs->total_sectors;
19dd29e8 1175 bdrv_set_aio_context(mirror_top_bs, bdrv_get_aio_context(bs));
4ef85a9c
KW
1176
1177 /* bdrv_append takes ownership of the mirror_top_bs reference, need to keep
7a25fcd0 1178 * it alive until block_job_create() succeeds even if bs has no parent. */
4ef85a9c
KW
1179 bdrv_ref(mirror_top_bs);
1180 bdrv_drained_begin(bs);
b2c2832c 1181 bdrv_append(mirror_top_bs, bs, &local_err);
4ef85a9c
KW
1182 bdrv_drained_end(bs);
1183
b2c2832c
KW
1184 if (local_err) {
1185 bdrv_unref(mirror_top_bs);
1186 error_propagate(errp, local_err);
1187 return;
1188 }
1189
4ef85a9c
KW
1190 /* Make sure that the source is not resized while the job is running */
1191 s = block_job_create(job_id, driver, mirror_top_bs,
1192 BLK_PERM_CONSISTENT_READ,
1193 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1194 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD, speed,
c6cc12bf 1195 creation_flags, cb, opaque, errp);
893f7eba 1196 if (!s) {
4ef85a9c 1197 goto fail;
893f7eba 1198 }
7a25fcd0
HR
1199 /* The block job now has a reference to this node */
1200 bdrv_unref(mirror_top_bs);
1201
4ef85a9c
KW
1202 s->source = bs;
1203 s->mirror_top_bs = mirror_top_bs;
1204
1205 /* No resize for the target either; while the mirror is still running, a
1206 * consistent read isn't necessarily possible. We could possibly allow
1207 * writes and graph modifications, though it would likely defeat the
1208 * purpose of a mirror, so leave them blocked for now.
1209 *
1210 * In the case of active commit, things look a bit different, though,
1211 * because the target is an already populated backing file in active use.
1212 * We can allow anything except resize there.*/
1213 target_is_backing = bdrv_chain_contains(bs, target);
1214 target_graph_mod = (backing_mode != MIRROR_LEAVE_BACKING_CHAIN);
1215 s->target = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE |
1216 (target_graph_mod ? BLK_PERM_GRAPH_MOD : 0),
1217 BLK_PERM_WRITE_UNCHANGED |
1218 (target_is_backing ? BLK_PERM_CONSISTENT_READ |
1219 BLK_PERM_WRITE |
1220 BLK_PERM_GRAPH_MOD : 0));
d7086422
KW
1221 ret = blk_insert_bs(s->target, target, errp);
1222 if (ret < 0) {
4ef85a9c 1223 goto fail;
d7086422 1224 }
e253f4b8 1225
09158f00 1226 s->replaces = g_strdup(replaces);
b952b558
PB
1227 s->on_source_error = on_source_error;
1228 s->on_target_error = on_target_error;
03544a6e 1229 s->is_none_mode = is_none_mode;
274fccee 1230 s->backing_mode = backing_mode;
5bc361b8 1231 s->base = base;
eee13dfe 1232 s->granularity = granularity;
48ac0a4d 1233 s->buf_size = ROUND_UP(buf_size, granularity);
0fc9f8ea 1234 s->unmap = unmap;
b49f7ead
WC
1235 if (auto_complete) {
1236 s->should_complete = true;
1237 }
b812f671 1238
0db6e54a 1239 s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
b8afb520 1240 if (!s->dirty_bitmap) {
88f9d1b3 1241 goto fail;
b8afb520 1242 }
10f3cd15 1243
4ef85a9c 1244 /* Required permissions are already taken with blk_new() */
76d554e2
KW
1245 block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
1246 &error_abort);
1247
f3ede4b0
AG
1248 /* In commit_active_start() all intermediate nodes disappear, so
1249 * any jobs in them must be blocked */
4ef85a9c 1250 if (target_is_backing) {
f3ede4b0
AG
1251 BlockDriverState *iter;
1252 for (iter = backing_bs(bs); iter != target; iter = backing_bs(iter)) {
4ef85a9c
KW
1253 /* XXX BLK_PERM_WRITE needs to be allowed so we don't block
1254 * ourselves at s->base (if writes are blocked for a node, they are
1255 * also blocked for its backing file). The other options would be a
1256 * second filter driver above s->base (== target). */
1257 ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
1258 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE,
1259 errp);
1260 if (ret < 0) {
1261 goto fail;
1262 }
f3ede4b0
AG
1263 }
1264 }
10f3cd15 1265
5ccac6f1
JS
1266 trace_mirror_start(bs, s, opaque);
1267 block_job_start(&s->common);
4ef85a9c
KW
1268 return;
1269
1270fail:
1271 if (s) {
7a25fcd0
HR
1272 /* Make sure this BDS does not go away until we have completed the graph
1273 * changes below */
1274 bdrv_ref(mirror_top_bs);
1275
4ef85a9c
KW
1276 g_free(s->replaces);
1277 blk_unref(s->target);
05b0d8e3 1278 block_job_early_fail(&s->common);
4ef85a9c
KW
1279 }
1280
c1cef672
FZ
1281 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
1282 &error_abort);
5fe31c25 1283 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
7a25fcd0
HR
1284
1285 bdrv_unref(mirror_top_bs);
893f7eba 1286}
03544a6e 1287
71aa9867
AG
1288void mirror_start(const char *job_id, BlockDriverState *bs,
1289 BlockDriverState *target, const char *replaces,
5fba6c0e 1290 int64_t speed, uint32_t granularity, int64_t buf_size,
274fccee
HR
1291 MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
1292 BlockdevOnError on_source_error,
03544a6e 1293 BlockdevOnError on_target_error,
6cdbceb1 1294 bool unmap, const char *filter_node_name, Error **errp)
03544a6e
FZ
1295{
1296 bool is_none_mode;
1297 BlockDriverState *base;
1298
4b80ab2b
JS
1299 if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
1300 error_setg(errp, "Sync mode 'incremental' not supported");
d58d8453
JS
1301 return;
1302 }
03544a6e 1303 is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
760e0063 1304 base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
47970dfb 1305 mirror_start_job(job_id, bs, BLOCK_JOB_DEFAULT, target, replaces,
274fccee 1306 speed, granularity, buf_size, backing_mode,
51ccfa2d 1307 on_source_error, on_target_error, unmap, NULL, NULL,
6cdbceb1 1308 &mirror_job_driver, is_none_mode, base, false,
51ccfa2d 1309 filter_node_name, errp);
03544a6e
FZ
1310}
1311
fd62c609 1312void commit_active_start(const char *job_id, BlockDriverState *bs,
47970dfb
JS
1313 BlockDriverState *base, int creation_flags,
1314 int64_t speed, BlockdevOnError on_error,
0db832f4 1315 const char *filter_node_name,
78bbd910
FZ
1316 BlockCompletionFunc *cb, void *opaque,
1317 bool auto_complete, Error **errp)
03544a6e 1318{
4da83585 1319 int orig_base_flags;
cc67f4d1 1320 Error *local_err = NULL;
4da83585
JC
1321
1322 orig_base_flags = bdrv_get_flags(base);
1323
20a63d2c
FZ
1324 if (bdrv_reopen(base, bs->open_flags, errp)) {
1325 return;
1326 }
4da83585 1327
47970dfb 1328 mirror_start_job(job_id, bs, creation_flags, base, NULL, speed, 0, 0,
71aa9867 1329 MIRROR_LEAVE_BACKING_CHAIN,
51ccfa2d 1330 on_error, on_error, true, cb, opaque,
6cdbceb1 1331 &commit_active_job_driver, false, base, auto_complete,
51ccfa2d 1332 filter_node_name, &local_err);
0fb6395c 1333 if (local_err) {
cc67f4d1 1334 error_propagate(errp, local_err);
4da83585
JC
1335 goto error_restore_flags;
1336 }
1337
1338 return;
1339
1340error_restore_flags:
1341 /* ignore error and errp for bdrv_reopen, because we want to propagate
1342 * the original error */
1343 bdrv_reopen(base, orig_base_flags, NULL);
1344 return;
03544a6e 1345}