4 * Copyright (C) 2013 Proxmox Server Solutions
7 * Dietmar Maurer (dietmar@proxmox.com)
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
14 #include "qemu/osdep.h"
17 #include "block/block.h"
18 #include "block/block_int.h"
19 #include "block/blockjob_int.h"
20 #include "block/block_backup.h"
21 #include "qapi/error.h"
22 #include "qapi/qmp/qerror.h"
23 #include "qemu/ratelimit.h"
24 #include "qemu/cutils.h"
25 #include "sysemu/block-backend.h"
26 #include "qemu/bitmap.h"
27 #include "qemu/error-report.h"
29 #define BACKUP_CLUSTER_SIZE_DEFAULT (1 << 16)
31 typedef struct CowRequest
{
34 QLIST_ENTRY(CowRequest
) list
;
35 CoQueue wait_queue
; /* coroutines blocked on this request */
38 typedef struct BackupBlockJob
{
41 /* bitmap for sync=incremental */
42 BdrvDirtyBitmap
*sync_bitmap
;
43 MirrorSyncMode sync_mode
;
44 BlockdevOnError on_source_error
;
45 BlockdevOnError on_target_error
;
46 CoRwlock flush_rwlock
;
51 NotifierWithReturn before_write
;
52 QLIST_HEAD(, CowRequest
) inflight_reqs
;
56 int64_t copy_range_size
;
58 bool serialize_target_writes
;
61 static const BlockJobDriver backup_job_driver
;
63 /* See if in-flight requests overlap and wait for them to complete */
64 static void coroutine_fn
wait_for_overlapping_requests(BackupBlockJob
*job
,
73 QLIST_FOREACH(req
, &job
->inflight_reqs
, list
) {
74 if (end
> req
->start_byte
&& start
< req
->end_byte
) {
75 qemu_co_queue_wait(&req
->wait_queue
, NULL
);
83 /* Keep track of an in-flight request */
84 static void cow_request_begin(CowRequest
*req
, BackupBlockJob
*job
,
85 int64_t start
, int64_t end
)
87 req
->start_byte
= start
;
89 qemu_co_queue_init(&req
->wait_queue
);
90 QLIST_INSERT_HEAD(&job
->inflight_reqs
, req
, list
);
93 /* Forget about a completed request */
94 static void cow_request_end(CowRequest
*req
)
96 QLIST_REMOVE(req
, list
);
97 qemu_co_queue_restart_all(&req
->wait_queue
);
100 /* Copy range to target with a bounce buffer and return the bytes copied. If
101 * error occurred, return a negative error number */
102 static int coroutine_fn
backup_cow_with_bounce_buffer(BackupBlockJob
*job
,
105 bool is_write_notifier
,
107 void **bounce_buffer
)
111 BlockBackend
*blk
= job
->common
.blk
;
113 int read_flags
= is_write_notifier
? BDRV_REQ_NO_SERIALISING
: 0;
114 int write_flags
= job
->serialize_target_writes
? BDRV_REQ_SERIALISING
: 0;
116 hbitmap_reset(job
->copy_bitmap
, start
/ job
->cluster_size
, 1);
117 nbytes
= MIN(job
->cluster_size
, job
->len
- start
);
118 if (!*bounce_buffer
) {
119 *bounce_buffer
= blk_blockalign(blk
, job
->cluster_size
);
121 qemu_iovec_init_buf(&qiov
, *bounce_buffer
, nbytes
);
123 ret
= blk_co_preadv(blk
, start
, qiov
.size
, &qiov
, read_flags
);
125 trace_backup_do_cow_read_fail(job
, start
, ret
);
127 *error_is_read
= true;
132 if (qemu_iovec_is_zero(&qiov
)) {
133 ret
= blk_co_pwrite_zeroes(job
->target
, start
,
134 qiov
.size
, write_flags
| BDRV_REQ_MAY_UNMAP
);
136 ret
= blk_co_pwritev(job
->target
, start
,
137 qiov
.size
, &qiov
, write_flags
|
138 (job
->compress
? BDRV_REQ_WRITE_COMPRESSED
: 0));
141 trace_backup_do_cow_write_fail(job
, start
, ret
);
143 *error_is_read
= false;
150 hbitmap_set(job
->copy_bitmap
, start
/ job
->cluster_size
, 1);
155 /* Copy range to target and return the bytes copied. If error occurred, return a
156 * negative error number. */
157 static int coroutine_fn
backup_cow_with_offload(BackupBlockJob
*job
,
160 bool is_write_notifier
)
164 BlockBackend
*blk
= job
->common
.blk
;
166 int read_flags
= is_write_notifier
? BDRV_REQ_NO_SERIALISING
: 0;
167 int write_flags
= job
->serialize_target_writes
? BDRV_REQ_SERIALISING
: 0;
169 assert(QEMU_IS_ALIGNED(job
->copy_range_size
, job
->cluster_size
));
170 nbytes
= MIN(job
->copy_range_size
, end
- start
);
171 nr_clusters
= DIV_ROUND_UP(nbytes
, job
->cluster_size
);
172 hbitmap_reset(job
->copy_bitmap
, start
/ job
->cluster_size
,
174 ret
= blk_co_copy_range(blk
, start
, job
->target
, start
, nbytes
,
175 read_flags
, write_flags
);
177 trace_backup_do_cow_copy_range_fail(job
, start
, ret
);
178 hbitmap_set(job
->copy_bitmap
, start
/ job
->cluster_size
,
186 static int coroutine_fn
backup_do_cow(BackupBlockJob
*job
,
187 int64_t offset
, uint64_t bytes
,
189 bool is_write_notifier
)
191 CowRequest cow_request
;
193 int64_t start
, end
; /* bytes */
194 void *bounce_buffer
= NULL
;
196 qemu_co_rwlock_rdlock(&job
->flush_rwlock
);
198 start
= QEMU_ALIGN_DOWN(offset
, job
->cluster_size
);
199 end
= QEMU_ALIGN_UP(bytes
+ offset
, job
->cluster_size
);
201 trace_backup_do_cow_enter(job
, start
, offset
, bytes
);
203 wait_for_overlapping_requests(job
, start
, end
);
204 cow_request_begin(&cow_request
, job
, start
, end
);
206 while (start
< end
) {
207 if (!hbitmap_get(job
->copy_bitmap
, start
/ job
->cluster_size
)) {
208 trace_backup_do_cow_skip(job
, start
);
209 start
+= job
->cluster_size
;
210 continue; /* already copied */
213 trace_backup_do_cow_process(job
, start
);
215 if (job
->use_copy_range
) {
216 ret
= backup_cow_with_offload(job
, start
, end
, is_write_notifier
);
218 job
->use_copy_range
= false;
221 if (!job
->use_copy_range
) {
222 ret
= backup_cow_with_bounce_buffer(job
, start
, end
, is_write_notifier
,
223 error_is_read
, &bounce_buffer
);
229 /* Publish progress, guest I/O counts as progress too. Note that the
230 * offset field is an opaque progress value, it is not a disk offset.
233 job
->bytes_read
+= ret
;
234 job_progress_update(&job
->common
.job
, ret
);
239 qemu_vfree(bounce_buffer
);
242 cow_request_end(&cow_request
);
244 trace_backup_do_cow_return(job
, offset
, bytes
, ret
);
246 qemu_co_rwlock_unlock(&job
->flush_rwlock
);
251 static int coroutine_fn
backup_before_write_notify(
252 NotifierWithReturn
*notifier
,
255 BackupBlockJob
*job
= container_of(notifier
, BackupBlockJob
, before_write
);
256 BdrvTrackedRequest
*req
= opaque
;
258 assert(req
->bs
== blk_bs(job
->common
.blk
));
259 assert(QEMU_IS_ALIGNED(req
->offset
, BDRV_SECTOR_SIZE
));
260 assert(QEMU_IS_ALIGNED(req
->bytes
, BDRV_SECTOR_SIZE
));
262 return backup_do_cow(job
, req
->offset
, req
->bytes
, NULL
, true);
265 static void backup_cleanup_sync_bitmap(BackupBlockJob
*job
, int ret
)
268 BlockDriverState
*bs
= blk_bs(job
->common
.blk
);
271 /* Merge the successor back into the parent, delete nothing. */
272 bm
= bdrv_reclaim_dirty_bitmap(bs
, job
->sync_bitmap
, NULL
);
275 /* Everything is fine, delete this bitmap and install the backup. */
276 bm
= bdrv_dirty_bitmap_abdicate(bs
, job
->sync_bitmap
, NULL
);
281 static void backup_commit(Job
*job
)
283 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
.job
);
284 if (s
->sync_bitmap
) {
285 backup_cleanup_sync_bitmap(s
, 0);
289 static void backup_abort(Job
*job
)
291 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
.job
);
292 if (s
->sync_bitmap
) {
293 backup_cleanup_sync_bitmap(s
, -1);
297 static void backup_clean(Job
*job
)
299 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
.job
);
301 blk_unref(s
->target
);
305 static void backup_attached_aio_context(BlockJob
*job
, AioContext
*aio_context
)
307 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
309 blk_set_aio_context(s
->target
, aio_context
);
312 void backup_do_checkpoint(BlockJob
*job
, Error
**errp
)
314 BackupBlockJob
*backup_job
= container_of(job
, BackupBlockJob
, common
);
317 assert(block_job_driver(job
) == &backup_job_driver
);
319 if (backup_job
->sync_mode
!= MIRROR_SYNC_MODE_NONE
) {
320 error_setg(errp
, "The backup job only supports block checkpoint in"
325 len
= DIV_ROUND_UP(backup_job
->len
, backup_job
->cluster_size
);
326 hbitmap_set(backup_job
->copy_bitmap
, 0, len
);
329 static void backup_drain(BlockJob
*job
)
331 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
333 /* Need to keep a reference in case blk_drain triggers execution
334 * of backup_complete...
337 BlockBackend
*target
= s
->target
;
344 static BlockErrorAction
backup_error_action(BackupBlockJob
*job
,
345 bool read
, int error
)
348 return block_job_error_action(&job
->common
, job
->on_source_error
,
351 return block_job_error_action(&job
->common
, job
->on_target_error
,
356 static bool coroutine_fn
yield_and_check(BackupBlockJob
*job
)
360 if (job_is_cancelled(&job
->common
.job
)) {
364 /* We need to yield even for delay_ns = 0 so that bdrv_drain_all() can
365 * return. Without a yield, the VM would not reboot. */
366 delay_ns
= block_job_ratelimit_get_delay(&job
->common
, job
->bytes_read
);
368 job_sleep_ns(&job
->common
.job
, delay_ns
);
370 if (job_is_cancelled(&job
->common
.job
)) {
377 static int coroutine_fn
backup_run_incremental(BackupBlockJob
*job
)
384 hbitmap_iter_init(&hbi
, job
->copy_bitmap
, 0);
385 while ((cluster
= hbitmap_iter_next(&hbi
)) != -1) {
387 if (yield_and_check(job
)) {
390 ret
= backup_do_cow(job
, cluster
* job
->cluster_size
,
391 job
->cluster_size
, &error_is_read
, false);
392 if (ret
< 0 && backup_error_action(job
, error_is_read
, -ret
) ==
393 BLOCK_ERROR_ACTION_REPORT
)
403 /* init copy_bitmap from sync_bitmap */
404 static void backup_incremental_init_copy_bitmap(BackupBlockJob
*job
)
406 BdrvDirtyBitmapIter
*dbi
;
408 int64_t end
= DIV_ROUND_UP(bdrv_dirty_bitmap_size(job
->sync_bitmap
),
411 dbi
= bdrv_dirty_iter_new(job
->sync_bitmap
);
412 while ((offset
= bdrv_dirty_iter_next(dbi
)) != -1) {
413 int64_t cluster
= offset
/ job
->cluster_size
;
414 int64_t next_cluster
;
416 offset
+= bdrv_dirty_bitmap_granularity(job
->sync_bitmap
);
417 if (offset
>= bdrv_dirty_bitmap_size(job
->sync_bitmap
)) {
418 hbitmap_set(job
->copy_bitmap
, cluster
, end
- cluster
);
422 offset
= bdrv_dirty_bitmap_next_zero(job
->sync_bitmap
, offset
,
425 hbitmap_set(job
->copy_bitmap
, cluster
, end
- cluster
);
429 next_cluster
= DIV_ROUND_UP(offset
, job
->cluster_size
);
430 hbitmap_set(job
->copy_bitmap
, cluster
, next_cluster
- cluster
);
431 if (next_cluster
>= end
) {
435 bdrv_set_dirty_iter(dbi
, next_cluster
* job
->cluster_size
);
438 /* TODO job_progress_set_remaining() would make more sense */
439 job_progress_update(&job
->common
.job
,
440 job
->len
- hbitmap_count(job
->copy_bitmap
) * job
->cluster_size
);
442 bdrv_dirty_iter_free(dbi
);
445 static int coroutine_fn
backup_run(Job
*job
, Error
**errp
)
447 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
.job
);
448 BlockDriverState
*bs
= blk_bs(s
->common
.blk
);
449 int64_t offset
, nb_clusters
;
452 QLIST_INIT(&s
->inflight_reqs
);
453 qemu_co_rwlock_init(&s
->flush_rwlock
);
455 nb_clusters
= DIV_ROUND_UP(s
->len
, s
->cluster_size
);
456 job_progress_set_remaining(job
, s
->len
);
458 s
->copy_bitmap
= hbitmap_alloc(nb_clusters
, 0);
459 if (s
->sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
) {
460 backup_incremental_init_copy_bitmap(s
);
462 hbitmap_set(s
->copy_bitmap
, 0, nb_clusters
);
466 s
->before_write
.notify
= backup_before_write_notify
;
467 bdrv_add_before_write_notifier(bs
, &s
->before_write
);
469 if (s
->sync_mode
== MIRROR_SYNC_MODE_NONE
) {
470 /* All bits are set in copy_bitmap to allow any cluster to be copied.
471 * This does not actually require them to be copied. */
472 while (!job_is_cancelled(job
)) {
473 /* Yield until the job is cancelled. We just let our before_write
474 * notify callback service CoW requests. */
477 } else if (s
->sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
) {
478 ret
= backup_run_incremental(s
);
480 /* Both FULL and TOP SYNC_MODE's require copying.. */
481 for (offset
= 0; offset
< s
->len
;
482 offset
+= s
->cluster_size
) {
486 if (yield_and_check(s
)) {
490 if (s
->sync_mode
== MIRROR_SYNC_MODE_TOP
) {
494 /* Check to see if these blocks are already in the
497 for (i
= 0; i
< s
->cluster_size
;) {
498 /* bdrv_is_allocated() only returns true/false based
499 * on the first set of sectors it comes across that
500 * are are all in the same state.
501 * For that reason we must verify each sector in the
502 * backup cluster length. We end up copying more than
503 * needed but at some point that is always the case. */
505 bdrv_is_allocated(bs
, offset
+ i
,
506 s
->cluster_size
- i
, &n
);
509 if (alloced
|| n
== 0) {
514 /* If the above loop never found any sectors that are in
515 * the topmost image, skip this backup. */
520 /* FULL sync mode we copy the whole drive. */
524 ret
= backup_do_cow(s
, offset
, s
->cluster_size
,
525 &error_is_read
, false);
528 /* Depending on error action, fail now or retry cluster */
529 BlockErrorAction action
=
530 backup_error_action(s
, error_is_read
, -ret
);
531 if (action
== BLOCK_ERROR_ACTION_REPORT
) {
534 offset
-= s
->cluster_size
;
541 notifier_with_return_remove(&s
->before_write
);
543 /* wait until pending backup_do_cow() calls have completed */
544 qemu_co_rwlock_wrlock(&s
->flush_rwlock
);
545 qemu_co_rwlock_unlock(&s
->flush_rwlock
);
546 hbitmap_free(s
->copy_bitmap
);
551 static const BlockJobDriver backup_job_driver
= {
553 .instance_size
= sizeof(BackupBlockJob
),
554 .job_type
= JOB_TYPE_BACKUP
,
555 .free
= block_job_free
,
556 .user_resume
= block_job_user_resume
,
557 .drain
= block_job_drain
,
559 .commit
= backup_commit
,
560 .abort
= backup_abort
,
561 .clean
= backup_clean
,
563 .attached_aio_context
= backup_attached_aio_context
,
564 .drain
= backup_drain
,
567 BlockJob
*backup_job_create(const char *job_id
, BlockDriverState
*bs
,
568 BlockDriverState
*target
, int64_t speed
,
569 MirrorSyncMode sync_mode
, BdrvDirtyBitmap
*sync_bitmap
,
571 BlockdevOnError on_source_error
,
572 BlockdevOnError on_target_error
,
574 BlockCompletionFunc
*cb
, void *opaque
,
575 JobTxn
*txn
, Error
**errp
)
579 BackupBlockJob
*job
= NULL
;
586 error_setg(errp
, "Source and target cannot be the same");
590 if (!bdrv_is_inserted(bs
)) {
591 error_setg(errp
, "Device is not inserted: %s",
592 bdrv_get_device_name(bs
));
596 if (!bdrv_is_inserted(target
)) {
597 error_setg(errp
, "Device is not inserted: %s",
598 bdrv_get_device_name(target
));
602 if (compress
&& target
->drv
->bdrv_co_pwritev_compressed
== NULL
) {
603 error_setg(errp
, "Compression is not supported for this drive %s",
604 bdrv_get_device_name(target
));
608 if (bdrv_op_is_blocked(bs
, BLOCK_OP_TYPE_BACKUP_SOURCE
, errp
)) {
612 if (bdrv_op_is_blocked(target
, BLOCK_OP_TYPE_BACKUP_TARGET
, errp
)) {
616 if (sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
) {
618 error_setg(errp
, "must provide a valid bitmap name for "
619 "\"incremental\" sync mode");
623 /* Create a new bitmap, and freeze/disable this one. */
624 if (bdrv_dirty_bitmap_create_successor(bs
, sync_bitmap
, errp
) < 0) {
627 } else if (sync_bitmap
) {
629 "a sync_bitmap was provided to backup_run, "
630 "but received an incompatible sync_mode (%s)",
631 MirrorSyncMode_str(sync_mode
));
635 len
= bdrv_getlength(bs
);
637 error_setg_errno(errp
, -len
, "unable to get length for '%s'",
638 bdrv_get_device_name(bs
));
642 /* job->len is fixed, so we can't allow resize */
643 job
= block_job_create(job_id
, &backup_job_driver
, txn
, bs
,
644 BLK_PERM_CONSISTENT_READ
,
645 BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE
|
646 BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_GRAPH_MOD
,
647 speed
, creation_flags
, cb
, opaque
, errp
);
652 /* The target must match the source in size, so no resize here either */
653 job
->target
= blk_new(BLK_PERM_WRITE
,
654 BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE
|
655 BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_GRAPH_MOD
);
656 ret
= blk_insert_bs(job
->target
, target
, errp
);
661 job
->on_source_error
= on_source_error
;
662 job
->on_target_error
= on_target_error
;
663 job
->sync_mode
= sync_mode
;
664 job
->sync_bitmap
= sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
?
666 job
->compress
= compress
;
668 /* Detect image-fleecing (and similar) schemes */
669 job
->serialize_target_writes
= bdrv_chain_contains(target
, bs
);
671 /* If there is no backing file on the target, we cannot rely on COW if our
672 * backup cluster size is smaller than the target cluster size. Even for
673 * targets with a backing file, try to avoid COW if possible. */
674 ret
= bdrv_get_info(target
, &bdi
);
675 if (ret
== -ENOTSUP
&& !target
->backing
) {
676 /* Cluster size is not defined */
677 warn_report("The target block device doesn't provide "
678 "information about the block size and it doesn't have a "
679 "backing file. The default block size of %u bytes is "
680 "used. If the actual block size of the target exceeds "
681 "this default, the backup may be unusable",
682 BACKUP_CLUSTER_SIZE_DEFAULT
);
683 job
->cluster_size
= BACKUP_CLUSTER_SIZE_DEFAULT
;
684 } else if (ret
< 0 && !target
->backing
) {
685 error_setg_errno(errp
, -ret
,
686 "Couldn't determine the cluster size of the target image, "
687 "which has no backing file");
688 error_append_hint(errp
,
689 "Aborting, since this may create an unusable destination image\n");
691 } else if (ret
< 0 && target
->backing
) {
692 /* Not fatal; just trudge on ahead. */
693 job
->cluster_size
= BACKUP_CLUSTER_SIZE_DEFAULT
;
695 job
->cluster_size
= MAX(BACKUP_CLUSTER_SIZE_DEFAULT
, bdi
.cluster_size
);
697 job
->use_copy_range
= true;
698 job
->copy_range_size
= MIN_NON_ZERO(blk_get_max_transfer(job
->common
.blk
),
699 blk_get_max_transfer(job
->target
));
700 job
->copy_range_size
= MAX(job
->cluster_size
,
701 QEMU_ALIGN_UP(job
->copy_range_size
,
704 /* Required permissions are already taken with target's blk_new() */
705 block_job_add_bdrv(&job
->common
, "target", target
, 0, BLK_PERM_ALL
,
713 bdrv_reclaim_dirty_bitmap(bs
, sync_bitmap
, NULL
);
716 backup_clean(&job
->common
.job
);
717 job_early_fail(&job
->common
.job
);