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
{
42 BdrvDirtyBitmap
*sync_bitmap
;
43 BdrvDirtyBitmap
*copy_bitmap
;
45 MirrorSyncMode sync_mode
;
46 BitmapSyncMode bitmap_mode
;
47 BlockdevOnError on_source_error
;
48 BlockdevOnError on_target_error
;
49 CoRwlock flush_rwlock
;
53 NotifierWithReturn before_write
;
54 QLIST_HEAD(, CowRequest
) inflight_reqs
;
57 int64_t copy_range_size
;
59 BdrvRequestFlags write_flags
;
60 bool initializing_bitmap
;
63 static const BlockJobDriver backup_job_driver
;
65 /* See if in-flight requests overlap and wait for them to complete */
66 static void coroutine_fn
wait_for_overlapping_requests(BackupBlockJob
*job
,
75 QLIST_FOREACH(req
, &job
->inflight_reqs
, list
) {
76 if (end
> req
->start_byte
&& start
< req
->end_byte
) {
77 qemu_co_queue_wait(&req
->wait_queue
, NULL
);
85 /* Keep track of an in-flight request */
86 static void cow_request_begin(CowRequest
*req
, BackupBlockJob
*job
,
87 int64_t start
, int64_t end
)
89 req
->start_byte
= start
;
91 qemu_co_queue_init(&req
->wait_queue
);
92 QLIST_INSERT_HEAD(&job
->inflight_reqs
, req
, list
);
95 /* Forget about a completed request */
96 static void cow_request_end(CowRequest
*req
)
98 QLIST_REMOVE(req
, list
);
99 qemu_co_queue_restart_all(&req
->wait_queue
);
102 /* Copy range to target with a bounce buffer and return the bytes copied. If
103 * error occurred, return a negative error number */
104 static int coroutine_fn
backup_cow_with_bounce_buffer(BackupBlockJob
*job
,
107 bool is_write_notifier
,
109 void **bounce_buffer
)
112 BlockBackend
*blk
= job
->common
.blk
;
114 int read_flags
= is_write_notifier
? BDRV_REQ_NO_SERIALISING
: 0;
116 assert(QEMU_IS_ALIGNED(start
, job
->cluster_size
));
117 bdrv_reset_dirty_bitmap(job
->copy_bitmap
, start
, job
->cluster_size
);
118 nbytes
= MIN(job
->cluster_size
, job
->len
- start
);
119 if (!*bounce_buffer
) {
120 *bounce_buffer
= blk_blockalign(blk
, job
->cluster_size
);
123 ret
= blk_co_pread(blk
, start
, nbytes
, *bounce_buffer
, read_flags
);
125 trace_backup_do_cow_read_fail(job
, start
, ret
);
127 *error_is_read
= true;
132 ret
= blk_co_pwrite(job
->target
, start
, nbytes
, *bounce_buffer
,
135 trace_backup_do_cow_write_fail(job
, start
, ret
);
137 *error_is_read
= false;
144 bdrv_set_dirty_bitmap(job
->copy_bitmap
, start
, job
->cluster_size
);
149 /* Copy range to target and return the bytes copied. If error occurred, return a
150 * negative error number. */
151 static int coroutine_fn
backup_cow_with_offload(BackupBlockJob
*job
,
154 bool is_write_notifier
)
158 BlockBackend
*blk
= job
->common
.blk
;
160 int read_flags
= is_write_notifier
? BDRV_REQ_NO_SERIALISING
: 0;
162 assert(QEMU_IS_ALIGNED(job
->copy_range_size
, job
->cluster_size
));
163 assert(QEMU_IS_ALIGNED(start
, job
->cluster_size
));
164 nbytes
= MIN(job
->copy_range_size
, end
- start
);
165 nr_clusters
= DIV_ROUND_UP(nbytes
, job
->cluster_size
);
166 bdrv_reset_dirty_bitmap(job
->copy_bitmap
, start
,
167 job
->cluster_size
* nr_clusters
);
168 ret
= blk_co_copy_range(blk
, start
, job
->target
, start
, nbytes
,
169 read_flags
, job
->write_flags
);
171 trace_backup_do_cow_copy_range_fail(job
, start
, ret
);
172 bdrv_set_dirty_bitmap(job
->copy_bitmap
, start
,
173 job
->cluster_size
* nr_clusters
);
181 * Check if the cluster starting at offset is allocated or not.
182 * return via pnum the number of contiguous clusters sharing this allocation.
184 static int backup_is_cluster_allocated(BackupBlockJob
*s
, int64_t offset
,
187 BlockDriverState
*bs
= blk_bs(s
->common
.blk
);
188 int64_t count
, total_count
= 0;
189 int64_t bytes
= s
->len
- offset
;
192 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
195 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &count
);
200 total_count
+= count
;
202 if (ret
|| count
== 0) {
204 * ret: partial segment(s) are considered allocated.
205 * otherwise: unallocated tail is treated as an entire segment.
207 *pnum
= DIV_ROUND_UP(total_count
, s
->cluster_size
);
211 /* Unallocated segment(s) with uncertain following segment(s) */
212 if (total_count
>= s
->cluster_size
) {
213 *pnum
= total_count
/ s
->cluster_size
;
223 * Reset bits in copy_bitmap starting at offset if they represent unallocated
224 * data in the image. May reset subsequent contiguous bits.
225 * @return 0 when the cluster at @offset was unallocated,
226 * 1 otherwise, and -ret on error.
228 static int64_t backup_bitmap_reset_unallocated(BackupBlockJob
*s
,
229 int64_t offset
, int64_t *count
)
232 int64_t clusters
, bytes
, estimate
;
234 ret
= backup_is_cluster_allocated(s
, offset
, &clusters
);
239 bytes
= clusters
* s
->cluster_size
;
242 bdrv_reset_dirty_bitmap(s
->copy_bitmap
, offset
, bytes
);
243 estimate
= bdrv_get_dirty_count(s
->copy_bitmap
);
244 job_progress_set_remaining(&s
->common
.job
, estimate
);
251 static int coroutine_fn
backup_do_cow(BackupBlockJob
*job
,
252 int64_t offset
, uint64_t bytes
,
254 bool is_write_notifier
)
256 CowRequest cow_request
;
258 int64_t start
, end
; /* bytes */
259 void *bounce_buffer
= NULL
;
260 int64_t status_bytes
;
262 qemu_co_rwlock_rdlock(&job
->flush_rwlock
);
264 start
= QEMU_ALIGN_DOWN(offset
, job
->cluster_size
);
265 end
= QEMU_ALIGN_UP(bytes
+ offset
, job
->cluster_size
);
267 trace_backup_do_cow_enter(job
, start
, offset
, bytes
);
269 wait_for_overlapping_requests(job
, start
, end
);
270 cow_request_begin(&cow_request
, job
, start
, end
);
272 while (start
< end
) {
275 if (!bdrv_dirty_bitmap_get(job
->copy_bitmap
, start
)) {
276 trace_backup_do_cow_skip(job
, start
);
277 start
+= job
->cluster_size
;
278 continue; /* already copied */
281 dirty_end
= bdrv_dirty_bitmap_next_zero(job
->copy_bitmap
, start
,
287 if (job
->initializing_bitmap
) {
288 ret
= backup_bitmap_reset_unallocated(job
, start
, &status_bytes
);
290 trace_backup_do_cow_skip_range(job
, start
, status_bytes
);
291 start
+= status_bytes
;
294 /* Clamp to known allocated region */
295 dirty_end
= MIN(dirty_end
, start
+ status_bytes
);
298 trace_backup_do_cow_process(job
, start
);
300 if (job
->use_copy_range
) {
301 ret
= backup_cow_with_offload(job
, start
, dirty_end
,
304 job
->use_copy_range
= false;
307 if (!job
->use_copy_range
) {
308 ret
= backup_cow_with_bounce_buffer(job
, start
, dirty_end
,
310 error_is_read
, &bounce_buffer
);
316 /* Publish progress, guest I/O counts as progress too. Note that the
317 * offset field is an opaque progress value, it is not a disk offset.
320 job
->bytes_read
+= ret
;
321 job_progress_update(&job
->common
.job
, ret
);
326 qemu_vfree(bounce_buffer
);
329 cow_request_end(&cow_request
);
331 trace_backup_do_cow_return(job
, offset
, bytes
, ret
);
333 qemu_co_rwlock_unlock(&job
->flush_rwlock
);
338 static int coroutine_fn
backup_before_write_notify(
339 NotifierWithReturn
*notifier
,
342 BackupBlockJob
*job
= container_of(notifier
, BackupBlockJob
, before_write
);
343 BdrvTrackedRequest
*req
= opaque
;
345 assert(req
->bs
== blk_bs(job
->common
.blk
));
346 assert(QEMU_IS_ALIGNED(req
->offset
, BDRV_SECTOR_SIZE
));
347 assert(QEMU_IS_ALIGNED(req
->bytes
, BDRV_SECTOR_SIZE
));
349 return backup_do_cow(job
, req
->offset
, req
->bytes
, NULL
, true);
352 static void backup_cleanup_sync_bitmap(BackupBlockJob
*job
, int ret
)
355 BlockDriverState
*bs
= blk_bs(job
->common
.blk
);
356 bool sync
= (((ret
== 0) || (job
->bitmap_mode
== BITMAP_SYNC_MODE_ALWAYS
)) \
357 && (job
->bitmap_mode
!= BITMAP_SYNC_MODE_NEVER
));
361 * We succeeded, or we always intended to sync the bitmap.
362 * Delete this bitmap and install the child.
364 bm
= bdrv_dirty_bitmap_abdicate(bs
, job
->sync_bitmap
, NULL
);
367 * We failed, or we never intended to sync the bitmap anyway.
368 * Merge the successor back into the parent, keeping all data.
370 bm
= bdrv_reclaim_dirty_bitmap(bs
, job
->sync_bitmap
, NULL
);
375 if (ret
< 0 && job
->bitmap_mode
== BITMAP_SYNC_MODE_ALWAYS
) {
376 /* If we failed and synced, merge in the bits we didn't copy: */
377 bdrv_dirty_bitmap_merge_internal(bm
, job
->copy_bitmap
,
382 static void backup_commit(Job
*job
)
384 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
.job
);
385 if (s
->sync_bitmap
) {
386 backup_cleanup_sync_bitmap(s
, 0);
390 static void backup_abort(Job
*job
)
392 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
.job
);
393 if (s
->sync_bitmap
) {
394 backup_cleanup_sync_bitmap(s
, -1);
398 static void backup_clean(Job
*job
)
400 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
.job
);
401 BlockDriverState
*bs
= blk_bs(s
->common
.blk
);
403 if (s
->copy_bitmap
) {
404 bdrv_release_dirty_bitmap(bs
, s
->copy_bitmap
);
405 s
->copy_bitmap
= NULL
;
409 blk_unref(s
->target
);
413 void backup_do_checkpoint(BlockJob
*job
, Error
**errp
)
415 BackupBlockJob
*backup_job
= container_of(job
, BackupBlockJob
, common
);
417 assert(block_job_driver(job
) == &backup_job_driver
);
419 if (backup_job
->sync_mode
!= MIRROR_SYNC_MODE_NONE
) {
420 error_setg(errp
, "The backup job only supports block checkpoint in"
425 bdrv_set_dirty_bitmap(backup_job
->copy_bitmap
, 0, backup_job
->len
);
428 static BlockErrorAction
backup_error_action(BackupBlockJob
*job
,
429 bool read
, int error
)
432 return block_job_error_action(&job
->common
, job
->on_source_error
,
435 return block_job_error_action(&job
->common
, job
->on_target_error
,
440 static bool coroutine_fn
yield_and_check(BackupBlockJob
*job
)
444 if (job_is_cancelled(&job
->common
.job
)) {
448 /* We need to yield even for delay_ns = 0 so that bdrv_drain_all() can
449 * return. Without a yield, the VM would not reboot. */
450 delay_ns
= block_job_ratelimit_get_delay(&job
->common
, job
->bytes_read
);
452 job_sleep_ns(&job
->common
.job
, delay_ns
);
454 if (job_is_cancelled(&job
->common
.job
)) {
461 static int coroutine_fn
backup_loop(BackupBlockJob
*job
)
465 BdrvDirtyBitmapIter
*bdbi
;
468 bdbi
= bdrv_dirty_iter_new(job
->copy_bitmap
);
469 while ((offset
= bdrv_dirty_iter_next(bdbi
)) != -1) {
471 if (yield_and_check(job
)) {
474 ret
= backup_do_cow(job
, offset
,
475 job
->cluster_size
, &error_is_read
, false);
476 if (ret
< 0 && backup_error_action(job
, error_is_read
, -ret
) ==
477 BLOCK_ERROR_ACTION_REPORT
)
485 bdrv_dirty_iter_free(bdbi
);
489 static void backup_init_copy_bitmap(BackupBlockJob
*job
)
494 if (job
->sync_mode
== MIRROR_SYNC_MODE_BITMAP
) {
495 ret
= bdrv_dirty_bitmap_merge_internal(job
->copy_bitmap
,
500 if (job
->sync_mode
== MIRROR_SYNC_MODE_TOP
) {
502 * We can't hog the coroutine to initialize this thoroughly.
503 * Set a flag and resume work when we are able to yield safely.
505 job
->initializing_bitmap
= true;
507 bdrv_set_dirty_bitmap(job
->copy_bitmap
, 0, job
->len
);
510 estimate
= bdrv_get_dirty_count(job
->copy_bitmap
);
511 job_progress_set_remaining(&job
->common
.job
, estimate
);
514 static int coroutine_fn
backup_run(Job
*job
, Error
**errp
)
516 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
.job
);
517 BlockDriverState
*bs
= blk_bs(s
->common
.blk
);
520 QLIST_INIT(&s
->inflight_reqs
);
521 qemu_co_rwlock_init(&s
->flush_rwlock
);
523 backup_init_copy_bitmap(s
);
525 s
->before_write
.notify
= backup_before_write_notify
;
526 bdrv_add_before_write_notifier(bs
, &s
->before_write
);
528 if (s
->sync_mode
== MIRROR_SYNC_MODE_TOP
) {
532 for (offset
= 0; offset
< s
->len
; ) {
533 if (yield_and_check(s
)) {
538 ret
= backup_bitmap_reset_unallocated(s
, offset
, &count
);
545 s
->initializing_bitmap
= false;
548 if (s
->sync_mode
== MIRROR_SYNC_MODE_NONE
) {
549 /* All bits are set in copy_bitmap to allow any cluster to be copied.
550 * This does not actually require them to be copied. */
551 while (!job_is_cancelled(job
)) {
552 /* Yield until the job is cancelled. We just let our before_write
553 * notify callback service CoW requests. */
557 ret
= backup_loop(s
);
561 notifier_with_return_remove(&s
->before_write
);
563 /* wait until pending backup_do_cow() calls have completed */
564 qemu_co_rwlock_wrlock(&s
->flush_rwlock
);
565 qemu_co_rwlock_unlock(&s
->flush_rwlock
);
570 static const BlockJobDriver backup_job_driver
= {
572 .instance_size
= sizeof(BackupBlockJob
),
573 .job_type
= JOB_TYPE_BACKUP
,
574 .free
= block_job_free
,
575 .user_resume
= block_job_user_resume
,
577 .commit
= backup_commit
,
578 .abort
= backup_abort
,
579 .clean
= backup_clean
,
583 static int64_t backup_calculate_cluster_size(BlockDriverState
*target
,
590 * If there is no backing file on the target, we cannot rely on COW if our
591 * backup cluster size is smaller than the target cluster size. Even for
592 * targets with a backing file, try to avoid COW if possible.
594 ret
= bdrv_get_info(target
, &bdi
);
595 if (ret
== -ENOTSUP
&& !target
->backing
) {
596 /* Cluster size is not defined */
597 warn_report("The target block device doesn't provide "
598 "information about the block size and it doesn't have a "
599 "backing file. The default block size of %u bytes is "
600 "used. If the actual block size of the target exceeds "
601 "this default, the backup may be unusable",
602 BACKUP_CLUSTER_SIZE_DEFAULT
);
603 return BACKUP_CLUSTER_SIZE_DEFAULT
;
604 } else if (ret
< 0 && !target
->backing
) {
605 error_setg_errno(errp
, -ret
,
606 "Couldn't determine the cluster size of the target image, "
607 "which has no backing file");
608 error_append_hint(errp
,
609 "Aborting, since this may create an unusable destination image\n");
611 } else if (ret
< 0 && target
->backing
) {
612 /* Not fatal; just trudge on ahead. */
613 return BACKUP_CLUSTER_SIZE_DEFAULT
;
616 return MAX(BACKUP_CLUSTER_SIZE_DEFAULT
, bdi
.cluster_size
);
619 BlockJob
*backup_job_create(const char *job_id
, BlockDriverState
*bs
,
620 BlockDriverState
*target
, int64_t speed
,
621 MirrorSyncMode sync_mode
, BdrvDirtyBitmap
*sync_bitmap
,
622 BitmapSyncMode bitmap_mode
,
624 BlockdevOnError on_source_error
,
625 BlockdevOnError on_target_error
,
627 BlockCompletionFunc
*cb
, void *opaque
,
628 JobTxn
*txn
, Error
**errp
)
631 BackupBlockJob
*job
= NULL
;
633 int64_t cluster_size
;
634 BdrvDirtyBitmap
*copy_bitmap
= NULL
;
639 /* QMP interface protects us from these cases */
640 assert(sync_mode
!= MIRROR_SYNC_MODE_INCREMENTAL
);
641 assert(sync_bitmap
|| sync_mode
!= MIRROR_SYNC_MODE_BITMAP
);
644 error_setg(errp
, "Source and target cannot be the same");
648 if (!bdrv_is_inserted(bs
)) {
649 error_setg(errp
, "Device is not inserted: %s",
650 bdrv_get_device_name(bs
));
654 if (!bdrv_is_inserted(target
)) {
655 error_setg(errp
, "Device is not inserted: %s",
656 bdrv_get_device_name(target
));
660 if (compress
&& !block_driver_can_compress(target
->drv
)) {
661 error_setg(errp
, "Compression is not supported for this drive %s",
662 bdrv_get_device_name(target
));
666 if (bdrv_op_is_blocked(bs
, BLOCK_OP_TYPE_BACKUP_SOURCE
, errp
)) {
670 if (bdrv_op_is_blocked(target
, BLOCK_OP_TYPE_BACKUP_TARGET
, errp
)) {
675 /* If we need to write to this bitmap, check that we can: */
676 if (bitmap_mode
!= BITMAP_SYNC_MODE_NEVER
&&
677 bdrv_dirty_bitmap_check(sync_bitmap
, BDRV_BITMAP_DEFAULT
, errp
)) {
681 /* Create a new bitmap, and freeze/disable this one. */
682 if (bdrv_dirty_bitmap_create_successor(bs
, sync_bitmap
, errp
) < 0) {
687 len
= bdrv_getlength(bs
);
689 error_setg_errno(errp
, -len
, "unable to get length for '%s'",
690 bdrv_get_device_name(bs
));
694 cluster_size
= backup_calculate_cluster_size(target
, errp
);
695 if (cluster_size
< 0) {
699 copy_bitmap
= bdrv_create_dirty_bitmap(bs
, cluster_size
, NULL
, errp
);
703 bdrv_disable_dirty_bitmap(copy_bitmap
);
705 /* job->len is fixed, so we can't allow resize */
706 job
= block_job_create(job_id
, &backup_job_driver
, txn
, bs
,
707 BLK_PERM_CONSISTENT_READ
,
708 BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE
|
709 BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_GRAPH_MOD
,
710 speed
, creation_flags
, cb
, opaque
, errp
);
715 /* The target must match the source in size, so no resize here either */
716 job
->target
= blk_new(job
->common
.job
.aio_context
,
718 BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE
|
719 BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_GRAPH_MOD
);
720 ret
= blk_insert_bs(job
->target
, target
, errp
);
724 blk_set_disable_request_queuing(job
->target
, true);
726 job
->on_source_error
= on_source_error
;
727 job
->on_target_error
= on_target_error
;
728 job
->sync_mode
= sync_mode
;
729 job
->sync_bitmap
= sync_bitmap
;
730 job
->bitmap_mode
= bitmap_mode
;
734 * 1. Detect image-fleecing (and similar) schemes
735 * 2. Handle compression
738 (bdrv_chain_contains(target
, bs
) ? BDRV_REQ_SERIALISING
: 0) |
739 (compress
? BDRV_REQ_WRITE_COMPRESSED
: 0);
741 job
->cluster_size
= cluster_size
;
742 job
->copy_bitmap
= copy_bitmap
;
744 job
->use_copy_range
= !compress
; /* compression isn't supported for it */
745 job
->copy_range_size
= MIN_NON_ZERO(blk_get_max_transfer(job
->common
.blk
),
746 blk_get_max_transfer(job
->target
));
747 job
->copy_range_size
= MAX(job
->cluster_size
,
748 QEMU_ALIGN_UP(job
->copy_range_size
,
751 /* Required permissions are already taken with target's blk_new() */
752 block_job_add_bdrv(&job
->common
, "target", target
, 0, BLK_PERM_ALL
,
760 assert(!job
|| !job
->copy_bitmap
);
761 bdrv_release_dirty_bitmap(bs
, copy_bitmap
);
764 bdrv_reclaim_dirty_bitmap(bs
, sync_bitmap
, NULL
);
767 backup_clean(&job
->common
.job
);
768 job_early_fail(&job
->common
.job
);