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