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.h"
20 #include "qapi/qmp/qerror.h"
21 #include "qemu/ratelimit.h"
22 #include "sysemu/block-backend.h"
24 #define BACKUP_CLUSTER_SIZE_DEFAULT (1 << 16)
25 #define SLICE_TIME 100000000ULL /* ns */
27 typedef struct CowRequest
{
30 QLIST_ENTRY(CowRequest
) list
;
31 CoQueue wait_queue
; /* coroutines blocked on this request */
34 typedef struct BackupBlockJob
{
36 BlockDriverState
*target
;
37 /* bitmap for sync=incremental */
38 BdrvDirtyBitmap
*sync_bitmap
;
39 MirrorSyncMode sync_mode
;
41 BlockdevOnError on_source_error
;
42 BlockdevOnError on_target_error
;
43 CoRwlock flush_rwlock
;
44 uint64_t sectors_read
;
47 QLIST_HEAD(, CowRequest
) inflight_reqs
;
50 /* Size of a cluster in sectors, instead of bytes. */
51 static inline int64_t cluster_size_sectors(BackupBlockJob
*job
)
53 return job
->cluster_size
/ BDRV_SECTOR_SIZE
;
56 /* See if in-flight requests overlap and wait for them to complete */
57 static void coroutine_fn
wait_for_overlapping_requests(BackupBlockJob
*job
,
66 QLIST_FOREACH(req
, &job
->inflight_reqs
, list
) {
67 if (end
> req
->start
&& start
< req
->end
) {
68 qemu_co_queue_wait(&req
->wait_queue
);
76 /* Keep track of an in-flight request */
77 static void cow_request_begin(CowRequest
*req
, BackupBlockJob
*job
,
78 int64_t start
, int64_t end
)
82 qemu_co_queue_init(&req
->wait_queue
);
83 QLIST_INSERT_HEAD(&job
->inflight_reqs
, req
, list
);
86 /* Forget about a completed request */
87 static void cow_request_end(CowRequest
*req
)
89 QLIST_REMOVE(req
, list
);
90 qemu_co_queue_restart_all(&req
->wait_queue
);
93 static int coroutine_fn
backup_do_cow(BlockDriverState
*bs
,
94 int64_t sector_num
, int nb_sectors
,
96 bool is_write_notifier
)
98 BackupBlockJob
*job
= (BackupBlockJob
*)bs
->job
;
99 CowRequest cow_request
;
101 QEMUIOVector bounce_qiov
;
102 void *bounce_buffer
= NULL
;
104 int64_t sectors_per_cluster
= cluster_size_sectors(job
);
108 qemu_co_rwlock_rdlock(&job
->flush_rwlock
);
110 start
= sector_num
/ sectors_per_cluster
;
111 end
= DIV_ROUND_UP(sector_num
+ nb_sectors
, sectors_per_cluster
);
113 trace_backup_do_cow_enter(job
, start
, sector_num
, nb_sectors
);
115 wait_for_overlapping_requests(job
, start
, end
);
116 cow_request_begin(&cow_request
, job
, start
, end
);
118 for (; start
< end
; start
++) {
119 if (hbitmap_get(job
->bitmap
, start
)) {
120 trace_backup_do_cow_skip(job
, start
);
121 continue; /* already copied */
124 trace_backup_do_cow_process(job
, start
);
126 n
= MIN(sectors_per_cluster
,
127 job
->common
.len
/ BDRV_SECTOR_SIZE
-
128 start
* sectors_per_cluster
);
130 if (!bounce_buffer
) {
131 bounce_buffer
= qemu_blockalign(bs
, job
->cluster_size
);
133 iov
.iov_base
= bounce_buffer
;
134 iov
.iov_len
= n
* BDRV_SECTOR_SIZE
;
135 qemu_iovec_init_external(&bounce_qiov
, &iov
, 1);
137 if (is_write_notifier
) {
138 ret
= bdrv_co_readv_no_serialising(bs
,
139 start
* sectors_per_cluster
,
142 ret
= bdrv_co_readv(bs
, start
* sectors_per_cluster
, n
,
146 trace_backup_do_cow_read_fail(job
, start
, ret
);
148 *error_is_read
= true;
153 if (buffer_is_zero(iov
.iov_base
, iov
.iov_len
)) {
154 ret
= bdrv_co_write_zeroes(job
->target
,
155 start
* sectors_per_cluster
,
156 n
, BDRV_REQ_MAY_UNMAP
);
158 ret
= bdrv_co_writev(job
->target
,
159 start
* sectors_per_cluster
, n
,
163 trace_backup_do_cow_write_fail(job
, start
, ret
);
165 *error_is_read
= false;
170 hbitmap_set(job
->bitmap
, start
, 1);
172 /* Publish progress, guest I/O counts as progress too. Note that the
173 * offset field is an opaque progress value, it is not a disk offset.
175 job
->sectors_read
+= n
;
176 job
->common
.offset
+= n
* BDRV_SECTOR_SIZE
;
181 qemu_vfree(bounce_buffer
);
184 cow_request_end(&cow_request
);
186 trace_backup_do_cow_return(job
, sector_num
, nb_sectors
, ret
);
188 qemu_co_rwlock_unlock(&job
->flush_rwlock
);
193 static int coroutine_fn
backup_before_write_notify(
194 NotifierWithReturn
*notifier
,
197 BdrvTrackedRequest
*req
= opaque
;
198 int64_t sector_num
= req
->offset
>> BDRV_SECTOR_BITS
;
199 int nb_sectors
= req
->bytes
>> BDRV_SECTOR_BITS
;
201 assert((req
->offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
202 assert((req
->bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
204 return backup_do_cow(req
->bs
, sector_num
, nb_sectors
, NULL
, true);
207 static void backup_set_speed(BlockJob
*job
, int64_t speed
, Error
**errp
)
209 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
212 error_setg(errp
, QERR_INVALID_PARAMETER
, "speed");
215 ratelimit_set_speed(&s
->limit
, speed
/ BDRV_SECTOR_SIZE
, SLICE_TIME
);
218 static void backup_iostatus_reset(BlockJob
*job
)
220 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
222 if (s
->target
->blk
) {
223 blk_iostatus_reset(s
->target
->blk
);
227 static void backup_cleanup_sync_bitmap(BackupBlockJob
*job
, int ret
)
230 BlockDriverState
*bs
= job
->common
.bs
;
232 if (ret
< 0 || block_job_is_cancelled(&job
->common
)) {
233 /* Merge the successor back into the parent, delete nothing. */
234 bm
= bdrv_reclaim_dirty_bitmap(bs
, job
->sync_bitmap
, NULL
);
237 /* Everything is fine, delete this bitmap and install the backup. */
238 bm
= bdrv_dirty_bitmap_abdicate(bs
, job
->sync_bitmap
, NULL
);
243 static void backup_commit(BlockJob
*job
)
245 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
246 if (s
->sync_bitmap
) {
247 backup_cleanup_sync_bitmap(s
, 0);
251 static void backup_abort(BlockJob
*job
)
253 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
254 if (s
->sync_bitmap
) {
255 backup_cleanup_sync_bitmap(s
, -1);
259 static const BlockJobDriver backup_job_driver
= {
260 .instance_size
= sizeof(BackupBlockJob
),
261 .job_type
= BLOCK_JOB_TYPE_BACKUP
,
262 .set_speed
= backup_set_speed
,
263 .iostatus_reset
= backup_iostatus_reset
,
264 .commit
= backup_commit
,
265 .abort
= backup_abort
,
268 static BlockErrorAction
backup_error_action(BackupBlockJob
*job
,
269 bool read
, int error
)
272 return block_job_error_action(&job
->common
, job
->common
.bs
,
273 job
->on_source_error
, true, error
);
275 return block_job_error_action(&job
->common
, job
->target
,
276 job
->on_target_error
, false, error
);
282 } BackupCompleteData
;
284 static void backup_complete(BlockJob
*job
, void *opaque
)
286 BackupBlockJob
*s
= container_of(job
, BackupBlockJob
, common
);
287 BackupCompleteData
*data
= opaque
;
289 bdrv_unref(s
->target
);
291 block_job_completed(job
, data
->ret
);
295 static bool coroutine_fn
yield_and_check(BackupBlockJob
*job
)
297 if (block_job_is_cancelled(&job
->common
)) {
301 /* we need to yield so that bdrv_drain_all() returns.
302 * (without, VM does not reboot)
304 if (job
->common
.speed
) {
305 uint64_t delay_ns
= ratelimit_calculate_delay(&job
->limit
,
307 job
->sectors_read
= 0;
308 block_job_sleep_ns(&job
->common
, QEMU_CLOCK_REALTIME
, delay_ns
);
310 block_job_sleep_ns(&job
->common
, QEMU_CLOCK_REALTIME
, 0);
313 if (block_job_is_cancelled(&job
->common
)) {
320 static int coroutine_fn
backup_run_incremental(BackupBlockJob
*job
)
324 int clusters_per_iter
;
325 uint32_t granularity
;
329 int64_t last_cluster
= -1;
330 int64_t sectors_per_cluster
= cluster_size_sectors(job
);
331 BlockDriverState
*bs
= job
->common
.bs
;
334 granularity
= bdrv_dirty_bitmap_granularity(job
->sync_bitmap
);
335 clusters_per_iter
= MAX((granularity
/ job
->cluster_size
), 1);
336 bdrv_dirty_iter_init(job
->sync_bitmap
, &hbi
);
338 /* Find the next dirty sector(s) */
339 while ((sector
= hbitmap_iter_next(&hbi
)) != -1) {
340 cluster
= sector
/ sectors_per_cluster
;
342 /* Fake progress updates for any clusters we skipped */
343 if (cluster
!= last_cluster
+ 1) {
344 job
->common
.offset
+= ((cluster
- last_cluster
- 1) *
348 for (end
= cluster
+ clusters_per_iter
; cluster
< end
; cluster
++) {
350 if (yield_and_check(job
)) {
353 ret
= backup_do_cow(bs
, cluster
* sectors_per_cluster
,
354 sectors_per_cluster
, &error_is_read
,
357 backup_error_action(job
, error_is_read
, -ret
) ==
358 BLOCK_ERROR_ACTION_REPORT
) {
364 /* If the bitmap granularity is smaller than the backup granularity,
365 * we need to advance the iterator pointer to the next cluster. */
366 if (granularity
< job
->cluster_size
) {
367 bdrv_set_dirty_iter(&hbi
, cluster
* sectors_per_cluster
);
370 last_cluster
= cluster
- 1;
373 /* Play some final catchup with the progress meter */
374 end
= DIV_ROUND_UP(job
->common
.len
, job
->cluster_size
);
375 if (last_cluster
+ 1 < end
) {
376 job
->common
.offset
+= ((end
- last_cluster
- 1) * job
->cluster_size
);
382 static void coroutine_fn
backup_run(void *opaque
)
384 BackupBlockJob
*job
= opaque
;
385 BackupCompleteData
*data
;
386 BlockDriverState
*bs
= job
->common
.bs
;
387 BlockDriverState
*target
= job
->target
;
388 BlockdevOnError on_target_error
= job
->on_target_error
;
389 NotifierWithReturn before_write
= {
390 .notify
= backup_before_write_notify
,
393 int64_t sectors_per_cluster
= cluster_size_sectors(job
);
396 QLIST_INIT(&job
->inflight_reqs
);
397 qemu_co_rwlock_init(&job
->flush_rwlock
);
400 end
= DIV_ROUND_UP(job
->common
.len
, job
->cluster_size
);
402 job
->bitmap
= hbitmap_alloc(end
, 0);
404 bdrv_set_enable_write_cache(target
, true);
406 blk_set_on_error(target
->blk
, on_target_error
, on_target_error
);
407 blk_iostatus_enable(target
->blk
);
410 bdrv_add_before_write_notifier(bs
, &before_write
);
412 if (job
->sync_mode
== MIRROR_SYNC_MODE_NONE
) {
413 while (!block_job_is_cancelled(&job
->common
)) {
414 /* Yield until the job is cancelled. We just let our before_write
415 * notify callback service CoW requests. */
416 job
->common
.busy
= false;
417 qemu_coroutine_yield();
418 job
->common
.busy
= true;
420 } else if (job
->sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
) {
421 ret
= backup_run_incremental(job
);
423 /* Both FULL and TOP SYNC_MODE's require copying.. */
424 for (; start
< end
; start
++) {
426 if (yield_and_check(job
)) {
430 if (job
->sync_mode
== MIRROR_SYNC_MODE_TOP
) {
434 /* Check to see if these blocks are already in the
437 for (i
= 0; i
< sectors_per_cluster
;) {
438 /* bdrv_is_allocated() only returns true/false based
439 * on the first set of sectors it comes across that
440 * are are all in the same state.
441 * For that reason we must verify each sector in the
442 * backup cluster length. We end up copying more than
443 * needed but at some point that is always the case. */
445 bdrv_is_allocated(bs
,
446 start
* sectors_per_cluster
+ i
,
447 sectors_per_cluster
- i
, &n
);
450 if (alloced
== 1 || n
== 0) {
455 /* If the above loop never found any sectors that are in
456 * the topmost image, skip this backup. */
461 /* FULL sync mode we copy the whole drive. */
462 ret
= backup_do_cow(bs
, start
* sectors_per_cluster
,
463 sectors_per_cluster
, &error_is_read
, false);
465 /* Depending on error action, fail now or retry cluster */
466 BlockErrorAction action
=
467 backup_error_action(job
, error_is_read
, -ret
);
468 if (action
== BLOCK_ERROR_ACTION_REPORT
) {
478 notifier_with_return_remove(&before_write
);
480 /* wait until pending backup_do_cow() calls have completed */
481 qemu_co_rwlock_wrlock(&job
->flush_rwlock
);
482 qemu_co_rwlock_unlock(&job
->flush_rwlock
);
483 hbitmap_free(job
->bitmap
);
486 blk_iostatus_disable(target
->blk
);
488 bdrv_op_unblock_all(target
, job
->common
.blocker
);
490 data
= g_malloc(sizeof(*data
));
492 block_job_defer_to_main_loop(&job
->common
, backup_complete
, data
);
495 void backup_start(BlockDriverState
*bs
, BlockDriverState
*target
,
496 int64_t speed
, MirrorSyncMode sync_mode
,
497 BdrvDirtyBitmap
*sync_bitmap
,
498 BlockdevOnError on_source_error
,
499 BlockdevOnError on_target_error
,
500 BlockCompletionFunc
*cb
, void *opaque
,
501 BlockJobTxn
*txn
, Error
**errp
)
512 error_setg(errp
, "Source and target cannot be the same");
516 if ((on_source_error
== BLOCKDEV_ON_ERROR_STOP
||
517 on_source_error
== BLOCKDEV_ON_ERROR_ENOSPC
) &&
518 (!bs
->blk
|| !blk_iostatus_is_enabled(bs
->blk
))) {
519 error_setg(errp
, QERR_INVALID_PARAMETER
, "on-source-error");
523 if (!bdrv_is_inserted(bs
)) {
524 error_setg(errp
, "Device is not inserted: %s",
525 bdrv_get_device_name(bs
));
529 if (!bdrv_is_inserted(target
)) {
530 error_setg(errp
, "Device is not inserted: %s",
531 bdrv_get_device_name(target
));
535 if (bdrv_op_is_blocked(bs
, BLOCK_OP_TYPE_BACKUP_SOURCE
, errp
)) {
539 if (bdrv_op_is_blocked(target
, BLOCK_OP_TYPE_BACKUP_TARGET
, errp
)) {
543 if (sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
) {
545 error_setg(errp
, "must provide a valid bitmap name for "
546 "\"incremental\" sync mode");
550 /* Create a new bitmap, and freeze/disable this one. */
551 if (bdrv_dirty_bitmap_create_successor(bs
, sync_bitmap
, errp
) < 0) {
554 } else if (sync_bitmap
) {
556 "a sync_bitmap was provided to backup_run, "
557 "but received an incompatible sync_mode (%s)",
558 MirrorSyncMode_lookup
[sync_mode
]);
562 len
= bdrv_getlength(bs
);
564 error_setg_errno(errp
, -len
, "unable to get length for '%s'",
565 bdrv_get_device_name(bs
));
569 BackupBlockJob
*job
= block_job_create(&backup_job_driver
, bs
, speed
,
575 job
->on_source_error
= on_source_error
;
576 job
->on_target_error
= on_target_error
;
577 job
->target
= target
;
578 job
->sync_mode
= sync_mode
;
579 job
->sync_bitmap
= sync_mode
== MIRROR_SYNC_MODE_INCREMENTAL
?
582 /* If there is no backing file on the target, we cannot rely on COW if our
583 * backup cluster size is smaller than the target cluster size. Even for
584 * targets with a backing file, try to avoid COW if possible. */
585 ret
= bdrv_get_info(job
->target
, &bdi
);
586 if (ret
< 0 && !target
->backing
) {
587 error_setg_errno(errp
, -ret
,
588 "Couldn't determine the cluster size of the target image, "
589 "which has no backing file");
590 error_append_hint(errp
,
591 "Aborting, since this may create an unusable destination image\n");
593 } else if (ret
< 0 && target
->backing
) {
594 /* Not fatal; just trudge on ahead. */
595 job
->cluster_size
= BACKUP_CLUSTER_SIZE_DEFAULT
;
597 job
->cluster_size
= MAX(BACKUP_CLUSTER_SIZE_DEFAULT
, bdi
.cluster_size
);
600 bdrv_op_block_all(target
, job
->common
.blocker
);
601 job
->common
.len
= len
;
602 job
->common
.co
= qemu_coroutine_create(backup_run
);
603 block_job_txn_add_job(txn
, &job
->common
);
604 qemu_coroutine_enter(job
->common
.co
, job
);
609 bdrv_reclaim_dirty_bitmap(bs
, sync_bitmap
, NULL
);