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"
28 #define BACKUP_CLUSTER_SIZE_DEFAULT (1 << 16)
29 #define SLICE_TIME 100000000ULL /* ns */
31 typedef struct BackupBlockJob
{
34 /* bitmap for sync=incremental */
35 BdrvDirtyBitmap
*sync_bitmap
;
36 MirrorSyncMode sync_mode
;
38 BlockdevOnError on_source_error
;
39 BlockdevOnError on_target_error
;
40 CoRwlock flush_rwlock
;
41 uint64_t sectors_read
;
42 unsigned long *done_bitmap
;
45 NotifierWithReturn before_write
;
46 QLIST_HEAD(, CowRequest
) inflight_reqs
;
49 /* Size of a cluster in sectors, instead of bytes. */
50 static inline int64_t cluster_size_sectors(BackupBlockJob
*job
)
52 return job
->cluster_size
/ BDRV_SECTOR_SIZE
;
55 /* See if in-flight requests overlap and wait for them to complete */
56 static void coroutine_fn
wait_for_overlapping_requests(BackupBlockJob
*job
,
65 QLIST_FOREACH(req
, &job
->inflight_reqs
, list
) {
66 if (end
> req
->start
&& start
< req
->end
) {
67 qemu_co_queue_wait(&req
->wait_queue
, NULL
);
75 /* Keep track of an in-flight request */
76 static void cow_request_begin(CowRequest
*req
, BackupBlockJob
*job
,
77 int64_t start
, int64_t end
)
81 qemu_co_queue_init(&req
->wait_queue
);
82 QLIST_INSERT_HEAD(&job
->inflight_reqs
, req
, list
);
85 /* Forget about a completed request */
86 static void cow_request_end(CowRequest
*req
)
88 QLIST_REMOVE(req
, list
);
89 qemu_co_queue_restart_all(&req
->wait_queue
);
92 static int coroutine_fn
backup_do_cow(BackupBlockJob
*job
,
93 int64_t sector_num
, int nb_sectors
,
95 bool is_write_notifier
)
97 BlockBackend
*blk
= job
->common
.blk
;
98 CowRequest cow_request
;
100 QEMUIOVector bounce_qiov
;
101 void *bounce_buffer
= NULL
;
103 int64_t sectors_per_cluster
= cluster_size_sectors(job
);
107 qemu_co_rwlock_rdlock(&job
->flush_rwlock
);
109 start
= sector_num
/ sectors_per_cluster
;
110 end
= DIV_ROUND_UP(sector_num
+ nb_sectors
, sectors_per_cluster
);
112 trace_backup_do_cow_enter(job
, start
, sector_num
, nb_sectors
);
114 wait_for_overlapping_requests(job
, start
, end
);
115 cow_request_begin(&cow_request
, job
, start
, end
);
117 for (; start
< end
; start
++) {
118 if (test_bit(start
, job
->done_bitmap
)) {
119 trace_backup_do_cow_skip(job
, start
);
120 continue; /* already copied */
123 trace_backup_do_cow_process(job
, start
);
125 n
= MIN(sectors_per_cluster
,
126 job
->common
.len
/ BDRV_SECTOR_SIZE
-
127 start
* sectors_per_cluster
);
129 if (!bounce_buffer
) {
130 bounce_buffer
= blk_blockalign(blk
, job
->cluster_size
);
132 iov
.iov_base
= bounce_buffer
;
133 iov
.iov_len
= n
* BDRV_SECTOR_SIZE
;
134 qemu_iovec_init_external(&bounce_qiov
, &iov
, 1);
136 ret
= blk_co_preadv(blk
, start
* job
->cluster_size
,
137 bounce_qiov
.size
, &bounce_qiov
,
138 is_write_notifier
? BDRV_REQ_NO_SERIALISING
: 0);
140 trace_backup_do_cow_read_fail(job
, start
, ret
);
142 *error_is_read
= true;
147 if (buffer_is_zero(iov
.iov_base
, iov
.iov_len
)) {
148 ret
= blk_co_pwrite_zeroes(job
->target
, start
* job
->cluster_size
,
149 bounce_qiov
.size
, BDRV_REQ_MAY_UNMAP
);
151 ret
= blk_co_pwritev(job
->target
, start
* job
->cluster_size
,
152 bounce_qiov
.size
, &bounce_qiov
,
153 job
->compress
? BDRV_REQ_WRITE_COMPRESSED
: 0);
156 trace_backup_do_cow_write_fail(job
, start
, ret
);
158 *error_is_read
= false;
163 set_bit(start
, job
->done_bitmap
);
165 /* Publish progress, guest I/O counts as progress too. Note that the
166 * offset field is an opaque progress value, it is not a disk offset.
168 job
->sectors_read
+= n
;
169 job
->common
.offset
+= n
* BDRV_SECTOR_SIZE
;
174 qemu_vfree(bounce_buffer
);
177 cow_request_end(&cow_request
);
179 trace_backup_do_cow_return(job
, sector_num
, nb_sectors
, ret
);
181 qemu_co_rwlock_unlock(&job
->flush_rwlock
);
186 static int coroutine_fn
backup_before_write_notify(
187 NotifierWithReturn
*notifier
,
190 BackupBlockJob
*job
= container_of(notifier
, BackupBlockJob
, before_write
);
191 BdrvTrackedRequest
*req
= opaque
;
192 int64_t sector_num
= req
->offset
>> BDRV_SECTOR_BITS
;
193 int nb_sectors
= req
->bytes
>> BDRV_SECTOR_BITS
;
195 assert(req
->bs
== blk_bs(job
->common
.blk
));
196 assert((req
->offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
197 assert((req
->bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
199 return backup_do_cow(job
, sector_num
, nb_sectors
, NULL
, true);
202 static void backup_set_speed(BlockJob
*job
, int64_t speed
, Error
**errp
)
204 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
207 error_setg(errp
, QERR_INVALID_PARAMETER
, "speed");
210 ratelimit_set_speed(&s
->limit
, speed
/ BDRV_SECTOR_SIZE
, SLICE_TIME
);
213 static void backup_cleanup_sync_bitmap(BackupBlockJob
*job
, int ret
)
216 BlockDriverState
*bs
= blk_bs(job
->common
.blk
);
218 if (ret
< 0 || block_job_is_cancelled(&job
->common
)) {
219 /* Merge the successor back into the parent, delete nothing. */
220 bm
= bdrv_reclaim_dirty_bitmap(bs
, job
->sync_bitmap
, NULL
);
223 /* Everything is fine, delete this bitmap and install the backup. */
224 bm
= bdrv_dirty_bitmap_abdicate(bs
, job
->sync_bitmap
, NULL
);
229 static void backup_commit(BlockJob
*job
)
231 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
232 if (s
->sync_bitmap
) {
233 backup_cleanup_sync_bitmap(s
, 0);
237 static void backup_abort(BlockJob
*job
)
239 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
240 if (s
->sync_bitmap
) {
241 backup_cleanup_sync_bitmap(s
, -1);
245 static void backup_clean(BlockJob
*job
)
247 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
249 blk_unref(s
->target
);
253 static void backup_attached_aio_context(BlockJob
*job
, AioContext
*aio_context
)
255 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
257 blk_set_aio_context(s
->target
, aio_context
);
260 void backup_do_checkpoint(BlockJob
*job
, Error
**errp
)
262 BackupBlockJob
*backup_job
= container_of(job
, BackupBlockJob
, common
);
265 assert(job
->driver
->job_type
== BLOCK_JOB_TYPE_BACKUP
);
267 if (backup_job
->sync_mode
!= MIRROR_SYNC_MODE_NONE
) {
268 error_setg(errp
, "The backup job only supports block checkpoint in"
273 len
= DIV_ROUND_UP(backup_job
->common
.len
, backup_job
->cluster_size
);
274 bitmap_zero(backup_job
->done_bitmap
, len
);
277 void backup_wait_for_overlapping_requests(BlockJob
*job
, int64_t sector_num
,
280 BackupBlockJob
*backup_job
= container_of(job
, BackupBlockJob
, common
);
281 int64_t sectors_per_cluster
= cluster_size_sectors(backup_job
);
284 assert(job
->driver
->job_type
== BLOCK_JOB_TYPE_BACKUP
);
286 start
= sector_num
/ sectors_per_cluster
;
287 end
= DIV_ROUND_UP(sector_num
+ nb_sectors
, sectors_per_cluster
);
288 wait_for_overlapping_requests(backup_job
, start
, end
);
291 void backup_cow_request_begin(CowRequest
*req
, BlockJob
*job
,
295 BackupBlockJob
*backup_job
= container_of(job
, BackupBlockJob
, common
);
296 int64_t sectors_per_cluster
= cluster_size_sectors(backup_job
);
299 assert(job
->driver
->job_type
== BLOCK_JOB_TYPE_BACKUP
);
301 start
= sector_num
/ sectors_per_cluster
;
302 end
= DIV_ROUND_UP(sector_num
+ nb_sectors
, sectors_per_cluster
);
303 cow_request_begin(req
, backup_job
, start
, end
);
306 void backup_cow_request_end(CowRequest
*req
)
308 cow_request_end(req
);
311 static void backup_drain(BlockJob
*job
)
313 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
315 /* Need to keep a reference in case blk_drain triggers execution
316 * of backup_complete...
319 BlockBackend
*target
= s
->target
;
326 static BlockErrorAction
backup_error_action(BackupBlockJob
*job
,
327 bool read
, int error
)
330 return block_job_error_action(&job
->common
, job
->on_source_error
,
333 return block_job_error_action(&job
->common
, job
->on_target_error
,
340 } BackupCompleteData
;
342 static void backup_complete(BlockJob
*job
, void *opaque
)
344 BackupCompleteData
*data
= opaque
;
346 block_job_completed(job
, data
->ret
);
350 static bool coroutine_fn
yield_and_check(BackupBlockJob
*job
)
352 if (block_job_is_cancelled(&job
->common
)) {
356 /* we need to yield so that bdrv_drain_all() returns.
357 * (without, VM does not reboot)
359 if (job
->common
.speed
) {
360 uint64_t delay_ns
= ratelimit_calculate_delay(&job
->limit
,
362 job
->sectors_read
= 0;
363 block_job_sleep_ns(&job
->common
, QEMU_CLOCK_REALTIME
, delay_ns
);
365 block_job_sleep_ns(&job
->common
, QEMU_CLOCK_REALTIME
, 0);
368 if (block_job_is_cancelled(&job
->common
)) {
375 static int coroutine_fn
backup_run_incremental(BackupBlockJob
*job
)
379 int clusters_per_iter
;
380 uint32_t granularity
;
384 int64_t last_cluster
= -1;
385 int64_t sectors_per_cluster
= cluster_size_sectors(job
);
386 BdrvDirtyBitmapIter
*dbi
;
388 granularity
= bdrv_dirty_bitmap_granularity(job
->sync_bitmap
);
389 clusters_per_iter
= MAX((granularity
/ job
->cluster_size
), 1);
390 dbi
= bdrv_dirty_iter_new(job
->sync_bitmap
, 0);
392 /* Find the next dirty sector(s) */
393 while ((sector
= bdrv_dirty_iter_next(dbi
)) != -1) {
394 cluster
= sector
/ sectors_per_cluster
;
396 /* Fake progress updates for any clusters we skipped */
397 if (cluster
!= last_cluster
+ 1) {
398 job
->common
.offset
+= ((cluster
- last_cluster
- 1) *
402 for (end
= cluster
+ clusters_per_iter
; cluster
< end
; cluster
++) {
404 if (yield_and_check(job
)) {
407 ret
= backup_do_cow(job
, cluster
* sectors_per_cluster
,
408 sectors_per_cluster
, &error_is_read
,
411 backup_error_action(job
, error_is_read
, -ret
) ==
412 BLOCK_ERROR_ACTION_REPORT
) {
418 /* If the bitmap granularity is smaller than the backup granularity,
419 * we need to advance the iterator pointer to the next cluster. */
420 if (granularity
< job
->cluster_size
) {
421 bdrv_set_dirty_iter(dbi
, cluster
* sectors_per_cluster
);
424 last_cluster
= cluster
- 1;
427 /* Play some final catchup with the progress meter */
428 end
= DIV_ROUND_UP(job
->common
.len
, job
->cluster_size
);
429 if (last_cluster
+ 1 < end
) {
430 job
->common
.offset
+= ((end
- last_cluster
- 1) * job
->cluster_size
);
434 bdrv_dirty_iter_free(dbi
);
438 static void coroutine_fn
backup_run(void *opaque
)
440 BackupBlockJob
*job
= opaque
;
441 BackupCompleteData
*data
;
442 BlockDriverState
*bs
= blk_bs(job
->common
.blk
);
444 int64_t sectors_per_cluster
= cluster_size_sectors(job
);
447 QLIST_INIT(&job
->inflight_reqs
);
448 qemu_co_rwlock_init(&job
->flush_rwlock
);
451 end
= DIV_ROUND_UP(job
->common
.len
, job
->cluster_size
);
453 job
->done_bitmap
= bitmap_new(end
);
455 job
->before_write
.notify
= backup_before_write_notify
;
456 bdrv_add_before_write_notifier(bs
, &job
->before_write
);
458 if (job
->sync_mode
== MIRROR_SYNC_MODE_NONE
) {
459 while (!block_job_is_cancelled(&job
->common
)) {
460 /* Yield until the job is cancelled. We just let our before_write
461 * notify callback service CoW requests. */
462 block_job_yield(&job
->common
);
464 } else if (job
->sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
) {
465 ret
= backup_run_incremental(job
);
467 /* Both FULL and TOP SYNC_MODE's require copying.. */
468 for (; start
< end
; start
++) {
470 if (yield_and_check(job
)) {
474 if (job
->sync_mode
== MIRROR_SYNC_MODE_TOP
) {
478 /* Check to see if these blocks are already in the
481 for (i
= 0; i
< sectors_per_cluster
;) {
482 /* bdrv_is_allocated() only returns true/false based
483 * on the first set of sectors it comes across that
484 * are are all in the same state.
485 * For that reason we must verify each sector in the
486 * backup cluster length. We end up copying more than
487 * needed but at some point that is always the case. */
489 bdrv_is_allocated(bs
,
490 start
* sectors_per_cluster
+ i
,
491 sectors_per_cluster
- i
, &n
);
494 if (alloced
== 1 || n
== 0) {
499 /* If the above loop never found any sectors that are in
500 * the topmost image, skip this backup. */
505 /* FULL sync mode we copy the whole drive. */
506 ret
= backup_do_cow(job
, start
* sectors_per_cluster
,
507 sectors_per_cluster
, &error_is_read
, false);
509 /* Depending on error action, fail now or retry cluster */
510 BlockErrorAction action
=
511 backup_error_action(job
, error_is_read
, -ret
);
512 if (action
== BLOCK_ERROR_ACTION_REPORT
) {
522 notifier_with_return_remove(&job
->before_write
);
524 /* wait until pending backup_do_cow() calls have completed */
525 qemu_co_rwlock_wrlock(&job
->flush_rwlock
);
526 qemu_co_rwlock_unlock(&job
->flush_rwlock
);
527 g_free(job
->done_bitmap
);
529 data
= g_malloc(sizeof(*data
));
531 block_job_defer_to_main_loop(&job
->common
, backup_complete
, data
);
534 static const BlockJobDriver backup_job_driver
= {
535 .instance_size
= sizeof(BackupBlockJob
),
536 .job_type
= BLOCK_JOB_TYPE_BACKUP
,
538 .set_speed
= backup_set_speed
,
539 .commit
= backup_commit
,
540 .abort
= backup_abort
,
541 .clean
= backup_clean
,
542 .attached_aio_context
= backup_attached_aio_context
,
543 .drain
= backup_drain
,
546 BlockJob
*backup_job_create(const char *job_id
, BlockDriverState
*bs
,
547 BlockDriverState
*target
, int64_t speed
,
548 MirrorSyncMode sync_mode
, BdrvDirtyBitmap
*sync_bitmap
,
550 BlockdevOnError on_source_error
,
551 BlockdevOnError on_target_error
,
553 BlockCompletionFunc
*cb
, void *opaque
,
554 BlockJobTxn
*txn
, Error
**errp
)
558 BackupBlockJob
*job
= NULL
;
565 error_setg(errp
, "Source and target cannot be the same");
569 if (!bdrv_is_inserted(bs
)) {
570 error_setg(errp
, "Device is not inserted: %s",
571 bdrv_get_device_name(bs
));
575 if (!bdrv_is_inserted(target
)) {
576 error_setg(errp
, "Device is not inserted: %s",
577 bdrv_get_device_name(target
));
581 if (compress
&& target
->drv
->bdrv_co_pwritev_compressed
== NULL
) {
582 error_setg(errp
, "Compression is not supported for this drive %s",
583 bdrv_get_device_name(target
));
587 if (bdrv_op_is_blocked(bs
, BLOCK_OP_TYPE_BACKUP_SOURCE
, errp
)) {
591 if (bdrv_op_is_blocked(target
, BLOCK_OP_TYPE_BACKUP_TARGET
, errp
)) {
595 if (sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
) {
597 error_setg(errp
, "must provide a valid bitmap name for "
598 "\"incremental\" sync mode");
602 /* Create a new bitmap, and freeze/disable this one. */
603 if (bdrv_dirty_bitmap_create_successor(bs
, sync_bitmap
, errp
) < 0) {
606 } else if (sync_bitmap
) {
608 "a sync_bitmap was provided to backup_run, "
609 "but received an incompatible sync_mode (%s)",
610 MirrorSyncMode_lookup
[sync_mode
]);
614 len
= bdrv_getlength(bs
);
616 error_setg_errno(errp
, -len
, "unable to get length for '%s'",
617 bdrv_get_device_name(bs
));
621 /* FIXME Use real permissions */
622 job
= block_job_create(job_id
, &backup_job_driver
, bs
, 0, BLK_PERM_ALL
,
623 speed
, creation_flags
, cb
, opaque
, errp
);
628 /* FIXME Use real permissions */
629 job
->target
= blk_new(0, BLK_PERM_ALL
);
630 ret
= blk_insert_bs(job
->target
, target
, errp
);
635 job
->on_source_error
= on_source_error
;
636 job
->on_target_error
= on_target_error
;
637 job
->sync_mode
= sync_mode
;
638 job
->sync_bitmap
= sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
?
640 job
->compress
= compress
;
642 /* If there is no backing file on the target, we cannot rely on COW if our
643 * backup cluster size is smaller than the target cluster size. Even for
644 * targets with a backing file, try to avoid COW if possible. */
645 ret
= bdrv_get_info(target
, &bdi
);
646 if (ret
< 0 && !target
->backing
) {
647 error_setg_errno(errp
, -ret
,
648 "Couldn't determine the cluster size of the target image, "
649 "which has no backing file");
650 error_append_hint(errp
,
651 "Aborting, since this may create an unusable destination image\n");
653 } else if (ret
< 0 && target
->backing
) {
654 /* Not fatal; just trudge on ahead. */
655 job
->cluster_size
= BACKUP_CLUSTER_SIZE_DEFAULT
;
657 job
->cluster_size
= MAX(BACKUP_CLUSTER_SIZE_DEFAULT
, bdi
.cluster_size
);
660 /* FIXME Use real permissions */
661 block_job_add_bdrv(&job
->common
, "target", target
, 0, BLK_PERM_ALL
,
663 job
->common
.len
= len
;
664 block_job_txn_add_job(txn
, &job
->common
);
670 bdrv_reclaim_dirty_bitmap(bs
, sync_bitmap
, NULL
);
673 backup_clean(&job
->common
);
674 block_job_unref(&job
->common
);