master
c 2,213 lines 74.1 KB
Raw
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 "block/dirty-bitmap.h"
22 #include "system/block-backend.h"
23 #include "qapi/error.h"
24 #include "qemu/ratelimit.h"
25 #include "qemu/bitmap.h"
26 #include "qemu/memalign.h"
27
28 #define MAX_IN_FLIGHT 16
29 #define MAX_IO_BYTES (1 << 20) /* 1 Mb */
30 #define DEFAULT_MIRROR_BUF_SIZE (MAX_IN_FLIGHT * MAX_IO_BYTES)
31
32 /* The mirroring buffer is a list of granularity-sized chunks.
33 * Free chunks are organized in a list.
34 */
35 typedef struct MirrorBuffer {
36 QSIMPLEQ_ENTRY(MirrorBuffer) next;
37 } MirrorBuffer;
38
39 typedef struct MirrorOp MirrorOp;
40
41 typedef struct MirrorBlockJob {
42 BlockJob common;
43 BlockBackend *target;
44 BlockDriverState *mirror_top_bs;
45 BlockDriverState *base;
46 BlockDriverState *base_overlay;
47
48 /* The name of the graph node to replace */
49 char *replaces;
50 /* The BDS to replace */
51 BlockDriverState *to_replace;
52 /* Used to block operations on the drive-mirror-replace target */
53 Error *replace_blocker;
54 MirrorSyncMode sync_mode;
55 BlockMirrorBackingMode backing_mode;
56 /* Whether the target should be assumed to be already zero initialized */
57 bool target_is_zero;
58 /*
59 * To be accesssed with atomics. Written only under the BQL (required by the
60 * current implementation of mirror_change()).
61 */
62 MirrorCopyMode copy_mode;
63 BlockdevOnError on_source_error, on_target_error;
64 /*
65 * To be accessed with atomics.
66 *
67 * Set when the target is synced (dirty bitmap is clean, nothing in flight)
68 * and the job is running in active mode.
69 */
70 bool actively_synced;
71 bool should_complete;
72 int64_t granularity;
73 size_t buf_size;
74 int64_t bdev_length;
75 unsigned long *cow_bitmap;
76 unsigned long *zero_bitmap;
77 BdrvDirtyBitmap *dirty_bitmap;
78 BdrvDirtyBitmapIter *dbi;
79 uint8_t *buf;
80 QSIMPLEQ_HEAD(, MirrorBuffer) buf_free;
81 int buf_free_count;
82
83 uint64_t last_pause_ns;
84 unsigned long *in_flight_bitmap;
85 unsigned in_flight;
86 int64_t bytes_in_flight;
87 QTAILQ_HEAD(, MirrorOp) ops_in_flight;
88 int ret;
89 bool unmap;
90 int target_cluster_size;
91 int max_iov;
92 bool initial_zeroing_ongoing;
93 int in_active_write_counter;
94 int64_t active_write_bytes_in_flight;
95 bool prepared;
96 bool in_drain;
97 bool base_ro;
98 } MirrorBlockJob;
99
100 typedef struct MirrorBDSOpaque {
101 MirrorBlockJob *job;
102 BdrvDirtyBitmap *dirty_bitmap;
103 bool stop;
104 bool is_commit;
105 } MirrorBDSOpaque;
106
107 struct MirrorOp {
108 MirrorBlockJob *s;
109 QEMUIOVector qiov;
110 int64_t offset;
111 uint64_t bytes;
112
113 /*
114 * These pointers are set by mirror_co_read(), mirror_co_zero(), and
115 * mirror_co_discard() before yielding for the first time
116 */
117 int64_t *bytes_handled;
118 bool *io_skipped;
119
120 bool is_pseudo_op;
121 bool is_active_write;
122 bool is_in_flight;
123 CoQueue waiting_requests;
124 Coroutine *co;
125 MirrorOp *waiting_for_op;
126
127 QTAILQ_ENTRY(MirrorOp) next;
128 };
129
130 typedef enum MirrorMethod {
131 MIRROR_METHOD_COPY,
132 MIRROR_METHOD_ZERO,
133 MIRROR_METHOD_DISCARD,
134 } MirrorMethod;
135
136 static BlockErrorAction mirror_error_action(MirrorBlockJob *s, bool read,
137 int error)
138 {
139 qatomic_set(&s->actively_synced, false);
140 if (read) {
141 return block_job_error_action(&s->common, s->on_source_error,
142 true, error);
143 } else {
144 return block_job_error_action(&s->common, s->on_target_error,
145 false, error);
146 }
147 }
148
149 static void coroutine_fn mirror_wait_on_conflicts(MirrorOp *self,
150 MirrorBlockJob *s,
151 uint64_t offset,
152 uint64_t bytes)
153 {
154 uint64_t self_start_chunk = offset / s->granularity;
155 uint64_t self_end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
156 uint64_t self_nb_chunks = self_end_chunk - self_start_chunk;
157
158 while (find_next_bit(s->in_flight_bitmap, self_end_chunk,
159 self_start_chunk) < self_end_chunk &&
160 s->ret >= 0)
161 {
162 MirrorOp *op;
163
164 QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
165 uint64_t op_start_chunk = op->offset / s->granularity;
166 uint64_t op_nb_chunks = DIV_ROUND_UP(op->offset + op->bytes,
167 s->granularity) -
168 op_start_chunk;
169
170 if (op == self) {
171 continue;
172 }
173
174 if (ranges_overlap(self_start_chunk, self_nb_chunks,
175 op_start_chunk, op_nb_chunks))
176 {
177 if (self) {
178 /*
179 * If the operation is already (indirectly) waiting for us,
180 * or will wait for us as soon as it wakes up, then just go
181 * on (instead of producing a deadlock in the former case).
182 */
183 if (op->waiting_for_op) {
184 continue;
185 }
186
187 self->waiting_for_op = op;
188 }
189
190 qemu_co_queue_wait(&op->waiting_requests, NULL);
191
192 if (self) {
193 self->waiting_for_op = NULL;
194 }
195
196 break;
197 }
198 }
199 }
200 }
201
202 static void coroutine_fn mirror_iteration_done(MirrorOp *op, int ret)
203 {
204 MirrorBlockJob *s = op->s;
205 struct iovec *iov;
206 int64_t chunk_num;
207 int i, nb_chunks;
208
209 trace_mirror_iteration_done(s, op->offset, op->bytes, ret);
210
211 s->in_flight--;
212 s->bytes_in_flight -= op->bytes;
213 iov = op->qiov.iov;
214 for (i = 0; i < op->qiov.niov; i++) {
215 MirrorBuffer *buf = (MirrorBuffer *) iov[i].iov_base;
216 QSIMPLEQ_INSERT_TAIL(&s->buf_free, buf, next);
217 s->buf_free_count++;
218 }
219
220 chunk_num = op->offset / s->granularity;
221 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
222
223 bitmap_clear(s->in_flight_bitmap, chunk_num, nb_chunks);
224 QTAILQ_REMOVE(&s->ops_in_flight, op, next);
225 if (ret >= 0) {
226 if (s->cow_bitmap) {
227 bitmap_set(s->cow_bitmap, chunk_num, nb_chunks);
228 }
229 if (!s->initial_zeroing_ongoing) {
230 job_progress_update(&s->common.job, op->bytes);
231 }
232 }
233 qemu_iovec_destroy(&op->qiov);
234
235 qemu_co_queue_restart_all(&op->waiting_requests);
236 g_free(op);
237 }
238
239 static void coroutine_fn mirror_write_complete(MirrorOp *op, int ret)
240 {
241 MirrorBlockJob *s = op->s;
242
243 if (ret < 0) {
244 BlockErrorAction action;
245
246 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
247 action = mirror_error_action(s, false, -ret);
248 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
249 s->ret = ret;
250 }
251 }
252
253 mirror_iteration_done(op, ret);
254 }
255
256 static void coroutine_fn mirror_read_complete(MirrorOp *op, int ret)
257 {
258 MirrorBlockJob *s = op->s;
259
260 if (ret < 0) {
261 BlockErrorAction action;
262
263 bdrv_set_dirty_bitmap(s->dirty_bitmap, op->offset, op->bytes);
264 action = mirror_error_action(s, true, -ret);
265 if (action == BLOCK_ERROR_ACTION_REPORT && s->ret >= 0) {
266 s->ret = ret;
267 }
268
269 mirror_iteration_done(op, ret);
270 return;
271 }
272
273 ret = blk_co_pwritev(s->target, op->offset, op->qiov.size, &op->qiov, 0);
274 mirror_write_complete(op, ret);
275 }
276
277 /* Clip bytes relative to offset to not exceed end-of-file */
278 static inline int64_t mirror_clip_bytes(MirrorBlockJob *s,
279 int64_t offset,
280 int64_t bytes)
281 {
282 return MIN(bytes, s->bdev_length - offset);
283 }
284
285 /* Round offset and/or bytes to target cluster if COW is needed, and
286 * return the offset of the adjusted tail against original. */
287 static int coroutine_fn mirror_cow_align(MirrorBlockJob *s, int64_t *offset,
288 uint64_t *bytes)
289 {
290 bool need_cow;
291 int ret = 0;
292 int64_t align_offset = *offset;
293 int64_t align_bytes = *bytes;
294 int max_bytes = s->granularity * s->max_iov;
295
296 need_cow = !test_bit(*offset / s->granularity, s->cow_bitmap);
297 need_cow |= !test_bit((*offset + *bytes - 1) / s->granularity,
298 s->cow_bitmap);
299 if (need_cow) {
300 bdrv_round_to_subclusters(blk_bs(s->target), *offset, *bytes,
301 &align_offset, &align_bytes);
302 }
303
304 if (align_bytes > max_bytes) {
305 align_bytes = max_bytes;
306 if (need_cow) {
307 align_bytes = QEMU_ALIGN_DOWN(align_bytes, s->target_cluster_size);
308 }
309 }
310 /* Clipping may result in align_bytes unaligned to chunk boundary, but
311 * that doesn't matter because it's already the end of source image. */
312 align_bytes = mirror_clip_bytes(s, align_offset, align_bytes);
313
314 ret = align_offset + align_bytes - (*offset + *bytes);
315 *offset = align_offset;
316 *bytes = align_bytes;
317 assert(ret >= 0);
318 return ret;
319 }
320
321 static inline void coroutine_fn
322 mirror_wait_for_free_in_flight_slot(MirrorBlockJob *s)
323 {
324 MirrorOp *op;
325
326 QTAILQ_FOREACH(op, &s->ops_in_flight, next) {
327 /*
328 * Do not wait on pseudo ops, because it may in turn wait on
329 * some other operation to start, which may in fact be the
330 * caller of this function. Since there is only one pseudo op
331 * at any given time, we will always find some real operation
332 * to wait on.
333 * Also, do not wait on active operations, because they do not
334 * use up in-flight slots.
335 */
336 if (!op->is_pseudo_op && op->is_in_flight && !op->is_active_write) {
337 qemu_co_queue_wait(&op->waiting_requests, NULL);
338 return;
339 }
340 }
341 abort();
342 }
343
344 /* Perform a mirror copy operation.
345 *
346 * *op->bytes_handled is set to the number of bytes copied after and
347 * including offset, excluding any bytes copied prior to offset due
348 * to alignment. This will be op->bytes if no alignment is necessary,
349 * or (new_end - op->offset) if the tail is rounded up or down due to
350 * alignment or buffer limit.
351 */
352 static void coroutine_fn mirror_co_read(void *opaque)
353 {
354 MirrorOp *op = opaque;
355 MirrorBlockJob *s = op->s;
356 int nb_chunks;
357 int ret = -1;
358 uint64_t max_bytes;
359
360 max_bytes = s->granularity * s->max_iov;
361
362 /* We can only handle as much as buf_size at a time. */
363 op->bytes = MIN(s->buf_size, MIN(max_bytes, op->bytes));
364 assert(op->bytes);
365 assert(op->bytes < BDRV_REQUEST_MAX_BYTES);
366 *op->bytes_handled = op->bytes;
367
368 if (s->cow_bitmap) {
369 *op->bytes_handled += mirror_cow_align(s, &op->offset, &op->bytes);
370 }
371 /* Cannot exceed BDRV_REQUEST_MAX_BYTES + INT_MAX */
372 assert(*op->bytes_handled <= UINT_MAX);
373 assert(op->bytes <= s->buf_size);
374 /* The offset is granularity-aligned because:
375 * 1) Caller passes in aligned values;
376 * 2) mirror_cow_align is used only when target cluster is larger. */
377 assert(QEMU_IS_ALIGNED(op->offset, s->granularity));
378 /* The range is sector-aligned, since bdrv_getlength() rounds up. */
379 assert(QEMU_IS_ALIGNED(op->bytes, BDRV_SECTOR_SIZE));
380 nb_chunks = DIV_ROUND_UP(op->bytes, s->granularity);
381
382 while (s->buf_free_count < nb_chunks) {
383 trace_mirror_yield_in_flight(s, op->offset, s->in_flight);
384 mirror_wait_for_free_in_flight_slot(s);
385 }
386
387 /* Now make a QEMUIOVector taking enough granularity-sized chunks
388 * from s->buf_free.
389 */
390 qemu_iovec_init(&op->qiov, nb_chunks);
391 while (nb_chunks-- > 0) {
392 MirrorBuffer *buf = QSIMPLEQ_FIRST(&s->buf_free);
393 size_t remaining = op->bytes - op->qiov.size;
394
395 QSIMPLEQ_REMOVE_HEAD(&s->buf_free, next);
396 s->buf_free_count--;
397 qemu_iovec_add(&op->qiov, buf, MIN(s->granularity, remaining));
398 }
399
400 /* Copy the dirty cluster. */
401 s->in_flight++;
402 s->bytes_in_flight += op->bytes;
403 op->is_in_flight = true;
404 trace_mirror_one_iteration(s, op->offset, op->bytes);
405
406 WITH_GRAPH_RDLOCK_GUARD() {
407 ret = bdrv_co_preadv(s->mirror_top_bs->backing, op->offset, op->bytes,
408 &op->qiov, 0);
409 }
410 mirror_read_complete(op, ret);
411 }
412
413 static void coroutine_fn mirror_co_zero(void *opaque)
414 {
415 MirrorOp *op = opaque;
416 bool write_needed = true;
417 int ret = 0;
418
419 op->s->in_flight++;
420 op->s->bytes_in_flight += op->bytes;
421 *op->bytes_handled = op->bytes;
422 op->is_in_flight = true;
423
424 if (op->s->zero_bitmap) {
425 unsigned long end = DIV_ROUND_UP(op->offset + op->bytes,
426 op->s->granularity);
427 assert(QEMU_IS_ALIGNED(op->offset, op->s->granularity));
428 assert(QEMU_IS_ALIGNED(op->bytes, op->s->granularity) ||
429 op->offset + op->bytes == op->s->bdev_length);
430 if (find_next_zero_bit(op->s->zero_bitmap, end,
431 op->offset / op->s->granularity) == end) {
432 write_needed = false;
433 *op->io_skipped = true;
434 }
435 }
436 if (write_needed) {
437 ret = blk_co_pwrite_zeroes(op->s->target, op->offset, op->bytes,
438 op->s->unmap ? BDRV_REQ_MAY_UNMAP : 0);
439 }
440 if (ret >= 0 && op->s->zero_bitmap) {
441 bitmap_set(op->s->zero_bitmap, op->offset / op->s->granularity,
442 DIV_ROUND_UP(op->bytes, op->s->granularity));
443 }
444 mirror_write_complete(op, ret);
445 }
446
447 static void coroutine_fn mirror_co_discard(void *opaque)
448 {
449 MirrorOp *op = opaque;
450 int ret;
451
452 op->s->in_flight++;
453 op->s->bytes_in_flight += op->bytes;
454 *op->bytes_handled = op->bytes;
455 op->is_in_flight = true;
456
457 ret = blk_co_pdiscard(op->s->target, op->offset, op->bytes, 0);
458 mirror_write_complete(op, ret);
459 }
460
461 static unsigned mirror_perform(MirrorBlockJob *s, int64_t offset,
462 unsigned bytes, MirrorMethod mirror_method,
463 bool *io_skipped)
464 {
465 MirrorOp *op;
466 Coroutine *co;
467 int64_t bytes_handled = -1;
468
469 assert(QEMU_IS_ALIGNED(offset, s->granularity));
470 assert(QEMU_IS_ALIGNED(bytes, s->granularity) ||
471 offset + bytes == s->bdev_length);
472 op = g_new(MirrorOp, 1);
473 *op = (MirrorOp){
474 .s = s,
475 .offset = offset,
476 .bytes = bytes,
477 .bytes_handled = &bytes_handled,
478 .io_skipped = io_skipped,
479 };
480 qemu_co_queue_init(&op->waiting_requests);
481
482 switch (mirror_method) {
483 case MIRROR_METHOD_COPY:
484 if (s->zero_bitmap) {
485 bitmap_clear(s->zero_bitmap, offset / s->granularity,
486 DIV_ROUND_UP(bytes, s->granularity));
487 }
488 co = qemu_coroutine_create(mirror_co_read, op);
489 break;
490 case MIRROR_METHOD_ZERO:
491 /* s->zero_bitmap handled in mirror_co_zero */
492 co = qemu_coroutine_create(mirror_co_zero, op);
493 break;
494 case MIRROR_METHOD_DISCARD:
495 if (s->zero_bitmap) {
496 bitmap_clear(s->zero_bitmap, offset / s->granularity,
497 DIV_ROUND_UP(bytes, s->granularity));
498 }
499 co = qemu_coroutine_create(mirror_co_discard, op);
500 break;
501 default:
502 abort();
503 }
504 op->co = co;
505
506 QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
507 qemu_coroutine_enter(co);
508 /* At this point, ownership of op has been moved to the coroutine
509 * and the object may already be freed */
510
511 /* Assert that this value has been set */
512 assert(bytes_handled >= 0);
513
514 /* Same assertion as in mirror_co_read() (and for mirror_co_read()
515 * and mirror_co_discard(), bytes_handled == op->bytes, which
516 * is the @bytes parameter given to this function) */
517 assert(bytes_handled <= UINT_MAX);
518 return bytes_handled;
519 }
520
521 static void coroutine_fn GRAPH_UNLOCKED mirror_iteration(MirrorBlockJob *s)
522 {
523 BlockDriverState *source;
524 MirrorOp *pseudo_op;
525 int64_t offset;
526 /* At least the first dirty chunk is mirrored in one iteration. */
527 int nb_chunks = 1;
528 bool write_zeroes_ok = bdrv_can_write_zeroes_with_unmap(blk_bs(s->target));
529 int max_io_bytes = MAX(s->buf_size / MAX_IN_FLIGHT, MAX_IO_BYTES);
530
531 bdrv_graph_co_rdlock();
532 source = s->mirror_top_bs->backing->bs;
533 bdrv_graph_co_rdunlock();
534
535 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
536 offset = bdrv_dirty_iter_next(s->dbi);
537 if (offset < 0) {
538 bdrv_set_dirty_iter(s->dbi, 0);
539 offset = bdrv_dirty_iter_next(s->dbi);
540 trace_mirror_restart_iter(s, bdrv_get_dirty_count(s->dirty_bitmap));
541 assert(offset >= 0);
542 }
543 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
544
545 /*
546 * Wait for concurrent requests to @offset. The next loop will limit the
547 * copied area based on in_flight_bitmap so we only copy an area that does
548 * not overlap with concurrent in-flight requests. Still, we would like to
549 * copy something, so wait until there are at least no more requests to the
550 * very beginning of the area.
551 */
552 mirror_wait_on_conflicts(NULL, s, offset, 1);
553
554 job_pause_point(&s->common.job);
555
556 /* Find the number of consecutive dirty chunks following the first dirty
557 * one, and wait for in flight requests in them. */
558 bdrv_dirty_bitmap_lock(s->dirty_bitmap);
559 while (nb_chunks * s->granularity < s->buf_size) {
560 int64_t next_dirty;
561 int64_t next_offset = offset + nb_chunks * s->granularity;
562 int64_t next_chunk = next_offset / s->granularity;
563 if (next_offset >= s->bdev_length ||
564 !bdrv_dirty_bitmap_get_locked(s->dirty_bitmap, next_offset)) {
565 break;
566 }
567 if (test_bit(next_chunk, s->in_flight_bitmap)) {
568 break;
569 }
570
571 next_dirty = bdrv_dirty_iter_next(s->dbi);
572 if (next_dirty > next_offset || next_dirty < 0) {
573 /* The bitmap iterator's cache is stale, refresh it */
574 bdrv_set_dirty_iter(s->dbi, next_offset);
575 next_dirty = bdrv_dirty_iter_next(s->dbi);
576 }
577 assert(next_dirty == next_offset);
578 nb_chunks++;
579 }
580
581 /* Clear dirty bits before querying the block status, because
582 * calling bdrv_block_status_above could yield - if some blocks are
583 * marked dirty in this window, we need to know.
584 */
585 bdrv_reset_dirty_bitmap_locked(s->dirty_bitmap, offset,
586 nb_chunks * s->granularity);
587 bdrv_dirty_bitmap_unlock(s->dirty_bitmap);
588
589 /* Before claiming an area in the in-flight bitmap, we have to
590 * create a MirrorOp for it so that conflicting requests can wait
591 * for it. mirror_perform() will create the real MirrorOps later,
592 * for now we just create a pseudo operation that will wake up all
593 * conflicting requests once all real operations have been
594 * launched. */
595 pseudo_op = g_new(MirrorOp, 1);
596 *pseudo_op = (MirrorOp){
597 .offset = offset,
598 .bytes = nb_chunks * s->granularity,
599 .is_pseudo_op = true,
600 };
601 qemu_co_queue_init(&pseudo_op->waiting_requests);
602 QTAILQ_INSERT_TAIL(&s->ops_in_flight, pseudo_op, next);
603
604 bitmap_set(s->in_flight_bitmap, offset / s->granularity, nb_chunks);
605 while (nb_chunks > 0 && offset < s->bdev_length) {
606 int ret = -1;
607 int64_t io_bytes;
608 int64_t io_bytes_acct;
609 bool io_skipped = false;
610 MirrorMethod mirror_method = MIRROR_METHOD_COPY;
611
612 assert(!(offset % s->granularity));
613 WITH_GRAPH_RDLOCK_GUARD() {
614 ret = bdrv_co_block_status_above(source, NULL, offset,
615 nb_chunks * s->granularity,
616 &io_bytes, NULL, NULL);
617 }
618 if (ret < 0) {
619 io_bytes = MIN(nb_chunks * s->granularity, max_io_bytes);
620 } else if (ret & BDRV_BLOCK_DATA) {
621 io_bytes = MIN(io_bytes, max_io_bytes);
622 }
623
624 io_bytes -= io_bytes % s->granularity;
625 if (io_bytes < s->granularity) {
626 io_bytes = s->granularity;
627 } else if (ret >= 0 && !(ret & BDRV_BLOCK_DATA)) {
628 int64_t target_offset;
629 int64_t target_bytes;
630 WITH_GRAPH_RDLOCK_GUARD() {
631 bdrv_round_to_subclusters(blk_bs(s->target), offset, io_bytes,
632 &target_offset, &target_bytes);
633 }
634 if (target_offset == offset &&
635 target_bytes == io_bytes) {
636 mirror_method = ret & BDRV_BLOCK_ZERO ?
637 MIRROR_METHOD_ZERO :
638 MIRROR_METHOD_DISCARD;
639 }
640 }
641
642 while (s->in_flight >= MAX_IN_FLIGHT) {
643 trace_mirror_yield_in_flight(s, offset, s->in_flight);
644 mirror_wait_for_free_in_flight_slot(s);
645 }
646
647 if (s->ret < 0) {
648 ret = 0;
649 goto fail;
650 }
651
652 io_bytes = mirror_clip_bytes(s, offset, io_bytes);
653 io_bytes = mirror_perform(s, offset, io_bytes, mirror_method,
654 &io_skipped);
655 if (io_skipped ||
656 (mirror_method != MIRROR_METHOD_COPY && write_zeroes_ok)) {
657 io_bytes_acct = 0;
658 } else {
659 io_bytes_acct = io_bytes;
660 }
661 assert(io_bytes);
662 offset += io_bytes;
663 nb_chunks -= DIV_ROUND_UP(io_bytes, s->granularity);
664 block_job_ratelimit_processed_bytes(&s->common, io_bytes_acct);
665 }
666
667 fail:
668 QTAILQ_REMOVE(&s->ops_in_flight, pseudo_op, next);
669 qemu_co_queue_restart_all(&pseudo_op->waiting_requests);
670 g_free(pseudo_op);
671 }
672
673 static void mirror_free_init(MirrorBlockJob *s)
674 {
675 int granularity = s->granularity;
676 size_t buf_size = s->buf_size;
677 uint8_t *buf = s->buf;
678
679 assert(s->buf_free_count == 0);
680 QSIMPLEQ_INIT(&s->buf_free);
681 while (buf_size != 0) {
682 MirrorBuffer *cur = (MirrorBuffer *)buf;
683 QSIMPLEQ_INSERT_TAIL(&s->buf_free, cur, next);
684 s->buf_free_count++;
685 buf_size -= granularity;
686 buf += granularity;
687 }
688 }
689
690 /* This is also used for the .pause callback. There is no matching
691 * mirror_resume() because mirror_run() will begin iterating again
692 * when the job is resumed.
693 */
694 static void coroutine_fn mirror_wait_for_all_io(MirrorBlockJob *s)
695 {
696 while (s->in_flight > 0) {
697 mirror_wait_for_free_in_flight_slot(s);
698 }
699 }
700
701 /**
702 * mirror_exit_common: handle both abort() and prepare() cases.
703 * for .prepare, returns 0 on success and -errno on failure.
704 * for .abort cases, denoted by abort = true, MUST return 0.
705 */
706 static int mirror_exit_common(Job *job)
707 {
708 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
709 BlockJob *bjob = &s->common;
710 MirrorBDSOpaque *bs_opaque;
711 BlockDriverState *src;
712 BlockDriverState *target_bs;
713 BlockDriverState *mirror_top_bs;
714 Error *local_err = NULL;
715 bool abort = job->ret < 0;
716 int ret = 0;
717
718 GLOBAL_STATE_CODE();
719
720 if (s->prepared) {
721 return 0;
722 }
723 s->prepared = true;
724
725 bdrv_graph_rdlock_main_loop();
726
727 mirror_top_bs = s->mirror_top_bs;
728 bs_opaque = mirror_top_bs->opaque;
729 src = mirror_top_bs->backing->bs;
730 target_bs = blk_bs(s->target);
731
732 if (bdrv_chain_contains(src, target_bs)) {
733 bdrv_unfreeze_backing_chain(mirror_top_bs, target_bs);
734 }
735
736 bdrv_release_dirty_bitmap(s->dirty_bitmap);
737
738 /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
739 * before we can call bdrv_drained_end */
740 bdrv_ref(src);
741 bdrv_ref(mirror_top_bs);
742 bdrv_ref(target_bs);
743
744 bdrv_graph_rdunlock_main_loop();
745
746 /*
747 * Remove target parent that still uses BLK_PERM_WRITE/RESIZE before
748 * inserting target_bs at s->to_replace, where we might not be able to get
749 * these permissions.
750 */
751 blk_unref(s->target);
752 s->target = NULL;
753
754 /* We don't access the source any more. Dropping any WRITE/RESIZE is
755 * required before it could become a backing file of target_bs. Not having
756 * these permissions any more means that we can't allow any new requests on
757 * mirror_top_bs from now on, so keep it drained. */
758 bdrv_drained_begin(mirror_top_bs);
759 bdrv_drained_begin(target_bs);
760 bs_opaque->stop = true;
761
762 bdrv_graph_rdlock_main_loop();
763 bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
764 &error_abort);
765 bdrv_graph_rdunlock_main_loop();
766
767 if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
768 BlockDriverState *backing;
769 BlockDriverState *unfiltered_target;
770
771 bdrv_graph_wrlock_drained();
772 unfiltered_target = bdrv_skip_filters(target_bs);
773
774 backing = s->sync_mode == MIRROR_SYNC_MODE_NONE ? src : s->base;
775 if (bdrv_cow_bs(unfiltered_target) != backing) {
776 bdrv_set_backing_hd(unfiltered_target, backing, &local_err);
777 if (local_err) {
778 error_report_err(local_err);
779 local_err = NULL;
780 ret = -EPERM;
781 }
782 }
783 bdrv_graph_wrunlock();
784 } else if (!abort && s->backing_mode == MIRROR_OPEN_BACKING_CHAIN) {
785 bdrv_graph_rdlock_main_loop();
786 assert(!bdrv_backing_chain_next(target_bs));
787 ret = bdrv_open_backing_file(bdrv_skip_filters(target_bs), NULL,
788 "backing", &local_err);
789 bdrv_graph_rdunlock_main_loop();
790 if (ret < 0) {
791 error_report_err(local_err);
792 local_err = NULL;
793 }
794 }
795
796 if (s->should_complete && !abort) {
797 BlockDriverState *to_replace = s->to_replace ?: src;
798 bool ro = bdrv_is_read_only(to_replace);
799
800 if (ro != bdrv_is_read_only(target_bs)) {
801 bdrv_reopen_set_read_only(target_bs, ro, NULL);
802 }
803
804 /* The mirror job has no requests in flight any more, but we need to
805 * drain potential other users of the BDS before changing the graph. */
806 assert(s->in_drain);
807 bdrv_drained_begin(to_replace);
808 /*
809 * Cannot use check_to_replace_node() here, because that would
810 * check for an op blocker on @to_replace, and we have our own
811 * there.
812 */
813 bdrv_graph_wrlock();
814 if (bdrv_recurse_can_replace(src, to_replace)) {
815 bdrv_replace_node(to_replace, target_bs, &local_err);
816 } else {
817 error_setg(&local_err, "Can no longer replace '%s' by '%s', "
818 "because it can no longer be guaranteed that doing so "
819 "would not lead to an abrupt change of visible data",
820 to_replace->node_name, target_bs->node_name);
821 }
822 bdrv_graph_wrunlock();
823 bdrv_drained_end(to_replace);
824 if (local_err) {
825 error_report_err(local_err);
826 ret = -EPERM;
827 }
828 }
829 if (s->to_replace) {
830 bdrv_op_unblock_all(s->to_replace, s->replace_blocker);
831 error_free(s->replace_blocker);
832 bdrv_unref(s->to_replace);
833 }
834 g_free(s->replaces);
835
836 /*
837 * Remove the mirror filter driver from the graph. Before this, get rid of
838 * the blockers on the intermediate nodes so that the resulting state is
839 * valid.
840 */
841 block_job_remove_all_bdrv(bjob);
842 bdrv_graph_wrlock();
843 bdrv_replace_node(mirror_top_bs, mirror_top_bs->backing->bs, &error_abort);
844 bdrv_graph_wrunlock();
845
846 if (abort && s->base_ro && !bdrv_is_read_only(target_bs)) {
847 bdrv_reopen_set_read_only(target_bs, true, NULL);
848 }
849
850 bdrv_drained_end(target_bs);
851 bdrv_unref(target_bs);
852
853 bs_opaque->job = NULL;
854
855 bdrv_drained_end(src);
856 bdrv_drained_end(mirror_top_bs);
857 s->in_drain = false;
858 bdrv_unref(mirror_top_bs);
859 bdrv_unref(src);
860
861 return ret;
862 }
863
864 static int mirror_prepare(Job *job)
865 {
866 return mirror_exit_common(job);
867 }
868
869 static void mirror_abort(Job *job)
870 {
871 int ret = mirror_exit_common(job);
872 assert(ret == 0);
873 }
874
875 static void coroutine_fn mirror_throttle(MirrorBlockJob *s)
876 {
877 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
878
879 if (now - s->last_pause_ns > BLOCK_JOB_SLICE_TIME) {
880 s->last_pause_ns = now;
881 job_sleep_ns(&s->common.job, 0);
882 } else {
883 job_pause_point(&s->common.job);
884 }
885 }
886
887 static int coroutine_fn GRAPH_UNLOCKED mirror_dirty_init(MirrorBlockJob *s)
888 {
889 int64_t offset;
890 BlockDriverState *bs;
891 BlockDriverState *target_bs = blk_bs(s->target);
892 int ret = -EIO;
893 int64_t count;
894 bool punch_holes =
895 target_bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
896 bdrv_can_write_zeroes_with_unmap(target_bs);
897 int64_t bitmap_length = DIV_ROUND_UP(s->bdev_length, s->granularity);
898
899 /* Determine if the image is already zero, regardless of sync mode. */
900 s->zero_bitmap = bitmap_new(bitmap_length);
901 bdrv_graph_co_rdlock();
902 bs = s->mirror_top_bs->backing->bs;
903 if (s->target_is_zero) {
904 ret = 1;
905 } else {
906 ret = bdrv_co_is_all_zeroes(target_bs);
907 }
908 bdrv_graph_co_rdunlock();
909
910 /* Determine if a pre-zeroing pass is necessary. */
911 if (ret < 0) {
912 return ret;
913 } else if (s->sync_mode == MIRROR_SYNC_MODE_TOP) {
914 /*
915 * In TOP mode, there is no benefit to a pre-zeroing pass, but
916 * the zero bitmap can be set if the destination already reads
917 * as zero and we are not punching holes.
918 */
919 if (ret > 0 && !punch_holes) {
920 bitmap_set(s->zero_bitmap, 0, bitmap_length);
921 }
922 } else if (ret == 0 || punch_holes) {
923 /*
924 * Here, we are in FULL mode; our goal is to avoid writing
925 * zeroes if the destination already reads as zero, except
926 * when we are trying to punch holes. This is possible if
927 * zeroing happened externally (ret > 0) or if we have a fast
928 * way to pre-zero the image (the dirty bitmap will be
929 * populated later by the non-zero portions, the same as for
930 * TOP mode). If pre-zeroing is not fast, or we need to visit
931 * the entire image in order to punch holes even in the
932 * non-allocated regions of the source, then just mark the
933 * entire image dirty and leave the zero bitmap clear at this
934 * point in time. Otherwise, it can be faster to pre-zero the
935 * image now, even if we re-write the allocated portions of
936 * the disk later, and the pre-zero pass will populate the
937 * zero bitmap.
938 */
939 if (!bdrv_can_write_zeroes_with_unmap(target_bs) || punch_holes) {
940 bdrv_set_dirty_bitmap(s->dirty_bitmap, 0, s->bdev_length);
941 return 0;
942 }
943
944 s->initial_zeroing_ongoing = true;
945 for (offset = 0; offset < s->bdev_length; ) {
946 int bytes = MIN(s->bdev_length - offset,
947 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
948 bool ignored;
949
950 mirror_throttle(s);
951
952 if (job_is_cancelled(&s->common.job)) {
953 s->initial_zeroing_ongoing = false;
954 return 0;
955 }
956
957 if (s->in_flight >= MAX_IN_FLIGHT) {
958 trace_mirror_yield(s, UINT64_MAX, s->buf_free_count,
959 s->in_flight);
960 mirror_wait_for_free_in_flight_slot(s);
961 continue;
962 }
963
964 mirror_perform(s, offset, bytes, MIRROR_METHOD_ZERO, &ignored);
965 offset += bytes;
966 }
967
968 mirror_wait_for_all_io(s);
969 s->initial_zeroing_ongoing = false;
970 } else {
971 /* In FULL mode, and image already reads as zero. */
972 bitmap_set(s->zero_bitmap, 0, bitmap_length);
973 }
974
975 /* First part, loop on the sectors and initialize the dirty bitmap. */
976 for (offset = 0; offset < s->bdev_length; ) {
977 /* Just to make sure we are not exceeding int limit. */
978 int bytes = MIN(s->bdev_length - offset,
979 QEMU_ALIGN_DOWN(INT_MAX, s->granularity));
980
981 mirror_throttle(s);
982
983 if (job_is_cancelled(&s->common.job)) {
984 return 0;
985 }
986
987 WITH_GRAPH_RDLOCK_GUARD() {
988 ret = bdrv_co_is_allocated_above(bs, s->base_overlay, true, offset,
989 bytes, &count);
990 }
991 if (ret < 0) {
992 return ret;
993 }
994
995 assert(count);
996 if (ret > 0) {
997 bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, count);
998 }
999 offset += count;
1000 }
1001 return 0;
1002 }
1003
1004 /* Called when going out of the streaming phase to flush the bulk of the
1005 * data to the medium, or just before completing.
1006 */
1007 static int coroutine_fn mirror_flush(MirrorBlockJob *s)
1008 {
1009 int ret = blk_co_flush(s->target);
1010 if (ret < 0) {
1011 if (mirror_error_action(s, false, -ret) == BLOCK_ERROR_ACTION_REPORT) {
1012 s->ret = ret;
1013 }
1014 }
1015 return ret;
1016 }
1017
1018 static int coroutine_fn mirror_run(Job *job, Error **errp)
1019 {
1020 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1021 BlockDriverState *bs;
1022 MirrorBDSOpaque *mirror_top_opaque = s->mirror_top_bs->opaque;
1023 BlockDriverState *target_bs = blk_bs(s->target);
1024 bool need_drain = true;
1025 BlockDeviceIoStatus iostatus = BLOCK_DEVICE_IO_STATUS__MAX;
1026 int64_t length;
1027 int64_t target_length;
1028 BlockDriverInfo bdi;
1029 char backing_filename[2]; /* we only need 2 characters because we are only
1030 checking for a NULL string */
1031 int ret = 0;
1032
1033 bdrv_graph_co_rdlock();
1034 bs = bdrv_filter_bs(s->mirror_top_bs);
1035 bdrv_graph_co_rdunlock();
1036
1037 if (job_is_cancelled(&s->common.job)) {
1038 goto immediate_exit;
1039 }
1040
1041 bdrv_graph_co_rdlock();
1042 s->bdev_length = bdrv_co_getlength(bs);
1043 bdrv_graph_co_rdunlock();
1044
1045 if (s->bdev_length < 0) {
1046 ret = s->bdev_length;
1047 goto immediate_exit;
1048 }
1049
1050 target_length = blk_co_getlength(s->target);
1051 if (target_length < 0) {
1052 ret = target_length;
1053 goto immediate_exit;
1054 }
1055
1056 /* Active commit must resize the base image if its size differs from the
1057 * active layer. */
1058 if (s->base == blk_bs(s->target)) {
1059 if (s->bdev_length > target_length) {
1060 ret = blk_co_truncate(s->target, s->bdev_length, false,
1061 PREALLOC_MODE_OFF, 0, NULL);
1062 if (ret < 0) {
1063 goto immediate_exit;
1064 }
1065 }
1066 } else if (s->bdev_length != target_length) {
1067 error_setg(errp, "Source and target image have different sizes");
1068 ret = -EINVAL;
1069 goto immediate_exit;
1070 }
1071
1072 if (s->bdev_length == 0) {
1073 /* Transition to the READY state and wait for complete. */
1074 job_transition_to_ready(&s->common.job);
1075 qatomic_set(&s->actively_synced, true);
1076 while (!job_cancel_requested(&s->common.job) && !s->should_complete) {
1077 job_yield(&s->common.job);
1078 }
1079 goto immediate_exit;
1080 }
1081
1082 length = DIV_ROUND_UP(s->bdev_length, s->granularity);
1083 s->in_flight_bitmap = bitmap_new(length);
1084
1085 /* If we have no backing file yet in the destination, we cannot let
1086 * the destination do COW. Instead, we copy sectors around the
1087 * dirty data if needed. We need a bitmap to do that.
1088 */
1089 bdrv_get_backing_filename(target_bs, backing_filename,
1090 sizeof(backing_filename));
1091 bdrv_graph_co_rdlock();
1092 if (!bdrv_co_get_info(target_bs, &bdi) && bdi.cluster_size) {
1093 s->target_cluster_size = bdi.cluster_size;
1094 } else {
1095 s->target_cluster_size = BDRV_SECTOR_SIZE;
1096 }
1097 if (backing_filename[0] && !bdrv_backing_chain_next(target_bs) &&
1098 s->granularity < s->target_cluster_size) {
1099 s->buf_size = MAX(s->buf_size, s->target_cluster_size);
1100 s->cow_bitmap = bitmap_new(length);
1101 }
1102 s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);
1103 bdrv_graph_co_rdunlock();
1104
1105 s->buf = qemu_try_blockalign(bs, s->buf_size);
1106 if (s->buf == NULL) {
1107 ret = -ENOMEM;
1108 goto immediate_exit;
1109 }
1110
1111 mirror_free_init(s);
1112
1113 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1114 if (s->sync_mode != MIRROR_SYNC_MODE_NONE) {
1115 ret = mirror_dirty_init(s);
1116 if (ret < 0 || job_is_cancelled(&s->common.job)) {
1117 goto immediate_exit;
1118 }
1119 }
1120
1121 /*
1122 * Only now the job is fully initialised and mirror_top_bs should start
1123 * accessing it.
1124 */
1125 mirror_top_opaque->job = s;
1126
1127 assert(!s->dbi);
1128 s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap);
1129 for (;;) {
1130 int64_t cnt, delta;
1131 bool should_complete;
1132
1133 if (s->ret < 0) {
1134 ret = s->ret;
1135 goto immediate_exit;
1136 }
1137
1138 job_pause_point(&s->common.job);
1139
1140 if (job_is_cancelled(&s->common.job)) {
1141 ret = 0;
1142 goto immediate_exit;
1143 }
1144
1145 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1146 /* cnt is the number of dirty bytes remaining and s->bytes_in_flight is
1147 * the number of bytes currently being processed; together those are
1148 * the current remaining operation length */
1149 job_progress_set_remaining(&s->common.job,
1150 s->bytes_in_flight + cnt +
1151 s->active_write_bytes_in_flight);
1152
1153 /* Note that even when no rate limit is applied we need to yield
1154 * periodically with no pending I/O so that bdrv_drain_all() returns.
1155 * We do so every BLKOCK_JOB_SLICE_TIME nanoseconds, or when there is
1156 * an error, or when the source is clean, whichever comes first. */
1157 delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;
1158 WITH_JOB_LOCK_GUARD() {
1159 iostatus = s->common.iostatus;
1160 }
1161 if (delta < BLOCK_JOB_SLICE_TIME &&
1162 iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
1163 if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||
1164 (cnt == 0 && s->in_flight > 0)) {
1165 trace_mirror_yield(s, cnt, s->buf_free_count, s->in_flight);
1166 mirror_wait_for_free_in_flight_slot(s);
1167 continue;
1168 } else if (cnt != 0) {
1169 mirror_iteration(s);
1170 }
1171 }
1172
1173 should_complete = false;
1174 if (s->in_flight == 0 && cnt == 0) {
1175 trace_mirror_before_flush(s);
1176 if (!job_is_ready(&s->common.job)) {
1177 if (mirror_flush(s) < 0) {
1178 /* Go check s->ret. */
1179 continue;
1180 }
1181 /* We're out of the streaming phase. From now on, if the job
1182 * is cancelled we will actually complete all pending I/O and
1183 * report completion. This way, block-job-cancel will leave
1184 * the target in a consistent state.
1185 */
1186 job_transition_to_ready(&s->common.job);
1187 }
1188 if (qatomic_read(&s->copy_mode) != MIRROR_COPY_MODE_BACKGROUND) {
1189 qatomic_set(&s->actively_synced, true);
1190 }
1191
1192 should_complete = s->should_complete ||
1193 job_cancel_requested(&s->common.job);
1194 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1195 }
1196
1197 if (cnt == 0 && should_complete) {
1198 /* The dirty bitmap is not updated while operations are pending.
1199 * If we're about to exit, wait for pending operations before
1200 * calling bdrv_get_dirty_count(bs), or we may exit while the
1201 * source has dirty data to copy!
1202 *
1203 * Note that I/O can be submitted by the guest while
1204 * mirror_populate runs, so pause it now. Before deciding
1205 * whether to switch to target check one last time if I/O has
1206 * come in the meanwhile, and if not flush the data to disk.
1207 */
1208 trace_mirror_before_drain(s, cnt);
1209
1210 s->in_drain = true;
1211 bdrv_drained_begin(bs);
1212
1213 /* Must be zero because we are drained */
1214 assert(s->in_active_write_counter == 0);
1215
1216 cnt = bdrv_get_dirty_count(s->dirty_bitmap);
1217 if (cnt > 0 || mirror_flush(s) < 0) {
1218 bdrv_drained_end(bs);
1219 s->in_drain = false;
1220 continue;
1221 }
1222
1223 /* The two disks are in sync. Exit and report successful
1224 * completion.
1225 */
1226 assert(QLIST_EMPTY(&bs->tracked_requests));
1227 need_drain = false;
1228 break;
1229 }
1230
1231 if (job_is_ready(&s->common.job) && !should_complete) {
1232 if (s->in_flight == 0 && cnt == 0) {
1233 trace_mirror_before_sleep(s, cnt, job_is_ready(&s->common.job),
1234 BLOCK_JOB_SLICE_TIME);
1235 job_sleep_ns(&s->common.job, BLOCK_JOB_SLICE_TIME);
1236 }
1237 } else {
1238 block_job_ratelimit_sleep(&s->common);
1239 }
1240 s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
1241 }
1242
1243 immediate_exit:
1244 if (s->in_flight > 0) {
1245 /* We get here only if something went wrong. Either the job failed,
1246 * or it was cancelled prematurely so that we do not guarantee that
1247 * the target is a copy of the source.
1248 */
1249 assert(ret < 0 || job_is_cancelled(&s->common.job));
1250 assert(need_drain);
1251 mirror_wait_for_all_io(s);
1252 }
1253
1254 assert(s->in_flight == 0);
1255 qemu_vfree(s->buf);
1256 g_free(s->cow_bitmap);
1257 g_free(s->zero_bitmap);
1258 g_free(s->in_flight_bitmap);
1259 bdrv_dirty_iter_free(s->dbi);
1260
1261 if (need_drain) {
1262 s->in_drain = true;
1263 bdrv_drained_begin(bs);
1264 }
1265
1266 return ret;
1267 }
1268
1269 static void mirror_complete(Job *job, Error **errp)
1270 {
1271 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1272
1273 if (!job_is_ready(job)) {
1274 error_setg(errp, "The active block job '%s' cannot be completed",
1275 job->id);
1276 return;
1277 }
1278
1279 if (!s->should_complete) {
1280 /* block all operations on to_replace bs */
1281 if (s->replaces) {
1282 s->to_replace = bdrv_find_node(s->replaces);
1283 if (!s->to_replace) {
1284 error_setg(errp, "Node name '%s' not found", s->replaces);
1285 return;
1286 }
1287
1288 /* TODO Translate this into child freeze system. */
1289 error_setg(&s->replace_blocker,
1290 "block device is in use by block-job-complete");
1291 bdrv_op_block_all(s->to_replace, s->replace_blocker);
1292 bdrv_ref(s->to_replace);
1293 }
1294
1295 s->should_complete = true;
1296 }
1297
1298 /* If the job is paused, it will be re-entered when it is resumed */
1299 WITH_JOB_LOCK_GUARD() {
1300 if (!job->paused) {
1301 job_enter_cond_locked(job, NULL);
1302 }
1303 }
1304 }
1305
1306 static void coroutine_fn mirror_pause(Job *job)
1307 {
1308 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1309
1310 mirror_wait_for_all_io(s);
1311 }
1312
1313 static bool mirror_drained_poll(BlockJob *job)
1314 {
1315 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1316
1317 /* If the job isn't paused nor cancelled, we can't be sure that it won't
1318 * issue more requests. We make an exception if we've reached this point
1319 * from one of our own drain sections, to avoid a deadlock waiting for
1320 * ourselves.
1321 */
1322 WITH_JOB_LOCK_GUARD() {
1323 if (!s->common.job.paused && !job_is_cancelled_locked(&job->job)
1324 && !s->in_drain) {
1325 return true;
1326 }
1327 }
1328
1329 return !!s->in_flight;
1330 }
1331
1332 static bool mirror_cancel(Job *job, bool force)
1333 {
1334 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
1335 BlockDriverState *target = blk_bs(s->target);
1336
1337 /*
1338 * Before the job is READY, we treat any cancellation like a
1339 * force-cancellation.
1340 */
1341 force = force || !job_is_ready(job);
1342
1343 if (force) {
1344 bdrv_cancel_in_flight(target);
1345 }
1346 return force;
1347 }
1348
1349 static bool commit_active_cancel(Job *job, bool force)
1350 {
1351 /* Same as above in mirror_cancel() */
1352 return force || !job_is_ready(job);
1353 }
1354
1355 static void mirror_change(BlockJob *job, BlockJobChangeOptions *opts,
1356 Error **errp)
1357 {
1358 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1359 BlockJobChangeOptionsMirror *change_opts = &opts->u.mirror;
1360 MirrorCopyMode current;
1361
1362 /*
1363 * The implementation relies on the fact that copy_mode is only written
1364 * under the BQL. Otherwise, further synchronization would be required.
1365 */
1366
1367 GLOBAL_STATE_CODE();
1368
1369 if (qatomic_read(&s->copy_mode) == change_opts->copy_mode) {
1370 return;
1371 }
1372
1373 if (change_opts->copy_mode != MIRROR_COPY_MODE_WRITE_BLOCKING) {
1374 error_setg(errp, "Change to copy mode '%s' is not implemented",
1375 MirrorCopyMode_str(change_opts->copy_mode));
1376 return;
1377 }
1378
1379 current = qatomic_cmpxchg(&s->copy_mode, MIRROR_COPY_MODE_BACKGROUND,
1380 change_opts->copy_mode);
1381 if (current != MIRROR_COPY_MODE_BACKGROUND) {
1382 error_setg(errp, "Expected current copy mode '%s', got '%s'",
1383 MirrorCopyMode_str(MIRROR_COPY_MODE_BACKGROUND),
1384 MirrorCopyMode_str(current));
1385 }
1386 }
1387
1388 static void mirror_query(BlockJob *job, BlockJobInfo *info)
1389 {
1390 MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);
1391
1392 info->u.mirror = (BlockJobInfoMirror) {
1393 .actively_synced = qatomic_read(&s->actively_synced),
1394 };
1395 }
1396
1397 static const BlockJobDriver mirror_job_driver = {
1398 .job_driver = {
1399 .instance_size = sizeof(MirrorBlockJob),
1400 .job_type = JOB_TYPE_MIRROR,
1401 .free = block_job_free,
1402 .user_resume = block_job_user_resume,
1403 .run = mirror_run,
1404 .prepare = mirror_prepare,
1405 .abort = mirror_abort,
1406 .pause = mirror_pause,
1407 .complete = mirror_complete,
1408 .cancel = mirror_cancel,
1409 },
1410 .drained_poll = mirror_drained_poll,
1411 .change = mirror_change,
1412 .query = mirror_query,
1413 };
1414
1415 static const BlockJobDriver commit_active_job_driver = {
1416 .job_driver = {
1417 .instance_size = sizeof(MirrorBlockJob),
1418 .job_type = JOB_TYPE_COMMIT,
1419 .free = block_job_free,
1420 .user_resume = block_job_user_resume,
1421 .run = mirror_run,
1422 .prepare = mirror_prepare,
1423 .abort = mirror_abort,
1424 .pause = mirror_pause,
1425 .complete = mirror_complete,
1426 .cancel = commit_active_cancel,
1427 },
1428 .drained_poll = mirror_drained_poll,
1429 };
1430
1431 static void coroutine_fn
1432 do_sync_target_write(MirrorBlockJob *job, MirrorMethod method,
1433 uint64_t offset, uint64_t bytes,
1434 QEMUIOVector *qiov, int flags)
1435 {
1436 int ret;
1437 size_t qiov_offset = 0;
1438 int64_t dirty_bitmap_offset, dirty_bitmap_end;
1439 int64_t zero_bitmap_offset, zero_bitmap_end;
1440
1441 if (!QEMU_IS_ALIGNED(offset, job->granularity) &&
1442 bdrv_dirty_bitmap_get(job->dirty_bitmap, offset))
1443 {
1444 /*
1445 * Dirty unaligned padding: ignore it.
1446 *
1447 * Reasoning:
1448 * 1. If we copy it, we can't reset corresponding bit in
1449 * dirty_bitmap as there may be some "dirty" bytes still not
1450 * copied.
1451 * 2. It's already dirty, so skipping it we don't diverge mirror
1452 * progress.
1453 *
1454 * Note, that because of this, guest write may have no contribution
1455 * into mirror converge, but that's not bad, as we have background
1456 * process of mirroring. If under some bad circumstances (high guest
1457 * IO load) background process starve, we will not converge anyway,
1458 * even if each write will contribute, as guest is not guaranteed to
1459 * rewrite the whole disk.
1460 */
1461 qiov_offset = QEMU_ALIGN_UP(offset, job->granularity) - offset;
1462 if (bytes <= qiov_offset) {
1463 /* nothing to do after shrink */
1464 return;
1465 }
1466 offset += qiov_offset;
1467 bytes -= qiov_offset;
1468 }
1469
1470 if (!QEMU_IS_ALIGNED(offset + bytes, job->granularity) &&
1471 bdrv_dirty_bitmap_get(job->dirty_bitmap, offset + bytes - 1))
1472 {
1473 uint64_t tail = (offset + bytes) % job->granularity;
1474
1475 if (bytes <= tail) {
1476 /* nothing to do after shrink */
1477 return;
1478 }
1479 bytes -= tail;
1480 }
1481
1482 /*
1483 * Tails are either clean or shrunk, so for dirty bitmap resetting
1484 * we safely align the range narrower. But for zero bitmap, round
1485 * range wider for checking or clearing, and narrower for setting.
1486 */
1487 dirty_bitmap_offset = QEMU_ALIGN_UP(offset, job->granularity);
1488 dirty_bitmap_end = QEMU_ALIGN_DOWN(offset + bytes, job->granularity);
1489 if (dirty_bitmap_offset < dirty_bitmap_end) {
1490 bdrv_reset_dirty_bitmap(job->dirty_bitmap, dirty_bitmap_offset,
1491 dirty_bitmap_end - dirty_bitmap_offset);
1492 }
1493 zero_bitmap_offset = offset / job->granularity;
1494 zero_bitmap_end = DIV_ROUND_UP(offset + bytes, job->granularity);
1495
1496 job_progress_increase_remaining(&job->common.job, bytes);
1497 job->active_write_bytes_in_flight += bytes;
1498
1499 switch (method) {
1500 case MIRROR_METHOD_COPY:
1501 if (job->zero_bitmap) {
1502 bitmap_clear(job->zero_bitmap, zero_bitmap_offset,
1503 zero_bitmap_end - zero_bitmap_offset);
1504 }
1505 ret = blk_co_pwritev_part(job->target, offset, bytes,
1506 qiov, qiov_offset, flags);
1507 break;
1508
1509 case MIRROR_METHOD_ZERO:
1510 if (job->zero_bitmap) {
1511 if (find_next_zero_bit(job->zero_bitmap, zero_bitmap_end,
1512 zero_bitmap_offset) == zero_bitmap_end) {
1513 ret = 0;
1514 break;
1515 }
1516 }
1517 assert(!qiov);
1518 ret = blk_co_pwrite_zeroes(job->target, offset, bytes, flags);
1519 if (job->zero_bitmap && ret >= 0) {
1520 if (dirty_bitmap_offset < dirty_bitmap_end) {
1521 bitmap_set(job->zero_bitmap,
1522 dirty_bitmap_offset / job->granularity,
1523 (dirty_bitmap_end - dirty_bitmap_offset) /
1524 job->granularity);
1525 }
1526 }
1527 break;
1528
1529 case MIRROR_METHOD_DISCARD:
1530 if (job->zero_bitmap) {
1531 bitmap_clear(job->zero_bitmap, zero_bitmap_offset,
1532 zero_bitmap_end - zero_bitmap_offset);
1533 }
1534 assert(!qiov);
1535 ret = blk_co_pdiscard(job->target, offset, bytes, 0);
1536 break;
1537
1538 default:
1539 abort();
1540 }
1541
1542 job->active_write_bytes_in_flight -= bytes;
1543 if (ret >= 0) {
1544 job_progress_update(&job->common.job, bytes);
1545 } else {
1546 BlockErrorAction action;
1547
1548 /*
1549 * We failed, so we should mark dirty the whole area, aligned up.
1550 * Note that we don't care about shrunk tails if any: they were dirty
1551 * at function start, and they must be still dirty, as we've locked
1552 * the region for in-flight op.
1553 */
1554 dirty_bitmap_offset = QEMU_ALIGN_DOWN(offset, job->granularity);
1555 dirty_bitmap_end = QEMU_ALIGN_UP(offset + bytes, job->granularity);
1556 bdrv_set_dirty_bitmap(job->dirty_bitmap, dirty_bitmap_offset,
1557 dirty_bitmap_end - dirty_bitmap_offset);
1558 qatomic_set(&job->actively_synced, false);
1559
1560 action = mirror_error_action(job, false, -ret);
1561 if (action == BLOCK_ERROR_ACTION_REPORT) {
1562 if (!job->ret) {
1563 job->ret = ret;
1564 }
1565 }
1566 }
1567 }
1568
1569 static MirrorOp *coroutine_fn active_write_prepare(MirrorBlockJob *s,
1570 uint64_t offset,
1571 uint64_t bytes)
1572 {
1573 MirrorOp *op;
1574 uint64_t start_chunk = offset / s->granularity;
1575 uint64_t end_chunk = DIV_ROUND_UP(offset + bytes, s->granularity);
1576
1577 op = g_new(MirrorOp, 1);
1578 *op = (MirrorOp){
1579 .s = s,
1580 .offset = offset,
1581 .bytes = bytes,
1582 .is_active_write = true,
1583 .is_in_flight = true,
1584 .co = qemu_coroutine_self(),
1585 };
1586 qemu_co_queue_init(&op->waiting_requests);
1587 QTAILQ_INSERT_TAIL(&s->ops_in_flight, op, next);
1588
1589 s->in_active_write_counter++;
1590
1591 /*
1592 * Wait for concurrent requests affecting the area. If there are already
1593 * running requests that are copying off now-to-be stale data in the area,
1594 * we must wait for them to finish before we begin writing fresh data to the
1595 * target so that the write operations appear in the correct order.
1596 * Note that background requests (see mirror_iteration()) in contrast only
1597 * wait for conflicting requests at the start of the dirty area, and then
1598 * (based on the in_flight_bitmap) truncate the area to copy so it will not
1599 * conflict with any requests beyond that. For active writes, however, we
1600 * cannot truncate that area. The request from our parent must be blocked
1601 * until the area is copied in full. Therefore, we must wait for the whole
1602 * area to become free of concurrent requests.
1603 */
1604 mirror_wait_on_conflicts(op, s, offset, bytes);
1605
1606 bitmap_set(s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1607
1608 return op;
1609 }
1610
1611 static void coroutine_fn GRAPH_RDLOCK active_write_settle(MirrorOp *op)
1612 {
1613 uint64_t start_chunk = op->offset / op->s->granularity;
1614 uint64_t end_chunk = DIV_ROUND_UP(op->offset + op->bytes,
1615 op->s->granularity);
1616
1617 if (!--op->s->in_active_write_counter &&
1618 qatomic_read(&op->s->actively_synced)) {
1619 BdrvChild *source = op->s->mirror_top_bs->backing;
1620
1621 if (QLIST_FIRST(&source->bs->parents) == source &&
1622 QLIST_NEXT(source, next_parent) == NULL)
1623 {
1624 /* Assert that we are back in sync once all active write
1625 * operations are settled.
1626 * Note that we can only assert this if the mirror node
1627 * is the source node's only parent. */
1628 assert(!bdrv_get_dirty_count(op->s->dirty_bitmap));
1629 }
1630 }
1631 bitmap_clear(op->s->in_flight_bitmap, start_chunk, end_chunk - start_chunk);
1632 QTAILQ_REMOVE(&op->s->ops_in_flight, op, next);
1633 qemu_co_queue_restart_all(&op->waiting_requests);
1634 g_free(op);
1635 }
1636
1637 static int coroutine_fn GRAPH_RDLOCK
1638 bdrv_mirror_top_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
1639 QEMUIOVector *qiov, BdrvRequestFlags flags)
1640 {
1641 return bdrv_co_preadv(bs->backing, offset, bytes, qiov, flags);
1642 }
1643
1644 static bool should_copy_to_target(MirrorBDSOpaque *s)
1645 {
1646 return s->job && s->job->ret >= 0 &&
1647 !job_is_cancelled(&s->job->common.job) &&
1648 qatomic_read(&s->job->copy_mode) == MIRROR_COPY_MODE_WRITE_BLOCKING;
1649 }
1650
1651 static int coroutine_fn GRAPH_RDLOCK
1652 bdrv_mirror_top_do_write(BlockDriverState *bs, MirrorMethod method,
1653 bool copy_to_target, uint64_t offset, uint64_t bytes,
1654 QEMUIOVector *qiov, int flags)
1655 {
1656 MirrorOp *op = NULL;
1657 MirrorBDSOpaque *s = bs->opaque;
1658 int ret = 0;
1659
1660 if (copy_to_target) {
1661 op = active_write_prepare(s->job, offset, bytes);
1662 }
1663
1664 switch (method) {
1665 case MIRROR_METHOD_COPY:
1666 ret = bdrv_co_pwritev(bs->backing, offset, bytes, qiov, flags);
1667 break;
1668
1669 case MIRROR_METHOD_ZERO:
1670 ret = bdrv_co_pwrite_zeroes(bs->backing, offset, bytes, flags);
1671 break;
1672
1673 case MIRROR_METHOD_DISCARD:
1674 ret = bdrv_co_pdiscard(bs->backing, offset, bytes);
1675 break;
1676
1677 default:
1678 abort();
1679 }
1680
1681 if (!copy_to_target) {
1682 if (s->job) {
1683 qatomic_set(&s->job->actively_synced, false);
1684 }
1685 bdrv_set_dirty_bitmap(s->dirty_bitmap, offset, bytes);
1686 }
1687
1688 if (ret < 0) {
1689 goto out;
1690 }
1691
1692 if (copy_to_target) {
1693 do_sync_target_write(s->job, method, offset, bytes, qiov, flags);
1694 }
1695
1696 out:
1697 if (copy_to_target) {
1698 active_write_settle(op);
1699 }
1700 return ret;
1701 }
1702
1703 static int coroutine_fn GRAPH_RDLOCK
1704 bdrv_mirror_top_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
1705 QEMUIOVector *qiov, BdrvRequestFlags flags)
1706 {
1707 QEMUIOVector bounce_qiov;
1708 void *bounce_buf;
1709 int ret = 0;
1710 bool copy_to_target = should_copy_to_target(bs->opaque);
1711
1712 if (copy_to_target) {
1713 /* The guest might concurrently modify the data to write; but
1714 * the data on source and destination must match, so we have
1715 * to use a bounce buffer if we are going to write to the
1716 * target now. */
1717 bounce_buf = qemu_blockalign(bs, bytes);
1718 iov_to_buf_full(qiov->iov, qiov->niov, 0, bounce_buf, bytes);
1719
1720 qemu_iovec_init(&bounce_qiov, 1);
1721 qemu_iovec_add(&bounce_qiov, bounce_buf, bytes);
1722 qiov = &bounce_qiov;
1723
1724 flags &= ~BDRV_REQ_REGISTERED_BUF;
1725 }
1726
1727 ret = bdrv_mirror_top_do_write(bs, MIRROR_METHOD_COPY, copy_to_target,
1728 offset, bytes, qiov, flags);
1729
1730 if (copy_to_target) {
1731 qemu_iovec_destroy(&bounce_qiov);
1732 qemu_vfree(bounce_buf);
1733 }
1734
1735 return ret;
1736 }
1737
1738 static int coroutine_fn GRAPH_RDLOCK bdrv_mirror_top_flush(BlockDriverState *bs)
1739 {
1740 if (bs->backing == NULL) {
1741 /* we can be here after failed bdrv_append in mirror_start_job */
1742 return 0;
1743 }
1744 return bdrv_co_flush(bs->backing->bs);
1745 }
1746
1747 static int coroutine_fn GRAPH_RDLOCK
1748 bdrv_mirror_top_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1749 int64_t bytes, BdrvRequestFlags flags)
1750 {
1751 bool copy_to_target = should_copy_to_target(bs->opaque);
1752 return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_ZERO, copy_to_target,
1753 offset, bytes, NULL, flags);
1754 }
1755
1756 static int coroutine_fn GRAPH_RDLOCK
1757 bdrv_mirror_top_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
1758 {
1759 bool copy_to_target = should_copy_to_target(bs->opaque);
1760 return bdrv_mirror_top_do_write(bs, MIRROR_METHOD_DISCARD, copy_to_target,
1761 offset, bytes, NULL, 0);
1762 }
1763
1764 static void GRAPH_RDLOCK bdrv_mirror_top_refresh_filename(BlockDriverState *bs)
1765 {
1766 if (bs->backing == NULL) {
1767 /* we can be here after failed bdrv_attach_child in
1768 * bdrv_set_backing_hd */
1769 return;
1770 }
1771 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
1772 bs->backing->bs->filename);
1773 }
1774
1775 static void bdrv_mirror_top_child_perm(BlockDriverState *bs, BdrvChild *c,
1776 BdrvChildRole role,
1777 BlockReopenQueue *reopen_queue,
1778 uint64_t perm, uint64_t shared,
1779 uint64_t *nperm, uint64_t *nshared)
1780 {
1781 MirrorBDSOpaque *s = bs->opaque;
1782
1783 if (s->stop) {
1784 /*
1785 * If the job is to be stopped, we do not need to forward
1786 * anything to the real image.
1787 */
1788 *nperm = 0;
1789 *nshared = BLK_PERM_ALL;
1790 return;
1791 }
1792
1793 bdrv_default_perms(bs, c, role, reopen_queue,
1794 perm, shared, nperm, nshared);
1795
1796 if (s->is_commit) {
1797 /*
1798 * For commit jobs, we cannot take CONSISTENT_READ, because
1799 * that permission is unshared for everything above the base
1800 * node (except for filters on the base node).
1801 * We also have to force-share the WRITE permission, or
1802 * otherwise we would block ourselves at the base node (if
1803 * writes are blocked for a node, they are also blocked for
1804 * its backing file).
1805 * (We could also share RESIZE, because it may be needed for
1806 * the target if its size is less than the top node's; but
1807 * bdrv_default_perms_for_cow() automatically shares RESIZE
1808 * for backing nodes if WRITE is shared, so there is no need
1809 * to do it here.)
1810 */
1811 *nperm &= ~BLK_PERM_CONSISTENT_READ;
1812 *nshared |= BLK_PERM_WRITE;
1813 }
1814 }
1815
1816 /* Dummy node that provides consistent read to its users without requiring it
1817 * from its backing file and that allows writes on the backing file chain. */
1818 static BlockDriver bdrv_mirror_top = {
1819 .format_name = "mirror_top",
1820 .bdrv_co_preadv = bdrv_mirror_top_preadv,
1821 .bdrv_co_pwritev = bdrv_mirror_top_pwritev,
1822 .bdrv_co_pwrite_zeroes = bdrv_mirror_top_pwrite_zeroes,
1823 .bdrv_co_pdiscard = bdrv_mirror_top_pdiscard,
1824 .bdrv_co_flush = bdrv_mirror_top_flush,
1825 .bdrv_refresh_filename = bdrv_mirror_top_refresh_filename,
1826 .bdrv_child_perm = bdrv_mirror_top_child_perm,
1827
1828 .is_filter = true,
1829 .filtered_child_is_backing = true,
1830 };
1831
1832 static BlockJob *mirror_start_job(
1833 const char *job_id, BlockDriverState *bs,
1834 int creation_flags, BlockDriverState *target,
1835 const char *replaces, int64_t speed,
1836 uint32_t granularity, int64_t buf_size,
1837 MirrorSyncMode sync_mode,
1838 BlockMirrorBackingMode backing_mode,
1839 bool target_is_zero,
1840 BlockdevOnError on_source_error,
1841 BlockdevOnError on_target_error,
1842 bool unmap,
1843 BlockCompletionFunc *cb,
1844 void *opaque,
1845 const BlockJobDriver *driver,
1846 BlockDriverState *base,
1847 bool auto_complete, const char *filter_node_name,
1848 bool is_mirror, MirrorCopyMode copy_mode,
1849 bool base_ro,
1850 Error **errp)
1851 {
1852 MirrorBlockJob *s;
1853 MirrorBDSOpaque *bs_opaque;
1854 BlockDriverState *mirror_top_bs;
1855 bool target_is_backing;
1856 uint64_t target_perms, target_shared_perms;
1857 int ret;
1858
1859 GLOBAL_STATE_CODE();
1860
1861 if (granularity == 0) {
1862 granularity = bdrv_get_default_bitmap_granularity(target);
1863 }
1864
1865 assert(is_power_of_2(granularity));
1866
1867 if (buf_size < 0) {
1868 error_setg(errp, "Invalid parameter 'buf-size'");
1869 return NULL;
1870 }
1871
1872 if (buf_size == 0) {
1873 buf_size = DEFAULT_MIRROR_BUF_SIZE;
1874 }
1875
1876 bdrv_graph_rdlock_main_loop();
1877 if (bdrv_skip_filters(bs) == bdrv_skip_filters(target)) {
1878 error_setg(errp, "Can't mirror node into itself");
1879 bdrv_graph_rdunlock_main_loop();
1880 return NULL;
1881 }
1882
1883 target_is_backing = bdrv_chain_contains(bs, target);
1884 bdrv_graph_rdunlock_main_loop();
1885
1886 /* In the case of active commit, add dummy driver to provide consistent
1887 * reads on the top, while disabling it in the intermediate nodes, and make
1888 * the backing chain writable. */
1889 mirror_top_bs = bdrv_new_open_driver(&bdrv_mirror_top, filter_node_name,
1890 BDRV_O_RDWR, errp);
1891 if (mirror_top_bs == NULL) {
1892 return NULL;
1893 }
1894 if (!filter_node_name) {
1895 mirror_top_bs->implicit = true;
1896 }
1897
1898 /* So that we can always drop this node */
1899 mirror_top_bs->never_freeze = true;
1900
1901 mirror_top_bs->total_sectors = bs->total_sectors;
1902 mirror_top_bs->supported_write_flags = BDRV_REQ_WRITE_UNCHANGED;
1903 mirror_top_bs->supported_zero_flags = BDRV_REQ_WRITE_UNCHANGED |
1904 BDRV_REQ_NO_FALLBACK;
1905 bs_opaque = g_new0(MirrorBDSOpaque, 1);
1906 mirror_top_bs->opaque = bs_opaque;
1907
1908 bs_opaque->is_commit = target_is_backing;
1909
1910 bdrv_drained_begin(bs);
1911 ret = bdrv_append(mirror_top_bs, bs, errp);
1912 if (ret < 0) {
1913 bdrv_drained_end(bs);
1914 bdrv_unref(mirror_top_bs);
1915 return NULL;
1916 }
1917
1918 bs_opaque->dirty_bitmap = bdrv_create_dirty_bitmap(mirror_top_bs,
1919 granularity,
1920 NULL, errp);
1921 if (!bs_opaque->dirty_bitmap) {
1922 bdrv_drained_end(bs);
1923 bdrv_unref(mirror_top_bs);
1924 return NULL;
1925 }
1926
1927 /*
1928 * The mirror job doesn't use the block layer's dirty tracking because it
1929 * needs to be able to switch seemlessly between background copy mode (which
1930 * does need dirty tracking) and write blocking mode (which doesn't) and
1931 * doing that would require draining the node. Instead, mirror_top_bs takes
1932 * care of updating the dirty bitmap as appropriate.
1933 *
1934 * Note that write blocking mode only becomes effective after mirror_run()
1935 * sets mirror_top_opaque->job (see should_copy_to_target()). Until then,
1936 * we're still in background copy mode irrespective of @copy_mode.
1937 */
1938 bdrv_disable_dirty_bitmap(bs_opaque->dirty_bitmap);
1939 bdrv_drained_end(bs);
1940
1941 /* Make sure that the source is not resized while the job is running */
1942 s = block_job_create(job_id, driver, NULL, mirror_top_bs,
1943 BLK_PERM_CONSISTENT_READ,
1944 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1945 BLK_PERM_WRITE, speed,
1946 creation_flags, cb, opaque, errp);
1947 if (!s) {
1948 goto fail;
1949 }
1950
1951 /* The block job now has a reference to this node */
1952 bdrv_unref(mirror_top_bs);
1953
1954 s->mirror_top_bs = mirror_top_bs;
1955 s->base_ro = base_ro;
1956
1957 /* No resize for the target either; while the mirror is still running, a
1958 * consistent read isn't necessarily possible. We could possibly allow
1959 * writes and graph modifications, though it would likely defeat the
1960 * purpose of a mirror, so leave them blocked for now.
1961 *
1962 * In the case of active commit, things look a bit different, though,
1963 * because the target is an already populated backing file in active use.
1964 * We can allow anything except resize there.*/
1965
1966 target_perms = BLK_PERM_WRITE;
1967 target_shared_perms = BLK_PERM_WRITE_UNCHANGED;
1968
1969 if (target_is_backing) {
1970 int64_t bs_size, target_size;
1971 bs_size = bdrv_getlength(bs);
1972 if (bs_size < 0) {
1973 error_setg_errno(errp, -bs_size,
1974 "Could not inquire top image size");
1975 goto fail;
1976 }
1977
1978 target_size = bdrv_getlength(target);
1979 if (target_size < 0) {
1980 error_setg_errno(errp, -target_size,
1981 "Could not inquire base image size");
1982 goto fail;
1983 }
1984
1985 if (target_size < bs_size) {
1986 target_perms |= BLK_PERM_RESIZE;
1987 }
1988
1989 target_shared_perms |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE;
1990 } else {
1991 bdrv_graph_rdlock_main_loop();
1992 if (bdrv_chain_contains(bs, bdrv_skip_filters(target))) {
1993 /*
1994 * We may want to allow this in the future, but it would
1995 * require taking some extra care.
1996 */
1997 error_setg(errp, "Cannot mirror to a filter on top of a node in "
1998 "the source's backing chain");
1999 bdrv_graph_rdunlock_main_loop();
2000 goto fail;
2001 }
2002 bdrv_graph_rdunlock_main_loop();
2003 }
2004
2005 s->target = blk_new(s->common.job.aio_context,
2006 target_perms, target_shared_perms);
2007 ret = blk_insert_bs(s->target, target, errp);
2008 if (ret < 0) {
2009 goto fail;
2010 }
2011 if (is_mirror) {
2012 /* XXX: Mirror target could be a NBD server of target QEMU in the case
2013 * of non-shared block migration. To allow migration completion, we
2014 * have to allow "inactivate" of the target BB. When that happens, we
2015 * know the job is drained, and the vcpus are stopped, so no write
2016 * operation will be performed. Block layer already has assertions to
2017 * ensure that. */
2018 blk_set_force_allow_inactivate(s->target);
2019 }
2020 blk_set_allow_aio_context_change(s->target, true);
2021 blk_set_disable_request_queuing(s->target, true);
2022
2023 bdrv_graph_rdlock_main_loop();
2024 s->replaces = g_strdup(replaces);
2025 s->on_source_error = on_source_error;
2026 s->on_target_error = on_target_error;
2027 s->sync_mode = sync_mode;
2028 s->backing_mode = backing_mode;
2029 s->target_is_zero = target_is_zero;
2030 qatomic_set(&s->copy_mode, copy_mode);
2031 s->base = base;
2032 s->base_overlay = bdrv_find_overlay(bs, base);
2033 s->granularity = granularity;
2034 s->buf_size = ROUND_UP(buf_size, granularity);
2035 s->dirty_bitmap = bs_opaque->dirty_bitmap;
2036 s->unmap = unmap;
2037 if (auto_complete) {
2038 s->should_complete = true;
2039 }
2040 bdrv_graph_rdunlock_main_loop();
2041
2042 bdrv_graph_wrlock_drained();
2043 ret = block_job_add_bdrv(&s->common, "source", bs, 0,
2044 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE |
2045 BLK_PERM_CONSISTENT_READ,
2046 errp);
2047 if (ret < 0) {
2048 bdrv_graph_wrunlock();
2049 goto fail;
2050 }
2051
2052 /* Required permissions are already taken with blk_new() */
2053 block_job_add_bdrv(&s->common, "target", target, 0, BLK_PERM_ALL,
2054 &error_abort);
2055
2056 /* In commit_active_start() all intermediate nodes disappear, so
2057 * any jobs in them must be blocked */
2058 if (target_is_backing) {
2059 BlockDriverState *iter, *filtered_target;
2060 uint64_t iter_shared_perms;
2061
2062 /*
2063 * The topmost node with
2064 * bdrv_skip_filters(filtered_target) == bdrv_skip_filters(target)
2065 */
2066 filtered_target = bdrv_cow_bs(bdrv_find_overlay(bs, target));
2067
2068 assert(bdrv_skip_filters(filtered_target) ==
2069 bdrv_skip_filters(target));
2070
2071 /*
2072 * XXX BLK_PERM_WRITE needs to be allowed so we don't block
2073 * ourselves at s->base (if writes are blocked for a node, they are
2074 * also blocked for its backing file). The other options would be a
2075 * second filter driver above s->base (== target).
2076 */
2077 iter_shared_perms = BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE;
2078
2079 for (iter = bdrv_filter_or_cow_bs(bs); iter != target;
2080 iter = bdrv_filter_or_cow_bs(iter))
2081 {
2082 if (iter == filtered_target) {
2083 /*
2084 * From here on, all nodes are filters on the base.
2085 * This allows us to share BLK_PERM_CONSISTENT_READ.
2086 */
2087 iter_shared_perms |= BLK_PERM_CONSISTENT_READ;
2088 }
2089
2090 ret = block_job_add_bdrv(&s->common, "intermediate node", iter, 0,
2091 iter_shared_perms, errp);
2092 if (ret < 0) {
2093 bdrv_graph_wrunlock();
2094 goto fail;
2095 }
2096 }
2097
2098 if (bdrv_freeze_backing_chain(mirror_top_bs, target, errp) < 0) {
2099 bdrv_graph_wrunlock();
2100 goto fail;
2101 }
2102 }
2103 bdrv_graph_wrunlock();
2104
2105 QTAILQ_INIT(&s->ops_in_flight);
2106
2107 trace_mirror_start(bs, s, opaque);
2108 job_start(&s->common.job);
2109
2110 return &s->common;
2111
2112 fail:
2113 if (s) {
2114 /* Make sure this BDS does not go away until we have completed the graph
2115 * changes below */
2116 bdrv_ref(mirror_top_bs);
2117
2118 g_free(s->replaces);
2119 blk_unref(s->target);
2120 bs_opaque->job = NULL;
2121 job_early_fail(&s->common.job);
2122 }
2123
2124 bs_opaque->stop = true;
2125 bdrv_drained_begin(bs);
2126 bdrv_graph_wrlock();
2127 assert(mirror_top_bs->backing->bs == bs);
2128 bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
2129 &error_abort);
2130 bdrv_replace_node(mirror_top_bs, bs, &error_abort);
2131 bdrv_graph_wrunlock();
2132 bdrv_drained_end(bs);
2133
2134 bdrv_release_dirty_bitmap(bs_opaque->dirty_bitmap);
2135 bdrv_unref(mirror_top_bs);
2136
2137 return NULL;
2138 }
2139
2140 void mirror_start(const char *job_id, BlockDriverState *bs,
2141 BlockDriverState *target, const char *replaces,
2142 int creation_flags, int64_t speed,
2143 uint32_t granularity, int64_t buf_size,
2144 MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
2145 bool target_is_zero,
2146 BlockdevOnError on_source_error,
2147 BlockdevOnError on_target_error,
2148 bool unmap, const char *filter_node_name,
2149 MirrorCopyMode copy_mode, Error **errp)
2150 {
2151 BlockDriverState *base;
2152
2153 GLOBAL_STATE_CODE();
2154
2155 if ((mode == MIRROR_SYNC_MODE_INCREMENTAL) ||
2156 (mode == MIRROR_SYNC_MODE_BITMAP)) {
2157 error_setg(errp, "Sync mode '%s' not supported",
2158 MirrorSyncMode_str(mode));
2159 return;
2160 }
2161
2162 bdrv_graph_rdlock_main_loop();
2163 base = mode == MIRROR_SYNC_MODE_TOP ? bdrv_backing_chain_next(bs) : NULL;
2164 bdrv_graph_rdunlock_main_loop();
2165
2166 mirror_start_job(job_id, bs, creation_flags, target, replaces,
2167 speed, granularity, buf_size, mode, backing_mode,
2168 target_is_zero, on_source_error, on_target_error, unmap,
2169 NULL, NULL, &mirror_job_driver, base, false,
2170 filter_node_name, true, copy_mode, false, errp);
2171 }
2172
2173 BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
2174 BlockDriverState *base, int creation_flags,
2175 int64_t speed, BlockdevOnError on_error,
2176 const char *filter_node_name,
2177 BlockCompletionFunc *cb, void *opaque,
2178 bool auto_complete, Error **errp)
2179 {
2180 bool base_read_only;
2181 BlockJob *job;
2182
2183 GLOBAL_STATE_CODE();
2184
2185 base_read_only = bdrv_is_read_only(base);
2186
2187 if (base_read_only) {
2188 if (bdrv_reopen_set_read_only(base, false, errp) < 0) {
2189 return NULL;
2190 }
2191 }
2192
2193 job = mirror_start_job(
2194 job_id, bs, creation_flags, base, NULL, speed, 0, 0,
2195 MIRROR_SYNC_MODE_TOP, MIRROR_LEAVE_BACKING_CHAIN, false,
2196 on_error, on_error, true, cb, opaque,
2197 &commit_active_job_driver, base, auto_complete,
2198 filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
2199 base_read_only, errp);
2200 if (!job) {
2201 goto error_restore_flags;
2202 }
2203
2204 return job;
2205
2206 error_restore_flags:
2207 /* ignore error and errp for bdrv_reopen, because we want to propagate
2208 * the original error */
2209 if (base_read_only) {
2210 bdrv_reopen_set_read_only(base, true, NULL);
2211 }
2212 return NULL;
2213 }