]> git.proxmox.com Git - mirror_qemu.git/blob - block/mirror.c
Merge remote-tracking branch 'remotes/palmer/tags/riscv-for-master-4.0-sf4' into...
[mirror_qemu.git] / block / mirror.c
1 /*
2 * Image mirroring
3 *
4 * Copyright Red Hat, Inc. 2012
5 *
6 * Authors:
7 * Paolo Bonzini <pbonzini@redhat.com>
8 *
9 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
10 * See the COPYING.LIB file in the top-level directory.
11 *
12 */
13
14 #include "qemu/osdep.h"
15 #include "qemu/cutils.h"
16 #include "qemu/coroutine.h"
17 #include "qemu/range.h"
18 #include "trace.h"
19 #include "block/blockjob_int.h"
20 #include "block/block_int.h"
21 #include "sysemu/block-backend.h"
22 #include "qapi/error.h"
23 #include "qapi/qmp/qerror.h"
24 #include "qemu/ratelimit.h"
25 #include "qemu/bitmap.h"
26
27 #define MAX_IN_FLIGHT 16
28 #define MAX_IO_BYTES (1 << 20) /* 1 Mb */
29 #define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
30
31 /* The mirroring buffer is a list of granularity-sized chunks.
32 * Free chunks are organized in a list.
33 */
34 typedef struct MirrorBuffer {
35 QSIMPLEQ_ENTRY(MirrorBuffer) next;
36 } MirrorBuffer;
37
38 typedef struct MirrorOp MirrorOp;
39
40 typedef struct MirrorBlockJob {
41 BlockJob common;
42 BlockBackend *target;
43 BlockDriverState *mirror_top_bs;
44 BlockDriverState *base;
45
46 /* The name of the graph node to replace */
47 char *replaces;
48 /* The BDS to replace */
49 BlockDriverState *to_replace;
50 /* Used to block operations on the drive-mirror-replace target */
51 Error *replace_blocker;
52 bool is_none_mode;
53 BlockMirrorBackingMode backing_mode;
54 MirrorCopyMode copy_mode;
55 BlockdevOnError on_source_error, on_target_error;
56 bool synced;
57 /* Set when the target is synced (dirty bitmap is clean, nothing
58 * in flight) and the job is running in active mode */
59 bool actively_synced;
60 bool should_complete;
61 int64_t granularity;
62 size_t buf_size;
63 int64_t bdev_length;
64 unsigned long *cow_bitmap;
65 BdrvDirtyBitmap *dirty_bitmap;
66 BdrvDirtyBitmapIter *dbi;
67 uint8_t *buf;
68 QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
69 int buf_free_count;
70
71 uint64_t last_pause_ns;
72 unsigned long *in_flight_bitmap;
73 int in_flight;
74 int64_t bytes_in_flight;
75 QTAILQ_HEAD(, MirrorOp) ops_in_flight;
76 int ret;
77 bool unmap;
78 int target_cluster_size;
79 int max_iov;
80 bool initial_zeroing_ongoing;
81 int in_active_write_counter;
82 bool prepared;
83 } MirrorBlockJob;
84
85 typedef struct MirrorBDSOpaque {
86 MirrorBlockJob *job;
87 } MirrorBDSOpaque;
88
89 struct MirrorOp {
90 MirrorBlockJob *s;
91 QEMUIOVector qiov;
92 int64_t offset;
93 uint64_t bytes;
94
95 /* The pointee is set by mirror_co_read(), mirror_co_zero(), and
96 * mirror_co_discard() before yielding for the first time */
97 int64_t *bytes_handled;
98
99 bool is_pseudo_op;
100 bool is_active_write;
101 CoQueue waiting_requests;
102
103 QTAILQ_ENTRY(MirrorOp) next;
104 };
105
106 typedef enum MirrorMethod {
107 MIRROR_METHOD_COPY,
108 MIRROR_METHOD_ZERO,
109 MIRROR_METHOD_DISCARD,
110 } MirrorMethod;
111
112 static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
113 int error)
114 {
115 s->synced = false;
116 s->actively_synced = false;
117 if (read) {
118 return block_job_error_action(&s->common, s->on_source_error,
119 true, error);
120 } else {
121 return block_job_error_action(&s->common, s->on_target_error,
122 false, error);
123 }
124 }
125
126 static void coroutine_fn mirror_wait_on_conflicts(MirrorOp *self,
127 MirrorBlockJob *s,
128 uint64_t offset,
129 uint64_t bytes)
130 {
131 uint64_t self_start_chunk = offset / s->granularity;
132 uint64_t self_end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
133 uint64_t self_nb_chunks = self_end_chunk - self_start_chunk;
134
135 while (find_next_bit(s->in_flight_bitmap, self_end_chunk,
136 self_start_chunk) < self_end_chunk &&
137 s->ret >= 0)
138 {
139 MirrorOp *op;
140
141 QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
142 uint64_t op_start_chunk = op->offset / s->granularity;
143 uint64_t op_nb_chunks = DIV_ROUND_UP(op->offset + op->bytes,
144 s->granularity) -
145 op_start_chunk;
146
147 if (op == self) {
148 continue;
149 }
150
151 if (ranges_overlap(self_start_chunk, self_nb_chunks,
152 op_start_chunk, op_nb_chunks))
153 {
154 qemu_co_queue_wait(&op->waiting_requests, NULL);
155 break;
156 }
157 }
158 }
159 }
160
161 static void coroutine_fn mirror_iteration_done(MirrorOp *op, int ret)
162 {
163 MirrorBlockJob *s = op->s;
164 struct iovec *iov;
165 int64_t chunk_num;
166 int i, nb_chunks;
167
168 trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
169
170 s->in_flight--;
171 s->bytes_in_flight -= op->bytes;
172 iov = op->qiov.iov;
173 for (i = 0; i < op->qiov.niov; i++) {
174 MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
175 QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
176 s->buf_free_count++;
177 }
178
179 chunk_num = op->offset / s->granularity;
180 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
181
182 bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
183 QTAILQ_REMOVE(&s->ops_in_flight, op, next);
184 if (ret >= 0) {
185 if (s->cow_bitmap) {
186 bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
187 }
188 if (!s->initial_zeroing_ongoing) {
189 job_progress_update(&s->common.job, op->bytes);
190 }
191 }
192 qemu_iovec_destroy(&op->qiov);
193
194 qemu_co_queue_restart_all(&op->waiting_requests);
195 g_free(op);
196 }
197
198 static void coroutine_fn mirror_write_complete(MirrorOp *op, int ret)
199 {
200 MirrorBlockJob *s = op->s;
201
202 if (ret < 0) {
203 BlockErrorAction action;
204
205 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
206 action = mirror_error_action(s, false, -ret);
207 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
208 s->ret = ret;
209 }
210 }
211
212 mirror_iteration_done(op, ret);
213 }
214
215 static void coroutine_fn mirror_read_complete(MirrorOp *op, int ret)
216 {
217 MirrorBlockJob *s = op->s;
218
219 if (ret < 0) {
220 BlockErrorAction action;
221
222 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
223 action = mirror_error_action(s, true, -ret);
224 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
225 s->ret = ret;
226 }
227
228 mirror_iteration_done(op, ret);
229 return;
230 }
231
232 ret = blk_co_pwritev(s->target, op->offset, op->qiov.size, &op->qiov, 0);
233 mirror_write_complete(op, ret);
234 }
235
236 /* Clip bytes relative to offset to not exceed end-of-file */
237 static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
238 int64_t offset,
239 int64_t bytes)
240 {
241 return MIN(bytes, s->bdev_length - offset);
242 }
243
244 /* Round offset and/or bytes to target cluster if COW is needed, and
245 * return the offset of the adjusted tail against original. */
246 static int mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
247 uint64_t *bytes)
248 {
249 bool need_cow;
250 int ret = 0;
251 int64_t align_offset = *offset;
252 int64_t align_bytes = *bytes;
253 int max_bytes = s->granularity * s->max_iov;
254
255 need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
256 need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
257 s->cow_bitmap);
258 if (need_cow) {
259 bdrv_round_to_clusters(blk_bs(s->target), *offset, *bytes,
260 &align_offset, &align_bytes);
261 }
262
263 if (align_bytes > max_bytes) {
264 align_bytes = max_bytes;
265 if (need_cow) {
266 align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
267 }
268 }
269 /* Clipping may result in align_bytes unaligned to chunk boundary, but
270 * that doesn't matter because it's already the end of source image. */
271 align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
272
273 ret = align_offset + align_bytes - (*offset + *bytes);
274 *offset = align_offset;
275 *bytes = align_bytes;
276 assert(ret >= 0);
277 return ret;
278 }
279
280 static inline void coroutine_fn
281 mirror_wait_for_any_operation(MirrorBlockJob *s, bool active)
282 {
283 MirrorOp *op;
284
285 QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
286 /* Do not wait on pseudo ops, because it may in turn wait on
287 * some other operation to start, which may in fact be the
288 * caller of this function. Since there is only one pseudo op
289 * at any given time, we will always find some real operation
290 * to wait on. */
291 if (!op->is_pseudo_op && op->is_active_write == active) {
292 qemu_co_queue_wait(&op->waiting_requests, NULL);
293 return;
294 }
295 }
296 abort();
297 }
298
299 static inline void coroutine_fn
300 mirror_wait_for_free_in_flight_slot(MirrorBlockJob *s)
301 {
302 /* Only non-active operations use up in-flight slots */
303 mirror_wait_for_any_operation(s, false);
304 }
305
306 /* Perform a mirror copy operation.
307 *
308 * *op->bytes_handled is set to the number of bytes copied after and
309 * including offset, excluding any bytes copied prior to offset due
310 * to alignment. This will be op->bytes if no alignment is necessary,
311 * or (new_end - op->offset) if the tail is rounded up or down due to
312 * alignment or buffer limit.
313 */
314 static void coroutine_fn mirror_co_read(void *opaque)
315 {
316 MirrorOp *op = opaque;
317 MirrorBlockJob *s = op->s;
318 int nb_chunks;
319 uint64_t ret;
320 uint64_t max_bytes;
321
322 max_bytes = s->granularity * s->max_iov;
323
324 /* We can only handle as much as buf_size at a time. */
325 op->bytes = MIN(s->buf_size, MIN(max_bytes, op->bytes));
326 assert(op->bytes);
327 assert(op->bytes < BDRV_REQUEST_MAX_BYTES);
328 *op->bytes_handled = op->bytes;
329
330 if (s->cow_bitmap) {
331 *op->bytes_handled += mirror_cow_align(s, &op->offset, &op->bytes);
332 }
333 /* Cannot exceed BDRV_REQUEST_MAX_BYTES + INT_MAX */
334 assert(*op->bytes_handled <= UINT_MAX);
335 assert(op->bytes <= s->buf_size);
336 /* The offset is granularity-aligned because:
337 * 1) Caller passes in aligned values;
338 * 2) mirror_cow_align is used only when target cluster is larger. */
339 assert(QEMU_IS_ALIGNED(op->offset, s->granularity));
340 /* The range is sector-aligned, since bdrv_getlength() rounds up. */
341 assert(QEMU_IS_ALIGNED(op->bytes, BDRV_SECTOR_SIZE));
342 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
343
344 while (s->buf_free_count < nb_chunks) {
345 trace_mirror_yield_in_flight(s, op->offset, s->in_flight);
346 mirror_wait_for_free_in_flight_slot(s);
347 }
348
349 /* Now make a QEMUIOVector taking enough granularity-sized chunks
350 * from s->buf_free.
351 */
352 qemu_iovec_init(&op->qiov, nb_chunks);
353 while (nb_chunks-- > 0) {
354 MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
355 size_t remaining = op->bytes - op->qiov.size;
356
357 QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
358 s->buf_free_count--;
359 qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
360 }
361
362 /* Copy the dirty cluster. */
363 s->in_flight++;
364 s->bytes_in_flight += op->bytes;
365 trace_mirror_one_iteration(s, op->offset, op->bytes);
366
367 ret = bdrv_co_preadv(s->mirror_top_bs->backing, op->offset, op->bytes,
368 &op->qiov, 0);
369 mirror_read_complete(op, ret);
370 }
371
372 static void coroutine_fn mirror_co_zero(void *opaque)
373 {
374 MirrorOp *op = opaque;
375 int ret;
376
377 op->s->in_flight++;
378 op->s->bytes_in_flight += op->bytes;
379 *op->bytes_handled = op->bytes;
380
381 ret = blk_co_pwrite_zeroes(op->s->target, op->offset, op->bytes,
382 op->s->unmap ? BDRV_REQ_MAY_UNMAP : 0);
383 mirror_write_complete(op, ret);
384 }
385
386 static void coroutine_fn mirror_co_discard(void *opaque)
387 {
388 MirrorOp *op = opaque;
389 int ret;
390
391 op->s->in_flight++;
392 op->s->bytes_in_flight += op->bytes;
393 *op->bytes_handled = op->bytes;
394
395 ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes);
396 mirror_write_complete(op, ret);
397 }
398
399 static unsigned mirror_perform(MirrorBlockJob *s, int64_t offset,
400 unsigned bytes, MirrorMethod mirror_method)
401 {
402 MirrorOp *op;
403 Coroutine *co;
404 int64_t bytes_handled = -1;
405
406 op = g_new(MirrorOp, 1);
407 *op = (MirrorOp){
408 .s = s,
409 .offset = offset,
410 .bytes = bytes,
411 .bytes_handled = &bytes_handled,
412 };
413 qemu_co_queue_init(&op->waiting_requests);
414
415 switch (mirror_method) {
416 case MIRROR_METHOD_COPY:
417 co = qemu_coroutine_create(mirror_co_read, op);
418 break;
419 case MIRROR_METHOD_ZERO:
420 co = qemu_coroutine_create(mirror_co_zero, op);
421 break;
422 case MIRROR_METHOD_DISCARD:
423 co = qemu_coroutine_create(mirror_co_discard, op);
424 break;
425 default:
426 abort();
427 }
428
429 QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
430 qemu_coroutine_enter(co);
431 /* At this point, ownership of op has been moved to the coroutine
432 * and the object may already be freed */
433
434 /* Assert that this value has been set */
435 assert(bytes_handled >= 0);
436
437 /* Same assertion as in mirror_co_read() (and for mirror_co_read()
438 * and mirror_co_discard(), bytes_handled == op->bytes, which
439 * is the @bytes parameter given to this function) */
440 assert(bytes_handled <= UINT_MAX);
441 return bytes_handled;
442 }
443
444 static uint64_t coroutine_fn mirror_iteration(MirrorBlockJob *s)
445 {
446 BlockDriverState *source = s->mirror_top_bs->backing->bs;
447 MirrorOp *pseudo_op;
448 int64_t offset;
449 uint64_t delay_ns = 0, ret = 0;
450 /* At least the first dirty chunk is mirrored in one iteration. */
451 int nb_chunks = 1;
452 bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
453 int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
454
455 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
456 offset = bdrv_dirty_iter_next(s->dbi);
457 if (offset < 0) {
458 bdrv_set_dirty_iter(s->dbi, 0);
459 offset = bdrv_dirty_iter_next(s->dbi);
460 trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
461 assert(offset >= 0);
462 }
463 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
464
465 mirror_wait_on_conflicts(NULL, s, offset, 1);
466
467 job_pause_point(&s->common.job);
468
469 /* Find the number of consective dirty chunks following the first dirty
470 * one, and wait for in flight requests in them. */
471 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
472 while (nb_chunks * s->granularity < s->buf_size) {
473 int64_t next_dirty;
474 int64_t next_offset = offset + nb_chunks * s->granularity;
475 int64_t next_chunk = next_offset / s->granularity;
476 if (next_offset >= s->bdev_length ||
477 !bdrv_get_dirty_locked(source, s->dirty_bitmap, next_offset)) {
478 break;
479 }
480 if (test_bit(next_chunk, s->in_flight_bitmap)) {
481 break;
482 }
483
484 next_dirty = bdrv_dirty_iter_next(s->dbi);
485 if (next_dirty > next_offset || next_dirty < 0) {
486 /* The bitmap iterator's cache is stale, refresh it */
487 bdrv_set_dirty_iter(s->dbi, next_offset);
488 next_dirty = bdrv_dirty_iter_next(s->dbi);
489 }
490 assert(next_dirty == next_offset);
491 nb_chunks++;
492 }
493
494 /* Clear dirty bits before querying the block status, because
495 * calling bdrv_block_status_above could yield - if some blocks are
496 * marked dirty in this window, we need to know.
497 */
498 bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
499 nb_chunks * s->granularity);
500 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
501
502 /* Before claiming an area in the in-flight bitmap, we have to
503 * create a MirrorOp for it so that conflicting requests can wait
504 * for it. mirror_perform() will create the real MirrorOps later,
505 * for now we just create a pseudo operation that will wake up all
506 * conflicting requests once all real operations have been
507 * launched. */
508 pseudo_op = g_new(MirrorOp, 1);
509 *pseudo_op = (MirrorOp){
510 .offset = offset,
511 .bytes = nb_chunks * s->granularity,
512 .is_pseudo_op = true,
513 };
514 qemu_co_queue_init(&pseudo_op->waiting_requests);
515 QTAILQ_INSERT_TAIL(&s->ops_in_flight, pseudo_op, next);
516
517 bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
518 while (nb_chunks > 0 && offset < s->bdev_length) {
519 int ret;
520 int64_t io_bytes;
521 int64_t io_bytes_acct;
522 MirrorMethod mirror_method = MIRROR_METHOD_COPY;
523
524 assert(!(offset % s->granularity));
525 ret = bdrv_block_status_above(source, NULL, offset,
526 nb_chunks * s->granularity,
527 &io_bytes, NULL, NULL);
528 if (ret < 0) {
529 io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
530 } else if (ret & BDRV_BLOCK_DATA) {
531 io_bytes = MIN(io_bytes, max_io_bytes);
532 }
533
534 io_bytes -= io_bytes % s->granularity;
535 if (io_bytes < s->granularity) {
536 io_bytes = s->granularity;
537 } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
538 int64_t target_offset;
539 int64_t target_bytes;
540 bdrv_round_to_clusters(blk_bs(s->target), offset, io_bytes,
541 &target_offset, &target_bytes);
542 if (target_offset == offset &&
543 target_bytes == io_bytes) {
544 mirror_method = ret & BDRV_BLOCK_ZERO ?
545 MIRROR_METHOD_ZERO :
546 MIRROR_METHOD_DISCARD;
547 }
548 }
549
550 while (s->in_flight >= MAX_IN_FLIGHT) {
551 trace_mirror_yield_in_flight(s, offset, s->in_flight);
552 mirror_wait_for_free_in_flight_slot(s);
553 }
554
555 if (s->ret < 0) {
556 ret = 0;
557 goto fail;
558 }
559
560 io_bytes = mirror_clip_bytes(s, offset, io_bytes);
561 io_bytes = mirror_perform(s, offset, io_bytes, mirror_method);
562 if (mirror_method != MIRROR_METHOD_COPY && write_zeroes_ok) {
563 io_bytes_acct = 0;
564 } else {
565 io_bytes_acct = io_bytes;
566 }
567 assert(io_bytes);
568 offset += io_bytes;
569 nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
570 delay_ns = block_job_ratelimit_get_delay(&s->common, io_bytes_acct);
571 }
572
573 ret = delay_ns;
574 fail:
575 QTAILQ_REMOVE(&s->ops_in_flight, pseudo_op, next);
576 qemu_co_queue_restart_all(&pseudo_op->waiting_requests);
577 g_free(pseudo_op);
578
579 return ret;
580 }
581
582 static void mirror_free_init(MirrorBlockJob *s)
583 {
584 int granularity = s->granularity;
585 size_t buf_size = s->buf_size;
586 uint8_t *buf = s->buf;
587
588 assert(s->buf_free_count == 0);
589 QSIMPLEQ_INIT(&s->buf_free);
590 while (buf_size != 0) {
591 MirrorBuffer *cur = (MirrorBuffer *)buf;
592 QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
593 s->buf_free_count++;
594 buf_size -= granularity;
595 buf += granularity;
596 }
597 }
598
599 /* This is also used for the .pause callback. There is no matching
600 * mirror_resume() because mirror_run() will begin iterating again
601 * when the job is resumed.
602 */
603 static void coroutine_fn mirror_wait_for_all_io(MirrorBlockJob *s)
604 {
605 while (s->in_flight > 0) {
606 mirror_wait_for_free_in_flight_slot(s);
607 }
608 }
609
610 /**
611 * mirror_exit_common: handle both abort() and prepare() cases.
612 * for .prepare, returns 0 on success and -errno on failure.
613 * for .abort cases, denoted by abort = true, MUST return 0.
614 */
615 static int mirror_exit_common(Job *job)
616 {
617 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
618 BlockJob *bjob = &s->common;
619 MirrorBDSOpaque *bs_opaque = s->mirror_top_bs->opaque;
620 AioContext *replace_aio_context = NULL;
621 BlockDriverState *src = s->mirror_top_bs->backing->bs;
622 BlockDriverState *target_bs = blk_bs(s->target);
623 BlockDriverState *mirror_top_bs = s->mirror_top_bs;
624 Error *local_err = NULL;
625 bool abort = job->ret < 0;
626 int ret = 0;
627
628 if (s->prepared) {
629 return 0;
630 }
631 s->prepared = true;
632
633 if (bdrv_chain_contains(src, target_bs)) {
634 bdrv_unfreeze_backing_chain(mirror_top_bs, target_bs);
635 }
636
637 bdrv_release_dirty_bitmap(src, s->dirty_bitmap);
638
639 /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
640 * before we can call bdrv_drained_end */
641 bdrv_ref(src);
642 bdrv_ref(mirror_top_bs);
643 bdrv_ref(target_bs);
644
645 /* Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
646 * inserting target_bs at s->to_replace, where we might not be able to get
647 * these permissions.
648 *
649 * Note that blk_unref() alone doesn't necessarily drop permissions because
650 * we might be running nested inside mirror_drain(), which takes an extra
651 * reference, so use an explicit blk_set_perm() first. */
652 blk_set_perm(s->target, 0, BLK_PERM_ALL, &error_abort);
653 blk_unref(s->target);
654 s->target = NULL;
655
656 /* We don't access the source any more. Dropping any WRITE/RESIZE is
657 * required before it could become a backing file of target_bs. */
658 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
659 &error_abort);
660 if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
661 BlockDriverState *backing = s->is_none_mode ? src : s->base;
662 if (backing_bs(target_bs) != backing) {
663 bdrv_set_backing_hd(target_bs, backing, &local_err);
664 if (local_err) {
665 error_report_err(local_err);
666 ret = -EPERM;
667 }
668 }
669 }
670
671 if (s->to_replace) {
672 replace_aio_context = bdrv_get_aio_context(s->to_replace);
673 aio_context_acquire(replace_aio_context);
674 }
675
676 if (s->should_complete && !abort) {
677 BlockDriverState *to_replace = s->to_replace ?: src;
678 bool ro = bdrv_is_read_only(to_replace);
679
680 if (ro != bdrv_is_read_only(target_bs)) {
681 bdrv_reopen_set_read_only(target_bs, ro, NULL);
682 }
683
684 /* The mirror job has no requests in flight any more, but we need to
685 * drain potential other users of the BDS before changing the graph. */
686 bdrv_drained_begin(target_bs);
687 bdrv_replace_node(to_replace, target_bs, &local_err);
688 bdrv_drained_end(target_bs);
689 if (local_err) {
690 error_report_err(local_err);
691 ret = -EPERM;
692 }
693 }
694 if (s->to_replace) {
695 bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
696 error_free(s->replace_blocker);
697 bdrv_unref(s->to_replace);
698 }
699 if (replace_aio_context) {
700 aio_context_release(replace_aio_context);
701 }
702 g_free(s->replaces);
703 bdrv_unref(target_bs);
704
705 /* Remove the mirror filter driver from the graph. Before this, get rid of
706 * the blockers on the intermediate nodes so that the resulting state is
707 * valid. Also give up permissions on mirror_top_bs->backing, which might
708 * block the removal. */
709 block_job_remove_all_bdrv(bjob);
710 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
711 &error_abort);
712 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
713
714 /* We just changed the BDS the job BB refers to (with either or both of the
715 * bdrv_replace_node() calls), so switch the BB back so the cleanup does
716 * the right thing. We don't need any permissions any more now. */
717 blk_remove_bs(bjob->blk);
718 blk_set_perm(bjob->blk, 0, BLK_PERM_ALL, &error_abort);
719 blk_insert_bs(bjob->blk, mirror_top_bs, &error_abort);
720
721 bs_opaque->job = NULL;
722
723 bdrv_drained_end(src);
724 bdrv_unref(mirror_top_bs);
725 bdrv_unref(src);
726
727 return ret;
728 }
729
730 static int mirror_prepare(Job *job)
731 {
732 return mirror_exit_common(job);
733 }
734
735 static void mirror_abort(Job *job)
736 {
737 int ret = mirror_exit_common(job);
738 assert(ret == 0);
739 }
740
741 static void coroutine_fn mirror_throttle(MirrorBlockJob *s)
742 {
743 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
744
745 if (now - s->last_pause_ns > BLOCK_JOB_SLICE_TIME) {
746 s->last_pause_ns = now;
747 job_sleep_ns(&s->common.job, 0);
748 } else {
749 job_pause_point(&s->common.job);
750 }
751 }
752
753 static int coroutine_fn mirror_dirty_init(MirrorBlockJob *s)
754 {
755 int64_t offset;
756 BlockDriverState *base = s->base;
757 BlockDriverState *bs = s->mirror_top_bs->backing->bs;
758 BlockDriverState *target_bs = blk_bs(s->target);
759 int ret;
760 int64_t count;
761
762 if (base == NULL && !bdrv_has_zero_init(target_bs)) {
763 if (!bdrv_can_write_zeroes_with_unmap(target_bs)) {
764 bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
765 return 0;
766 }
767
768 s->initial_zeroing_ongoing = true;
769 for (offset = 0; offset < s->bdev_length; ) {
770 int bytes = MIN(s->bdev_length - offset,
771 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
772
773 mirror_throttle(s);
774
775 if (job_is_cancelled(&s->common.job)) {
776 s->initial_zeroing_ongoing = false;
777 return 0;
778 }
779
780 if (s->in_flight >= MAX_IN_FLIGHT) {
781 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
782 s->in_flight);
783 mirror_wait_for_free_in_flight_slot(s);
784 continue;
785 }
786
787 mirror_perform(s, offset, bytes, MIRROR_METHOD_ZERO);
788 offset += bytes;
789 }
790
791 mirror_wait_for_all_io(s);
792 s->initial_zeroing_ongoing = false;
793 }
794
795 /* First part, loop on the sectors and initialize the dirty bitmap. */
796 for (offset = 0; offset < s->bdev_length; ) {
797 /* Just to make sure we are not exceeding int limit. */
798 int bytes = MIN(s->bdev_length - offset,
799 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
800
801 mirror_throttle(s);
802
803 if (job_is_cancelled(&s->common.job)) {
804 return 0;
805 }
806
807 ret = bdrv_is_allocated_above(bs, base, offset, bytes, &count);
808 if (ret < 0) {
809 return ret;
810 }
811
812 assert(count);
813 if (ret == 1) {
814 bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
815 }
816 offset += count;
817 }
818 return 0;
819 }
820
821 /* Called when going out of the streaming phase to flush the bulk of the
822 * data to the medium, or just before completing.
823 */
824 static int mirror_flush(MirrorBlockJob *s)
825 {
826 int ret = blk_flush(s->target);
827 if (ret < 0) {
828 if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
829 s->ret = ret;
830 }
831 }
832 return ret;
833 }
834
835 static int coroutine_fn mirror_run(Job *job, Error **errp)
836 {
837 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
838 BlockDriverState *bs = s->mirror_top_bs->backing->bs;
839 BlockDriverState *target_bs = blk_bs(s->target);
840 bool need_drain = true;
841 int64_t length;
842 BlockDriverInfo bdi;
843 char backing_filename[2]; /* we only need 2 characters because we are only
844 checking for a NULL string */
845 int ret = 0;
846
847 if (job_is_cancelled(&s->common.job)) {
848 goto immediate_exit;
849 }
850
851 s->bdev_length = bdrv_getlength(bs);
852 if (s->bdev_length < 0) {
853 ret = s->bdev_length;
854 goto immediate_exit;
855 }
856
857 /* Active commit must resize the base image if its size differs from the
858 * active layer. */
859 if (s->base == blk_bs(s->target)) {
860 int64_t base_length;
861
862 base_length = blk_getlength(s->target);
863 if (base_length < 0) {
864 ret = base_length;
865 goto immediate_exit;
866 }
867
868 if (s->bdev_length > base_length) {
869 ret = blk_truncate(s->target, s->bdev_length, PREALLOC_MODE_OFF,
870 NULL);
871 if (ret < 0) {
872 goto immediate_exit;
873 }
874 }
875 }
876
877 if (s->bdev_length == 0) {
878 /* Transition to the READY state and wait for complete. */
879 job_transition_to_ready(&s->common.job);
880 s->synced = true;
881 s->actively_synced = true;
882 while (!job_is_cancelled(&s->common.job) && !s->should_complete) {
883 job_yield(&s->common.job);
884 }
885 s->common.job.cancelled = false;
886 goto immediate_exit;
887 }
888
889 length = DIV_ROUND_UP(s->bdev_length, s->granularity);
890 s->in_flight_bitmap = bitmap_new(length);
891
892 /* If we have no backing file yet in the destination, we cannot let
893 * the destination do COW. Instead, we copy sectors around the
894 * dirty data if needed. We need a bitmap to do that.
895 */
896 bdrv_get_backing_filename(target_bs, backing_filename,
897 sizeof(backing_filename));
898 if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {
899 s->target_cluster_size = bdi.cluster_size;
900 } else {
901 s->target_cluster_size = BDRV_SECTOR_SIZE;
902 }
903 if (backing_filename[0] && !target_bs->backing &&
904 s->granularity < s->target_cluster_size) {
905 s->buf_size = MAX(s->buf_size, s->target_cluster_size);
906 s->cow_bitmap = bitmap_new(length);
907 }
908 s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
909
910 s->buf = qemu_try_blockalign(bs, s->buf_size);
911 if (s->buf == NULL) {
912 ret = -ENOMEM;
913 goto immediate_exit;
914 }
915
916 mirror_free_init(s);
917
918 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
919 if (!s->is_none_mode) {
920 ret = mirror_dirty_init(s);
921 if (ret < 0 || job_is_cancelled(&s->common.job)) {
922 goto immediate_exit;
923 }
924 }
925
926 assert(!s->dbi);
927 s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
928 for (;;) {
929 uint64_t delay_ns = 0;
930 int64_t cnt, delta;
931 bool should_complete;
932
933 /* Do not start passive operations while there are active
934 * writes in progress */
935 while (s->in_active_write_counter) {
936 mirror_wait_for_any_operation(s, true);
937 }
938
939 if (s->ret < 0) {
940 ret = s->ret;
941 goto immediate_exit;
942 }
943
944 job_pause_point(&s->common.job);
945
946 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
947 /* cnt is the number of dirty bytes remaining and s->bytes_in_flight is
948 * the number of bytes currently being processed; together those are
949 * the current remaining operation length */
950 job_progress_set_remaining(&s->common.job, s->bytes_in_flight + cnt);
951
952 /* Note that even when no rate limit is applied we need to yield
953 * periodically with no pending I/O so that bdrv_drain_all() returns.
954 * We do so every BLKOCK_JOB_SLICE_TIME nanoseconds, or when there is
955 * an error, or when the source is clean, whichever comes first. */
956 delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
957 if (delta < BLOCK_JOB_SLICE_TIME &&
958 s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
959 if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
960 (cnt == 0 && s->in_flight > 0)) {
961 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
962 mirror_wait_for_free_in_flight_slot(s);
963 continue;
964 } else if (cnt != 0) {
965 delay_ns = mirror_iteration(s);
966 }
967 }
968
969 should_complete = false;
970 if (s->in_flight == 0 && cnt == 0) {
971 trace_mirror_before_flush(s);
972 if (!s->synced) {
973 if (mirror_flush(s) < 0) {
974 /* Go check s->ret. */
975 continue;
976 }
977 /* We're out of the streaming phase. From now on, if the job
978 * is cancelled we will actually complete all pending I/O and
979 * report completion. This way, block-job-cancel will leave
980 * the target in a consistent state.
981 */
982 job_transition_to_ready(&s->common.job);
983 s->synced = true;
984 if (s->copy_mode != MIRROR_COPY_MODE_BACKGROUND) {
985 s->actively_synced = true;
986 }
987 }
988
989 should_complete = s->should_complete ||
990 job_is_cancelled(&s->common.job);
991 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
992 }
993
994 if (cnt == 0 && should_complete) {
995 /* The dirty bitmap is not updated while operations are pending.
996 * If we're about to exit, wait for pending operations before
997 * calling bdrv_get_dirty_count(bs), or we may exit while the
998 * source has dirty data to copy!
999 *
1000 * Note that I/O can be submitted by the guest while
1001 * mirror_populate runs, so pause it now. Before deciding
1002 * whether to switch to target check one last time if I/O has
1003 * come in the meanwhile, and if not flush the data to disk.
1004 */
1005 trace_mirror_before_drain(s, cnt);
1006
1007 bdrv_drained_begin(bs);
1008 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1009 if (cnt > 0 || mirror_flush(s) < 0) {
1010 bdrv_drained_end(bs);
1011 continue;
1012 }
1013
1014 /* The two disks are in sync. Exit and report successful
1015 * completion.
1016 */
1017 assert(QLIST_EMPTY(&bs->tracked_requests));
1018 s->common.job.cancelled = false;
1019 need_drain = false;
1020 break;
1021 }
1022
1023 ret = 0;
1024
1025 if (s->synced && !should_complete) {
1026 delay_ns = (s->in_flight == 0 &&
1027 cnt == 0 ? BLOCK_JOB_SLICE_TIME : 0);
1028 }
1029 trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);
1030 job_sleep_ns(&s->common.job, delay_ns);
1031 if (job_is_cancelled(&s->common.job) &&
1032 (!s->synced || s->common.job.force_cancel))
1033 {
1034 break;
1035 }
1036 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1037 }
1038
1039 immediate_exit:
1040 if (s->in_flight > 0) {
1041 /* We get here only if something went wrong. Either the job failed,
1042 * or it was cancelled prematurely so that we do not guarantee that
1043 * the target is a copy of the source.
1044 */
1045 assert(ret < 0 || ((s->common.job.force_cancel || !s->synced) &&
1046 job_is_cancelled(&s->common.job)));
1047 assert(need_drain);
1048 mirror_wait_for_all_io(s);
1049 }
1050
1051 assert(s->in_flight == 0);
1052 qemu_vfree(s->buf);
1053 g_free(s->cow_bitmap);
1054 g_free(s->in_flight_bitmap);
1055 bdrv_dirty_iter_free(s->dbi);
1056
1057 if (need_drain) {
1058 bdrv_drained_begin(bs);
1059 }
1060
1061 return ret;
1062 }
1063
1064 static void mirror_complete(Job *job, Error **errp)
1065 {
1066 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1067 BlockDriverState *target;
1068
1069 target = blk_bs(s->target);
1070
1071 if (!s->synced) {
1072 error_setg(errp, "The active block job '%s' cannot be completed",
1073 job->id);
1074 return;
1075 }
1076
1077 if (s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
1078 int ret;
1079
1080 assert(!target->backing);
1081 ret = bdrv_open_backing_file(target, NULL, "backing", errp);
1082 if (ret < 0) {
1083 return;
1084 }
1085 }
1086
1087 /* block all operations on to_replace bs */
1088 if (s->replaces) {
1089 AioContext *replace_aio_context;
1090
1091 s->to_replace = bdrv_find_node(s->replaces);
1092 if (!s->to_replace) {
1093 error_setg(errp, "Node name '%s' not found", s->replaces);
1094 return;
1095 }
1096
1097 replace_aio_context = bdrv_get_aio_context(s->to_replace);
1098 aio_context_acquire(replace_aio_context);
1099
1100 /* TODO Translate this into permission system. Current definition of
1101 * GRAPH_MOD would require to request it for the parents; they might
1102 * not even be BlockDriverStates, however, so a BdrvChild can't address
1103 * them. May need redefinition of GRAPH_MOD. */
1104 error_setg(&s->replace_blocker,
1105 "block device is in use by block-job-complete");
1106 bdrv_op_block_all(s->to_replace, s->replace_blocker);
1107 bdrv_ref(s->to_replace);
1108
1109 aio_context_release(replace_aio_context);
1110 }
1111
1112 s->should_complete = true;
1113 job_enter(job);
1114 }
1115
1116 static void coroutine_fn mirror_pause(Job *job)
1117 {
1118 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1119
1120 mirror_wait_for_all_io(s);
1121 }
1122
1123 static bool mirror_drained_poll(BlockJob *job)
1124 {
1125 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1126 return !!s->in_flight;
1127 }
1128
1129 static void mirror_attached_aio_context(BlockJob *job, AioContext *new_context)
1130 {
1131 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1132
1133 blk_set_aio_context(s->target, new_context);
1134 }
1135
1136 static void mirror_drain(BlockJob *job)
1137 {
1138 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1139
1140 /* Need to keep a reference in case blk_drain triggers execution
1141 * of mirror_complete...
1142 */
1143 if (s->target) {
1144 BlockBackend *target = s->target;
1145 blk_ref(target);
1146 blk_drain(target);
1147 blk_unref(target);
1148 }
1149 }
1150
1151 static const BlockJobDriver mirror_job_driver = {
1152 .job_driver = {
1153 .instance_size = sizeof(MirrorBlockJob),
1154 .job_type = JOB_TYPE_MIRROR,
1155 .free = block_job_free,
1156 .user_resume = block_job_user_resume,
1157 .drain = block_job_drain,
1158 .run = mirror_run,
1159 .prepare = mirror_prepare,
1160 .abort = mirror_abort,
1161 .pause = mirror_pause,
1162 .complete = mirror_complete,
1163 },
1164 .drained_poll = mirror_drained_poll,
1165 .attached_aio_context = mirror_attached_aio_context,
1166 .drain = mirror_drain,
1167 };
1168
1169 static const BlockJobDriver commit_active_job_driver = {
1170 .job_driver = {
1171 .instance_size = sizeof(MirrorBlockJob),
1172 .job_type = JOB_TYPE_COMMIT,
1173 .free = block_job_free,
1174 .user_resume = block_job_user_resume,
1175 .drain = block_job_drain,
1176 .run = mirror_run,
1177 .prepare = mirror_prepare,
1178 .abort = mirror_abort,
1179 .pause = mirror_pause,
1180 .complete = mirror_complete,
1181 },
1182 .drained_poll = mirror_drained_poll,
1183 .attached_aio_context = mirror_attached_aio_context,
1184 .drain = mirror_drain,
1185 };
1186
1187 static void coroutine_fn
1188 do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
1189 uint64_t offset, uint64_t bytes,
1190 QEMUIOVector *qiov, int flags)
1191 {
1192 QEMUIOVector target_qiov;
1193 uint64_t dirty_offset = offset;
1194 uint64_t dirty_bytes;
1195
1196 if (qiov) {
1197 qemu_iovec_init(&target_qiov, qiov->niov);
1198 }
1199
1200 while (true) {
1201 bool valid_area;
1202 int ret;
1203
1204 bdrv_dirty_bitmap_lock(job->dirty_bitmap);
1205 dirty_bytes = MIN(offset + bytes - dirty_offset, INT_MAX);
1206 valid_area = bdrv_dirty_bitmap_next_dirty_area(job->dirty_bitmap,
1207 &dirty_offset,
1208 &dirty_bytes);
1209 if (!valid_area) {
1210 bdrv_dirty_bitmap_unlock(job->dirty_bitmap);
1211 break;
1212 }
1213
1214 bdrv_reset_dirty_bitmap_locked(job->dirty_bitmap,
1215 dirty_offset, dirty_bytes);
1216 bdrv_dirty_bitmap_unlock(job->dirty_bitmap);
1217
1218 job_progress_increase_remaining(&job->common.job, dirty_bytes);
1219
1220 assert(dirty_offset - offset <= SIZE_MAX);
1221 if (qiov) {
1222 qemu_iovec_reset(&target_qiov);
1223 qemu_iovec_concat(&target_qiov, qiov,
1224 dirty_offset - offset, dirty_bytes);
1225 }
1226
1227 switch (method) {
1228 case MIRROR_METHOD_COPY:
1229 ret = blk_co_pwritev(job->target, dirty_offset, dirty_bytes,
1230 qiov ? &target_qiov : NULL, flags);
1231 break;
1232
1233 case MIRROR_METHOD_ZERO:
1234 assert(!qiov);
1235 ret = blk_co_pwrite_zeroes(job->target, dirty_offset, dirty_bytes,
1236 flags);
1237 break;
1238
1239 case MIRROR_METHOD_DISCARD:
1240 assert(!qiov);
1241 ret = blk_co_pdiscard(job->target, dirty_offset, dirty_bytes);
1242 break;
1243
1244 default:
1245 abort();
1246 }
1247
1248 if (ret >= 0) {
1249 job_progress_update(&job->common.job, dirty_bytes);
1250 } else {
1251 BlockErrorAction action;
1252
1253 bdrv_set_dirty_bitmap(job->dirty_bitmap, dirty_offset, dirty_bytes);
1254 job->actively_synced = false;
1255
1256 action = mirror_error_action(job, false, -ret);
1257 if (action == BLOCK_ERROR_ACTION_REPORT) {
1258 if (!job->ret) {
1259 job->ret = ret;
1260 }
1261 break;
1262 }
1263 }
1264
1265 dirty_offset += dirty_bytes;
1266 }
1267
1268 if (qiov) {
1269 qemu_iovec_destroy(&target_qiov);
1270 }
1271 }
1272
1273 static MirrorOp *coroutine_fn active_write_prepare(MirrorBlockJob *s,
1274 uint64_t offset,
1275 uint64_t bytes)
1276 {
1277 MirrorOp *op;
1278 uint64_t start_chunk = offset / s->granularity;
1279 uint64_t end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1280
1281 op = g_new(MirrorOp, 1);
1282 *op = (MirrorOp){
1283 .s = s,
1284 .offset = offset,
1285 .bytes = bytes,
1286 .is_active_write = true,
1287 };
1288 qemu_co_queue_init(&op->waiting_requests);
1289 QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
1290
1291 s->in_active_write_counter++;
1292
1293 mirror_wait_on_conflicts(op, s, offset, bytes);
1294
1295 bitmap_set(s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1296
1297 return op;
1298 }
1299
1300 static void coroutine_fn active_write_settle(MirrorOp *op)
1301 {
1302 uint64_t start_chunk = op->offset / op->s->granularity;
1303 uint64_t end_chunk = DIV_ROUND_UP(op->offset + op->bytes,
1304 op->s->granularity);
1305
1306 if (!--op->s->in_active_write_counter && op->s->actively_synced) {
1307 BdrvChild *source = op->s->mirror_top_bs->backing;
1308
1309 if (QLIST_FIRST(&source->bs->parents) == source &&
1310 QLIST_NEXT(source, next_parent) == NULL)
1311 {
1312 /* Assert that we are back in sync once all active write
1313 * operations are settled.
1314 * Note that we can only assert this if the mirror node
1315 * is the source node's only parent. */
1316 assert(!bdrv_get_dirty_count(op->s->dirty_bitmap));
1317 }
1318 }
1319 bitmap_clear(op->s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1320 QTAILQ_REMOVE(&op->s->ops_in_flight, op, next);
1321 qemu_co_queue_restart_all(&op->waiting_requests);
1322 g_free(op);
1323 }
1324
1325 static int coroutine_fn bdrv_mirror_top_preadv(BlockDriverState *bs,
1326 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1327 {
1328 return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
1329 }
1330
1331 static int coroutine_fn bdrv_mirror_top_do_write(BlockDriverState *bs,
1332 MirrorMethod method, uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
1333 int flags)
1334 {
1335 MirrorOp *op = NULL;
1336 MirrorBDSOpaque *s = bs->opaque;
1337 int ret = 0;
1338 bool copy_to_target;
1339
1340 copy_to_target = s->job->ret >= 0 &&
1341 s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1342
1343 if (copy_to_target) {
1344 op = active_write_prepare(s->job, offset, bytes);
1345 }
1346
1347 switch (method) {
1348 case MIRROR_METHOD_COPY:
1349 ret = bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1350 break;
1351
1352 case MIRROR_METHOD_ZERO:
1353 ret = bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
1354 break;
1355
1356 case MIRROR_METHOD_DISCARD:
1357 ret = bdrv_co_pdiscard(bs->backing, offset, bytes);
1358 break;
1359
1360 default:
1361 abort();
1362 }
1363
1364 if (ret < 0) {
1365 goto out;
1366 }
1367
1368 if (copy_to_target) {
1369 do_sync_target_write(s->job, method, offset, bytes, qiov, flags);
1370 }
1371
1372 out:
1373 if (copy_to_target) {
1374 active_write_settle(op);
1375 }
1376 return ret;
1377 }
1378
1379 static int coroutine_fn bdrv_mirror_top_pwritev(BlockDriverState *bs,
1380 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
1381 {
1382 MirrorBDSOpaque *s = bs->opaque;
1383 QEMUIOVector bounce_qiov;
1384 void *bounce_buf;
1385 int ret = 0;
1386 bool copy_to_target;
1387
1388 copy_to_target = s->job->ret >= 0 &&
1389 s->job->copy_mode == MIRROR_COPY_MODE_WRITE_BLOCKING;
1390
1391 if (copy_to_target) {
1392 /* The guest might concurrently modify the data to write; but
1393 * the data on source and destination must match, so we have
1394 * to use a bounce buffer if we are going to write to the
1395 * target now. */
1396 bounce_buf = qemu_blockalign(bs, bytes);
1397 iov_to_buf_full(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
1398
1399 qemu_iovec_init(&bounce_qiov, 1);
1400 qemu_iovec_add(&bounce_qiov, bounce_buf, bytes);
1401 qiov = &bounce_qiov;
1402 }
1403
1404 ret = bdrv_mirror_top_do_write(bs, MIRROR_METHOD_COPY, offset, bytes, qiov,
1405 flags);
1406
1407 if (copy_to_target) {
1408 qemu_iovec_destroy(&bounce_qiov);
1409 qemu_vfree(bounce_buf);
1410 }
1411
1412 return ret;
1413 }
1414
1415 static int coroutine_fn bdrv_mirror_top_flush(BlockDriverState *bs)
1416 {
1417 if (bs->backing == NULL) {
1418 /* we can be here after failed bdrv_append in mirror_start_job */
1419 return 0;
1420 }
1421 return bdrv_co_flush(bs->backing->bs);
1422 }
1423
1424 static int coroutine_fn bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs,
1425 int64_t offset, int bytes, BdrvRequestFlags flags)
1426 {
1427 return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_ZERO, offset, bytes, NULL,
1428 flags);
1429 }
1430
1431 static int coroutine_fn bdrv_mirror_top_pdiscard(BlockDriverState *bs,
1432 int64_t offset, int bytes)
1433 {
1434 return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_DISCARD, offset, bytes,
1435 NULL, 0);
1436 }
1437
1438 static void bdrv_mirror_top_refresh_filename(BlockDriverState *bs)
1439 {
1440 if (bs->backing == NULL) {
1441 /* we can be here after failed bdrv_attach_child in
1442 * bdrv_set_backing_hd */
1443 return;
1444 }
1445 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1446 bs->backing->bs->filename);
1447 }
1448
1449 static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1450 const BdrvChildRole *role,
1451 BlockReopenQueue *reopen_queue,
1452 uint64_t perm, uint64_t shared,
1453 uint64_t *nperm, uint64_t *nshared)
1454 {
1455 /* Must be able to forward guest writes to the real image */
1456 *nperm = 0;
1457 if (perm & BLK_PERM_WRITE) {
1458 *nperm |= BLK_PERM_WRITE;
1459 }
1460
1461 *nshared = BLK_PERM_ALL;
1462 }
1463
1464 /* Dummy node that provides consistent read to its users without requiring it
1465 * from its backing file and that allows writes on the backing file chain. */
1466 static BlockDriver bdrv_mirror_top = {
1467 .format_name = "mirror_top",
1468 .bdrv_co_preadv = bdrv_mirror_top_preadv,
1469 .bdrv_co_pwritev = bdrv_mirror_top_pwritev,
1470 .bdrv_co_pwrite_zeroes = bdrv_mirror_top_pwrite_zeroes,
1471 .bdrv_co_pdiscard = bdrv_mirror_top_pdiscard,
1472 .bdrv_co_flush = bdrv_mirror_top_flush,
1473 .bdrv_co_block_status = bdrv_co_block_status_from_backing,
1474 .bdrv_refresh_filename = bdrv_mirror_top_refresh_filename,
1475 .bdrv_child_perm = bdrv_mirror_top_child_perm,
1476 };
1477
1478 static void mirror_start_job(const char *job_id, BlockDriverState *bs,
1479 int creation_flags, BlockDriverState *target,
1480 const char *replaces, int64_t speed,
1481 uint32_t granularity, int64_t buf_size,
1482 BlockMirrorBackingMode backing_mode,
1483 BlockdevOnError on_source_error,
1484 BlockdevOnError on_target_error,
1485 bool unmap,
1486 BlockCompletionFunc *cb,
1487 void *opaque,
1488 const BlockJobDriver *driver,
1489 bool is_none_mode, BlockDriverState *base,
1490 bool auto_complete, const char *filter_node_name,
1491 bool is_mirror, MirrorCopyMode copy_mode,
1492 Error **errp)
1493 {
1494 MirrorBlockJob *s;
1495 MirrorBDSOpaque *bs_opaque;
1496 BlockDriverState *mirror_top_bs;
1497 bool target_graph_mod;
1498 bool target_is_backing;
1499 Error *local_err = NULL;
1500 int ret;
1501
1502 if (granularity == 0) {
1503 granularity = bdrv_get_default_bitmap_granularity(target);
1504 }
1505
1506 assert(is_power_of_2(granularity));
1507
1508 if (buf_size < 0) {
1509 error_setg(errp, "Invalid parameter 'buf-size'");
1510 return;
1511 }
1512
1513 if (buf_size == 0) {
1514 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1515 }
1516
1517 if (bs == target) {
1518 error_setg(errp, "Can't mirror node into itself");
1519 return;
1520 }
1521
1522 /* In the case of active commit, add dummy driver to provide consistent
1523 * reads on the top, while disabling it in the intermediate nodes, and make
1524 * the backing chain writable. */
1525 mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
1526 BDRV_O_RDWR, errp);
1527 if (mirror_top_bs == NULL) {
1528 return;
1529 }
1530 if (!filter_node_name) {
1531 mirror_top_bs->implicit = true;
1532 }
1533 mirror_top_bs->total_sectors = bs->total_sectors;
1534 mirror_top_bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED;
1535 mirror_top_bs->supported_zero_flags = BDRV_REQ_WRITE_UNCHANGED;
1536 bs_opaque = g_new0(MirrorBDSOpaque, 1);
1537 mirror_top_bs->opaque = bs_opaque;
1538 bdrv_set_aio_context(mirror_top_bs, bdrv_get_aio_context(bs));
1539
1540 /* bdrv_append takes ownership of the mirror_top_bs reference, need to keep
1541 * it alive until block_job_create() succeeds even if bs has no parent. */
1542 bdrv_ref(mirror_top_bs);
1543 bdrv_drained_begin(bs);
1544 bdrv_append(mirror_top_bs, bs, &local_err);
1545 bdrv_drained_end(bs);
1546
1547 if (local_err) {
1548 bdrv_unref(mirror_top_bs);
1549 error_propagate(errp, local_err);
1550 return;
1551 }
1552
1553 /* Make sure that the source is not resized while the job is running */
1554 s = block_job_create(job_id, driver, NULL, mirror_top_bs,
1555 BLK_PERM_CONSISTENT_READ,
1556 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1557 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD, speed,
1558 creation_flags, cb, opaque, errp);
1559 if (!s) {
1560 goto fail;
1561 }
1562 bs_opaque->job = s;
1563
1564 /* The block job now has a reference to this node */
1565 bdrv_unref(mirror_top_bs);
1566
1567 s->mirror_top_bs = mirror_top_bs;
1568
1569 /* No resize for the target either; while the mirror is still running, a
1570 * consistent read isn't necessarily possible. We could possibly allow
1571 * writes and graph modifications, though it would likely defeat the
1572 * purpose of a mirror, so leave them blocked for now.
1573 *
1574 * In the case of active commit, things look a bit different, though,
1575 * because the target is an already populated backing file in active use.
1576 * We can allow anything except resize there.*/
1577 target_is_backing = bdrv_chain_contains(bs, target);
1578 target_graph_mod = (backing_mode != MIRROR_LEAVE_BACKING_CHAIN);
1579 s->target = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE |
1580 (target_graph_mod ? BLK_PERM_GRAPH_MOD : 0),
1581 BLK_PERM_WRITE_UNCHANGED |
1582 (target_is_backing ? BLK_PERM_CONSISTENT_READ |
1583 BLK_PERM_WRITE |
1584 BLK_PERM_GRAPH_MOD : 0));
1585 ret = blk_insert_bs(s->target, target, errp);
1586 if (ret < 0) {
1587 goto fail;
1588 }
1589 if (is_mirror) {
1590 /* XXX: Mirror target could be a NBD server of target QEMU in the case
1591 * of non-shared block migration. To allow migration completion, we
1592 * have to allow "inactivate" of the target BB. When that happens, we
1593 * know the job is drained, and the vcpus are stopped, so no write
1594 * operation will be performed. Block layer already has assertions to
1595 * ensure that. */
1596 blk_set_force_allow_inactivate(s->target);
1597 }
1598
1599 s->replaces = g_strdup(replaces);
1600 s->on_source_error = on_source_error;
1601 s->on_target_error = on_target_error;
1602 s->is_none_mode = is_none_mode;
1603 s->backing_mode = backing_mode;
1604 s->copy_mode = copy_mode;
1605 s->base = base;
1606 s->granularity = granularity;
1607 s->buf_size = ROUND_UP(buf_size, granularity);
1608 s->unmap = unmap;
1609 if (auto_complete) {
1610 s->should_complete = true;
1611 }
1612
1613 s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
1614 if (!s->dirty_bitmap) {
1615 goto fail;
1616 }
1617
1618 ret = block_job_add_bdrv(&s->common, "source", bs, 0,
1619 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE |
1620 BLK_PERM_CONSISTENT_READ,
1621 errp);
1622 if (ret < 0) {
1623 goto fail;
1624 }
1625
1626 /* Required permissions are already taken with blk_new() */
1627 block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
1628 &error_abort);
1629
1630 /* In commit_active_start() all intermediate nodes disappear, so
1631 * any jobs in them must be blocked */
1632 if (target_is_backing) {
1633 BlockDriverState *iter;
1634 for (iter = backing_bs(bs); iter != target; iter = backing_bs(iter)) {
1635 /* XXX BLK_PERM_WRITE needs to be allowed so we don't block
1636 * ourselves at s->base (if writes are blocked for a node, they are
1637 * also blocked for its backing file). The other options would be a
1638 * second filter driver above s->base (== target). */
1639 ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
1640 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE,
1641 errp);
1642 if (ret < 0) {
1643 goto fail;
1644 }
1645 }
1646
1647 if (bdrv_freeze_backing_chain(mirror_top_bs, target, errp) < 0) {
1648 goto fail;
1649 }
1650 }
1651
1652 QTAILQ_INIT(&s->ops_in_flight);
1653
1654 trace_mirror_start(bs, s, opaque);
1655 job_start(&s->common.job);
1656 return;
1657
1658 fail:
1659 if (s) {
1660 /* Make sure this BDS does not go away until we have completed the graph
1661 * changes below */
1662 bdrv_ref(mirror_top_bs);
1663
1664 g_free(s->replaces);
1665 blk_unref(s->target);
1666 bs_opaque->job = NULL;
1667 if (s->dirty_bitmap) {
1668 bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);
1669 }
1670 job_early_fail(&s->common.job);
1671 }
1672
1673 bdrv_child_try_set_perm(mirror_top_bs->backing, 0, BLK_PERM_ALL,
1674 &error_abort);
1675 bdrv_replace_node(mirror_top_bs, backing_bs(mirror_top_bs), &error_abort);
1676
1677 bdrv_unref(mirror_top_bs);
1678 }
1679
1680 void mirror_start(const char *job_id, BlockDriverState *bs,
1681 BlockDriverState *target, const char *replaces,
1682 int creation_flags, int64_t speed,
1683 uint32_t granularity, int64_t buf_size,
1684 MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
1685 BlockdevOnError on_source_error,
1686 BlockdevOnError on_target_error,
1687 bool unmap, const char *filter_node_name,
1688 MirrorCopyMode copy_mode, Error **errp)
1689 {
1690 bool is_none_mode;
1691 BlockDriverState *base;
1692
1693 if (mode == MIRROR_SYNC_MODE_INCREMENTAL) {
1694 error_setg(errp, "Sync mode 'incremental' not supported");
1695 return;
1696 }
1697 is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
1698 base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
1699 mirror_start_job(job_id, bs, creation_flags, target, replaces,
1700 speed, granularity, buf_size, backing_mode,
1701 on_source_error, on_target_error, unmap, NULL, NULL,
1702 &mirror_job_driver, is_none_mode, base, false,
1703 filter_node_name, true, copy_mode, errp);
1704 }
1705
1706 void commit_active_start(const char *job_id, BlockDriverState *bs,
1707 BlockDriverState *base, int creation_flags,
1708 int64_t speed, BlockdevOnError on_error,
1709 const char *filter_node_name,
1710 BlockCompletionFunc *cb, void *opaque,
1711 bool auto_complete, Error **errp)
1712 {
1713 bool base_read_only;
1714 Error *local_err = NULL;
1715
1716 base_read_only = bdrv_is_read_only(base);
1717
1718 if (base_read_only) {
1719 if (bdrv_reopen_set_read_only(base, false, errp) < 0) {
1720 return;
1721 }
1722 }
1723
1724 mirror_start_job(job_id, bs, creation_flags, base, NULL, speed, 0, 0,
1725 MIRROR_LEAVE_BACKING_CHAIN,
1726 on_error, on_error, true, cb, opaque,
1727 &commit_active_job_driver, false, base, auto_complete,
1728 filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
1729 &local_err);
1730 if (local_err) {
1731 error_propagate(errp, local_err);
1732 goto error_restore_flags;
1733 }
1734
1735 return;
1736
1737 error_restore_flags:
1738 /* ignore error and errp for bdrv_reopen, because we want to propagate
1739 * the original error */
1740 if (base_read_only) {
1741 bdrv_reopen_set_read_only(base, true, NULL);
1742 }
1743 return;
1744 }