backup: simplify non-dirty bits progress processing
[qemu/ar7.git] / block / backup.c
blob8ee220076b9bc19f725d5f87822fa7c17c752b06
1 /*
2 * QEMU backup
4 * Copyright (C) 2013 Proxmox Server Solutions
6 * Authors:
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"
16 #include "trace.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)
30 #define SLICE_TIME 100000000ULL /* ns */
32 typedef struct BackupBlockJob {
33 BlockJob common;
34 BlockBackend *target;
35 /* bitmap for sync=incremental */
36 BdrvDirtyBitmap *sync_bitmap;
37 MirrorSyncMode sync_mode;
38 RateLimit limit;
39 BlockdevOnError on_source_error;
40 BlockdevOnError on_target_error;
41 CoRwlock flush_rwlock;
42 uint64_t bytes_read;
43 int64_t cluster_size;
44 bool compress;
45 NotifierWithReturn before_write;
46 QLIST_HEAD(, CowRequest) inflight_reqs;
48 HBitmap *copy_bitmap;
49 } BackupBlockJob;
51 /* See if in-flight requests overlap and wait for them to complete */
52 static void coroutine_fn wait_for_overlapping_requests(BackupBlockJob *job,
53 int64_t start,
54 int64_t end)
56 CowRequest *req;
57 bool retry;
59 do {
60 retry = false;
61 QLIST_FOREACH(req, &job->inflight_reqs, list) {
62 if (end > req->start_byte && start < req->end_byte) {
63 qemu_co_queue_wait(&req->wait_queue, NULL);
64 retry = true;
65 break;
68 } while (retry);
71 /* Keep track of an in-flight request */
72 static void cow_request_begin(CowRequest *req, BackupBlockJob *job,
73 int64_t start, int64_t end)
75 req->start_byte = start;
76 req->end_byte = end;
77 qemu_co_queue_init(&req->wait_queue);
78 QLIST_INSERT_HEAD(&job->inflight_reqs, req, list);
81 /* Forget about a completed request */
82 static void cow_request_end(CowRequest *req)
84 QLIST_REMOVE(req, list);
85 qemu_co_queue_restart_all(&req->wait_queue);
88 static int coroutine_fn backup_do_cow(BackupBlockJob *job,
89 int64_t offset, uint64_t bytes,
90 bool *error_is_read,
91 bool is_write_notifier)
93 BlockBackend *blk = job->common.blk;
94 CowRequest cow_request;
95 struct iovec iov;
96 QEMUIOVector bounce_qiov;
97 void *bounce_buffer = NULL;
98 int ret = 0;
99 int64_t start, end; /* bytes */
100 int n; /* bytes */
102 qemu_co_rwlock_rdlock(&job->flush_rwlock);
104 start = QEMU_ALIGN_DOWN(offset, job->cluster_size);
105 end = QEMU_ALIGN_UP(bytes + offset, job->cluster_size);
107 trace_backup_do_cow_enter(job, start, offset, bytes);
109 wait_for_overlapping_requests(job, start, end);
110 cow_request_begin(&cow_request, job, start, end);
112 for (; start < end; start += job->cluster_size) {
113 if (!hbitmap_get(job->copy_bitmap, start / job->cluster_size)) {
114 trace_backup_do_cow_skip(job, start);
115 continue; /* already copied */
117 hbitmap_reset(job->copy_bitmap, start / job->cluster_size, 1);
119 trace_backup_do_cow_process(job, start);
121 n = MIN(job->cluster_size, job->common.len - start);
123 if (!bounce_buffer) {
124 bounce_buffer = blk_blockalign(blk, job->cluster_size);
126 iov.iov_base = bounce_buffer;
127 iov.iov_len = n;
128 qemu_iovec_init_external(&bounce_qiov, &iov, 1);
130 ret = blk_co_preadv(blk, start, bounce_qiov.size, &bounce_qiov,
131 is_write_notifier ? BDRV_REQ_NO_SERIALISING : 0);
132 if (ret < 0) {
133 trace_backup_do_cow_read_fail(job, start, ret);
134 if (error_is_read) {
135 *error_is_read = true;
137 hbitmap_set(job->copy_bitmap, start / job->cluster_size, 1);
138 goto out;
141 if (buffer_is_zero(iov.iov_base, iov.iov_len)) {
142 ret = blk_co_pwrite_zeroes(job->target, start,
143 bounce_qiov.size, BDRV_REQ_MAY_UNMAP);
144 } else {
145 ret = blk_co_pwritev(job->target, start,
146 bounce_qiov.size, &bounce_qiov,
147 job->compress ? BDRV_REQ_WRITE_COMPRESSED : 0);
149 if (ret < 0) {
150 trace_backup_do_cow_write_fail(job, start, ret);
151 if (error_is_read) {
152 *error_is_read = false;
154 hbitmap_set(job->copy_bitmap, start / job->cluster_size, 1);
155 goto out;
158 /* Publish progress, guest I/O counts as progress too. Note that the
159 * offset field is an opaque progress value, it is not a disk offset.
161 job->bytes_read += n;
162 job->common.offset += n;
165 out:
166 if (bounce_buffer) {
167 qemu_vfree(bounce_buffer);
170 cow_request_end(&cow_request);
172 trace_backup_do_cow_return(job, offset, bytes, ret);
174 qemu_co_rwlock_unlock(&job->flush_rwlock);
176 return ret;
179 static int coroutine_fn backup_before_write_notify(
180 NotifierWithReturn *notifier,
181 void *opaque)
183 BackupBlockJob *job = container_of(notifier, BackupBlockJob, before_write);
184 BdrvTrackedRequest *req = opaque;
186 assert(req->bs == blk_bs(job->common.blk));
187 assert(QEMU_IS_ALIGNED(req->offset, BDRV_SECTOR_SIZE));
188 assert(QEMU_IS_ALIGNED(req->bytes, BDRV_SECTOR_SIZE));
190 return backup_do_cow(job, req->offset, req->bytes, NULL, true);
193 static void backup_set_speed(BlockJob *job, int64_t speed, Error **errp)
195 BackupBlockJob *s = container_of(job, BackupBlockJob, common);
197 if (speed < 0) {
198 error_setg(errp, QERR_INVALID_PARAMETER, "speed");
199 return;
201 ratelimit_set_speed(&s->limit, speed, SLICE_TIME);
204 static void backup_cleanup_sync_bitmap(BackupBlockJob *job, int ret)
206 BdrvDirtyBitmap *bm;
207 BlockDriverState *bs = blk_bs(job->common.blk);
209 if (ret < 0 || block_job_is_cancelled(&job->common)) {
210 /* Merge the successor back into the parent, delete nothing. */
211 bm = bdrv_reclaim_dirty_bitmap(bs, job->sync_bitmap, NULL);
212 assert(bm);
213 } else {
214 /* Everything is fine, delete this bitmap and install the backup. */
215 bm = bdrv_dirty_bitmap_abdicate(bs, job->sync_bitmap, NULL);
216 assert(bm);
220 static void backup_commit(BlockJob *job)
222 BackupBlockJob *s = container_of(job, BackupBlockJob, common);
223 if (s->sync_bitmap) {
224 backup_cleanup_sync_bitmap(s, 0);
228 static void backup_abort(BlockJob *job)
230 BackupBlockJob *s = container_of(job, BackupBlockJob, common);
231 if (s->sync_bitmap) {
232 backup_cleanup_sync_bitmap(s, -1);
236 static void backup_clean(BlockJob *job)
238 BackupBlockJob *s = container_of(job, BackupBlockJob, common);
239 assert(s->target);
240 blk_unref(s->target);
241 s->target = NULL;
244 static void backup_attached_aio_context(BlockJob *job, AioContext *aio_context)
246 BackupBlockJob *s = container_of(job, BackupBlockJob, common);
248 blk_set_aio_context(s->target, aio_context);
251 void backup_do_checkpoint(BlockJob *job, Error **errp)
253 BackupBlockJob *backup_job = container_of(job, BackupBlockJob, common);
254 int64_t len;
256 assert(job->driver->job_type == BLOCK_JOB_TYPE_BACKUP);
258 if (backup_job->sync_mode != MIRROR_SYNC_MODE_NONE) {
259 error_setg(errp, "The backup job only supports block checkpoint in"
260 " sync=none mode");
261 return;
264 len = DIV_ROUND_UP(backup_job->common.len, backup_job->cluster_size);
265 hbitmap_set(backup_job->copy_bitmap, 0, len);
268 void backup_wait_for_overlapping_requests(BlockJob *job, int64_t offset,
269 uint64_t bytes)
271 BackupBlockJob *backup_job = container_of(job, BackupBlockJob, common);
272 int64_t start, end;
274 assert(job->driver->job_type == BLOCK_JOB_TYPE_BACKUP);
276 start = QEMU_ALIGN_DOWN(offset, backup_job->cluster_size);
277 end = QEMU_ALIGN_UP(offset + bytes, backup_job->cluster_size);
278 wait_for_overlapping_requests(backup_job, start, end);
281 void backup_cow_request_begin(CowRequest *req, BlockJob *job,
282 int64_t offset, uint64_t bytes)
284 BackupBlockJob *backup_job = container_of(job, BackupBlockJob, common);
285 int64_t start, end;
287 assert(job->driver->job_type == BLOCK_JOB_TYPE_BACKUP);
289 start = QEMU_ALIGN_DOWN(offset, backup_job->cluster_size);
290 end = QEMU_ALIGN_UP(offset + bytes, backup_job->cluster_size);
291 cow_request_begin(req, backup_job, start, end);
294 void backup_cow_request_end(CowRequest *req)
296 cow_request_end(req);
299 static void backup_drain(BlockJob *job)
301 BackupBlockJob *s = container_of(job, BackupBlockJob, common);
303 /* Need to keep a reference in case blk_drain triggers execution
304 * of backup_complete...
306 if (s->target) {
307 BlockBackend *target = s->target;
308 blk_ref(target);
309 blk_drain(target);
310 blk_unref(target);
314 static BlockErrorAction backup_error_action(BackupBlockJob *job,
315 bool read, int error)
317 if (read) {
318 return block_job_error_action(&job->common, job->on_source_error,
319 true, error);
320 } else {
321 return block_job_error_action(&job->common, job->on_target_error,
322 false, error);
326 typedef struct {
327 int ret;
328 } BackupCompleteData;
330 static void backup_complete(BlockJob *job, void *opaque)
332 BackupCompleteData *data = opaque;
334 block_job_completed(job, data->ret);
335 g_free(data);
338 static bool coroutine_fn yield_and_check(BackupBlockJob *job)
340 if (block_job_is_cancelled(&job->common)) {
341 return true;
344 /* we need to yield so that bdrv_drain_all() returns.
345 * (without, VM does not reboot)
347 if (job->common.speed) {
348 uint64_t delay_ns = ratelimit_calculate_delay(&job->limit,
349 job->bytes_read);
350 job->bytes_read = 0;
351 block_job_sleep_ns(&job->common, delay_ns);
352 } else {
353 block_job_sleep_ns(&job->common, 0);
356 if (block_job_is_cancelled(&job->common)) {
357 return true;
360 return false;
363 static int coroutine_fn backup_run_incremental(BackupBlockJob *job)
365 bool error_is_read;
366 int ret = 0;
367 int clusters_per_iter;
368 uint32_t granularity;
369 int64_t offset;
370 int64_t cluster;
371 int64_t end;
372 BdrvDirtyBitmapIter *dbi;
374 granularity = bdrv_dirty_bitmap_granularity(job->sync_bitmap);
375 clusters_per_iter = MAX((granularity / job->cluster_size), 1);
376 dbi = bdrv_dirty_iter_new(job->sync_bitmap);
378 /* Find the next dirty sector(s) */
379 while ((offset = bdrv_dirty_iter_next(dbi)) >= 0) {
380 cluster = offset / job->cluster_size;
382 for (end = cluster + clusters_per_iter; cluster < end; cluster++) {
383 do {
384 if (yield_and_check(job)) {
385 goto out;
387 ret = backup_do_cow(job, cluster * job->cluster_size,
388 job->cluster_size, &error_is_read,
389 false);
390 if ((ret < 0) &&
391 backup_error_action(job, error_is_read, -ret) ==
392 BLOCK_ERROR_ACTION_REPORT) {
393 goto out;
395 } while (ret < 0);
398 /* If the bitmap granularity is smaller than the backup granularity,
399 * we need to advance the iterator pointer to the next cluster. */
400 if (granularity < job->cluster_size) {
401 bdrv_set_dirty_iter(dbi, cluster * job->cluster_size);
405 out:
406 bdrv_dirty_iter_free(dbi);
407 return ret;
410 /* init copy_bitmap from sync_bitmap */
411 static void backup_incremental_init_copy_bitmap(BackupBlockJob *job)
413 BdrvDirtyBitmapIter *dbi;
414 int64_t offset;
415 int64_t end = DIV_ROUND_UP(bdrv_dirty_bitmap_size(job->sync_bitmap),
416 job->cluster_size);
418 dbi = bdrv_dirty_iter_new(job->sync_bitmap);
419 while ((offset = bdrv_dirty_iter_next(dbi)) != -1) {
420 int64_t cluster = offset / job->cluster_size;
421 int64_t next_cluster;
423 offset += bdrv_dirty_bitmap_granularity(job->sync_bitmap);
424 if (offset >= bdrv_dirty_bitmap_size(job->sync_bitmap)) {
425 hbitmap_set(job->copy_bitmap, cluster, end - cluster);
426 break;
429 offset = bdrv_dirty_bitmap_next_zero(job->sync_bitmap, offset);
430 if (offset == -1) {
431 hbitmap_set(job->copy_bitmap, cluster, end - cluster);
432 break;
435 next_cluster = DIV_ROUND_UP(offset, job->cluster_size);
436 hbitmap_set(job->copy_bitmap, cluster, next_cluster - cluster);
437 if (next_cluster >= end) {
438 break;
441 bdrv_set_dirty_iter(dbi, next_cluster * job->cluster_size);
444 job->common.offset = job->common.len -
445 hbitmap_count(job->copy_bitmap) * job->cluster_size;
447 bdrv_dirty_iter_free(dbi);
450 static void coroutine_fn backup_run(void *opaque)
452 BackupBlockJob *job = opaque;
453 BackupCompleteData *data;
454 BlockDriverState *bs = blk_bs(job->common.blk);
455 int64_t offset, nb_clusters;
456 int ret = 0;
458 QLIST_INIT(&job->inflight_reqs);
459 qemu_co_rwlock_init(&job->flush_rwlock);
461 nb_clusters = DIV_ROUND_UP(job->common.len, job->cluster_size);
462 job->copy_bitmap = hbitmap_alloc(nb_clusters, 0);
463 if (job->sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
464 backup_incremental_init_copy_bitmap(job);
465 } else {
466 hbitmap_set(job->copy_bitmap, 0, nb_clusters);
470 job->before_write.notify = backup_before_write_notify;
471 bdrv_add_before_write_notifier(bs, &job->before_write);
473 if (job->sync_mode == MIRROR_SYNC_MODE_NONE) {
474 /* All bits are set in copy_bitmap to allow any cluster to be copied.
475 * This does not actually require them to be copied. */
476 while (!block_job_is_cancelled(&job->common)) {
477 /* Yield until the job is cancelled. We just let our before_write
478 * notify callback service CoW requests. */
479 block_job_yield(&job->common);
481 } else if (job->sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
482 ret = backup_run_incremental(job);
483 } else {
484 /* Both FULL and TOP SYNC_MODE's require copying.. */
485 for (offset = 0; offset < job->common.len;
486 offset += job->cluster_size) {
487 bool error_is_read;
488 int alloced = 0;
490 if (yield_and_check(job)) {
491 break;
494 if (job->sync_mode == MIRROR_SYNC_MODE_TOP) {
495 int i;
496 int64_t n;
498 /* Check to see if these blocks are already in the
499 * backing file. */
501 for (i = 0; i < job->cluster_size;) {
502 /* bdrv_is_allocated() only returns true/false based
503 * on the first set of sectors it comes across that
504 * are are all in the same state.
505 * For that reason we must verify each sector in the
506 * backup cluster length. We end up copying more than
507 * needed but at some point that is always the case. */
508 alloced =
509 bdrv_is_allocated(bs, offset + i,
510 job->cluster_size - i, &n);
511 i += n;
513 if (alloced || n == 0) {
514 break;
518 /* If the above loop never found any sectors that are in
519 * the topmost image, skip this backup. */
520 if (alloced == 0) {
521 continue;
524 /* FULL sync mode we copy the whole drive. */
525 if (alloced < 0) {
526 ret = alloced;
527 } else {
528 ret = backup_do_cow(job, offset, job->cluster_size,
529 &error_is_read, false);
531 if (ret < 0) {
532 /* Depending on error action, fail now or retry cluster */
533 BlockErrorAction action =
534 backup_error_action(job, error_is_read, -ret);
535 if (action == BLOCK_ERROR_ACTION_REPORT) {
536 break;
537 } else {
538 offset -= job->cluster_size;
539 continue;
545 notifier_with_return_remove(&job->before_write);
547 /* wait until pending backup_do_cow() calls have completed */
548 qemu_co_rwlock_wrlock(&job->flush_rwlock);
549 qemu_co_rwlock_unlock(&job->flush_rwlock);
550 hbitmap_free(job->copy_bitmap);
552 data = g_malloc(sizeof(*data));
553 data->ret = ret;
554 block_job_defer_to_main_loop(&job->common, backup_complete, data);
557 static const BlockJobDriver backup_job_driver = {
558 .instance_size = sizeof(BackupBlockJob),
559 .job_type = BLOCK_JOB_TYPE_BACKUP,
560 .start = backup_run,
561 .set_speed = backup_set_speed,
562 .commit = backup_commit,
563 .abort = backup_abort,
564 .clean = backup_clean,
565 .attached_aio_context = backup_attached_aio_context,
566 .drain = backup_drain,
569 BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
570 BlockDriverState *target, int64_t speed,
571 MirrorSyncMode sync_mode, BdrvDirtyBitmap *sync_bitmap,
572 bool compress,
573 BlockdevOnError on_source_error,
574 BlockdevOnError on_target_error,
575 int creation_flags,
576 BlockCompletionFunc *cb, void *opaque,
577 BlockJobTxn *txn, Error **errp)
579 int64_t len;
580 BlockDriverInfo bdi;
581 BackupBlockJob *job = NULL;
582 int ret;
584 assert(bs);
585 assert(target);
587 if (bs == target) {
588 error_setg(errp, "Source and target cannot be the same");
589 return NULL;
592 if (!bdrv_is_inserted(bs)) {
593 error_setg(errp, "Device is not inserted: %s",
594 bdrv_get_device_name(bs));
595 return NULL;
598 if (!bdrv_is_inserted(target)) {
599 error_setg(errp, "Device is not inserted: %s",
600 bdrv_get_device_name(target));
601 return NULL;
604 if (compress && target->drv->bdrv_co_pwritev_compressed == NULL) {
605 error_setg(errp, "Compression is not supported for this drive %s",
606 bdrv_get_device_name(target));
607 return NULL;
610 if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {
611 return NULL;
614 if (bdrv_op_is_blocked(target, BLOCK_OP_TYPE_BACKUP_TARGET, errp)) {
615 return NULL;
618 if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
619 if (!sync_bitmap) {
620 error_setg(errp, "must provide a valid bitmap name for "
621 "\"incremental\" sync mode");
622 return NULL;
625 /* Create a new bitmap, and freeze/disable this one. */
626 if (bdrv_dirty_bitmap_create_successor(bs, sync_bitmap, errp) < 0) {
627 return NULL;
629 } else if (sync_bitmap) {
630 error_setg(errp,
631 "a sync_bitmap was provided to backup_run, "
632 "but received an incompatible sync_mode (%s)",
633 MirrorSyncMode_str(sync_mode));
634 return NULL;
637 len = bdrv_getlength(bs);
638 if (len < 0) {
639 error_setg_errno(errp, -len, "unable to get length for '%s'",
640 bdrv_get_device_name(bs));
641 goto error;
644 /* job->common.len is fixed, so we can't allow resize */
645 job = block_job_create(job_id, &backup_job_driver, bs,
646 BLK_PERM_CONSISTENT_READ,
647 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE |
648 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_GRAPH_MOD,
649 speed, creation_flags, cb, opaque, errp);
650 if (!job) {
651 goto error;
654 /* The target must match the source in size, so no resize here either */
655 job->target = blk_new(BLK_PERM_WRITE,
656 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE |
657 BLK_PERM_WRITE_UNCHANGED | BLK_PERM_GRAPH_MOD);
658 ret = blk_insert_bs(job->target, target, errp);
659 if (ret < 0) {
660 goto error;
663 job->on_source_error = on_source_error;
664 job->on_target_error = on_target_error;
665 job->sync_mode = sync_mode;
666 job->sync_bitmap = sync_mode == MIRROR_SYNC_MODE_INCREMENTAL ?
667 sync_bitmap : NULL;
668 job->compress = compress;
670 /* If there is no backing file on the target, we cannot rely on COW if our
671 * backup cluster size is smaller than the target cluster size. Even for
672 * targets with a backing file, try to avoid COW if possible. */
673 ret = bdrv_get_info(target, &bdi);
674 if (ret == -ENOTSUP && !target->backing) {
675 /* Cluster size is not defined */
676 warn_report("The target block device doesn't provide "
677 "information about the block size and it doesn't have a "
678 "backing file. The default block size of %u bytes is "
679 "used. If the actual block size of the target exceeds "
680 "this default, the backup may be unusable",
681 BACKUP_CLUSTER_SIZE_DEFAULT);
682 job->cluster_size = BACKUP_CLUSTER_SIZE_DEFAULT;
683 } else if (ret < 0 && !target->backing) {
684 error_setg_errno(errp, -ret,
685 "Couldn't determine the cluster size of the target image, "
686 "which has no backing file");
687 error_append_hint(errp,
688 "Aborting, since this may create an unusable destination image\n");
689 goto error;
690 } else if (ret < 0 && target->backing) {
691 /* Not fatal; just trudge on ahead. */
692 job->cluster_size = BACKUP_CLUSTER_SIZE_DEFAULT;
693 } else {
694 job->cluster_size = MAX(BACKUP_CLUSTER_SIZE_DEFAULT, bdi.cluster_size);
697 /* Required permissions are already taken with target's blk_new() */
698 block_job_add_bdrv(&job->common, "target", target, 0, BLK_PERM_ALL,
699 &error_abort);
700 job->common.len = len;
701 block_job_txn_add_job(txn, &job->common);
703 return &job->common;
705 error:
706 if (sync_bitmap) {
707 bdrv_reclaim_dirty_bitmap(bs, sync_bitmap, NULL);
709 if (job) {
710 backup_clean(&job->common);
711 block_job_early_fail(&job->common);
714 return NULL;