4 * Copyright (C) 2013 Proxmox Server Solutions
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 BackupBlockJob {
34 /* bitmap for sync=incremental */
35 BdrvDirtyBitmap *sync_bitmap;
36 MirrorSyncMode sync_mode;
37 BlockdevOnError on_source_error;
38 BlockdevOnError on_target_error;
39 CoRwlock flush_rwlock;
44 NotifierWithReturn before_write;
45 QLIST_HEAD(, CowRequest) inflight_reqs;
49 int64_t copy_range_size;
51 bool serialize_target_writes;
54 static const BlockJobDriver backup_job_driver;
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_byte && start < req->end_byte) {
68 qemu_co_queue_wait(&req->wait_queue, NULL);
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)
80 req->start_byte = start;
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 /* Copy range to target with a bounce buffer and return the bytes copied. If
94 * error occurred, return a negative error number */
95 static int coroutine_fn backup_cow_with_bounce_buffer(BackupBlockJob *job,
98 bool is_write_notifier,
100 void **bounce_buffer)
105 BlockBackend *blk = job->common.blk;
107 int read_flags = is_write_notifier ? BDRV_REQ_NO_SERIALISING : 0;
108 int write_flags = job->serialize_target_writes ? BDRV_REQ_SERIALISING : 0;
110 hbitmap_reset(job->copy_bitmap, start / job->cluster_size, 1);
111 nbytes = MIN(job->cluster_size, job->len - start);
112 if (!*bounce_buffer) {
113 *bounce_buffer = blk_blockalign(blk, job->cluster_size);
115 iov.iov_base = *bounce_buffer;
116 iov.iov_len = nbytes;
117 qemu_iovec_init_external(&qiov, &iov, 1);
119 ret = blk_co_preadv(blk, start, qiov.size, &qiov, read_flags);
121 trace_backup_do_cow_read_fail(job, start, ret);
123 *error_is_read = true;
128 if (qemu_iovec_is_zero(&qiov)) {
129 ret = blk_co_pwrite_zeroes(job->target, start,
130 qiov.size, write_flags | BDRV_REQ_MAY_UNMAP);
132 ret = blk_co_pwritev(job->target, start,
133 qiov.size, &qiov, write_flags |
134 (job->compress ? BDRV_REQ_WRITE_COMPRESSED : 0));
137 trace_backup_do_cow_write_fail(job, start, ret);
139 *error_is_read = false;
146 hbitmap_set(job->copy_bitmap, start / job->cluster_size, 1);
151 /* Copy range to target and return the bytes copied. If error occurred, return a
152 * negative error number. */
153 static int coroutine_fn backup_cow_with_offload(BackupBlockJob *job,
156 bool is_write_notifier)
160 BlockBackend *blk = job->common.blk;
162 int read_flags = is_write_notifier ? BDRV_REQ_NO_SERIALISING : 0;
163 int write_flags = job->serialize_target_writes ? BDRV_REQ_SERIALISING : 0;
165 assert(QEMU_IS_ALIGNED(job->copy_range_size, job->cluster_size));
166 nbytes = MIN(job->copy_range_size, end - start);
167 nr_clusters = DIV_ROUND_UP(nbytes, job->cluster_size);
168 hbitmap_reset(job->copy_bitmap, start / job->cluster_size,
170 ret = blk_co_copy_range(blk, start, job->target, start, nbytes,
171 read_flags, write_flags);
173 trace_backup_do_cow_copy_range_fail(job, start, ret);
174 hbitmap_set(job->copy_bitmap, start / job->cluster_size,
182 static int coroutine_fn backup_do_cow(BackupBlockJob *job,
183 int64_t offset, uint64_t bytes,
185 bool is_write_notifier)
187 CowRequest cow_request;
189 int64_t start, end; /* bytes */
190 void *bounce_buffer = NULL;
192 qemu_co_rwlock_rdlock(&job->flush_rwlock);
194 start = QEMU_ALIGN_DOWN(offset, job->cluster_size);
195 end = QEMU_ALIGN_UP(bytes + offset, job->cluster_size);
197 trace_backup_do_cow_enter(job, start, offset, bytes);
199 wait_for_overlapping_requests(job, start, end);
200 cow_request_begin(&cow_request, job, start, end);
202 while (start < end) {
203 if (!hbitmap_get(job->copy_bitmap, start / job->cluster_size)) {
204 trace_backup_do_cow_skip(job, start);
205 start += job->cluster_size;
206 continue; /* already copied */
209 trace_backup_do_cow_process(job, start);
211 if (job->use_copy_range) {
212 ret = backup_cow_with_offload(job, start, end, is_write_notifier);
214 job->use_copy_range = false;
217 if (!job->use_copy_range) {
218 ret = backup_cow_with_bounce_buffer(job, start, end, is_write_notifier,
219 error_is_read, &bounce_buffer);
225 /* Publish progress, guest I/O counts as progress too. Note that the
226 * offset field is an opaque progress value, it is not a disk offset.
229 job->bytes_read += ret;
230 job_progress_update(&job->common.job, ret);
235 qemu_vfree(bounce_buffer);
238 cow_request_end(&cow_request);
240 trace_backup_do_cow_return(job, offset, bytes, ret);
242 qemu_co_rwlock_unlock(&job->flush_rwlock);
247 static int coroutine_fn backup_before_write_notify(
248 NotifierWithReturn *notifier,
251 BackupBlockJob *job = container_of(notifier, BackupBlockJob, before_write);
252 BdrvTrackedRequest *req = opaque;
254 assert(req->bs == blk_bs(job->common.blk));
255 assert(QEMU_IS_ALIGNED(req->offset, BDRV_SECTOR_SIZE));
256 assert(QEMU_IS_ALIGNED(req->bytes, BDRV_SECTOR_SIZE));
258 return backup_do_cow(job, req->offset, req->bytes, NULL, true);
261 static void backup_cleanup_sync_bitmap(BackupBlockJob *job, int ret)
264 BlockDriverState *bs = blk_bs(job->common.blk);
267 /* Merge the successor back into the parent, delete nothing. */
268 bm = bdrv_reclaim_dirty_bitmap(bs, job->sync_bitmap, NULL);
271 /* Everything is fine, delete this bitmap and install the backup. */
272 bm = bdrv_dirty_bitmap_abdicate(bs, job->sync_bitmap, NULL);
277 static void backup_commit(Job *job)
279 BackupBlockJob *s = container_of(job, BackupBlockJob, common.job);
280 if (s->sync_bitmap) {
281 backup_cleanup_sync_bitmap(s, 0);
285 static void backup_abort(Job *job)
287 BackupBlockJob *s = container_of(job, BackupBlockJob, common.job);
288 if (s->sync_bitmap) {
289 backup_cleanup_sync_bitmap(s, -1);
293 static void backup_clean(Job *job)
295 BackupBlockJob *s = container_of(job, BackupBlockJob, common.job);
297 blk_unref(s->target);
301 static void backup_attached_aio_context(BlockJob *job, AioContext *aio_context)
303 BackupBlockJob *s = container_of(job, BackupBlockJob, common);
305 blk_set_aio_context(s->target, aio_context);
308 void backup_do_checkpoint(BlockJob *job, Error **errp)
310 BackupBlockJob *backup_job = container_of(job, BackupBlockJob, common);
313 assert(block_job_driver(job) == &backup_job_driver);
315 if (backup_job->sync_mode != MIRROR_SYNC_MODE_NONE) {
316 error_setg(errp, "The backup job only supports block checkpoint in"
321 len = DIV_ROUND_UP(backup_job->len, backup_job->cluster_size);
322 hbitmap_set(backup_job->copy_bitmap, 0, len);
325 void backup_wait_for_overlapping_requests(BlockJob *job, int64_t offset,
328 BackupBlockJob *backup_job = container_of(job, BackupBlockJob, common);
331 assert(block_job_driver(job) == &backup_job_driver);
333 start = QEMU_ALIGN_DOWN(offset, backup_job->cluster_size);
334 end = QEMU_ALIGN_UP(offset + bytes, backup_job->cluster_size);
335 wait_for_overlapping_requests(backup_job, start, end);
338 void backup_cow_request_begin(CowRequest *req, BlockJob *job,
339 int64_t offset, uint64_t bytes)
341 BackupBlockJob *backup_job = container_of(job, BackupBlockJob, common);
344 assert(block_job_driver(job) == &backup_job_driver);
346 start = QEMU_ALIGN_DOWN(offset, backup_job->cluster_size);
347 end = QEMU_ALIGN_UP(offset + bytes, backup_job->cluster_size);
348 cow_request_begin(req, backup_job, start, end);
351 void backup_cow_request_end(CowRequest *req)
353 cow_request_end(req);
356 static void backup_drain(BlockJob *job)
358 BackupBlockJob *s = container_of(job, BackupBlockJob, common);
360 /* Need to keep a reference in case blk_drain triggers execution
361 * of backup_complete...
364 BlockBackend *target = s->target;
371 static BlockErrorAction backup_error_action(BackupBlockJob *job,
372 bool read, int error)
375 return block_job_error_action(&job->common, job->on_source_error,
378 return block_job_error_action(&job->common, job->on_target_error,
385 } BackupCompleteData;
387 static void backup_complete(Job *job, void *opaque)
389 BackupCompleteData *data = opaque;
391 job_completed(job, data->ret, NULL);
395 static bool coroutine_fn yield_and_check(BackupBlockJob *job)
399 if (job_is_cancelled(&job->common.job)) {
403 /* We need to yield even for delay_ns = 0 so that bdrv_drain_all() can
404 * return. Without a yield, the VM would not reboot. */
405 delay_ns = block_job_ratelimit_get_delay(&job->common, job->bytes_read);
407 job_sleep_ns(&job->common.job, delay_ns);
409 if (job_is_cancelled(&job->common.job)) {
416 static int coroutine_fn backup_run_incremental(BackupBlockJob *job)
423 hbitmap_iter_init(&hbi, job->copy_bitmap, 0);
424 while ((cluster = hbitmap_iter_next(&hbi, true)) != -1) {
426 if (yield_and_check(job)) {
429 ret = backup_do_cow(job, cluster * job->cluster_size,
430 job->cluster_size, &error_is_read, false);
431 if (ret < 0 && backup_error_action(job, error_is_read, -ret) ==
432 BLOCK_ERROR_ACTION_REPORT)
442 /* init copy_bitmap from sync_bitmap */
443 static void backup_incremental_init_copy_bitmap(BackupBlockJob *job)
445 BdrvDirtyBitmapIter *dbi;
447 int64_t end = DIV_ROUND_UP(bdrv_dirty_bitmap_size(job->sync_bitmap),
450 dbi = bdrv_dirty_iter_new(job->sync_bitmap);
451 while ((offset = bdrv_dirty_iter_next(dbi)) != -1) {
452 int64_t cluster = offset / job->cluster_size;
453 int64_t next_cluster;
455 offset += bdrv_dirty_bitmap_granularity(job->sync_bitmap);
456 if (offset >= bdrv_dirty_bitmap_size(job->sync_bitmap)) {
457 hbitmap_set(job->copy_bitmap, cluster, end - cluster);
461 offset = bdrv_dirty_bitmap_next_zero(job->sync_bitmap, offset);
463 hbitmap_set(job->copy_bitmap, cluster, end - cluster);
467 next_cluster = DIV_ROUND_UP(offset, job->cluster_size);
468 hbitmap_set(job->copy_bitmap, cluster, next_cluster - cluster);
469 if (next_cluster >= end) {
473 bdrv_set_dirty_iter(dbi, next_cluster * job->cluster_size);
476 /* TODO job_progress_set_remaining() would make more sense */
477 job_progress_update(&job->common.job,
478 job->len - hbitmap_count(job->copy_bitmap) * job->cluster_size);
480 bdrv_dirty_iter_free(dbi);
483 static int coroutine_fn backup_run(Job *opaque_job, Error **errp)
485 BackupBlockJob *job = container_of(opaque_job, BackupBlockJob, common.job);
486 BackupCompleteData *data;
487 BlockDriverState *bs = blk_bs(job->common.blk);
488 int64_t offset, nb_clusters;
491 QLIST_INIT(&job->inflight_reqs);
492 qemu_co_rwlock_init(&job->flush_rwlock);
494 nb_clusters = DIV_ROUND_UP(job->len, job->cluster_size);
495 job_progress_set_remaining(&job->common.job, job->len);
497 job->copy_bitmap = hbitmap_alloc(nb_clusters, 0);
498 if (job->sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
499 backup_incremental_init_copy_bitmap(job);
501 hbitmap_set(job->copy_bitmap, 0, nb_clusters);
505 job->before_write.notify = backup_before_write_notify;
506 bdrv_add_before_write_notifier(bs, &job->before_write);
508 if (job->sync_mode == MIRROR_SYNC_MODE_NONE) {
509 /* All bits are set in copy_bitmap to allow any cluster to be copied.
510 * This does not actually require them to be copied. */
511 while (!job_is_cancelled(&job->common.job)) {
512 /* Yield until the job is cancelled. We just let our before_write
513 * notify callback service CoW requests. */
514 job_yield(&job->common.job);
516 } else if (job->sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
517 ret = backup_run_incremental(job);
519 /* Both FULL and TOP SYNC_MODE's require copying.. */
520 for (offset = 0; offset < job->len;
521 offset += job->cluster_size) {
525 if (yield_and_check(job)) {
529 if (job->sync_mode == MIRROR_SYNC_MODE_TOP) {
533 /* Check to see if these blocks are already in the
536 for (i = 0; i < job->cluster_size;) {
537 /* bdrv_is_allocated() only returns true/false based
538 * on the first set of sectors it comes across that
539 * are are all in the same state.
540 * For that reason we must verify each sector in the
541 * backup cluster length. We end up copying more than
542 * needed but at some point that is always the case. */
544 bdrv_is_allocated(bs, offset + i,
545 job->cluster_size - i, &n);
548 if (alloced || n == 0) {
553 /* If the above loop never found any sectors that are in
554 * the topmost image, skip this backup. */
559 /* FULL sync mode we copy the whole drive. */
563 ret = backup_do_cow(job, offset, job->cluster_size,
564 &error_is_read, false);
567 /* Depending on error action, fail now or retry cluster */
568 BlockErrorAction action =
569 backup_error_action(job, error_is_read, -ret);
570 if (action == BLOCK_ERROR_ACTION_REPORT) {
573 offset -= job->cluster_size;
580 notifier_with_return_remove(&job->before_write);
582 /* wait until pending backup_do_cow() calls have completed */
583 qemu_co_rwlock_wrlock(&job->flush_rwlock);
584 qemu_co_rwlock_unlock(&job->flush_rwlock);
585 hbitmap_free(job->copy_bitmap);
587 data = g_malloc(sizeof(*data));
589 job_defer_to_main_loop(&job->common.job, backup_complete, data);
593 static const BlockJobDriver backup_job_driver = {
595 .instance_size = sizeof(BackupBlockJob),
596 .job_type = JOB_TYPE_BACKUP,
597 .free = block_job_free,
598 .user_resume = block_job_user_resume,
599 .drain = block_job_drain,
601 .commit = backup_commit,
602 .abort = backup_abort,
603 .clean = backup_clean,
605 .attached_aio_context = backup_attached_aio_context,
606 .drain = backup_drain,
609 BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
610 BlockDriverState *target, int64_t speed,
611 MirrorSyncMode sync_mode, BdrvDirtyBitmap *sync_bitmap,
613 BlockdevOnError on_source_error,
614 BlockdevOnError on_target_error,
616 BlockCompletionFunc *cb, void *opaque,
617 JobTxn *txn, Error **errp)
621 BackupBlockJob *job = NULL;
628 error_setg(errp, "Source and target cannot be the same");
632 if (!bdrv_is_inserted(bs)) {
633 error_setg(errp, "Device is not inserted: %s",
634 bdrv_get_device_name(bs));
638 if (!bdrv_is_inserted(target)) {
639 error_setg(errp, "Device is not inserted: %s",
640 bdrv_get_device_name(target));
644 if (compress && target->drv->bdrv_co_pwritev_compressed == NULL) {
645 error_setg(errp, "Compression is not supported for this drive %s",
646 bdrv_get_device_name(target));
650 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
654 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_BACKUP_TARGET, errp)) {
658 if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
660 error_setg(errp, "must provide a valid bitmap name for "
661 "\"incremental\" sync mode");
665 /* Create a new bitmap, and freeze/disable this one. */
666 if (bdrv_dirty_bitmap_create_successor(bs, sync_bitmap, errp) < 0) {
669 } else if (sync_bitmap) {
671 "a sync_bitmap was provided to backup_run, "
672 "but received an incompatible sync_mode (%s)",
673 MirrorSyncMode_str(sync_mode));
677 len = bdrv_getlength(bs);
679 error_setg_errno(errp, -len, "unable to get length for '%s'",
680 bdrv_get_device_name(bs));
684 /* job->len is fixed, so we can't allow resize */
685 job = block_job_create(job_id, &backup_job_driver, txn, bs,
686 BLK_PERM_CONSISTENT_READ,
687 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE |
688 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_GRAPH_MOD,
689 speed, creation_flags, cb, opaque, errp);
694 /* The target must match the source in size, so no resize here either */
695 job->target = blk_new(BLK_PERM_WRITE,
696 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE |
697 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_GRAPH_MOD);
698 ret = blk_insert_bs(job->target, target, errp);
703 job->on_source_error = on_source_error;
704 job->on_target_error = on_target_error;
705 job->sync_mode = sync_mode;
706 job->sync_bitmap = sync_mode == MIRROR_SYNC_MODE_INCREMENTAL ?
708 job->compress = compress;
710 /* Detect image-fleecing (and similar) schemes */
711 job->serialize_target_writes = bdrv_chain_contains(target, bs);
713 /* If there is no backing file on the target, we cannot rely on COW if our
714 * backup cluster size is smaller than the target cluster size. Even for
715 * targets with a backing file, try to avoid COW if possible. */
716 ret = bdrv_get_info(target, &bdi);
717 if (ret == -ENOTSUP && !target->backing) {
718 /* Cluster size is not defined */
719 warn_report("The target block device doesn't provide "
720 "information about the block size and it doesn't have a "
721 "backing file. The default block size of %u bytes is "
722 "used. If the actual block size of the target exceeds "
723 "this default, the backup may be unusable",
724 BACKUP_CLUSTER_SIZE_DEFAULT);
725 job->cluster_size = BACKUP_CLUSTER_SIZE_DEFAULT;
726 } else if (ret < 0 && !target->backing) {
727 error_setg_errno(errp, -ret,
728 "Couldn't determine the cluster size of the target image, "
729 "which has no backing file");
730 error_append_hint(errp,
731 "Aborting, since this may create an unusable destination image\n");
733 } else if (ret < 0 && target->backing) {
734 /* Not fatal; just trudge on ahead. */
735 job->cluster_size = BACKUP_CLUSTER_SIZE_DEFAULT;
737 job->cluster_size = MAX(BACKUP_CLUSTER_SIZE_DEFAULT, bdi.cluster_size);
739 job->use_copy_range = true;
740 job->copy_range_size = MIN_NON_ZERO(blk_get_max_transfer(job->common.blk),
741 blk_get_max_transfer(job->target));
742 job->copy_range_size = MAX(job->cluster_size,
743 QEMU_ALIGN_UP(job->copy_range_size,
746 /* Required permissions are already taken with target's blk_new() */
747 block_job_add_bdrv(&job->common, "target", target, 0, BLK_PERM_ALL,
755 bdrv_reclaim_dirty_bitmap(bs, sync_bitmap, NULL);
758 backup_clean(&job->common.job);
759 job_early_fail(&job->common.job);