]> git.proxmox.com Git - pve-qemu.git/commitdiff
debian/patches: squash some followup patches and regroup a bit more together
authorThomas Lamprecht <t.lamprecht@proxmox.com>
Thu, 2 Jul 2020 11:07:28 +0000 (13:07 +0200)
committerThomas Lamprecht <t.lamprecht@proxmox.com>
Thu, 2 Jul 2020 11:33:16 +0000 (13:33 +0200)
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
58 files changed:
debian/patches/pve/0013-PVE-Up-qemu-img-dd-add-n-skip_create.patch
debian/patches/pve/0017-PVE-internal-snapshot-async.patch
debian/patches/pve/0018-PVE-block-add-the-zeroinit-block-driver-filter.patch [deleted file]
debian/patches/pve/0018-add-optional-buffer-size-to-QEMUFile.patch [new file with mode: 0644]
debian/patches/pve/0019-PVE-Add-dummy-id-command-line-parameter.patch [deleted file]
debian/patches/pve/0019-PVE-block-add-the-zeroinit-block-driver-filter.patch [new file with mode: 0644]
debian/patches/pve/0020-PVE-Add-dummy-id-command-line-parameter.patch [new file with mode: 0644]
debian/patches/pve/0020-PVE-Config-Revert-target-i386-disable-LINT0-after-re.patch [deleted file]
debian/patches/pve/0021-PVE-Config-Revert-target-i386-disable-LINT0-after-re.patch [new file with mode: 0644]
debian/patches/pve/0021-PVE-Up-Config-file-posix-make-locking-optiono-on-cre.patch [deleted file]
debian/patches/pve/0022-PVE-Up-Config-file-posix-make-locking-optiono-on-cre.patch [new file with mode: 0644]
debian/patches/pve/0022-PVE-savevm-async-kick-AIO-wait-on-block-state-write.patch [deleted file]
debian/patches/pve/0023-PVE-monitor-disable-oob-capability.patch [new file with mode: 0644]
debian/patches/pve/0023-PVE-move-snapshot-cleanup-into-bottom-half.patch [deleted file]
debian/patches/pve/0024-PVE-Compat-4.0-used-balloon-qemu-4-0-config-size-fal.patch [new file with mode: 0644]
debian/patches/pve/0024-PVE-monitor-disable-oob-capability.patch [deleted file]
debian/patches/pve/0025-PVE-Allow-version-code-in-machine-type.patch [new file with mode: 0644]
debian/patches/pve/0025-PVE-Compat-4.0-used-balloon-qemu-4-0-config-size-fal.patch [deleted file]
debian/patches/pve/0026-PVE-Allow-version-code-in-machine-type.patch [deleted file]
debian/patches/pve/0026-PVE-Backup-modify-job-api.patch [new file with mode: 0644]
debian/patches/pve/0027-PVE-Backup-add-vma-backup-format-code.patch [new file with mode: 0644]
debian/patches/pve/0027-PVE-Backup-modify-job-api.patch [deleted file]
debian/patches/pve/0028-PVE-Backup-add-backup-dump-block-driver.patch [new file with mode: 0644]
debian/patches/pve/0028-PVE-Backup-add-vma-backup-format-code.patch [deleted file]
debian/patches/pve/0029-PVE-Backup-add-backup-dump-block-driver.patch [deleted file]
debian/patches/pve/0029-PVE-Backup-proxmox-backup-patches-for-qemu.patch [new file with mode: 0644]
debian/patches/pve/0030-PVE-Backup-pbs-restore-new-command-to-restore-from-p.patch [new file with mode: 0644]
debian/patches/pve/0030-PVE-Backup-proxmox-backup-patches-for-qemu.patch [deleted file]
debian/patches/pve/0031-PVE-Backup-aquire-aio_context-before-calling-backup_.patch [deleted file]
debian/patches/pve/0031-PVE-Backup-avoid-coroutines-to-fix-AIO-freeze-cleanu.patch [new file with mode: 0644]
debian/patches/pve/0032-PVE-Backup-pbs-restore-new-command-to-restore-from-p.patch [deleted file]
debian/patches/pve/0032-drive-mirror-add-support-for-sync-bitmap-mode-never.patch [new file with mode: 0644]
debian/patches/pve/0033-PVE-Backup-avoid-coroutines-to-fix-AIO-freeze-cleanu.patch [deleted file]
debian/patches/pve/0033-drive-mirror-add-support-for-conditional-and-always-.patch [new file with mode: 0644]
debian/patches/pve/0034-drive-mirror-add-support-for-sync-bitmap-mode-never.patch [deleted file]
debian/patches/pve/0034-mirror-add-check-for-bitmap-mode-without-bitmap.patch [new file with mode: 0644]
debian/patches/pve/0035-drive-mirror-add-support-for-conditional-and-always-.patch [deleted file]
debian/patches/pve/0035-mirror-switch-to-bdrv_dirty_bitmap_merge_internal.patch [new file with mode: 0644]
debian/patches/pve/0036-iotests-add-test-for-bitmap-mirror.patch [new file with mode: 0644]
debian/patches/pve/0036-mirror-add-check-for-bitmap-mode-without-bitmap.patch [deleted file]
debian/patches/pve/0037-mirror-move-some-checks-to-qmp.patch [new file with mode: 0644]
debian/patches/pve/0037-mirror-switch-to-bdrv_dirty_bitmap_merge_internal.patch [deleted file]
debian/patches/pve/0038-PVE-Backup-Add-dirty-bitmap-tracking-for-incremental.patch [new file with mode: 0644]
debian/patches/pve/0038-iotests-add-test-for-bitmap-mirror.patch [deleted file]
debian/patches/pve/0039-mirror-move-some-checks-to-qmp.patch [deleted file]
debian/patches/pve/0040-PVE-savevm-async-set-up-migration-state.patch [deleted file]
debian/patches/pve/0041-PVE-Backup-avoid-use-QemuRecMutex-inside-coroutines.patch [deleted file]
debian/patches/pve/0042-PVE-Backup-use-QemuMutex-instead-of-QemuRecMutex.patch [deleted file]
debian/patches/pve/0043-move-savevm-async-back-into-a-coroutine.patch [deleted file]
debian/patches/pve/0044-add-optional-buffer-size-to-QEMUFile.patch [deleted file]
debian/patches/pve/0045-savevm-async-move-more-code-to-cleanup-and-rename-to.patch [deleted file]
debian/patches/pve/0046-util-async-Add-aio_co_reschedule_self.patch [deleted file]
debian/patches/pve/0047-savevm-async-flush-IOThread-drives-async-before-ente.patch [deleted file]
debian/patches/pve/0048-savevm-async-add-debug-timing-prints.patch [deleted file]
debian/patches/pve/0049-Add-some-qemu_vfree-statements-to-prevent-memory-lea.patch [deleted file]
debian/patches/pve/0050-Fix-backup-for-not-64k-aligned-storages.patch [deleted file]
debian/patches/pve/0051-PVE-Backup-Add-dirty-bitmap-tracking-for-incremental.patch [deleted file]
debian/patches/series

index dbf33f60b3b22d53d6577e2a472b97ce79abdae5..a5b23d0c78b5a5ce9f9b79a5268371c1061212b0 100644 (file)
@@ -1,7 +1,7 @@
 From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
 From: Alexandre Derumier <aderumier@odiso.com>
 Date: Mon, 6 Apr 2020 12:16:42 +0200
-Subject: [PATCH] PVE: [Up] qemu-img dd : add -n skip_create
+Subject: [PATCH] PVE: [Up] qemu-img dd: add -n skip_create
 
 Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
 ---
index b0e73eafeedcc703424baa46fb20c7c82412f4ab..b887939237b20e3559a018c38ed9a29f16832c78 100644 (file)
@@ -5,21 +5,30 @@ Subject: [PATCH] PVE: internal snapshot async
 
 Truncate at 1024 boundary (Fabian Ebner will send a patch for stable)
 
+Put qemu_savevm_state_{header,setup} into the main loop and the rest
+of the iteration into a coroutine. The former need to lock the
+iothread (and we can't unlock it in the coroutine), and the latter
+can't deal with being in a separate thread, so a coroutine it must
+be.
+
 Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
 Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
+Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
 ---
  Makefile.objs                |   1 +
  hmp-commands-info.hx         |  13 +
  hmp-commands.hx              |  32 +++
+ include/block/aio.h          |  10 +
  include/migration/snapshot.h |   1 +
  include/monitor/hmp.h        |   5 +
- monitor/hmp-cmds.c           |  57 +++++
+ monitor/hmp-cmds.c           |  57 ++++
  qapi/migration.json          |  34 +++
  qapi/misc.json               |  32 +++
  qemu-options.hx              |  12 +
- savevm-async.c               | 464 +++++++++++++++++++++++++++++++++++
+ savevm-async.c               | 542 +++++++++++++++++++++++++++++++++++
  softmmu/vl.c                 |  10 +
- 11 files changed, 661 insertions(+)
+ util/async.c                 |  30 ++
+ 13 files changed, 779 insertions(+)
  create mode 100644 savevm-async.c
 
 diff --git a/Makefile.objs b/Makefile.objs
@@ -98,6 +107,34 @@ index 7f0f3974ad..81fe305d07 100644
 +        .help       = "Resume VM after snaphot.",
 +        .cmd = hmp_savevm_end,
 +    },
+diff --git a/include/block/aio.h b/include/block/aio.h
+index 62ed954344..d5399c67d6 100644
+--- a/include/block/aio.h
++++ b/include/block/aio.h
+@@ -17,6 +17,7 @@
+ #ifdef CONFIG_LINUX_IO_URING
+ #include <liburing.h>
+ #endif
++#include "qemu/coroutine.h"
+ #include "qemu/queue.h"
+ #include "qemu/event_notifier.h"
+ #include "qemu/thread.h"
+@@ -654,6 +655,15 @@ static inline bool aio_node_check(AioContext *ctx, bool is_external)
+  */
+ void aio_co_schedule(AioContext *ctx, struct Coroutine *co);
++/**
++ * aio_co_reschedule_self:
++ * @new_ctx: the new context
++ *
++ * Move the currently running coroutine to new_ctx. If the coroutine is already
++ * running in new_ctx, do nothing.
++ */
++void coroutine_fn aio_co_reschedule_self(AioContext *new_ctx);
++
+ /**
+  * aio_co_wake:
+  * @co: the coroutine
 diff --git a/include/migration/snapshot.h b/include/migration/snapshot.h
 index c85b6ec75b..4411b7121d 100644
 --- a/include/migration/snapshot.h
@@ -313,10 +350,10 @@ index 292d4e7c0c..55eef64ddf 100644
      "-daemonize      daemonize QEMU after initializing\n", QEMU_ARCH_ALL)
 diff --git a/savevm-async.c b/savevm-async.c
 new file mode 100644
-index 0000000000..54ceeae26c
+index 0000000000..7fd8a69374
 --- /dev/null
 +++ b/savevm-async.c
-@@ -0,0 +1,464 @@
+@@ -0,0 +1,542 @@
 +#include "qemu/osdep.h"
 +#include "migration/migration.h"
 +#include "migration/savevm.h"
@@ -369,8 +406,8 @@ index 0000000000..54ceeae26c
 +    int saved_vm_running;
 +    QEMUFile *file;
 +    int64_t total_time;
-+    QEMUBH *cleanup_bh;
-+    QemuThread thread;
++    QEMUBH *finalize_bh;
++    Coroutine *co;
 +} snap_state;
 +
 +SaveVMInfo *qmp_query_savevm(Error **errp)
@@ -477,6 +514,7 @@ index 0000000000..54ceeae26c
 +    BlkRwCo *rwco = opaque;
 +    rwco->ret = blk_co_pwritev(snap_state.target, rwco->offset, rwco->qiov->size,
 +                               rwco->qiov, 0);
++    aio_wait_kick();
 +}
 +
 +static ssize_t block_state_writev_buffer(void *opaque, struct iovec *iov,
@@ -514,14 +552,50 @@ index 0000000000..54ceeae26c
 +    .close =          block_state_close,
 +};
 +
-+static void process_savevm_cleanup(void *opaque)
++static void process_savevm_finalize(void *opaque)
 +{
 +    int ret;
-+    qemu_bh_delete(snap_state.cleanup_bh);
-+    snap_state.cleanup_bh = NULL;
-+    qemu_mutex_unlock_iothread();
-+    qemu_thread_join(&snap_state.thread);
-+    qemu_mutex_lock_iothread();
++    AioContext *iohandler_ctx = iohandler_get_aio_context();
++    MigrationState *ms = migrate_get_current();
++
++#ifdef DEBUG_SAVEVM_STATE
++    int64_t start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
++#endif
++
++    qemu_bh_delete(snap_state.finalize_bh);
++    snap_state.finalize_bh = NULL;
++    snap_state.co = NULL;
++
++    /* We need to own the target bdrv's context for the following functions,
++     * so move it back. It can stay in the main context and live out its live
++     * there, since we're done with it after this method ends anyway.
++     */
++    aio_context_acquire(iohandler_ctx);
++    blk_set_aio_context(snap_state.target, qemu_get_aio_context(), NULL);
++    aio_context_release(iohandler_ctx);
++
++    ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
++    if (ret < 0) {
++        save_snapshot_error("vm_stop_force_state error %d", ret);
++    }
++
++    (void)qemu_savevm_state_complete_precopy(snap_state.file, false, false);
++    ret = qemu_file_get_error(snap_state.file);
++    if (ret < 0) {
++            save_snapshot_error("qemu_savevm_state_iterate error %d", ret);
++    }
++
++    DPRINTF("state saving complete\n");
++    DPRINTF("timing: process_savevm_finalize (state saving) took %ld ms\n",
++        qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - start_time);
++
++    /* clear migration state */
++    migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP,
++                      ret ? MIGRATION_STATUS_FAILED : MIGRATION_STATUS_COMPLETED);
++    ms->to_dst_file = NULL;
++
++    qemu_savevm_state_cleanup();
++
 +    ret = save_snapshot_cleanup();
 +    if (ret < 0) {
 +        save_snapshot_error("save_snapshot_cleanup error %d", ret);
@@ -535,23 +609,26 @@ index 0000000000..54ceeae26c
 +        vm_start();
 +        snap_state.saved_vm_running = false;
 +    }
++
++    DPRINTF("timing: process_savevm_finalize (full) took %ld ms\n",
++        qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - start_time);
 +}
 +
-+static void *process_savevm_thread(void *opaque)
++static void coroutine_fn process_savevm_co(void *opaque)
 +{
 +    int ret;
 +    int64_t maxlen;
++    BdrvNextIterator it;
++    BlockDriverState *bs = NULL;
 +
-+    rcu_register_thread();
++#ifdef DEBUG_SAVEVM_STATE
++    int64_t start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
++#endif
 +
-+    qemu_savevm_state_header(snap_state.file);
-+    qemu_savevm_state_setup(snap_state.file);
 +    ret = qemu_file_get_error(snap_state.file);
-+
 +    if (ret < 0) {
 +        save_snapshot_error("qemu_savevm_state_setup failed");
-+        rcu_unregister_thread();
-+        return NULL;
++        return;
 +    }
 +
 +    while (snap_state.state == SAVE_STATE_ACTIVE) {
@@ -563,54 +640,63 @@ index 0000000000..54ceeae26c
 +        maxlen = blk_getlength(snap_state.target) - 30*1024*1024;
 +
 +        if (pending_size > 400000 && snap_state.bs_pos + pending_size < maxlen) {
-+            qemu_mutex_lock_iothread();
 +            ret = qemu_savevm_state_iterate(snap_state.file, false);
 +            if (ret < 0) {
 +                save_snapshot_error("qemu_savevm_state_iterate error %d", ret);
 +                break;
 +            }
-+            qemu_mutex_unlock_iothread();
-+            DPRINTF("savevm inerate pending size %lu ret %d\n", pending_size, ret);
++            DPRINTF("savevm iterate pending size %lu ret %d\n", pending_size, ret);
 +        } else {
-+            qemu_mutex_lock_iothread();
 +            qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
 +            ret = global_state_store();
 +            if (ret) {
 +                save_snapshot_error("global_state_store error %d", ret);
 +                break;
 +            }
-+            ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
-+            if (ret < 0) {
-+                save_snapshot_error("vm_stop_force_state error %d", ret);
-+                break;
-+            }
-+            DPRINTF("savevm inerate finished\n");
-+            /* upstream made the return value here inconsistent
-+             * (-1 instead of 'ret' in one case and 0 after flush which can
-+             * still set a file error...)
-+             */
-+            (void)qemu_savevm_state_complete_precopy(snap_state.file, false, false);
-+            ret = qemu_file_get_error(snap_state.file);
-+            if (ret < 0) {
-+                    save_snapshot_error("qemu_savevm_state_iterate error %d", ret);
-+                    break;
-+            }
-+            qemu_savevm_state_cleanup();
-+            DPRINTF("save complete\n");
++
++            DPRINTF("savevm iterate complete\n");
 +            break;
 +        }
 +    }
 +
-+    qemu_bh_schedule(snap_state.cleanup_bh);
-+    qemu_mutex_unlock_iothread();
++    DPRINTF("timing: process_savevm_co took %ld ms\n",
++        qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - start_time);
++
++#ifdef DEBUG_SAVEVM_STATE
++    int64_t start_time_flush = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
++#endif
++    /* If a drive runs in an IOThread we can flush it async, and only
++     * need to sync-flush whatever IO happens between now and
++     * vm_stop_force_state. bdrv_next can only be called from main AioContext,
++     * so move there now and after every flush.
++     */
++    aio_co_reschedule_self(qemu_get_aio_context());
++    for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
++        /* target has BDRV_O_NO_FLUSH, no sense calling bdrv_flush on it */
++        if (bs == blk_bs(snap_state.target)) {
++            continue;
++        }
++
++        AioContext *bs_ctx = bdrv_get_aio_context(bs);
++        if (bs_ctx != qemu_get_aio_context()) {
++            DPRINTF("savevm: async flushing drive %s\n", bs->filename);
++            aio_co_reschedule_self(bs_ctx);
++            bdrv_flush(bs);
++            aio_co_reschedule_self(qemu_get_aio_context());
++        }
++    }
++
++    DPRINTF("timing: async flushing took %ld ms\n",
++        qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - start_time_flush);
 +
-+    rcu_unregister_thread();
-+    return NULL;
++    qemu_bh_schedule(snap_state.finalize_bh);
 +}
 +
 +void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
 +{
 +    Error *local_err = NULL;
++    MigrationState *ms = migrate_get_current();
++    AioContext *iohandler_ctx = iohandler_get_aio_context();
 +
 +    int bdrv_oflags = BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH;
 +
@@ -620,6 +706,17 @@ index 0000000000..54ceeae26c
 +        return;
 +    }
 +
++    if (migration_is_running(ms->state)) {
++        error_set(errp, ERROR_CLASS_GENERIC_ERROR, QERR_MIGRATION_ACTIVE);
++        return;
++    }
++
++    if (migrate_use_block()) {
++        error_set(errp, ERROR_CLASS_GENERIC_ERROR,
++                  "Block migration and snapshots are incompatible");
++        return;
++    }
++
 +    /* initialize snapshot info */
 +    snap_state.saved_vm_running = runstate_is_running();
 +    snap_state.bs_pos = 0;
@@ -658,14 +755,32 @@ index 0000000000..54ceeae26c
 +        goto restart;
 +    }
 +
++    /*
++     * qemu_savevm_* paths use migration code and expect a migration state.
++     * State is cleared in process_savevm_co, but has to be initialized
++     * here (blocking main thread, from QMP) to avoid race conditions.
++     */
++    migrate_init(ms);
++    memset(&ram_counters, 0, sizeof(ram_counters));
++    ms->to_dst_file = snap_state.file;
 +
 +    error_setg(&snap_state.blocker, "block device is in use by savevm");
 +    blk_op_block_all(snap_state.target, snap_state.blocker);
 +
 +    snap_state.state = SAVE_STATE_ACTIVE;
-+    snap_state.cleanup_bh = qemu_bh_new(process_savevm_cleanup, &snap_state);
-+    qemu_thread_create(&snap_state.thread, "savevm-async", process_savevm_thread,
-+                       NULL, QEMU_THREAD_JOINABLE);
++    snap_state.finalize_bh = qemu_bh_new(process_savevm_finalize, &snap_state);
++    snap_state.co = qemu_coroutine_create(&process_savevm_co, NULL);
++    qemu_mutex_unlock_iothread();
++    qemu_savevm_state_header(snap_state.file);
++    qemu_savevm_state_setup(snap_state.file);
++    qemu_mutex_lock_iothread();
++
++    /* Async processing from here on out happens in iohandler context, so let
++     * the target bdrv have its home there.
++     */
++    blk_set_aio_context(snap_state.target, iohandler_ctx, &local_err);
++
++    aio_co_schedule(iohandler_ctx, snap_state.co);
 +
 +    return;
 +
@@ -816,3 +931,44 @@ index 32c0047889..4b45eb0c37 100644
      }
      if (replay_mode != REPLAY_MODE_NONE) {
          replay_vmstate_init();
+diff --git a/util/async.c b/util/async.c
+index 3165a28f2f..4eba1e6f1b 100644
+--- a/util/async.c
++++ b/util/async.c
+@@ -558,6 +558,36 @@ void aio_co_schedule(AioContext *ctx, Coroutine *co)
+     aio_context_unref(ctx);
+ }
++typedef struct AioCoRescheduleSelf {
++    Coroutine *co;
++    AioContext *new_ctx;
++} AioCoRescheduleSelf;
++
++static void aio_co_reschedule_self_bh(void *opaque)
++{
++    AioCoRescheduleSelf *data = opaque;
++    aio_co_schedule(data->new_ctx, data->co);
++}
++
++void coroutine_fn aio_co_reschedule_self(AioContext *new_ctx)
++{
++    AioContext *old_ctx = qemu_get_current_aio_context();
++
++    if (old_ctx != new_ctx) {
++        AioCoRescheduleSelf data = {
++            .co = qemu_coroutine_self(),
++            .new_ctx = new_ctx,
++        };
++        /*
++         * We can't directly schedule the coroutine in the target context
++         * because this would be racy: The other thread could try to enter the
++         * coroutine before it has yielded in this one.
++         */
++        aio_bh_schedule_oneshot(old_ctx, aio_co_reschedule_self_bh, &data);
++        qemu_coroutine_yield();
++    }
++}
++
+ void aio_co_wake(struct Coroutine *co)
+ {
+     AioContext *ctx;
diff --git a/debian/patches/pve/0018-PVE-block-add-the-zeroinit-block-driver-filter.patch b/debian/patches/pve/0018-PVE-block-add-the-zeroinit-block-driver-filter.patch
deleted file mode 100644 (file)
index 52f7afc..0000000
+++ /dev/null
@@ -1,227 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:47 +0200
-Subject: [PATCH] PVE: block: add the zeroinit block driver filter
-
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- block/Makefile.objs |   1 +
- block/zeroinit.c    | 197 ++++++++++++++++++++++++++++++++++++++++++++
- 2 files changed, 198 insertions(+)
- create mode 100644 block/zeroinit.c
-
-diff --git a/block/Makefile.objs b/block/Makefile.objs
-index 3635b6b4c1..1282445672 100644
---- a/block/Makefile.objs
-+++ b/block/Makefile.objs
-@@ -11,6 +11,7 @@ block-obj-$(CONFIG_QED) += qed.o qed-l2-cache.o qed-table.o qed-cluster.o
- block-obj-$(CONFIG_QED) += qed-check.o
- block-obj-y += vhdx.o vhdx-endian.o vhdx-log.o
- block-obj-y += quorum.o
-+block-obj-y += zeroinit.o
- block-obj-y += blkdebug.o blkverify.o blkreplay.o
- block-obj-$(CONFIG_PARALLELS) += parallels.o
- block-obj-y += blklogwrites.o
-diff --git a/block/zeroinit.c b/block/zeroinit.c
-new file mode 100644
-index 0000000000..ff38388d94
---- /dev/null
-+++ b/block/zeroinit.c
-@@ -0,0 +1,197 @@
-+/*
-+ * Filter to fake a zero-initialized block device.
-+ *
-+ * Copyright (c) 2016 Wolfgang Bumiller <w.bumiller@proxmox.com>
-+ * Copyright (c) 2016 Proxmox Server Solutions GmbH
-+ *
-+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
-+ * See the COPYING file in the top-level directory.
-+ */
-+
-+#include "qemu/osdep.h"
-+#include "qapi/error.h"
-+#include "block/block_int.h"
-+#include "qapi/qmp/qdict.h"
-+#include "qapi/qmp/qstring.h"
-+#include "qemu/cutils.h"
-+#include "qemu/option.h"
-+#include "qemu/module.h"
-+
-+typedef struct {
-+    bool has_zero_init;
-+    int64_t extents;
-+} BDRVZeroinitState;
-+
-+/* Valid blkverify filenames look like blkverify:path/to/raw_image:path/to/image */
-+static void zeroinit_parse_filename(const char *filename, QDict *options,
-+                                     Error **errp)
-+{
-+    QString *raw_path;
-+
-+    /* Parse the blkverify: prefix */
-+    if (!strstart(filename, "zeroinit:", &filename)) {
-+        /* There was no prefix; therefore, all options have to be already
-+           present in the QDict (except for the filename) */
-+        return;
-+    }
-+
-+    raw_path = qstring_from_str(filename);
-+    qdict_put(options, "x-next", raw_path);
-+}
-+
-+static QemuOptsList runtime_opts = {
-+    .name = "zeroinit",
-+    .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
-+    .desc = {
-+        {
-+            .name = "x-next",
-+            .type = QEMU_OPT_STRING,
-+            .help = "[internal use only, will be removed]",
-+        },
-+        {
-+            .name = "x-zeroinit",
-+            .type = QEMU_OPT_BOOL,
-+            .help = "set has_initialized_zero flag",
-+        },
-+        { /* end of list */ }
-+    },
-+};
-+
-+static int zeroinit_open(BlockDriverState *bs, QDict *options, int flags,
-+                          Error **errp)
-+{
-+    BDRVZeroinitState *s = bs->opaque;
-+    QemuOpts *opts;
-+    Error *local_err = NULL;
-+    int ret;
-+
-+    s->extents = 0;
-+
-+    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
-+    qemu_opts_absorb_qdict(opts, options, &local_err);
-+    if (local_err) {
-+        error_propagate(errp, local_err);
-+        ret = -EINVAL;
-+        goto fail;
-+    }
-+
-+    /* Open the raw file */
-+    bs->file = bdrv_open_child(qemu_opt_get(opts, "x-next"), options, "next",
-+                               bs, &child_file, false, &local_err);
-+    if (local_err) {
-+        ret = -EINVAL;
-+        error_propagate(errp, local_err);
-+        goto fail;
-+    }
-+
-+    /* set the options */
-+    s->has_zero_init = qemu_opt_get_bool(opts, "x-zeroinit", true);
-+
-+    ret = 0;
-+fail:
-+    if (ret < 0) {
-+        bdrv_unref_child(bs, bs->file);
-+    }
-+    qemu_opts_del(opts);
-+    return ret;
-+}
-+
-+static void zeroinit_close(BlockDriverState *bs)
-+{
-+    BDRVZeroinitState *s = bs->opaque;
-+    (void)s;
-+}
-+
-+static int64_t zeroinit_getlength(BlockDriverState *bs)
-+{
-+    return bdrv_getlength(bs->file->bs);
-+}
-+
-+static int coroutine_fn zeroinit_co_preadv(BlockDriverState *bs,
-+    uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
-+{
-+    return bdrv_co_preadv(bs->file, offset, bytes, qiov, flags);
-+}
-+
-+static int coroutine_fn zeroinit_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
-+                                                 int count, BdrvRequestFlags flags)
-+{
-+    BDRVZeroinitState *s = bs->opaque;
-+    if (offset >= s->extents)
-+        return 0;
-+    return bdrv_pwrite_zeroes(bs->file, offset, count, flags);
-+}
-+
-+static int coroutine_fn zeroinit_co_pwritev(BlockDriverState *bs,
-+    uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
-+{
-+    BDRVZeroinitState *s = bs->opaque;
-+    int64_t extents = offset + bytes;
-+    if (extents > s->extents)
-+        s->extents = extents;
-+    return bdrv_co_pwritev(bs->file, offset, bytes, qiov, flags);
-+}
-+
-+static coroutine_fn int zeroinit_co_flush(BlockDriverState *bs)
-+{
-+    return bdrv_co_flush(bs->file->bs);
-+}
-+
-+static int zeroinit_has_zero_init(BlockDriverState *bs)
-+{
-+    BDRVZeroinitState *s = bs->opaque;
-+    return s->has_zero_init;
-+}
-+
-+static int coroutine_fn zeroinit_co_pdiscard(BlockDriverState *bs,
-+                                             int64_t offset, int count)
-+{
-+    return bdrv_co_pdiscard(bs->file, offset, count);
-+}
-+
-+static int zeroinit_co_truncate(BlockDriverState *bs, int64_t offset,
-+                                _Bool exact, PreallocMode prealloc, Error **errp)
-+{
-+    return bdrv_co_truncate(bs->file, offset, exact, prealloc, errp);
-+}
-+
-+static int zeroinit_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
-+{
-+    return bdrv_get_info(bs->file->bs, bdi);
-+}
-+
-+static BlockDriver bdrv_zeroinit = {
-+    .format_name                      = "zeroinit",
-+    .protocol_name                    = "zeroinit",
-+    .instance_size                    = sizeof(BDRVZeroinitState),
-+
-+    .bdrv_parse_filename              = zeroinit_parse_filename,
-+    .bdrv_file_open                   = zeroinit_open,
-+    .bdrv_close                       = zeroinit_close,
-+    .bdrv_getlength                   = zeroinit_getlength,
-+    .bdrv_child_perm                  = bdrv_filter_default_perms,
-+    .bdrv_co_flush_to_disk            = zeroinit_co_flush,
-+
-+    .bdrv_co_pwrite_zeroes            = zeroinit_co_pwrite_zeroes,
-+    .bdrv_co_pwritev                  = zeroinit_co_pwritev,
-+    .bdrv_co_preadv                   = zeroinit_co_preadv,
-+    .bdrv_co_flush                    = zeroinit_co_flush,
-+
-+    .is_filter                        = true,
-+
-+    .bdrv_has_zero_init               = zeroinit_has_zero_init,
-+
-+    .bdrv_co_block_status             = bdrv_co_block_status_from_file,
-+
-+    .bdrv_co_pdiscard                 = zeroinit_co_pdiscard,
-+
-+    .bdrv_co_truncate                 = zeroinit_co_truncate,
-+    .bdrv_get_info                    = zeroinit_get_info,
-+};
-+
-+static void bdrv_zeroinit_init(void)
-+{
-+    bdrv_register(&bdrv_zeroinit);
-+}
-+
-+block_init(bdrv_zeroinit_init);
diff --git a/debian/patches/pve/0018-add-optional-buffer-size-to-QEMUFile.patch b/debian/patches/pve/0018-add-optional-buffer-size-to-QEMUFile.patch
new file mode 100644 (file)
index 0000000..96ca8aa
--- /dev/null
@@ -0,0 +1,183 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Date: Mon, 4 May 2020 11:05:08 +0200
+Subject: [PATCH] add optional buffer size to QEMUFile
+
+So we can use a 4M buffer for savevm-async which should
+increase performance storing the state onto ceph.
+
+Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
+---
+ migration/qemu-file.c | 36 ++++++++++++++++++++++++------------
+ migration/qemu-file.h |  1 +
+ savevm-async.c        |  4 ++--
+ 3 files changed, 27 insertions(+), 14 deletions(-)
+
+diff --git a/migration/qemu-file.c b/migration/qemu-file.c
+index 1c3a358a14..7362e51c71 100644
+--- a/migration/qemu-file.c
++++ b/migration/qemu-file.c
+@@ -30,7 +30,7 @@
+ #include "trace.h"
+ #include "qapi/error.h"
+-#define IO_BUF_SIZE 32768
++#define DEFAULT_IO_BUF_SIZE 32768
+ #define MAX_IOV_SIZE MIN(IOV_MAX, 64)
+ struct QEMUFile {
+@@ -45,7 +45,8 @@ struct QEMUFile {
+                     when reading */
+     int buf_index;
+     int buf_size; /* 0 when writing */
+-    uint8_t buf[IO_BUF_SIZE];
++    size_t buf_allocated_size;
++    uint8_t *buf;
+     DECLARE_BITMAP(may_free, MAX_IOV_SIZE);
+     struct iovec iov[MAX_IOV_SIZE];
+@@ -101,7 +102,7 @@ bool qemu_file_mode_is_not_valid(const char *mode)
+     return false;
+ }
+-QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)
++QEMUFile *qemu_fopen_ops_sized(void *opaque, const QEMUFileOps *ops, size_t buffer_size)
+ {
+     QEMUFile *f;
+@@ -109,9 +110,17 @@ QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)
+     f->opaque = opaque;
+     f->ops = ops;
++    f->buf_allocated_size = buffer_size;
++    f->buf = malloc(buffer_size);
++
+     return f;
+ }
++QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)
++{
++    return qemu_fopen_ops_sized(opaque, ops, DEFAULT_IO_BUF_SIZE);
++}
++
+ void qemu_file_set_hooks(QEMUFile *f, const QEMUFileHooks *hooks)
+ {
+@@ -346,7 +355,7 @@ static ssize_t qemu_fill_buffer(QEMUFile *f)
+     }
+     len = f->ops->get_buffer(f->opaque, f->buf + pending, f->pos,
+-                             IO_BUF_SIZE - pending, &local_error);
++                             f->buf_allocated_size - pending, &local_error);
+     if (len > 0) {
+         f->buf_size += len;
+         f->pos += len;
+@@ -386,6 +395,9 @@ int qemu_fclose(QEMUFile *f)
+             ret = ret2;
+         }
+     }
++
++    free(f->buf);
++
+     /* If any error was spotted before closing, we should report it
+      * instead of the close() return value.
+      */
+@@ -435,7 +447,7 @@ static void add_buf_to_iovec(QEMUFile *f, size_t len)
+ {
+     if (!add_to_iovec(f, f->buf + f->buf_index, len, false)) {
+         f->buf_index += len;
+-        if (f->buf_index == IO_BUF_SIZE) {
++        if (f->buf_index == f->buf_allocated_size) {
+             qemu_fflush(f);
+         }
+     }
+@@ -461,7 +473,7 @@ void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, size_t size)
+     }
+     while (size > 0) {
+-        l = IO_BUF_SIZE - f->buf_index;
++        l = f->buf_allocated_size - f->buf_index;
+         if (l > size) {
+             l = size;
+         }
+@@ -508,8 +520,8 @@ size_t qemu_peek_buffer(QEMUFile *f, uint8_t **buf, size_t size, size_t offset)
+     size_t index;
+     assert(!qemu_file_is_writable(f));
+-    assert(offset < IO_BUF_SIZE);
+-    assert(size <= IO_BUF_SIZE - offset);
++    assert(offset < f->buf_allocated_size);
++    assert(size <= f->buf_allocated_size - offset);
+     /* The 1st byte to read from */
+     index = f->buf_index + offset;
+@@ -559,7 +571,7 @@ size_t qemu_get_buffer(QEMUFile *f, uint8_t *buf, size_t size)
+         size_t res;
+         uint8_t *src;
+-        res = qemu_peek_buffer(f, &src, MIN(pending, IO_BUF_SIZE), 0);
++        res = qemu_peek_buffer(f, &src, MIN(pending, f->buf_allocated_size), 0);
+         if (res == 0) {
+             return done;
+         }
+@@ -593,7 +605,7 @@ size_t qemu_get_buffer(QEMUFile *f, uint8_t *buf, size_t size)
+  */
+ size_t qemu_get_buffer_in_place(QEMUFile *f, uint8_t **buf, size_t size)
+ {
+-    if (size < IO_BUF_SIZE) {
++    if (size < f->buf_allocated_size) {
+         size_t res;
+         uint8_t *src;
+@@ -618,7 +630,7 @@ int qemu_peek_byte(QEMUFile *f, int offset)
+     int index = f->buf_index + offset;
+     assert(!qemu_file_is_writable(f));
+-    assert(offset < IO_BUF_SIZE);
++    assert(offset < f->buf_allocated_size);
+     if (index >= f->buf_size) {
+         qemu_fill_buffer(f);
+@@ -770,7 +782,7 @@ static int qemu_compress_data(z_stream *stream, uint8_t *dest, size_t dest_len,
+ ssize_t qemu_put_compression_data(QEMUFile *f, z_stream *stream,
+                                   const uint8_t *p, size_t size)
+ {
+-    ssize_t blen = IO_BUF_SIZE - f->buf_index - sizeof(int32_t);
++    ssize_t blen = f->buf_allocated_size - f->buf_index - sizeof(int32_t);
+     if (blen < compressBound(size)) {
+         return -1;
+diff --git a/migration/qemu-file.h b/migration/qemu-file.h
+index a9b6d6ccb7..8752d27c74 100644
+--- a/migration/qemu-file.h
++++ b/migration/qemu-file.h
+@@ -120,6 +120,7 @@ typedef struct QEMUFileHooks {
+ } QEMUFileHooks;
+ QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops);
++QEMUFile *qemu_fopen_ops_sized(void *opaque, const QEMUFileOps *ops, size_t buffer_size);
+ void qemu_file_set_hooks(QEMUFile *f, const QEMUFileHooks *hooks);
+ int qemu_get_fd(QEMUFile *f);
+ int qemu_fclose(QEMUFile *f);
+diff --git a/savevm-async.c b/savevm-async.c
+index 7fd8a69374..0388cebbe9 100644
+--- a/savevm-async.c
++++ b/savevm-async.c
+@@ -392,7 +392,7 @@ void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
+         goto restart;
+     }
+-    snap_state.file = qemu_fopen_ops(&snap_state, &block_file_ops);
++    snap_state.file = qemu_fopen_ops_sized(&snap_state, &block_file_ops, 4 * 1024 * 1024);
+     if (!snap_state.file) {
+         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "failed to open '%s'", statefile);
+@@ -514,7 +514,7 @@ int load_snapshot_from_blockdev(const char *filename, Error **errp)
+     blk_op_block_all(be, blocker);
+     /* restore the VM state */
+-    f = qemu_fopen_ops(be, &loadstate_file_ops);
++    f = qemu_fopen_ops_sized(be, &loadstate_file_ops, 4 * 1024 * 1024);
+     if (!f) {
+         error_setg(errp, "Could not open VM state file");
+         goto the_end;
diff --git a/debian/patches/pve/0019-PVE-Add-dummy-id-command-line-parameter.patch b/debian/patches/pve/0019-PVE-Add-dummy-id-command-line-parameter.patch
deleted file mode 100644 (file)
index dd35c9f..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:48 +0200
-Subject: [PATCH] PVE: Add dummy -id command line parameter
-
-This used to be part of the qemu-side PVE authentication for
-VNC. Now this does nothing.
-
-Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- qemu-options.hx | 3 +++
- softmmu/vl.c    | 8 ++++++++
- 2 files changed, 11 insertions(+)
-
-diff --git a/qemu-options.hx b/qemu-options.hx
-index 55eef64ddf..e11b4f8ff5 100644
---- a/qemu-options.hx
-+++ b/qemu-options.hx
-@@ -904,6 +904,9 @@ DEFHEADING()
- DEFHEADING(Block device options:)
-+DEF("id", HAS_ARG, QEMU_OPTION_id,
-+    "-id n           set the VMID", QEMU_ARCH_ALL)
-+
- DEF("fda", HAS_ARG, QEMU_OPTION_fda,
-     "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n", QEMU_ARCH_ALL)
- DEF("fdb", HAS_ARG, QEMU_OPTION_fdb, "", QEMU_ARCH_ALL)
-diff --git a/softmmu/vl.c b/softmmu/vl.c
-index 4b45eb0c37..9de81875fd 100644
---- a/softmmu/vl.c
-+++ b/softmmu/vl.c
-@@ -2815,6 +2815,7 @@ static void create_default_memdev(MachineState *ms, const char *path)
- void qemu_init(int argc, char **argv, char **envp)
- {
-     int i;
-+    long vm_id;
-     int snapshot, linux_boot;
-     const char *initrd_filename;
-     const char *kernel_filename, *kernel_cmdline;
-@@ -3518,6 +3519,13 @@ void qemu_init(int argc, char **argv, char **envp)
-                     exit(1);
-                 }
-                 break;
-+            case QEMU_OPTION_id:
-+                vm_id = strtol(optarg, (char **)&optarg, 10);
-+                if (*optarg != 0 || vm_id < 100 || vm_id > INT_MAX) {
-+                    error_report("invalid -id argument %s", optarg);
-+                    exit(1);
-+                }
-+                break;
-             case QEMU_OPTION_vnc:
-                 vnc_parse(optarg, &error_fatal);
-                 break;
diff --git a/debian/patches/pve/0019-PVE-block-add-the-zeroinit-block-driver-filter.patch b/debian/patches/pve/0019-PVE-block-add-the-zeroinit-block-driver-filter.patch
new file mode 100644 (file)
index 0000000..52f7afc
--- /dev/null
@@ -0,0 +1,227 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:47 +0200
+Subject: [PATCH] PVE: block: add the zeroinit block driver filter
+
+Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
+---
+ block/Makefile.objs |   1 +
+ block/zeroinit.c    | 197 ++++++++++++++++++++++++++++++++++++++++++++
+ 2 files changed, 198 insertions(+)
+ create mode 100644 block/zeroinit.c
+
+diff --git a/block/Makefile.objs b/block/Makefile.objs
+index 3635b6b4c1..1282445672 100644
+--- a/block/Makefile.objs
++++ b/block/Makefile.objs
+@@ -11,6 +11,7 @@ block-obj-$(CONFIG_QED) += qed.o qed-l2-cache.o qed-table.o qed-cluster.o
+ block-obj-$(CONFIG_QED) += qed-check.o
+ block-obj-y += vhdx.o vhdx-endian.o vhdx-log.o
+ block-obj-y += quorum.o
++block-obj-y += zeroinit.o
+ block-obj-y += blkdebug.o blkverify.o blkreplay.o
+ block-obj-$(CONFIG_PARALLELS) += parallels.o
+ block-obj-y += blklogwrites.o
+diff --git a/block/zeroinit.c b/block/zeroinit.c
+new file mode 100644
+index 0000000000..ff38388d94
+--- /dev/null
++++ b/block/zeroinit.c
+@@ -0,0 +1,197 @@
++/*
++ * Filter to fake a zero-initialized block device.
++ *
++ * Copyright (c) 2016 Wolfgang Bumiller <w.bumiller@proxmox.com>
++ * Copyright (c) 2016 Proxmox Server Solutions GmbH
++ *
++ * This work is licensed under the terms of the GNU GPL, version 2 or later.
++ * See the COPYING file in the top-level directory.
++ */
++
++#include "qemu/osdep.h"
++#include "qapi/error.h"
++#include "block/block_int.h"
++#include "qapi/qmp/qdict.h"
++#include "qapi/qmp/qstring.h"
++#include "qemu/cutils.h"
++#include "qemu/option.h"
++#include "qemu/module.h"
++
++typedef struct {
++    bool has_zero_init;
++    int64_t extents;
++} BDRVZeroinitState;
++
++/* Valid blkverify filenames look like blkverify:path/to/raw_image:path/to/image */
++static void zeroinit_parse_filename(const char *filename, QDict *options,
++                                     Error **errp)
++{
++    QString *raw_path;
++
++    /* Parse the blkverify: prefix */
++    if (!strstart(filename, "zeroinit:", &filename)) {
++        /* There was no prefix; therefore, all options have to be already
++           present in the QDict (except for the filename) */
++        return;
++    }
++
++    raw_path = qstring_from_str(filename);
++    qdict_put(options, "x-next", raw_path);
++}
++
++static QemuOptsList runtime_opts = {
++    .name = "zeroinit",
++    .head = QTAILQ_HEAD_INITIALIZER(runtime_opts.head),
++    .desc = {
++        {
++            .name = "x-next",
++            .type = QEMU_OPT_STRING,
++            .help = "[internal use only, will be removed]",
++        },
++        {
++            .name = "x-zeroinit",
++            .type = QEMU_OPT_BOOL,
++            .help = "set has_initialized_zero flag",
++        },
++        { /* end of list */ }
++    },
++};
++
++static int zeroinit_open(BlockDriverState *bs, QDict *options, int flags,
++                          Error **errp)
++{
++    BDRVZeroinitState *s = bs->opaque;
++    QemuOpts *opts;
++    Error *local_err = NULL;
++    int ret;
++
++    s->extents = 0;
++
++    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
++    qemu_opts_absorb_qdict(opts, options, &local_err);
++    if (local_err) {
++        error_propagate(errp, local_err);
++        ret = -EINVAL;
++        goto fail;
++    }
++
++    /* Open the raw file */
++    bs->file = bdrv_open_child(qemu_opt_get(opts, "x-next"), options, "next",
++                               bs, &child_file, false, &local_err);
++    if (local_err) {
++        ret = -EINVAL;
++        error_propagate(errp, local_err);
++        goto fail;
++    }
++
++    /* set the options */
++    s->has_zero_init = qemu_opt_get_bool(opts, "x-zeroinit", true);
++
++    ret = 0;
++fail:
++    if (ret < 0) {
++        bdrv_unref_child(bs, bs->file);
++    }
++    qemu_opts_del(opts);
++    return ret;
++}
++
++static void zeroinit_close(BlockDriverState *bs)
++{
++    BDRVZeroinitState *s = bs->opaque;
++    (void)s;
++}
++
++static int64_t zeroinit_getlength(BlockDriverState *bs)
++{
++    return bdrv_getlength(bs->file->bs);
++}
++
++static int coroutine_fn zeroinit_co_preadv(BlockDriverState *bs,
++    uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
++{
++    return bdrv_co_preadv(bs->file, offset, bytes, qiov, flags);
++}
++
++static int coroutine_fn zeroinit_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
++                                                 int count, BdrvRequestFlags flags)
++{
++    BDRVZeroinitState *s = bs->opaque;
++    if (offset >= s->extents)
++        return 0;
++    return bdrv_pwrite_zeroes(bs->file, offset, count, flags);
++}
++
++static int coroutine_fn zeroinit_co_pwritev(BlockDriverState *bs,
++    uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)
++{
++    BDRVZeroinitState *s = bs->opaque;
++    int64_t extents = offset + bytes;
++    if (extents > s->extents)
++        s->extents = extents;
++    return bdrv_co_pwritev(bs->file, offset, bytes, qiov, flags);
++}
++
++static coroutine_fn int zeroinit_co_flush(BlockDriverState *bs)
++{
++    return bdrv_co_flush(bs->file->bs);
++}
++
++static int zeroinit_has_zero_init(BlockDriverState *bs)
++{
++    BDRVZeroinitState *s = bs->opaque;
++    return s->has_zero_init;
++}
++
++static int coroutine_fn zeroinit_co_pdiscard(BlockDriverState *bs,
++                                             int64_t offset, int count)
++{
++    return bdrv_co_pdiscard(bs->file, offset, count);
++}
++
++static int zeroinit_co_truncate(BlockDriverState *bs, int64_t offset,
++                                _Bool exact, PreallocMode prealloc, Error **errp)
++{
++    return bdrv_co_truncate(bs->file, offset, exact, prealloc, errp);
++}
++
++static int zeroinit_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
++{
++    return bdrv_get_info(bs->file->bs, bdi);
++}
++
++static BlockDriver bdrv_zeroinit = {
++    .format_name                      = "zeroinit",
++    .protocol_name                    = "zeroinit",
++    .instance_size                    = sizeof(BDRVZeroinitState),
++
++    .bdrv_parse_filename              = zeroinit_parse_filename,
++    .bdrv_file_open                   = zeroinit_open,
++    .bdrv_close                       = zeroinit_close,
++    .bdrv_getlength                   = zeroinit_getlength,
++    .bdrv_child_perm                  = bdrv_filter_default_perms,
++    .bdrv_co_flush_to_disk            = zeroinit_co_flush,
++
++    .bdrv_co_pwrite_zeroes            = zeroinit_co_pwrite_zeroes,
++    .bdrv_co_pwritev                  = zeroinit_co_pwritev,
++    .bdrv_co_preadv                   = zeroinit_co_preadv,
++    .bdrv_co_flush                    = zeroinit_co_flush,
++
++    .is_filter                        = true,
++
++    .bdrv_has_zero_init               = zeroinit_has_zero_init,
++
++    .bdrv_co_block_status             = bdrv_co_block_status_from_file,
++
++    .bdrv_co_pdiscard                 = zeroinit_co_pdiscard,
++
++    .bdrv_co_truncate                 = zeroinit_co_truncate,
++    .bdrv_get_info                    = zeroinit_get_info,
++};
++
++static void bdrv_zeroinit_init(void)
++{
++    bdrv_register(&bdrv_zeroinit);
++}
++
++block_init(bdrv_zeroinit_init);
diff --git a/debian/patches/pve/0020-PVE-Add-dummy-id-command-line-parameter.patch b/debian/patches/pve/0020-PVE-Add-dummy-id-command-line-parameter.patch
new file mode 100644 (file)
index 0000000..dd35c9f
--- /dev/null
@@ -0,0 +1,55 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:48 +0200
+Subject: [PATCH] PVE: Add dummy -id command line parameter
+
+This used to be part of the qemu-side PVE authentication for
+VNC. Now this does nothing.
+
+Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
+---
+ qemu-options.hx | 3 +++
+ softmmu/vl.c    | 8 ++++++++
+ 2 files changed, 11 insertions(+)
+
+diff --git a/qemu-options.hx b/qemu-options.hx
+index 55eef64ddf..e11b4f8ff5 100644
+--- a/qemu-options.hx
++++ b/qemu-options.hx
+@@ -904,6 +904,9 @@ DEFHEADING()
+ DEFHEADING(Block device options:)
++DEF("id", HAS_ARG, QEMU_OPTION_id,
++    "-id n           set the VMID", QEMU_ARCH_ALL)
++
+ DEF("fda", HAS_ARG, QEMU_OPTION_fda,
+     "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n", QEMU_ARCH_ALL)
+ DEF("fdb", HAS_ARG, QEMU_OPTION_fdb, "", QEMU_ARCH_ALL)
+diff --git a/softmmu/vl.c b/softmmu/vl.c
+index 4b45eb0c37..9de81875fd 100644
+--- a/softmmu/vl.c
++++ b/softmmu/vl.c
+@@ -2815,6 +2815,7 @@ static void create_default_memdev(MachineState *ms, const char *path)
+ void qemu_init(int argc, char **argv, char **envp)
+ {
+     int i;
++    long vm_id;
+     int snapshot, linux_boot;
+     const char *initrd_filename;
+     const char *kernel_filename, *kernel_cmdline;
+@@ -3518,6 +3519,13 @@ void qemu_init(int argc, char **argv, char **envp)
+                     exit(1);
+                 }
+                 break;
++            case QEMU_OPTION_id:
++                vm_id = strtol(optarg, (char **)&optarg, 10);
++                if (*optarg != 0 || vm_id < 100 || vm_id > INT_MAX) {
++                    error_report("invalid -id argument %s", optarg);
++                    exit(1);
++                }
++                break;
+             case QEMU_OPTION_vnc:
+                 vnc_parse(optarg, &error_fatal);
+                 break;
diff --git a/debian/patches/pve/0020-PVE-Config-Revert-target-i386-disable-LINT0-after-re.patch b/debian/patches/pve/0020-PVE-Config-Revert-target-i386-disable-LINT0-after-re.patch
deleted file mode 100644 (file)
index c8da15b..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:49 +0200
-Subject: [PATCH] PVE: [Config] Revert "target-i386: disable LINT0 after reset"
-
-This reverts commit b8eb5512fd8a115f164edbbe897cdf8884920ccb.
-
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- hw/intc/apic_common.c | 9 +++++++++
- 1 file changed, 9 insertions(+)
-
-diff --git a/hw/intc/apic_common.c b/hw/intc/apic_common.c
-index 9ec0f2deb2..a00d45251f 100644
---- a/hw/intc/apic_common.c
-+++ b/hw/intc/apic_common.c
-@@ -259,6 +259,15 @@ static void apic_reset_common(DeviceState *dev)
-     info->vapic_base_update(s);
-     apic_init_reset(dev);
-+
-+    if (bsp) {
-+        /*
-+         * LINT0 delivery mode on CPU #0 is set to ExtInt at initialization
-+         * time typically by BIOS, so PIC interrupt can be delivered to the
-+         * processor when local APIC is enabled.
-+         */
-+        s->lvt[APIC_LVT_LINT0] = 0x700;
-+    }
- }
- static const VMStateDescription vmstate_apic_common;
diff --git a/debian/patches/pve/0021-PVE-Config-Revert-target-i386-disable-LINT0-after-re.patch b/debian/patches/pve/0021-PVE-Config-Revert-target-i386-disable-LINT0-after-re.patch
new file mode 100644 (file)
index 0000000..c8da15b
--- /dev/null
@@ -0,0 +1,32 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:49 +0200
+Subject: [PATCH] PVE: [Config] Revert "target-i386: disable LINT0 after reset"
+
+This reverts commit b8eb5512fd8a115f164edbbe897cdf8884920ccb.
+
+Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
+---
+ hw/intc/apic_common.c | 9 +++++++++
+ 1 file changed, 9 insertions(+)
+
+diff --git a/hw/intc/apic_common.c b/hw/intc/apic_common.c
+index 9ec0f2deb2..a00d45251f 100644
+--- a/hw/intc/apic_common.c
++++ b/hw/intc/apic_common.c
+@@ -259,6 +259,15 @@ static void apic_reset_common(DeviceState *dev)
+     info->vapic_base_update(s);
+     apic_init_reset(dev);
++
++    if (bsp) {
++        /*
++         * LINT0 delivery mode on CPU #0 is set to ExtInt at initialization
++         * time typically by BIOS, so PIC interrupt can be delivered to the
++         * processor when local APIC is enabled.
++         */
++        s->lvt[APIC_LVT_LINT0] = 0x700;
++    }
+ }
+ static const VMStateDescription vmstate_apic_common;
diff --git a/debian/patches/pve/0021-PVE-Up-Config-file-posix-make-locking-optiono-on-cre.patch b/debian/patches/pve/0021-PVE-Up-Config-file-posix-make-locking-optiono-on-cre.patch
deleted file mode 100644 (file)
index afecbfc..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:50 +0200
-Subject: [PATCH] PVE: [Up+Config] file-posix: make locking optiono on create
-
-Otherwise creating images on nfs/cifs can be problematic.
-
-Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- block/file-posix.c   | 61 +++++++++++++++++++++++++++++---------------
- qapi/block-core.json |  3 ++-
- 2 files changed, 43 insertions(+), 21 deletions(-)
-
-diff --git a/block/file-posix.c b/block/file-posix.c
-index b527e82a82..36ebd0967e 100644
---- a/block/file-posix.c
-+++ b/block/file-posix.c
-@@ -2309,6 +2309,7 @@ raw_co_create(BlockdevCreateOptions *options, Error **errp)
-     int fd;
-     uint64_t perm, shared;
-     int result = 0;
-+    bool locked = false;
-     /* Validate options and set default values */
-     assert(options->driver == BLOCKDEV_DRIVER_FILE);
-@@ -2342,19 +2343,22 @@ raw_co_create(BlockdevCreateOptions *options, Error **errp)
-     perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
-     shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
--    /* Step one: Take locks */
--    result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
--    if (result < 0) {
--        goto out_close;
--    }
-+    if (file_opts->locking != ON_OFF_AUTO_OFF) {
-+        /* Step one: Take locks */
-+        result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
-+        if (result < 0) {
-+            goto out_close;
-+        }
-+        locked = true;
--    /* Step two: Check that nobody else has taken conflicting locks */
--    result = raw_check_lock_bytes(fd, perm, shared, errp);
--    if (result < 0) {
--        error_append_hint(errp,
--                          "Is another process using the image [%s]?\n",
--                          file_opts->filename);
--        goto out_unlock;
-+        /* Step two: Check that nobody else has taken conflicting locks */
-+        result = raw_check_lock_bytes(fd, perm, shared, errp);
-+        if (result < 0) {
-+            error_append_hint(errp,
-+                              "Is another process using the image [%s]?\n",
-+                              file_opts->filename);
-+            goto out_unlock;
-+        }
-     }
-     /* Clear the file by truncating it to 0 */
-@@ -2387,13 +2391,15 @@ raw_co_create(BlockdevCreateOptions *options, Error **errp)
-     }
- out_unlock:
--    raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
--    if (local_err) {
--        /* The above call should not fail, and if it does, that does
--         * not mean the whole creation operation has failed.  So
--         * report it the user for their convenience, but do not report
--         * it to the caller. */
--        warn_report_err(local_err);
-+    if (locked) {
-+        raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
-+        if (local_err) {
-+            /* The above call should not fail, and if it does, that does
-+             * not mean the whole creation operation has failed.  So
-+             * report it the user for their convenience, but do not report
-+             * it to the caller. */
-+            warn_report_err(local_err);
-+        }
-     }
- out_close:
-@@ -2416,6 +2422,7 @@ static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
-     PreallocMode prealloc;
-     char *buf = NULL;
-     Error *local_err = NULL;
-+    OnOffAuto locking;
-     /* Skip file: protocol prefix */
-     strstart(filename, "file:", &filename);
-@@ -2433,6 +2440,18 @@ static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
-         return -EINVAL;
-     }
-+    locking = qapi_enum_parse(&OnOffAuto_lookup,
-+                              qemu_opt_get(opts, "locking"),
-+                              ON_OFF_AUTO_AUTO, &local_err);
-+    if (local_err) {
-+        error_propagate(errp, local_err);
-+        return -EINVAL;
-+    }
-+
-+    if (locking == ON_OFF_AUTO_AUTO) {
-+        locking = ON_OFF_AUTO_OFF;
-+    }
-+
-     options = (BlockdevCreateOptions) {
-         .driver     = BLOCKDEV_DRIVER_FILE,
-         .u.file     = {
-@@ -2442,6 +2461,8 @@ static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
-             .preallocation      = prealloc,
-             .has_nocow          = true,
-             .nocow              = nocow,
-+            .has_locking        = true,
-+            .locking            = locking,
-         },
-     };
-     return raw_co_create(&options, errp);
-@@ -2983,7 +3004,7 @@ static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
-     }
-     /* Copy locks to the new fd */
--    if (s->perm_change_fd) {
-+    if (s->use_lock && s->perm_change_fd) {
-         ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
-                                    false, errp);
-         if (ret < 0) {
-diff --git a/qapi/block-core.json b/qapi/block-core.json
-index 943df1926a..4c55464f86 100644
---- a/qapi/block-core.json
-+++ b/qapi/block-core.json
-@@ -4183,7 +4183,8 @@
-   'data': { 'filename':         'str',
-             'size':             'size',
-             '*preallocation':   'PreallocMode',
--            '*nocow':           'bool' } }
-+            '*nocow':           'bool',
-+            '*locking':         'OnOffAuto' } }
- ##
- # @BlockdevCreateOptionsGluster:
diff --git a/debian/patches/pve/0022-PVE-Up-Config-file-posix-make-locking-optiono-on-cre.patch b/debian/patches/pve/0022-PVE-Up-Config-file-posix-make-locking-optiono-on-cre.patch
new file mode 100644 (file)
index 0000000..afecbfc
--- /dev/null
@@ -0,0 +1,143 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:50 +0200
+Subject: [PATCH] PVE: [Up+Config] file-posix: make locking optiono on create
+
+Otherwise creating images on nfs/cifs can be problematic.
+
+Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
+---
+ block/file-posix.c   | 61 +++++++++++++++++++++++++++++---------------
+ qapi/block-core.json |  3 ++-
+ 2 files changed, 43 insertions(+), 21 deletions(-)
+
+diff --git a/block/file-posix.c b/block/file-posix.c
+index b527e82a82..36ebd0967e 100644
+--- a/block/file-posix.c
++++ b/block/file-posix.c
+@@ -2309,6 +2309,7 @@ raw_co_create(BlockdevCreateOptions *options, Error **errp)
+     int fd;
+     uint64_t perm, shared;
+     int result = 0;
++    bool locked = false;
+     /* Validate options and set default values */
+     assert(options->driver == BLOCKDEV_DRIVER_FILE);
+@@ -2342,19 +2343,22 @@ raw_co_create(BlockdevCreateOptions *options, Error **errp)
+     perm = BLK_PERM_WRITE | BLK_PERM_RESIZE;
+     shared = BLK_PERM_ALL & ~BLK_PERM_RESIZE;
+-    /* Step one: Take locks */
+-    result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
+-    if (result < 0) {
+-        goto out_close;
+-    }
++    if (file_opts->locking != ON_OFF_AUTO_OFF) {
++        /* Step one: Take locks */
++        result = raw_apply_lock_bytes(NULL, fd, perm, ~shared, false, errp);
++        if (result < 0) {
++            goto out_close;
++        }
++        locked = true;
+-    /* Step two: Check that nobody else has taken conflicting locks */
+-    result = raw_check_lock_bytes(fd, perm, shared, errp);
+-    if (result < 0) {
+-        error_append_hint(errp,
+-                          "Is another process using the image [%s]?\n",
+-                          file_opts->filename);
+-        goto out_unlock;
++        /* Step two: Check that nobody else has taken conflicting locks */
++        result = raw_check_lock_bytes(fd, perm, shared, errp);
++        if (result < 0) {
++            error_append_hint(errp,
++                              "Is another process using the image [%s]?\n",
++                              file_opts->filename);
++            goto out_unlock;
++        }
+     }
+     /* Clear the file by truncating it to 0 */
+@@ -2387,13 +2391,15 @@ raw_co_create(BlockdevCreateOptions *options, Error **errp)
+     }
+ out_unlock:
+-    raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
+-    if (local_err) {
+-        /* The above call should not fail, and if it does, that does
+-         * not mean the whole creation operation has failed.  So
+-         * report it the user for their convenience, but do not report
+-         * it to the caller. */
+-        warn_report_err(local_err);
++    if (locked) {
++        raw_apply_lock_bytes(NULL, fd, 0, 0, true, &local_err);
++        if (local_err) {
++            /* The above call should not fail, and if it does, that does
++             * not mean the whole creation operation has failed.  So
++             * report it the user for their convenience, but do not report
++             * it to the caller. */
++            warn_report_err(local_err);
++        }
+     }
+ out_close:
+@@ -2416,6 +2422,7 @@ static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
+     PreallocMode prealloc;
+     char *buf = NULL;
+     Error *local_err = NULL;
++    OnOffAuto locking;
+     /* Skip file: protocol prefix */
+     strstart(filename, "file:", &filename);
+@@ -2433,6 +2440,18 @@ static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
+         return -EINVAL;
+     }
++    locking = qapi_enum_parse(&OnOffAuto_lookup,
++                              qemu_opt_get(opts, "locking"),
++                              ON_OFF_AUTO_AUTO, &local_err);
++    if (local_err) {
++        error_propagate(errp, local_err);
++        return -EINVAL;
++    }
++
++    if (locking == ON_OFF_AUTO_AUTO) {
++        locking = ON_OFF_AUTO_OFF;
++    }
++
+     options = (BlockdevCreateOptions) {
+         .driver     = BLOCKDEV_DRIVER_FILE,
+         .u.file     = {
+@@ -2442,6 +2461,8 @@ static int coroutine_fn raw_co_create_opts(BlockDriver *drv,
+             .preallocation      = prealloc,
+             .has_nocow          = true,
+             .nocow              = nocow,
++            .has_locking        = true,
++            .locking            = locking,
+         },
+     };
+     return raw_co_create(&options, errp);
+@@ -2983,7 +3004,7 @@ static int raw_check_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared,
+     }
+     /* Copy locks to the new fd */
+-    if (s->perm_change_fd) {
++    if (s->use_lock && s->perm_change_fd) {
+         ret = raw_apply_lock_bytes(NULL, s->perm_change_fd, perm, ~shared,
+                                    false, errp);
+         if (ret < 0) {
+diff --git a/qapi/block-core.json b/qapi/block-core.json
+index 943df1926a..4c55464f86 100644
+--- a/qapi/block-core.json
++++ b/qapi/block-core.json
+@@ -4183,7 +4183,8 @@
+   'data': { 'filename':         'str',
+             'size':             'size',
+             '*preallocation':   'PreallocMode',
+-            '*nocow':           'bool' } }
++            '*nocow':           'bool',
++            '*locking':         'OnOffAuto' } }
+ ##
+ # @BlockdevCreateOptionsGluster:
diff --git a/debian/patches/pve/0022-PVE-savevm-async-kick-AIO-wait-on-block-state-write.patch b/debian/patches/pve/0022-PVE-savevm-async-kick-AIO-wait-on-block-state-write.patch
deleted file mode 100644 (file)
index fc2c000..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Thomas Lamprecht <t.lamprecht@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:51 +0200
-Subject: [PATCH] PVE: savevm-async: kick AIO wait on block state write
-
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- savevm-async.c | 1 +
- 1 file changed, 1 insertion(+)
-
-diff --git a/savevm-async.c b/savevm-async.c
-index 54ceeae26c..393d55af2a 100644
---- a/savevm-async.c
-+++ b/savevm-async.c
-@@ -158,6 +158,7 @@ static void coroutine_fn block_state_write_entry(void *opaque) {
-     BlkRwCo *rwco = opaque;
-     rwco->ret = blk_co_pwritev(snap_state.target, rwco->offset, rwco->qiov->size,
-                                rwco->qiov, 0);
-+    aio_wait_kick();
- }
- static ssize_t block_state_writev_buffer(void *opaque, struct iovec *iov,
diff --git a/debian/patches/pve/0023-PVE-monitor-disable-oob-capability.patch b/debian/patches/pve/0023-PVE-monitor-disable-oob-capability.patch
new file mode 100644 (file)
index 0000000..893b3ef
--- /dev/null
@@ -0,0 +1,33 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:53 +0200
+Subject: [PATCH] PVE: monitor: disable oob capability
+
+A bisect revealed that commit 8258292e18c3
+("monitor: Remove "x-oob", offer capability "oob" unconditionally")
+causes unexpected hangs when restoring live snapshots from some
+types of block devices (particularly RBD).
+We need to figure out what's happnening there. For now, since we
+had this disabled before and probably don't need it now either,
+disable oob, so we can get a functioning qemu out...
+
+Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
+---
+ monitor/qmp.c | 3 +--
+ 1 file changed, 1 insertion(+), 2 deletions(-)
+
+diff --git a/monitor/qmp.c b/monitor/qmp.c
+index f89e7daf27..ed5e39fcf7 100644
+--- a/monitor/qmp.c
++++ b/monitor/qmp.c
+@@ -406,8 +406,7 @@ void monitor_init_qmp(Chardev *chr, bool pretty, Error **errp)
+     qemu_chr_fe_set_echo(&mon->common.chr, true);
+     /* Note: we run QMP monitor in I/O thread when @chr supports that */
+-    monitor_data_init(&mon->common, true, false,
+-                      qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
++    monitor_data_init(&mon->common, true, false, false);
+     mon->pretty = pretty;
diff --git a/debian/patches/pve/0023-PVE-move-snapshot-cleanup-into-bottom-half.patch b/debian/patches/pve/0023-PVE-move-snapshot-cleanup-into-bottom-half.patch
deleted file mode 100644 (file)
index c3b20bc..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:52 +0200
-Subject: [PATCH] PVE: move snapshot cleanup into bottom half
-
-as per:
-    (0ceccd858a8d) migration: qemu_savevm_state_cleanup() in cleanup
-
-may affect held locks and therefore change assumptions made
-by that function!
-
-Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- savevm-async.c | 3 ++-
- 1 file changed, 2 insertions(+), 1 deletion(-)
-
-diff --git a/savevm-async.c b/savevm-async.c
-index 393d55af2a..790e27ae37 100644
---- a/savevm-async.c
-+++ b/savevm-async.c
-@@ -201,6 +201,8 @@ static void process_savevm_cleanup(void *opaque)
-     int ret;
-     qemu_bh_delete(snap_state.cleanup_bh);
-     snap_state.cleanup_bh = NULL;
-+    qemu_savevm_state_cleanup();
-+
-     qemu_mutex_unlock_iothread();
-     qemu_thread_join(&snap_state.thread);
-     qemu_mutex_lock_iothread();
-@@ -277,7 +279,6 @@ static void *process_savevm_thread(void *opaque)
-                     save_snapshot_error("qemu_savevm_state_iterate error %d", ret);
-                     break;
-             }
--            qemu_savevm_state_cleanup();
-             DPRINTF("save complete\n");
-             break;
-         }
diff --git a/debian/patches/pve/0024-PVE-Compat-4.0-used-balloon-qemu-4-0-config-size-fal.patch b/debian/patches/pve/0024-PVE-Compat-4.0-used-balloon-qemu-4-0-config-size-fal.patch
new file mode 100644 (file)
index 0000000..0680d1f
--- /dev/null
@@ -0,0 +1,41 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Thomas Lamprecht <t.lamprecht@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:54 +0200
+Subject: [PATCH] PVE: [Compat]: 4.0 used balloon qemu-4-0-config-size false
+ here
+
+The underlying issue why this change from upstream to us arised in
+the first place is that QEMU 4.0 was already released at the point we
+run into this migration issue, so we did the then obvious fallback to
+false for virtio-balloon-device qemu-4-0-config-size.
+
+QEMU made that switch back in 4.1, where it now uses a backward
+compatible mechanism to detect if the bigger CFG sizes should be
+used, i.e., checking the VIRTIO_BALLOON_F_PAGE_POISON or
+VIRTIO_BALLOON_F_FREE_PAGE_HINT balloon feature flags.
+As for them, upstream released version 4.0 had this to true they keep
+it to true in their compatibility record for the 4.0 machine, to
+allow live migrations from 4.0 to 4.1.
+As for us, downstream released version 4.0 (first public release of
+this QEMU) had this to false, we change it back to false again, for
+the same reason.
+
+Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
+---
+ hw/core/machine.c | 3 ++-
+ 1 file changed, 2 insertions(+), 1 deletion(-)
+
+diff --git a/hw/core/machine.c b/hw/core/machine.c
+index c1a444cb75..9f56ecc4e8 100644
+--- a/hw/core/machine.c
++++ b/hw/core/machine.c
+@@ -56,7 +56,8 @@ GlobalProperty hw_compat_4_0[] = {
+     { "virtio-vga",     "edid", "false" },
+     { "virtio-gpu-device", "edid", "false" },
+     { "virtio-device", "use-started", "false" },
+-    { "virtio-balloon-device", "qemu-4-0-config-size", "true" },
++    // PVE differed from upstream for 4.0 balloon cfg size
++    { "virtio-balloon-device", "qemu-4-0-config-size", "false" },
+     { "pl031", "migrate-tick-offset", "false" },
+ };
+ const size_t hw_compat_4_0_len = G_N_ELEMENTS(hw_compat_4_0);
diff --git a/debian/patches/pve/0024-PVE-monitor-disable-oob-capability.patch b/debian/patches/pve/0024-PVE-monitor-disable-oob-capability.patch
deleted file mode 100644 (file)
index 893b3ef..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:53 +0200
-Subject: [PATCH] PVE: monitor: disable oob capability
-
-A bisect revealed that commit 8258292e18c3
-("monitor: Remove "x-oob", offer capability "oob" unconditionally")
-causes unexpected hangs when restoring live snapshots from some
-types of block devices (particularly RBD).
-We need to figure out what's happnening there. For now, since we
-had this disabled before and probably don't need it now either,
-disable oob, so we can get a functioning qemu out...
-
-Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- monitor/qmp.c | 3 +--
- 1 file changed, 1 insertion(+), 2 deletions(-)
-
-diff --git a/monitor/qmp.c b/monitor/qmp.c
-index f89e7daf27..ed5e39fcf7 100644
---- a/monitor/qmp.c
-+++ b/monitor/qmp.c
-@@ -406,8 +406,7 @@ void monitor_init_qmp(Chardev *chr, bool pretty, Error **errp)
-     qemu_chr_fe_set_echo(&mon->common.chr, true);
-     /* Note: we run QMP monitor in I/O thread when @chr supports that */
--    monitor_data_init(&mon->common, true, false,
--                      qemu_chr_has_feature(chr, QEMU_CHAR_FEATURE_GCONTEXT));
-+    monitor_data_init(&mon->common, true, false, false);
-     mon->pretty = pretty;
diff --git a/debian/patches/pve/0025-PVE-Allow-version-code-in-machine-type.patch b/debian/patches/pve/0025-PVE-Allow-version-code-in-machine-type.patch
new file mode 100644 (file)
index 0000000..e160f5c
--- /dev/null
@@ -0,0 +1,101 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Dietmar Maurer <dietmar@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:55 +0200
+Subject: [PATCH] PVE: Allow version code in machine type
+
+E.g. pc-i440fx-4.0+pve3 would print 'pve3' as version code while
+selecting pc-i440fx-4.0 as machine type.
+
+Version is made available as 'pve-version' in query-machines (same as,
+and only if 'is-current').
+
+Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
+---
+ hw/core/machine-qmp-cmds.c |  6 ++++++
+ include/hw/boards.h        |  2 ++
+ qapi/machine.json          |  3 ++-
+ softmmu/vl.c               | 15 ++++++++++++++-
+ 4 files changed, 24 insertions(+), 2 deletions(-)
+
+diff --git a/hw/core/machine-qmp-cmds.c b/hw/core/machine-qmp-cmds.c
+index 1953633e82..ca8c0dc53d 100644
+--- a/hw/core/machine-qmp-cmds.c
++++ b/hw/core/machine-qmp-cmds.c
+@@ -234,6 +234,12 @@ MachineInfoList *qmp_query_machines(Error **errp)
+         if (strcmp(mc->name, MACHINE_GET_CLASS(current_machine)->name) == 0) {
+             info->has_is_current = true;
+             info->is_current = true;
++
++            // PVE version string only exists for current machine
++            if (mc->pve_version) {
++                info->has_pve_version = true;
++                info->pve_version = g_strdup(mc->pve_version);
++            }
+         }
+         if (mc->default_cpu_type) {
+diff --git a/include/hw/boards.h b/include/hw/boards.h
+index fd4d62b501..dd395e9232 100644
+--- a/include/hw/boards.h
++++ b/include/hw/boards.h
+@@ -170,6 +170,8 @@ struct MachineClass {
+     const char *desc;
+     const char *deprecation_reason;
++    const char *pve_version;
++
+     void (*init)(MachineState *state);
+     void (*reset)(MachineState *state);
+     void (*wakeup)(MachineState *state);
+diff --git a/qapi/machine.json b/qapi/machine.json
+index f6cf28f9fd..a7f9c79a59 100644
+--- a/qapi/machine.json
++++ b/qapi/machine.json
+@@ -363,7 +363,8 @@
+   'data': { 'name': 'str', '*alias': 'str',
+             '*is-default': 'bool', '*is-current': 'bool', 'cpu-max': 'int',
+             'hotpluggable-cpus': 'bool',  'numa-mem-supported': 'bool',
+-            'deprecated': 'bool', '*default-cpu-type': 'str' } }
++            'deprecated': 'bool', '*default-cpu-type': 'str',
++            '*pve-version': 'str' } }
+ ##
+ # @query-machines:
+diff --git a/softmmu/vl.c b/softmmu/vl.c
+index 9de81875fd..8340c4ca53 100644
+--- a/softmmu/vl.c
++++ b/softmmu/vl.c
+@@ -2300,6 +2300,8 @@ static MachineClass *machine_parse(const char *name, GSList *machines)
+ {
+     MachineClass *mc;
+     GSList *el;
++    size_t pvever_index = 0;
++    gchar *name_clean;
+     if (is_help_option(name)) {
+         printf("Supported machines are:\n");
+@@ -2316,12 +2318,23 @@ static MachineClass *machine_parse(const char *name, GSList *machines)
+         exit(0);
+     }
+-    mc = find_machine(name, machines);
++    // PVE version is specified with '+' as seperator, e.g. pc-i440fx+pvever
++    pvever_index = strcspn(name, "+");
++
++    name_clean = g_strndup(name, pvever_index);
++    mc = find_machine(name_clean, machines);
++    g_free(name_clean);
++
+     if (!mc) {
+         error_report("unsupported machine type");
+         error_printf("Use -machine help to list supported machines\n");
+         exit(1);
+     }
++
++    if (pvever_index < strlen(name)) {
++        mc->pve_version = &name[pvever_index+1];
++    }
++
+     return mc;
+ }
diff --git a/debian/patches/pve/0025-PVE-Compat-4.0-used-balloon-qemu-4-0-config-size-fal.patch b/debian/patches/pve/0025-PVE-Compat-4.0-used-balloon-qemu-4-0-config-size-fal.patch
deleted file mode 100644 (file)
index 0680d1f..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Thomas Lamprecht <t.lamprecht@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:54 +0200
-Subject: [PATCH] PVE: [Compat]: 4.0 used balloon qemu-4-0-config-size false
- here
-
-The underlying issue why this change from upstream to us arised in
-the first place is that QEMU 4.0 was already released at the point we
-run into this migration issue, so we did the then obvious fallback to
-false for virtio-balloon-device qemu-4-0-config-size.
-
-QEMU made that switch back in 4.1, where it now uses a backward
-compatible mechanism to detect if the bigger CFG sizes should be
-used, i.e., checking the VIRTIO_BALLOON_F_PAGE_POISON or
-VIRTIO_BALLOON_F_FREE_PAGE_HINT balloon feature flags.
-As for them, upstream released version 4.0 had this to true they keep
-it to true in their compatibility record for the 4.0 machine, to
-allow live migrations from 4.0 to 4.1.
-As for us, downstream released version 4.0 (first public release of
-this QEMU) had this to false, we change it back to false again, for
-the same reason.
-
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- hw/core/machine.c | 3 ++-
- 1 file changed, 2 insertions(+), 1 deletion(-)
-
-diff --git a/hw/core/machine.c b/hw/core/machine.c
-index c1a444cb75..9f56ecc4e8 100644
---- a/hw/core/machine.c
-+++ b/hw/core/machine.c
-@@ -56,7 +56,8 @@ GlobalProperty hw_compat_4_0[] = {
-     { "virtio-vga",     "edid", "false" },
-     { "virtio-gpu-device", "edid", "false" },
-     { "virtio-device", "use-started", "false" },
--    { "virtio-balloon-device", "qemu-4-0-config-size", "true" },
-+    // PVE differed from upstream for 4.0 balloon cfg size
-+    { "virtio-balloon-device", "qemu-4-0-config-size", "false" },
-     { "pl031", "migrate-tick-offset", "false" },
- };
- const size_t hw_compat_4_0_len = G_N_ELEMENTS(hw_compat_4_0);
diff --git a/debian/patches/pve/0026-PVE-Allow-version-code-in-machine-type.patch b/debian/patches/pve/0026-PVE-Allow-version-code-in-machine-type.patch
deleted file mode 100644 (file)
index e160f5c..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Dietmar Maurer <dietmar@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:55 +0200
-Subject: [PATCH] PVE: Allow version code in machine type
-
-E.g. pc-i440fx-4.0+pve3 would print 'pve3' as version code while
-selecting pc-i440fx-4.0 as machine type.
-
-Version is made available as 'pve-version' in query-machines (same as,
-and only if 'is-current').
-
-Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
----
- hw/core/machine-qmp-cmds.c |  6 ++++++
- include/hw/boards.h        |  2 ++
- qapi/machine.json          |  3 ++-
- softmmu/vl.c               | 15 ++++++++++++++-
- 4 files changed, 24 insertions(+), 2 deletions(-)
-
-diff --git a/hw/core/machine-qmp-cmds.c b/hw/core/machine-qmp-cmds.c
-index 1953633e82..ca8c0dc53d 100644
---- a/hw/core/machine-qmp-cmds.c
-+++ b/hw/core/machine-qmp-cmds.c
-@@ -234,6 +234,12 @@ MachineInfoList *qmp_query_machines(Error **errp)
-         if (strcmp(mc->name, MACHINE_GET_CLASS(current_machine)->name) == 0) {
-             info->has_is_current = true;
-             info->is_current = true;
-+
-+            // PVE version string only exists for current machine
-+            if (mc->pve_version) {
-+                info->has_pve_version = true;
-+                info->pve_version = g_strdup(mc->pve_version);
-+            }
-         }
-         if (mc->default_cpu_type) {
-diff --git a/include/hw/boards.h b/include/hw/boards.h
-index fd4d62b501..dd395e9232 100644
---- a/include/hw/boards.h
-+++ b/include/hw/boards.h
-@@ -170,6 +170,8 @@ struct MachineClass {
-     const char *desc;
-     const char *deprecation_reason;
-+    const char *pve_version;
-+
-     void (*init)(MachineState *state);
-     void (*reset)(MachineState *state);
-     void (*wakeup)(MachineState *state);
-diff --git a/qapi/machine.json b/qapi/machine.json
-index f6cf28f9fd..a7f9c79a59 100644
---- a/qapi/machine.json
-+++ b/qapi/machine.json
-@@ -363,7 +363,8 @@
-   'data': { 'name': 'str', '*alias': 'str',
-             '*is-default': 'bool', '*is-current': 'bool', 'cpu-max': 'int',
-             'hotpluggable-cpus': 'bool',  'numa-mem-supported': 'bool',
--            'deprecated': 'bool', '*default-cpu-type': 'str' } }
-+            'deprecated': 'bool', '*default-cpu-type': 'str',
-+            '*pve-version': 'str' } }
- ##
- # @query-machines:
-diff --git a/softmmu/vl.c b/softmmu/vl.c
-index 9de81875fd..8340c4ca53 100644
---- a/softmmu/vl.c
-+++ b/softmmu/vl.c
-@@ -2300,6 +2300,8 @@ static MachineClass *machine_parse(const char *name, GSList *machines)
- {
-     MachineClass *mc;
-     GSList *el;
-+    size_t pvever_index = 0;
-+    gchar *name_clean;
-     if (is_help_option(name)) {
-         printf("Supported machines are:\n");
-@@ -2316,12 +2318,23 @@ static MachineClass *machine_parse(const char *name, GSList *machines)
-         exit(0);
-     }
--    mc = find_machine(name, machines);
-+    // PVE version is specified with '+' as seperator, e.g. pc-i440fx+pvever
-+    pvever_index = strcspn(name, "+");
-+
-+    name_clean = g_strndup(name, pvever_index);
-+    mc = find_machine(name_clean, machines);
-+    g_free(name_clean);
-+
-     if (!mc) {
-         error_report("unsupported machine type");
-         error_printf("Use -machine help to list supported machines\n");
-         exit(1);
-     }
-+
-+    if (pvever_index < strlen(name)) {
-+        mc->pve_version = &name[pvever_index+1];
-+    }
-+
-     return mc;
- }
diff --git a/debian/patches/pve/0026-PVE-Backup-modify-job-api.patch b/debian/patches/pve/0026-PVE-Backup-modify-job-api.patch
new file mode 100644 (file)
index 0000000..bd61512
--- /dev/null
@@ -0,0 +1,92 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Wolfgang Bumiller <w.bumiller@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:56 +0200
+Subject: [PATCH] PVE-Backup: modify job api
+
+Introduce a pause_count parameter to start a backup in
+paused mode. This way backups of multiple drives can be
+started up sequentially via the completion callback while
+having been started at the same point in time.
+
+Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
+---
+ block/backup.c            | 3 +++
+ block/replication.c       | 2 +-
+ blockdev.c                | 3 ++-
+ include/block/block_int.h | 1 +
+ job.c                     | 2 +-
+ 5 files changed, 8 insertions(+), 3 deletions(-)
+
+diff --git a/block/backup.c b/block/backup.c
+index a7a7dcaf4c..ecd93e91e0 100644
+--- a/block/backup.c
++++ b/block/backup.c
+@@ -338,6 +338,7 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
+                   BlockdevOnError on_target_error,
+                   int creation_flags,
+                   BlockCompletionFunc *cb, void *opaque,
++                  int pause_count,
+                   JobTxn *txn, Error **errp)
+ {
+     int64_t len;
+@@ -459,6 +460,8 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
+     block_job_add_bdrv(&job->common, "target", target, 0, BLK_PERM_ALL,
+                        &error_abort);
++    job->common.job.pause_count += pause_count;
++
+     return &job->common;
+  error:
+diff --git a/block/replication.c b/block/replication.c
+index da013c2041..17246a822c 100644
+--- a/block/replication.c
++++ b/block/replication.c
+@@ -554,7 +554,7 @@ static void replication_start(ReplicationState *rs, ReplicationMode mode,
+                                 0, MIRROR_SYNC_MODE_NONE, NULL, 0, false, NULL,
+                                 BLOCKDEV_ON_ERROR_REPORT,
+                                 BLOCKDEV_ON_ERROR_REPORT, JOB_INTERNAL,
+-                                backup_job_completed, bs, NULL, &local_err);
++                                backup_job_completed, bs, 0, NULL, &local_err);
+         if (local_err) {
+             error_propagate(errp, local_err);
+             backup_job_cleanup(bs);
+diff --git a/blockdev.c b/blockdev.c
+index 5faddaa705..65c358e4ef 100644
+--- a/blockdev.c
++++ b/blockdev.c
+@@ -3114,7 +3114,8 @@ static BlockJob *do_backup_common(BackupCommon *backup,
+                             backup->filter_node_name,
+                             backup->on_source_error,
+                             backup->on_target_error,
+-                            job_flags, NULL, NULL, txn, errp);
++                            job_flags, NULL, NULL, 0, txn, errp);
++
+     return job;
+ }
+diff --git a/include/block/block_int.h b/include/block/block_int.h
+index 4c3587ea19..336f71e69d 100644
+--- a/include/block/block_int.h
++++ b/include/block/block_int.h
+@@ -1219,6 +1219,7 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
+                             BlockdevOnError on_target_error,
+                             int creation_flags,
+                             BlockCompletionFunc *cb, void *opaque,
++                            int pause_count,
+                             JobTxn *txn, Error **errp);
+ BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
+diff --git a/job.c b/job.c
+index 53be57a3a0..e82253e041 100644
+--- a/job.c
++++ b/job.c
+@@ -918,7 +918,7 @@ void job_start(Job *job)
+     job->co = qemu_coroutine_create(job_co_entry, job);
+     job->pause_count--;
+     job->busy = true;
+-    job->paused = false;
++    job->paused = job->pause_count > 0;
+     job_state_transition(job, JOB_STATUS_RUNNING);
+     aio_co_enter(job->aio_context, job->co);
+ }
diff --git a/debian/patches/pve/0027-PVE-Backup-add-vma-backup-format-code.patch b/debian/patches/pve/0027-PVE-Backup-add-vma-backup-format-code.patch
new file mode 100644 (file)
index 0000000..b44d882
--- /dev/null
@@ -0,0 +1,2711 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Dietmar Maurer <dietmar@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:57 +0200
+Subject: [PATCH] PVE-Backup: add vma backup format code
+
+---
+ Makefile      |   3 +-
+ Makefile.objs |   1 +
+ vma-reader.c  | 857 ++++++++++++++++++++++++++++++++++++++++++++++++++
+ vma-writer.c  | 790 ++++++++++++++++++++++++++++++++++++++++++++++
+ vma.c         | 839 ++++++++++++++++++++++++++++++++++++++++++++++++
+ vma.h         | 150 +++++++++
+ 6 files changed, 2639 insertions(+), 1 deletion(-)
+ create mode 100644 vma-reader.c
+ create mode 100644 vma-writer.c
+ create mode 100644 vma.c
+ create mode 100644 vma.h
+
+diff --git a/Makefile b/Makefile
+index 8a9113e666..74c2039005 100644
+--- a/Makefile
++++ b/Makefile
+@@ -479,7 +479,7 @@ dummy := $(call unnest-vars,, \
+ include $(SRC_PATH)/tests/Makefile.include
+-all: $(DOCS) $(if $(BUILD_DOCS),sphinxdocs) $(TOOLS) $(HELPERS-y) recurse-all modules $(vhost-user-json-y)
++all: $(DOCS) $(if $(BUILD_DOCS),sphinxdocs) $(TOOLS) vma$(EXESUF) $(HELPERS-y) recurse-all modules $(vhost-user-json-y)
+ qemu-version.h: FORCE
+       $(call quiet-command, \
+@@ -608,6 +608,7 @@ qemu-img$(EXESUF): qemu-img.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io
+ qemu-nbd$(EXESUF): qemu-nbd.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+ qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+ qemu-storage-daemon$(EXESUF): qemu-storage-daemon.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(chardev-obj-y) $(io-obj-y) $(qom-obj-y) $(storage-daemon-obj-y) $(COMMON_LDADDS)
++vma$(EXESUF): vma.o vma-reader.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+ qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o $(COMMON_LDADDS)
+diff --git a/Makefile.objs b/Makefile.objs
+index d0b4dde836..05031a3da7 100644
+--- a/Makefile.objs
++++ b/Makefile.objs
+@@ -18,6 +18,7 @@ block-obj-y += block.o blockjob.o job.o
+ block-obj-y += block/ scsi/
+ block-obj-y += qemu-io-cmds.o
+ block-obj-$(CONFIG_REPLICATION) += replication.o
++block-obj-y += vma-writer.o
+ block-obj-m = block/
+diff --git a/vma-reader.c b/vma-reader.c
+new file mode 100644
+index 0000000000..2b1d1cdab3
+--- /dev/null
++++ b/vma-reader.c
+@@ -0,0 +1,857 @@
++/*
++ * VMA: Virtual Machine Archive
++ *
++ * Copyright (C) 2012 Proxmox Server Solutions
++ *
++ * Authors:
++ *  Dietmar Maurer (dietmar@proxmox.com)
++ *
++ * This work is licensed under the terms of the GNU GPL, version 2 or later.
++ * See the COPYING file in the top-level directory.
++ *
++ */
++
++#include "qemu/osdep.h"
++#include <glib.h>
++#include <uuid/uuid.h>
++
++#include "qemu-common.h"
++#include "qemu/timer.h"
++#include "qemu/ratelimit.h"
++#include "vma.h"
++#include "block/block.h"
++#include "sysemu/block-backend.h"
++
++static unsigned char zero_vma_block[VMA_BLOCK_SIZE];
++
++typedef struct VmaRestoreState {
++    BlockBackend *target;
++    bool write_zeroes;
++    unsigned long *bitmap;
++    int bitmap_size;
++}  VmaRestoreState;
++
++struct VmaReader {
++    int fd;
++    GChecksum *md5csum;
++    GHashTable *blob_hash;
++    unsigned char *head_data;
++    VmaDeviceInfo devinfo[256];
++    VmaRestoreState rstate[256];
++    GList *cdata_list;
++    guint8 vmstate_stream;
++    uint32_t vmstate_clusters;
++    /* to show restore percentage if run with -v */
++    time_t start_time;
++    int64_t cluster_count;
++    int64_t clusters_read;
++    int64_t zero_cluster_data;
++    int64_t partial_zero_cluster_data;
++    int clusters_read_per;
++};
++
++static guint
++g_int32_hash(gconstpointer v)
++{
++    return *(const uint32_t *)v;
++}
++
++static gboolean
++g_int32_equal(gconstpointer v1, gconstpointer v2)
++{
++    return *((const uint32_t *)v1) == *((const uint32_t *)v2);
++}
++
++static int vma_reader_get_bitmap(VmaRestoreState *rstate, int64_t cluster_num)
++{
++    assert(rstate);
++    assert(rstate->bitmap);
++
++    unsigned long val, idx, bit;
++
++    idx = cluster_num / BITS_PER_LONG;
++
++    assert(rstate->bitmap_size > idx);
++
++    bit = cluster_num % BITS_PER_LONG;
++    val = rstate->bitmap[idx];
++
++    return !!(val & (1UL << bit));
++}
++
++static void vma_reader_set_bitmap(VmaRestoreState *rstate, int64_t cluster_num,
++                                  int dirty)
++{
++    assert(rstate);
++    assert(rstate->bitmap);
++
++    unsigned long val, idx, bit;
++
++    idx = cluster_num / BITS_PER_LONG;
++
++    assert(rstate->bitmap_size > idx);
++
++    bit = cluster_num % BITS_PER_LONG;
++    val = rstate->bitmap[idx];
++    if (dirty) {
++        if (!(val & (1UL << bit))) {
++            val |= 1UL << bit;
++        }
++    } else {
++        if (val & (1UL << bit)) {
++            val &= ~(1UL << bit);
++        }
++    }
++    rstate->bitmap[idx] = val;
++}
++
++typedef struct VmaBlob {
++    uint32_t start;
++    uint32_t len;
++    void *data;
++} VmaBlob;
++
++static const VmaBlob *get_header_blob(VmaReader *vmar, uint32_t pos)
++{
++    assert(vmar);
++    assert(vmar->blob_hash);
++
++    return g_hash_table_lookup(vmar->blob_hash, &pos);
++}
++
++static const char *get_header_str(VmaReader *vmar, uint32_t pos)
++{
++    const VmaBlob *blob = get_header_blob(vmar, pos);
++    if (!blob) {
++        return NULL;
++    }
++    const char *res = (char *)blob->data;
++    if (res[blob->len-1] != '\0') {
++        return NULL;
++    }
++    return res;
++}
++
++static ssize_t
++safe_read(int fd, unsigned char *buf, size_t count)
++{
++    ssize_t n;
++
++    do {
++        n = read(fd, buf, count);
++    } while (n < 0 && errno == EINTR);
++
++    return n;
++}
++
++static ssize_t
++full_read(int fd, unsigned char *buf, size_t len)
++{
++    ssize_t n;
++    size_t total;
++
++    total = 0;
++
++    while (len > 0) {
++        n = safe_read(fd, buf, len);
++
++        if (n == 0) {
++            return total;
++        }
++
++        if (n <= 0) {
++            break;
++        }
++
++        buf += n;
++        total += n;
++        len -= n;
++    }
++
++    if (len) {
++        return -1;
++    }
++
++    return total;
++}
++
++void vma_reader_destroy(VmaReader *vmar)
++{
++    assert(vmar);
++
++    if (vmar->fd >= 0) {
++        close(vmar->fd);
++    }
++
++    if (vmar->cdata_list) {
++        g_list_free(vmar->cdata_list);
++    }
++
++    int i;
++    for (i = 1; i < 256; i++) {
++        if (vmar->rstate[i].bitmap) {
++            g_free(vmar->rstate[i].bitmap);
++        }
++    }
++
++    if (vmar->md5csum) {
++        g_checksum_free(vmar->md5csum);
++    }
++
++    if (vmar->blob_hash) {
++        g_hash_table_destroy(vmar->blob_hash);
++    }
++
++    if (vmar->head_data) {
++        g_free(vmar->head_data);
++    }
++
++    g_free(vmar);
++
++};
++
++static int vma_reader_read_head(VmaReader *vmar, Error **errp)
++{
++    assert(vmar);
++    assert(errp);
++    assert(*errp == NULL);
++
++    unsigned char md5sum[16];
++    int i;
++    int ret = 0;
++
++    vmar->head_data = g_malloc(sizeof(VmaHeader));
++
++    if (full_read(vmar->fd, vmar->head_data, sizeof(VmaHeader)) !=
++        sizeof(VmaHeader)) {
++        error_setg(errp, "can't read vma header - %s",
++                   errno ? g_strerror(errno) : "got EOF");
++        return -1;
++    }
++
++    VmaHeader *h = (VmaHeader *)vmar->head_data;
++
++    if (h->magic != VMA_MAGIC) {
++        error_setg(errp, "not a vma file - wrong magic number");
++        return -1;
++    }
++
++    uint32_t header_size = GUINT32_FROM_BE(h->header_size);
++    int need = header_size - sizeof(VmaHeader);
++    if (need <= 0) {
++        error_setg(errp, "wrong vma header size %d", header_size);
++        return -1;
++    }
++
++    vmar->head_data = g_realloc(vmar->head_data, header_size);
++    h = (VmaHeader *)vmar->head_data;
++
++    if (full_read(vmar->fd, vmar->head_data + sizeof(VmaHeader), need) !=
++        need) {
++        error_setg(errp, "can't read vma header data - %s",
++                   errno ? g_strerror(errno) : "got EOF");
++        return -1;
++    }
++
++    memcpy(md5sum, h->md5sum, 16);
++    memset(h->md5sum, 0, 16);
++
++    g_checksum_reset(vmar->md5csum);
++    g_checksum_update(vmar->md5csum, vmar->head_data, header_size);
++    gsize csize = 16;
++    g_checksum_get_digest(vmar->md5csum, (guint8 *)(h->md5sum), &csize);
++
++    if (memcmp(md5sum, h->md5sum, 16) != 0) {
++        error_setg(errp, "wrong vma header chechsum");
++        return -1;
++    }
++
++    /* we can modify header data after checksum verify */
++    h->header_size = header_size;
++
++    h->version = GUINT32_FROM_BE(h->version);
++    if (h->version != 1) {
++        error_setg(errp, "wrong vma version %d", h->version);
++        return -1;
++    }
++
++    h->ctime = GUINT64_FROM_BE(h->ctime);
++    h->blob_buffer_offset = GUINT32_FROM_BE(h->blob_buffer_offset);
++    h->blob_buffer_size = GUINT32_FROM_BE(h->blob_buffer_size);
++
++    uint32_t bstart = h->blob_buffer_offset + 1;
++    uint32_t bend = h->blob_buffer_offset + h->blob_buffer_size;
++
++    if (bstart <= sizeof(VmaHeader)) {
++        error_setg(errp, "wrong vma blob buffer offset %d",
++                   h->blob_buffer_offset);
++        return -1;
++    }
++
++    if (bend > header_size) {
++        error_setg(errp, "wrong vma blob buffer size %d/%d",
++                   h->blob_buffer_offset, h->blob_buffer_size);
++        return -1;
++    }
++
++    while ((bstart + 2) <= bend) {
++        uint32_t size = vmar->head_data[bstart] +
++            (vmar->head_data[bstart+1] << 8);
++        if ((bstart + size + 2) <= bend) {
++            VmaBlob *blob = g_new0(VmaBlob, 1);
++            blob->start = bstart - h->blob_buffer_offset;
++            blob->len = size;
++            blob->data = vmar->head_data + bstart + 2;
++            g_hash_table_insert(vmar->blob_hash, &blob->start, blob);
++        }
++        bstart += size + 2;
++    }
++
++
++    int count = 0;
++    for (i = 1; i < 256; i++) {
++        VmaDeviceInfoHeader *dih = &h->dev_info[i];
++        uint32_t devname_ptr = GUINT32_FROM_BE(dih->devname_ptr);
++        uint64_t size = GUINT64_FROM_BE(dih->size);
++        const char *devname =  get_header_str(vmar, devname_ptr);
++
++        if (size && devname) {
++            count++;
++            vmar->devinfo[i].size = size;
++            vmar->devinfo[i].devname = devname;
++
++            if (strcmp(devname, "vmstate") == 0) {
++                vmar->vmstate_stream = i;
++            }
++        }
++    }
++
++    for (i = 0; i < VMA_MAX_CONFIGS; i++) {
++        uint32_t name_ptr = GUINT32_FROM_BE(h->config_names[i]);
++        uint32_t data_ptr = GUINT32_FROM_BE(h->config_data[i]);
++
++        if (!(name_ptr && data_ptr)) {
++            continue;
++        }
++        const char *name =  get_header_str(vmar, name_ptr);
++        const VmaBlob *blob = get_header_blob(vmar, data_ptr);
++
++        if (!(name && blob)) {
++            error_setg(errp, "vma contains invalid data pointers");
++            return -1;
++        }
++
++        VmaConfigData *cdata = g_new0(VmaConfigData, 1);
++        cdata->name = name;
++        cdata->data = blob->data;
++        cdata->len = blob->len;
++
++        vmar->cdata_list = g_list_append(vmar->cdata_list, cdata);
++    }
++
++    return ret;
++};
++
++VmaReader *vma_reader_create(const char *filename, Error **errp)
++{
++    assert(filename);
++    assert(errp);
++
++    VmaReader *vmar = g_new0(VmaReader, 1);
++
++    if (strcmp(filename, "-") == 0) {
++        vmar->fd = dup(0);
++    } else {
++        vmar->fd = open(filename, O_RDONLY);
++    }
++
++    if (vmar->fd < 0) {
++        error_setg(errp, "can't open file %s - %s\n", filename,
++                   g_strerror(errno));
++        goto err;
++    }
++
++    vmar->md5csum = g_checksum_new(G_CHECKSUM_MD5);
++    if (!vmar->md5csum) {
++        error_setg(errp, "can't allocate cmsum\n");
++        goto err;
++    }
++
++    vmar->blob_hash = g_hash_table_new_full(g_int32_hash, g_int32_equal,
++                                            NULL, g_free);
++
++    if (vma_reader_read_head(vmar, errp) < 0) {
++        goto err;
++    }
++
++    return vmar;
++
++err:
++    if (vmar) {
++        vma_reader_destroy(vmar);
++    }
++
++    return NULL;
++}
++
++VmaHeader *vma_reader_get_header(VmaReader *vmar)
++{
++    assert(vmar);
++    assert(vmar->head_data);
++
++    return (VmaHeader *)(vmar->head_data);
++}
++
++GList *vma_reader_get_config_data(VmaReader *vmar)
++{
++    assert(vmar);
++    assert(vmar->head_data);
++
++    return vmar->cdata_list;
++}
++
++VmaDeviceInfo *vma_reader_get_device_info(VmaReader *vmar, guint8 dev_id)
++{
++    assert(vmar);
++    assert(dev_id);
++
++    if (vmar->devinfo[dev_id].size && vmar->devinfo[dev_id].devname) {
++        return &vmar->devinfo[dev_id];
++    }
++
++    return NULL;
++}
++
++static void allocate_rstate(VmaReader *vmar,  guint8 dev_id,
++                            BlockBackend *target, bool write_zeroes)
++{
++    assert(vmar);
++    assert(dev_id);
++
++    vmar->rstate[dev_id].target = target;
++    vmar->rstate[dev_id].write_zeroes = write_zeroes;
++
++    int64_t size = vmar->devinfo[dev_id].size;
++
++    int64_t bitmap_size = (size/BDRV_SECTOR_SIZE) +
++        (VMA_CLUSTER_SIZE/BDRV_SECTOR_SIZE) * BITS_PER_LONG - 1;
++    bitmap_size /= (VMA_CLUSTER_SIZE/BDRV_SECTOR_SIZE) * BITS_PER_LONG;
++
++    vmar->rstate[dev_id].bitmap_size = bitmap_size;
++    vmar->rstate[dev_id].bitmap = g_new0(unsigned long, bitmap_size);
++
++    vmar->cluster_count += size/VMA_CLUSTER_SIZE;
++}
++
++int vma_reader_register_bs(VmaReader *vmar, guint8 dev_id, BlockBackend *target,
++                           bool write_zeroes, Error **errp)
++{
++    assert(vmar);
++    assert(target != NULL);
++    assert(dev_id);
++    assert(vmar->rstate[dev_id].target == NULL);
++
++    int64_t size = blk_getlength(target);
++    int64_t size_diff = size - vmar->devinfo[dev_id].size;
++
++    /* storage types can have different size restrictions, so it
++     * is not always possible to create an image with exact size.
++     * So we tolerate a size difference up to 4MB.
++     */
++    if ((size_diff < 0) || (size_diff > 4*1024*1024)) {
++        error_setg(errp, "vma_reader_register_bs for stream %s failed - "
++                   "unexpected size %zd != %zd", vmar->devinfo[dev_id].devname,
++                   size, vmar->devinfo[dev_id].size);
++        return -1;
++    }
++
++    allocate_rstate(vmar, dev_id, target, write_zeroes);
++
++    return 0;
++}
++
++static ssize_t safe_write(int fd, void *buf, size_t count)
++{
++    ssize_t n;
++
++    do {
++        n = write(fd, buf, count);
++    } while (n < 0 && errno == EINTR);
++
++    return n;
++}
++
++static size_t full_write(int fd, void *buf, size_t len)
++{
++    ssize_t n;
++    size_t total;
++
++    total = 0;
++
++    while (len > 0) {
++        n = safe_write(fd, buf, len);
++        if (n < 0) {
++            return n;
++        }
++        buf += n;
++        total += n;
++        len -= n;
++    }
++
++    if (len) {
++        /* incomplete write ? */
++        return -1;
++    }
++
++    return total;
++}
++
++static int restore_write_data(VmaReader *vmar, guint8 dev_id,
++                              BlockBackend *target, int vmstate_fd,
++                              unsigned char *buf, int64_t sector_num,
++                              int nb_sectors, Error **errp)
++{
++    assert(vmar);
++
++    if (dev_id == vmar->vmstate_stream) {
++        if (vmstate_fd >= 0) {
++            int len = nb_sectors * BDRV_SECTOR_SIZE;
++            int res = full_write(vmstate_fd, buf, len);
++            if (res < 0) {
++                error_setg(errp, "write vmstate failed %d", res);
++                return -1;
++            }
++        }
++    } else {
++        int res = blk_pwrite(target, sector_num * BDRV_SECTOR_SIZE, buf, nb_sectors * BDRV_SECTOR_SIZE, 0);
++        if (res < 0) {
++            error_setg(errp, "blk_pwrite to %s failed (%d)",
++                       bdrv_get_device_name(blk_bs(target)), res);
++            return -1;
++        }
++    }
++    return 0;
++}
++
++static int restore_extent(VmaReader *vmar, unsigned char *buf,
++                          int extent_size, int vmstate_fd,
++                          bool verbose, bool verify, Error **errp)
++{
++    assert(vmar);
++    assert(buf);
++
++    VmaExtentHeader *ehead = (VmaExtentHeader *)buf;
++    int start = VMA_EXTENT_HEADER_SIZE;
++    int i;
++
++    for (i = 0; i < VMA_BLOCKS_PER_EXTENT; i++) {
++        uint64_t block_info = GUINT64_FROM_BE(ehead->blockinfo[i]);
++        uint64_t cluster_num = block_info & 0xffffffff;
++        uint8_t dev_id = (block_info >> 32) & 0xff;
++        uint16_t mask = block_info >> (32+16);
++        int64_t max_sector;
++
++        if (!dev_id) {
++            continue;
++        }
++
++        VmaRestoreState *rstate = &vmar->rstate[dev_id];
++        BlockBackend *target = NULL;
++
++        if (dev_id != vmar->vmstate_stream) {
++            target = rstate->target;
++            if (!verify && !target) {
++                error_setg(errp, "got wrong dev id %d", dev_id);
++                return -1;
++            }
++
++            if (vma_reader_get_bitmap(rstate, cluster_num)) {
++                error_setg(errp, "found duplicated cluster %zd for stream %s",
++                          cluster_num, vmar->devinfo[dev_id].devname);
++                return -1;
++            }
++            vma_reader_set_bitmap(rstate, cluster_num, 1);
++
++            max_sector = vmar->devinfo[dev_id].size/BDRV_SECTOR_SIZE;
++        } else {
++            max_sector = G_MAXINT64;
++            if (cluster_num != vmar->vmstate_clusters) {
++                error_setg(errp, "found out of order vmstate data");
++                return -1;
++            }
++            vmar->vmstate_clusters++;
++        }
++
++        vmar->clusters_read++;
++
++        if (verbose) {
++            time_t duration = time(NULL) - vmar->start_time;
++            int percent = (vmar->clusters_read*100)/vmar->cluster_count;
++            if (percent != vmar->clusters_read_per) {
++                printf("progress %d%% (read %zd bytes, duration %zd sec)\n",
++                       percent, vmar->clusters_read*VMA_CLUSTER_SIZE,
++                       duration);
++                fflush(stdout);
++                vmar->clusters_read_per = percent;
++            }
++        }
++
++        /* try to write whole clusters to speedup restore */
++        if (mask == 0xffff) {
++            if ((start + VMA_CLUSTER_SIZE) > extent_size) {
++                error_setg(errp, "short vma extent - too many blocks");
++                return -1;
++            }
++            int64_t sector_num = (cluster_num * VMA_CLUSTER_SIZE) /
++                BDRV_SECTOR_SIZE;
++            int64_t end_sector = sector_num +
++                VMA_CLUSTER_SIZE/BDRV_SECTOR_SIZE;
++
++            if (end_sector > max_sector) {
++                end_sector = max_sector;
++            }
++
++            if (end_sector <= sector_num) {
++                error_setg(errp, "got wrong block address - write beyond end");
++                return -1;
++            }
++
++            if (!verify) {
++                int nb_sectors = end_sector - sector_num;
++                if (restore_write_data(vmar, dev_id, target, vmstate_fd,
++                                       buf + start, sector_num, nb_sectors,
++                                       errp) < 0) {
++                    return -1;
++                }
++            }
++
++            start += VMA_CLUSTER_SIZE;
++        } else {
++            int j;
++            int bit = 1;
++
++            for (j = 0; j < 16; j++) {
++                int64_t sector_num = (cluster_num*VMA_CLUSTER_SIZE +
++                                      j*VMA_BLOCK_SIZE)/BDRV_SECTOR_SIZE;
++
++                int64_t end_sector = sector_num +
++                    VMA_BLOCK_SIZE/BDRV_SECTOR_SIZE;
++                if (end_sector > max_sector) {
++                    end_sector = max_sector;
++                }
++
++                if (mask & bit) {
++                    if ((start + VMA_BLOCK_SIZE) > extent_size) {
++                        error_setg(errp, "short vma extent - too many blocks");
++                        return -1;
++                    }
++
++                    if (end_sector <= sector_num) {
++                        error_setg(errp, "got wrong block address - "
++                                   "write beyond end");
++                        return -1;
++                    }
++
++                    if (!verify) {
++                        int nb_sectors = end_sector - sector_num;
++                        if (restore_write_data(vmar, dev_id, target, vmstate_fd,
++                                               buf + start, sector_num,
++                                               nb_sectors, errp) < 0) {
++                            return -1;
++                        }
++                    }
++
++                    start += VMA_BLOCK_SIZE;
++
++                } else {
++
++
++                    if (end_sector > sector_num) {
++                        /* Todo: use bdrv_co_write_zeroes (but that need to
++                         * be run inside coroutine?)
++                         */
++                        int nb_sectors = end_sector - sector_num;
++                        int zero_size = BDRV_SECTOR_SIZE*nb_sectors;
++                        vmar->zero_cluster_data += zero_size;
++                        if (mask != 0) {
++                            vmar->partial_zero_cluster_data += zero_size;
++                        }
++
++                        if (rstate->write_zeroes && !verify) {
++                            if (restore_write_data(vmar, dev_id, target, vmstate_fd,
++                                                   zero_vma_block, sector_num,
++                                                   nb_sectors, errp) < 0) {
++                                return -1;
++                            }
++                        }
++                    }
++                }
++
++                bit = bit << 1;
++            }
++        }
++    }
++
++    if (start != extent_size) {
++        error_setg(errp, "vma extent error - missing blocks");
++        return -1;
++    }
++
++    return 0;
++}
++
++static int vma_reader_restore_full(VmaReader *vmar, int vmstate_fd,
++                                   bool verbose, bool verify,
++                                   Error **errp)
++{
++    assert(vmar);
++    assert(vmar->head_data);
++
++    int ret = 0;
++    unsigned char buf[VMA_MAX_EXTENT_SIZE];
++    int buf_pos = 0;
++    unsigned char md5sum[16];
++    VmaHeader *h = (VmaHeader *)vmar->head_data;
++
++    vmar->start_time = time(NULL);
++
++    while (1) {
++        int bytes = full_read(vmar->fd, buf + buf_pos, sizeof(buf) - buf_pos);
++        if (bytes < 0) {
++            error_setg(errp, "read failed - %s", g_strerror(errno));
++            return -1;
++        }
++
++        buf_pos += bytes;
++
++        if (!buf_pos) {
++            break; /* EOF */
++        }
++
++        if (buf_pos < VMA_EXTENT_HEADER_SIZE) {
++            error_setg(errp, "read short extent (%d bytes)", buf_pos);
++            return -1;
++        }
++
++        VmaExtentHeader *ehead = (VmaExtentHeader *)buf;
++
++        /* extract md5sum */
++        memcpy(md5sum, ehead->md5sum, sizeof(ehead->md5sum));
++        memset(ehead->md5sum, 0, sizeof(ehead->md5sum));
++
++        g_checksum_reset(vmar->md5csum);
++        g_checksum_update(vmar->md5csum, buf, VMA_EXTENT_HEADER_SIZE);
++        gsize csize = 16;
++        g_checksum_get_digest(vmar->md5csum, ehead->md5sum, &csize);
++
++        if (memcmp(md5sum, ehead->md5sum, 16) != 0) {
++            error_setg(errp, "wrong vma extent header chechsum");
++            return -1;
++        }
++
++        if (memcmp(h->uuid, ehead->uuid, sizeof(ehead->uuid)) != 0) {
++            error_setg(errp, "wrong vma extent uuid");
++            return -1;
++        }
++
++        if (ehead->magic != VMA_EXTENT_MAGIC || ehead->reserved1 != 0) {
++            error_setg(errp, "wrong vma extent header magic");
++            return -1;
++        }
++
++        int block_count = GUINT16_FROM_BE(ehead->block_count);
++        int extent_size = VMA_EXTENT_HEADER_SIZE + block_count*VMA_BLOCK_SIZE;
++
++        if (buf_pos < extent_size) {
++            error_setg(errp, "short vma extent (%d < %d)", buf_pos,
++                       extent_size);
++            return -1;
++        }
++
++        if (restore_extent(vmar, buf, extent_size, vmstate_fd, verbose,
++                           verify, errp) < 0) {
++            return -1;
++        }
++
++        if (buf_pos > extent_size) {
++            memmove(buf, buf + extent_size, buf_pos - extent_size);
++            buf_pos = buf_pos - extent_size;
++        } else {
++            buf_pos = 0;
++        }
++    }
++
++    bdrv_drain_all();
++
++    int i;
++    for (i = 1; i < 256; i++) {
++        VmaRestoreState *rstate = &vmar->rstate[i];
++        if (!rstate->target) {
++            continue;
++        }
++
++        if (blk_flush(rstate->target) < 0) {
++            error_setg(errp, "vma blk_flush %s failed",
++                       vmar->devinfo[i].devname);
++            return -1;
++        }
++
++        if (vmar->devinfo[i].size &&
++            (strcmp(vmar->devinfo[i].devname, "vmstate") != 0)) {
++            assert(rstate->bitmap);
++
++            int64_t cluster_num, end;
++
++            end = (vmar->devinfo[i].size + VMA_CLUSTER_SIZE - 1) /
++                VMA_CLUSTER_SIZE;
++
++            for (cluster_num = 0; cluster_num < end; cluster_num++) {
++                if (!vma_reader_get_bitmap(rstate, cluster_num)) {
++                    error_setg(errp, "detected missing cluster %zd "
++                               "for stream %s", cluster_num,
++                               vmar->devinfo[i].devname);
++                    return -1;
++                }
++            }
++        }
++    }
++
++    if (verbose) {
++        if (vmar->clusters_read) {
++            printf("total bytes read %zd, sparse bytes %zd (%.3g%%)\n",
++                   vmar->clusters_read*VMA_CLUSTER_SIZE,
++                   vmar->zero_cluster_data,
++                   (double)(100.0*vmar->zero_cluster_data)/
++                   (vmar->clusters_read*VMA_CLUSTER_SIZE));
++
++            int64_t datasize = vmar->clusters_read*VMA_CLUSTER_SIZE-vmar->zero_cluster_data;
++            if (datasize) { // this does not make sense for empty files
++                printf("space reduction due to 4K zero blocks %.3g%%\n",
++                       (double)(100.0*vmar->partial_zero_cluster_data) / datasize);
++            }
++        } else {
++            printf("vma archive contains no image data\n");
++        }
++    }
++    return ret;
++}
++
++int vma_reader_restore(VmaReader *vmar, int vmstate_fd, bool verbose,
++                       Error **errp)
++{
++    return vma_reader_restore_full(vmar, vmstate_fd, verbose, false, errp);
++}
++
++int vma_reader_verify(VmaReader *vmar, bool verbose, Error **errp)
++{
++    guint8 dev_id;
++
++    for (dev_id = 1; dev_id < 255; dev_id++) {
++        if (vma_reader_get_device_info(vmar, dev_id)) {
++            allocate_rstate(vmar, dev_id, NULL, false);
++        }
++    }
++
++    return vma_reader_restore_full(vmar, -1, verbose, true, errp);
++}
++
+diff --git a/vma-writer.c b/vma-writer.c
+new file mode 100644
+index 0000000000..f5d2c5d23c
+--- /dev/null
++++ b/vma-writer.c
+@@ -0,0 +1,790 @@
++/*
++ * VMA: Virtual Machine Archive
++ *
++ * Copyright (C) 2012 Proxmox Server Solutions
++ *
++ * Authors:
++ *  Dietmar Maurer (dietmar@proxmox.com)
++ *
++ * This work is licensed under the terms of the GNU GPL, version 2 or later.
++ * See the COPYING file in the top-level directory.
++ *
++ */
++
++#include "qemu/osdep.h"
++#include <glib.h>
++#include <uuid/uuid.h>
++
++#include "vma.h"
++#include "block/block.h"
++#include "monitor/monitor.h"
++#include "qemu/main-loop.h"
++#include "qemu/coroutine.h"
++#include "qemu/cutils.h"
++
++#define DEBUG_VMA 0
++
++#define DPRINTF(fmt, ...)\
++    do { if (DEBUG_VMA) { printf("vma: " fmt, ## __VA_ARGS__); } } while (0)
++
++#define WRITE_BUFFERS 5
++#define HEADER_CLUSTERS 8
++#define HEADERBUF_SIZE (VMA_CLUSTER_SIZE*HEADER_CLUSTERS)
++
++struct VmaWriter {
++    int fd;
++    FILE *cmd;
++    int status;
++    char errmsg[8192];
++    uuid_t uuid;
++    bool header_written;
++    bool closed;
++
++    /* we always write extents */
++    unsigned char *outbuf;
++    int outbuf_pos; /* in bytes */
++    int outbuf_count; /* in VMA_BLOCKS */
++    uint64_t outbuf_block_info[VMA_BLOCKS_PER_EXTENT];
++
++    unsigned char *headerbuf;
++
++    GChecksum *md5csum;
++    CoMutex flush_lock;
++    Coroutine *co_writer;
++
++    /* drive informations */
++    VmaStreamInfo stream_info[256];
++    guint stream_count;
++
++    guint8 vmstate_stream;
++    uint32_t vmstate_clusters;
++
++    /* header blob table */
++    char *header_blob_table;
++    uint32_t header_blob_table_size;
++    uint32_t header_blob_table_pos;
++
++    /* store for config blobs */
++    uint32_t config_names[VMA_MAX_CONFIGS]; /* offset into blob_buffer table */
++    uint32_t config_data[VMA_MAX_CONFIGS];  /* offset into blob_buffer table */
++    uint32_t config_count;
++};
++
++void vma_writer_set_error(VmaWriter *vmaw, const char *fmt, ...)
++{
++    va_list ap;
++
++    if (vmaw->status < 0) {
++        return;
++    }
++
++    vmaw->status = -1;
++
++    va_start(ap, fmt);
++    g_vsnprintf(vmaw->errmsg, sizeof(vmaw->errmsg), fmt, ap);
++    va_end(ap);
++
++    DPRINTF("vma_writer_set_error: %s\n", vmaw->errmsg);
++}
++
++static uint32_t allocate_header_blob(VmaWriter *vmaw, const char *data,
++                                     size_t len)
++{
++    if (len > 65535) {
++        return 0;
++    }
++
++    if (!vmaw->header_blob_table ||
++        (vmaw->header_blob_table_size <
++         (vmaw->header_blob_table_pos + len + 2))) {
++        int newsize = vmaw->header_blob_table_size + ((len + 2 + 511)/512)*512;
++
++        vmaw->header_blob_table = g_realloc(vmaw->header_blob_table, newsize);
++        memset(vmaw->header_blob_table + vmaw->header_blob_table_size,
++               0, newsize - vmaw->header_blob_table_size);
++        vmaw->header_blob_table_size = newsize;
++    }
++
++    uint32_t cpos = vmaw->header_blob_table_pos;
++    vmaw->header_blob_table[cpos] = len & 255;
++    vmaw->header_blob_table[cpos+1] = (len >> 8) & 255;
++    memcpy(vmaw->header_blob_table + cpos + 2, data, len);
++    vmaw->header_blob_table_pos += len + 2;
++    return cpos;
++}
++
++static uint32_t allocate_header_string(VmaWriter *vmaw, const char *str)
++{
++    assert(vmaw);
++
++    size_t len = strlen(str) + 1;
++
++    return allocate_header_blob(vmaw, str, len);
++}
++
++int vma_writer_add_config(VmaWriter *vmaw, const char *name, gpointer data,
++                          gsize len)
++{
++    assert(vmaw);
++    assert(!vmaw->header_written);
++    assert(vmaw->config_count < VMA_MAX_CONFIGS);
++    assert(name);
++    assert(data);
++
++    gchar *basename = g_path_get_basename(name);
++    uint32_t name_ptr = allocate_header_string(vmaw, basename);
++    g_free(basename);
++
++    if (!name_ptr) {
++        return -1;
++    }
++
++    uint32_t data_ptr = allocate_header_blob(vmaw, data, len);
++    if (!data_ptr) {
++        return -1;
++    }
++
++    vmaw->config_names[vmaw->config_count] = name_ptr;
++    vmaw->config_data[vmaw->config_count] = data_ptr;
++
++    vmaw->config_count++;
++
++    return 0;
++}
++
++int vma_writer_register_stream(VmaWriter *vmaw, const char *devname,
++                               size_t size)
++{
++    assert(vmaw);
++    assert(devname);
++    assert(!vmaw->status);
++
++    if (vmaw->header_written) {
++        vma_writer_set_error(vmaw, "vma_writer_register_stream: header "
++                             "already written");
++        return -1;
++    }
++
++    guint n = vmaw->stream_count + 1;
++
++    /* we can have dev_ids form 1 to 255 (0 reserved)
++     * 255(-1) reseverd for safety
++     */
++    if (n > 254) {
++        vma_writer_set_error(vmaw, "vma_writer_register_stream: "
++                             "too many drives");
++        return -1;
++    }
++
++    if (size <= 0) {
++        vma_writer_set_error(vmaw, "vma_writer_register_stream: "
++                             "got strange size %zd", size);
++        return -1;
++    }
++
++    DPRINTF("vma_writer_register_stream %s %zu %d\n", devname, size, n);
++
++    vmaw->stream_info[n].devname = g_strdup(devname);
++    vmaw->stream_info[n].size = size;
++
++    vmaw->stream_info[n].cluster_count = (size + VMA_CLUSTER_SIZE - 1) /
++        VMA_CLUSTER_SIZE;
++
++    vmaw->stream_count = n;
++
++    if (strcmp(devname, "vmstate") == 0) {
++        vmaw->vmstate_stream = n;
++    }
++
++    return n;
++}
++
++static void coroutine_fn yield_until_fd_writable(int fd)
++{
++    assert(qemu_in_coroutine());
++    AioContext *ctx = qemu_get_current_aio_context();
++    aio_set_fd_handler(ctx, fd, false, NULL, (IOHandler *)qemu_coroutine_enter,
++                       NULL, qemu_coroutine_self());
++    qemu_coroutine_yield();
++    aio_set_fd_handler(ctx, fd, false, NULL, NULL, NULL, NULL);
++}
++
++static ssize_t coroutine_fn
++vma_queue_write(VmaWriter *vmaw, const void *buf, size_t bytes)
++{
++    DPRINTF("vma_queue_write enter %zd\n", bytes);
++
++    assert(vmaw);
++    assert(buf);
++    assert(bytes <= VMA_MAX_EXTENT_SIZE);
++
++    size_t done = 0;
++    ssize_t ret;
++
++    assert(vmaw->co_writer == NULL);
++
++    vmaw->co_writer = qemu_coroutine_self();
++
++    while (done < bytes) {
++        if (vmaw->status < 0) {
++            DPRINTF("vma_queue_write detected canceled backup\n");
++            done = -1;
++            break;
++        }
++        yield_until_fd_writable(vmaw->fd);
++        ret = write(vmaw->fd, buf + done, bytes - done);
++        if (ret > 0) {
++            done += ret;
++            DPRINTF("vma_queue_write written %zd %zd\n", done, ret);
++        } else if (ret < 0) {
++            if (errno == EAGAIN || errno == EWOULDBLOCK) {
++                /* try again */
++           } else {
++                vma_writer_set_error(vmaw, "vma_queue_write: write error - %s",
++                                     g_strerror(errno));
++                done = -1; /* always return failure for partial writes */
++                break;
++            }
++        } else if (ret == 0) {
++            /* should not happen - simply try again */
++        }
++    }
++
++    vmaw->co_writer = NULL;
++
++    return (done == bytes) ? bytes : -1;
++}
++
++VmaWriter *vma_writer_create(const char *filename, uuid_t uuid, Error **errp)
++{
++    const char *p;
++
++    assert(sizeof(VmaHeader) == (4096 + 8192));
++    assert(G_STRUCT_OFFSET(VmaHeader, config_names) == 2044);
++    assert(G_STRUCT_OFFSET(VmaHeader, config_data) == 3068);
++    assert(G_STRUCT_OFFSET(VmaHeader, dev_info) == 4096);
++    assert(sizeof(VmaExtentHeader) == 512);
++
++    VmaWriter *vmaw = g_new0(VmaWriter, 1);
++    vmaw->fd = -1;
++
++    vmaw->md5csum = g_checksum_new(G_CHECKSUM_MD5);
++    if (!vmaw->md5csum) {
++        error_setg(errp, "can't allocate cmsum\n");
++        goto err;
++    }
++
++    if (strstart(filename, "exec:", &p)) {
++        vmaw->cmd = popen(p, "w");
++        if (vmaw->cmd == NULL) {
++            error_setg(errp, "can't popen command '%s' - %s\n", p,
++                       g_strerror(errno));
++            goto err;
++        }
++        vmaw->fd = fileno(vmaw->cmd);
++
++        /* try to use O_NONBLOCK */
++        fcntl(vmaw->fd, F_SETFL, fcntl(vmaw->fd, F_GETFL)|O_NONBLOCK);
++
++    } else {
++        struct stat st;
++        int oflags;
++        const char *tmp_id_str;
++
++        if ((stat(filename, &st) == 0) && S_ISFIFO(st.st_mode)) {
++            oflags = O_NONBLOCK|O_WRONLY;
++            vmaw->fd = qemu_open(filename, oflags, 0644);
++        } else if (strstart(filename, "/dev/fdset/", &tmp_id_str)) {
++            oflags = O_NONBLOCK|O_WRONLY;
++            vmaw->fd = qemu_open(filename, oflags, 0644);
++        } else if (strstart(filename, "/dev/fdname/", &tmp_id_str)) {
++            vmaw->fd = monitor_get_fd(cur_mon, tmp_id_str, errp);
++            if (vmaw->fd < 0) {
++                goto err;
++            }
++            /* try to use O_NONBLOCK */
++            fcntl(vmaw->fd, F_SETFL, fcntl(vmaw->fd, F_GETFL)|O_NONBLOCK);
++        } else  {
++            oflags = O_NONBLOCK|O_DIRECT|O_WRONLY|O_CREAT|O_EXCL;
++            vmaw->fd = qemu_open(filename, oflags, 0644);
++        }
++
++        if (vmaw->fd < 0) {
++            error_setg(errp, "can't open file %s - %s\n", filename,
++                       g_strerror(errno));
++            goto err;
++        }
++    }
++
++    /* we use O_DIRECT, so we need to align IO buffers */
++
++    vmaw->outbuf = qemu_memalign(512, VMA_MAX_EXTENT_SIZE);
++    vmaw->headerbuf = qemu_memalign(512, HEADERBUF_SIZE);
++
++    vmaw->outbuf_count = 0;
++    vmaw->outbuf_pos = VMA_EXTENT_HEADER_SIZE;
++
++    vmaw->header_blob_table_pos = 1; /* start at pos 1 */
++
++    qemu_co_mutex_init(&vmaw->flush_lock);
++
++    uuid_copy(vmaw->uuid, uuid);
++
++    return vmaw;
++
++err:
++    if (vmaw) {
++        if (vmaw->cmd) {
++            pclose(vmaw->cmd);
++        } else if (vmaw->fd >= 0) {
++            close(vmaw->fd);
++        }
++
++        if (vmaw->md5csum) {
++            g_checksum_free(vmaw->md5csum);
++        }
++
++        g_free(vmaw);
++    }
++
++    return NULL;
++}
++
++static int coroutine_fn vma_write_header(VmaWriter *vmaw)
++{
++    assert(vmaw);
++    unsigned char *buf = vmaw->headerbuf;
++    VmaHeader *head = (VmaHeader *)buf;
++
++    int i;
++
++    DPRINTF("VMA WRITE HEADER\n");
++
++    if (vmaw->status < 0) {
++        return vmaw->status;
++    }
++
++    memset(buf, 0, HEADERBUF_SIZE);
++
++    head->magic = VMA_MAGIC;
++    head->version = GUINT32_TO_BE(1); /* v1 */
++    memcpy(head->uuid, vmaw->uuid, 16);
++
++    time_t ctime = time(NULL);
++    head->ctime = GUINT64_TO_BE(ctime);
++
++    for (i = 0; i < VMA_MAX_CONFIGS; i++) {
++        head->config_names[i] = GUINT32_TO_BE(vmaw->config_names[i]);
++        head->config_data[i] = GUINT32_TO_BE(vmaw->config_data[i]);
++    }
++
++    /* 32 bytes per device (12 used currently) = 8192 bytes max */
++    for (i = 1; i <= 254; i++) {
++        VmaStreamInfo *si = &vmaw->stream_info[i];
++        if (si->size) {
++            assert(si->devname);
++            uint32_t devname_ptr = allocate_header_string(vmaw, si->devname);
++            if (!devname_ptr) {
++                return -1;
++            }
++            head->dev_info[i].devname_ptr = GUINT32_TO_BE(devname_ptr);
++            head->dev_info[i].size = GUINT64_TO_BE(si->size);
++        }
++    }
++
++    uint32_t header_size = sizeof(VmaHeader) + vmaw->header_blob_table_size;
++    head->header_size = GUINT32_TO_BE(header_size);
++
++    if (header_size > HEADERBUF_SIZE) {
++        return -1; /* just to be sure */
++    }
++
++    uint32_t blob_buffer_offset = sizeof(VmaHeader);
++    memcpy(buf + blob_buffer_offset, vmaw->header_blob_table,
++           vmaw->header_blob_table_size);
++    head->blob_buffer_offset = GUINT32_TO_BE(blob_buffer_offset);
++    head->blob_buffer_size = GUINT32_TO_BE(vmaw->header_blob_table_pos);
++
++    g_checksum_reset(vmaw->md5csum);
++    g_checksum_update(vmaw->md5csum, (const guchar *)buf, header_size);
++    gsize csize = 16;
++    g_checksum_get_digest(vmaw->md5csum, (guint8 *)(head->md5sum), &csize);
++
++    return vma_queue_write(vmaw, buf, header_size);
++}
++
++static int coroutine_fn vma_writer_flush(VmaWriter *vmaw)
++{
++    assert(vmaw);
++
++    int ret;
++    int i;
++
++    if (vmaw->status < 0) {
++        return vmaw->status;
++    }
++
++    if (!vmaw->header_written) {
++        vmaw->header_written = true;
++        ret = vma_write_header(vmaw);
++        if (ret < 0) {
++            vma_writer_set_error(vmaw, "vma_writer_flush: write header failed");
++            return ret;
++        }
++    }
++
++    DPRINTF("VMA WRITE FLUSH %d %d\n", vmaw->outbuf_count, vmaw->outbuf_pos);
++
++
++    VmaExtentHeader *ehead = (VmaExtentHeader *)vmaw->outbuf;
++
++    ehead->magic = VMA_EXTENT_MAGIC;
++    ehead->reserved1 = 0;
++
++    for (i = 0; i < VMA_BLOCKS_PER_EXTENT; i++) {
++        ehead->blockinfo[i] = GUINT64_TO_BE(vmaw->outbuf_block_info[i]);
++    }
++
++    guint16 block_count = (vmaw->outbuf_pos - VMA_EXTENT_HEADER_SIZE) /
++        VMA_BLOCK_SIZE;
++
++    ehead->block_count = GUINT16_TO_BE(block_count);
++
++    memcpy(ehead->uuid, vmaw->uuid, sizeof(ehead->uuid));
++    memset(ehead->md5sum, 0, sizeof(ehead->md5sum));
++
++    g_checksum_reset(vmaw->md5csum);
++    g_checksum_update(vmaw->md5csum, vmaw->outbuf, VMA_EXTENT_HEADER_SIZE);
++    gsize csize = 16;
++    g_checksum_get_digest(vmaw->md5csum, ehead->md5sum, &csize);
++
++    int bytes = vmaw->outbuf_pos;
++    ret = vma_queue_write(vmaw, vmaw->outbuf, bytes);
++    if (ret != bytes) {
++        vma_writer_set_error(vmaw, "vma_writer_flush: failed write");
++    }
++
++    vmaw->outbuf_count = 0;
++    vmaw->outbuf_pos = VMA_EXTENT_HEADER_SIZE;
++
++    for (i = 0; i < VMA_BLOCKS_PER_EXTENT; i++) {
++        vmaw->outbuf_block_info[i] = 0;
++    }
++
++    return vmaw->status;
++}
++
++static int vma_count_open_streams(VmaWriter *vmaw)
++{
++    g_assert(vmaw != NULL);
++
++    int i;
++    int open_drives = 0;
++    for (i = 0; i <= 255; i++) {
++        if (vmaw->stream_info[i].size && !vmaw->stream_info[i].finished) {
++            open_drives++;
++        }
++    }
++
++    return open_drives;
++}
++
++
++/**
++ * You need to call this if the vma archive does not contain
++ * any data stream.
++ */
++int coroutine_fn
++vma_writer_flush_output(VmaWriter *vmaw)
++{
++    qemu_co_mutex_lock(&vmaw->flush_lock);
++    int ret = vma_writer_flush(vmaw);
++    qemu_co_mutex_unlock(&vmaw->flush_lock);
++    if (ret < 0) {
++        vma_writer_set_error(vmaw, "vma_writer_flush_header failed");
++    }
++    return ret;
++}
++
++/**
++ * all jobs should call this when there is no more data
++ * Returns: number of remaining stream (0 ==> finished)
++ */
++int coroutine_fn
++vma_writer_close_stream(VmaWriter *vmaw, uint8_t dev_id)
++{
++    g_assert(vmaw != NULL);
++
++    DPRINTF("vma_writer_set_status %d\n", dev_id);
++    if (!vmaw->stream_info[dev_id].size) {
++        vma_writer_set_error(vmaw, "vma_writer_close_stream: "
++                             "no such stream %d", dev_id);
++        return -1;
++    }
++    if (vmaw->stream_info[dev_id].finished) {
++        vma_writer_set_error(vmaw, "vma_writer_close_stream: "
++                             "stream already closed %d", dev_id);
++        return -1;
++    }
++
++    vmaw->stream_info[dev_id].finished = true;
++
++    int open_drives = vma_count_open_streams(vmaw);
++
++    if (open_drives <= 0) {
++        DPRINTF("vma_writer_set_status all drives completed\n");
++        vma_writer_flush_output(vmaw);
++    }
++
++    return open_drives;
++}
++
++int vma_writer_get_status(VmaWriter *vmaw, VmaStatus *status)
++{
++    int i;
++
++    g_assert(vmaw != NULL);
++
++    if (status) {
++        status->status = vmaw->status;
++        g_strlcpy(status->errmsg, vmaw->errmsg, sizeof(status->errmsg));
++        for (i = 0; i <= 255; i++) {
++            status->stream_info[i] = vmaw->stream_info[i];
++        }
++
++        uuid_unparse_lower(vmaw->uuid, status->uuid_str);
++    }
++
++    status->closed = vmaw->closed;
++
++    return vmaw->status;
++}
++
++static int vma_writer_get_buffer(VmaWriter *vmaw)
++{
++    int ret = 0;
++
++    qemu_co_mutex_lock(&vmaw->flush_lock);
++
++    /* wait until buffer is available */
++    while (vmaw->outbuf_count >= (VMA_BLOCKS_PER_EXTENT - 1)) {
++        ret = vma_writer_flush(vmaw);
++        if (ret < 0) {
++            vma_writer_set_error(vmaw, "vma_writer_get_buffer: flush failed");
++            break;
++        }
++    }
++
++    qemu_co_mutex_unlock(&vmaw->flush_lock);
++
++    return ret;
++}
++
++
++int64_t coroutine_fn
++vma_writer_write(VmaWriter *vmaw, uint8_t dev_id, int64_t cluster_num,
++                 const unsigned char *buf, size_t *zero_bytes)
++{
++    g_assert(vmaw != NULL);
++    g_assert(zero_bytes != NULL);
++
++    *zero_bytes = 0;
++
++    if (vmaw->status < 0) {
++        return vmaw->status;
++    }
++
++    if (!dev_id || !vmaw->stream_info[dev_id].size) {
++        vma_writer_set_error(vmaw, "vma_writer_write: "
++                             "no such stream %d", dev_id);
++        return -1;
++    }
++
++    if (vmaw->stream_info[dev_id].finished) {
++        vma_writer_set_error(vmaw, "vma_writer_write: "
++                             "stream already closed %d", dev_id);
++        return -1;
++    }
++
++
++    if (cluster_num >= (((uint64_t)1)<<32)) {
++        vma_writer_set_error(vmaw, "vma_writer_write: "
++                             "cluster number out of range");
++        return -1;
++    }
++
++    if (dev_id == vmaw->vmstate_stream) {
++        if (cluster_num != vmaw->vmstate_clusters) {
++            vma_writer_set_error(vmaw, "vma_writer_write: "
++                                 "non sequential vmstate write");
++        }
++        vmaw->vmstate_clusters++;
++    } else if (cluster_num >= vmaw->stream_info[dev_id].cluster_count) {
++        vma_writer_set_error(vmaw, "vma_writer_write: cluster number too big");
++        return -1;
++    }
++
++    /* wait until buffer is available */
++    if (vma_writer_get_buffer(vmaw) < 0) {
++        vma_writer_set_error(vmaw, "vma_writer_write: "
++                             "vma_writer_get_buffer failed");
++        return -1;
++    }
++
++    DPRINTF("VMA WRITE %d %zd\n", dev_id, cluster_num);
++
++    uint64_t dev_size = vmaw->stream_info[dev_id].size;
++    uint16_t mask = 0;
++
++    if (buf) {
++        int i;
++        int bit = 1;
++        uint64_t byte_offset = cluster_num * VMA_CLUSTER_SIZE;
++        for (i = 0; i < 16; i++) {
++            const unsigned char *vmablock = buf + (i*VMA_BLOCK_SIZE);
++
++            // Note: If the source is not 64k-aligned, we might reach 4k blocks
++            // after the end of the device. Always mark these as zero in the
++            // mask, so the restore handles them correctly.
++            if (byte_offset < dev_size &&
++                !buffer_is_zero(vmablock, VMA_BLOCK_SIZE))
++            {
++                mask |= bit;
++                memcpy(vmaw->outbuf + vmaw->outbuf_pos, vmablock,
++                       VMA_BLOCK_SIZE);
++
++                // prevent memory leakage on unaligned last block
++                if (byte_offset + VMA_BLOCK_SIZE > dev_size) {
++                    uint64_t real_data_in_block = dev_size - byte_offset;
++                    memset(vmaw->outbuf + vmaw->outbuf_pos + real_data_in_block,
++                           0, VMA_BLOCK_SIZE - real_data_in_block);
++                }
++
++                vmaw->outbuf_pos += VMA_BLOCK_SIZE;
++            } else {
++                DPRINTF("VMA WRITE %zd ZERO BLOCK %d\n", cluster_num, i);
++                vmaw->stream_info[dev_id].zero_bytes += VMA_BLOCK_SIZE;
++                *zero_bytes += VMA_BLOCK_SIZE;
++            }
++
++            byte_offset += VMA_BLOCK_SIZE;
++            bit = bit << 1;
++        }
++    } else {
++        DPRINTF("VMA WRITE %zd ZERO CLUSTER\n", cluster_num);
++        vmaw->stream_info[dev_id].zero_bytes += VMA_CLUSTER_SIZE;
++        *zero_bytes += VMA_CLUSTER_SIZE;
++    }
++
++    uint64_t block_info = ((uint64_t)mask) << (32+16);
++    block_info |= ((uint64_t)dev_id) << 32;
++    block_info |= (cluster_num & 0xffffffff);
++    vmaw->outbuf_block_info[vmaw->outbuf_count] = block_info;
++
++    DPRINTF("VMA WRITE MASK %zd %zx\n", cluster_num, block_info);
++
++    vmaw->outbuf_count++;
++
++    /** NOTE: We allways write whole clusters, but we correctly set
++     * transferred bytes. So transferred == size when when everything
++     * went OK.
++     */
++    size_t transferred = VMA_CLUSTER_SIZE;
++
++    if (dev_id != vmaw->vmstate_stream) {
++        uint64_t last = (cluster_num + 1) * VMA_CLUSTER_SIZE;
++        if (last > dev_size) {
++            uint64_t diff = last - dev_size;
++            if (diff >= VMA_CLUSTER_SIZE) {
++                vma_writer_set_error(vmaw, "vma_writer_write: "
++                                     "read after last cluster");
++                return -1;
++            }
++            transferred -= diff;
++        }
++    }
++
++    vmaw->stream_info[dev_id].transferred += transferred;
++
++    return transferred;
++}
++
++void vma_writer_error_propagate(VmaWriter *vmaw, Error **errp)
++{
++    if (vmaw->status < 0 && *errp == NULL) {
++        error_setg(errp, "%s", vmaw->errmsg);
++    }
++}
++
++int vma_writer_close(VmaWriter *vmaw, Error **errp)
++{
++    g_assert(vmaw != NULL);
++
++    int i;
++
++    qemu_co_mutex_lock(&vmaw->flush_lock); // wait for pending writes
++
++    assert(vmaw->co_writer == NULL);
++
++    if (vmaw->cmd) {
++        if (pclose(vmaw->cmd) < 0) {
++            vma_writer_set_error(vmaw, "vma_writer_close: "
++                                 "pclose failed - %s", g_strerror(errno));
++        }
++    } else {
++        if (close(vmaw->fd) < 0) {
++            vma_writer_set_error(vmaw, "vma_writer_close: "
++                                 "close failed - %s", g_strerror(errno));
++        }
++    }
++
++    for (i = 0; i <= 255; i++) {
++        VmaStreamInfo *si = &vmaw->stream_info[i];
++        if (si->size) {
++            if (!si->finished) {
++                vma_writer_set_error(vmaw, "vma_writer_close: "
++                                     "detected open stream '%s'", si->devname);
++            } else if ((si->transferred != si->size) &&
++                       (i != vmaw->vmstate_stream)) {
++                vma_writer_set_error(vmaw, "vma_writer_close: "
++                                     "incomplete stream '%s' (%zd != %zd)",
++                                     si->devname, si->transferred, si->size);
++            }
++        }
++    }
++
++    for (i = 0; i <= 255; i++) {
++        vmaw->stream_info[i].finished = 1; /* mark as closed */
++    }
++
++    vmaw->closed = 1;
++
++    if (vmaw->status < 0 && *errp == NULL) {
++        error_setg(errp, "%s", vmaw->errmsg);
++    }
++
++    qemu_co_mutex_unlock(&vmaw->flush_lock);
++
++    return vmaw->status;
++}
++
++void vma_writer_destroy(VmaWriter *vmaw)
++{
++    assert(vmaw);
++
++    int i;
++
++    for (i = 0; i <= 255; i++) {
++        if (vmaw->stream_info[i].devname) {
++            g_free(vmaw->stream_info[i].devname);
++        }
++    }
++
++    if (vmaw->md5csum) {
++        g_checksum_free(vmaw->md5csum);
++    }
++
++    qemu_vfree(vmaw->headerbuf);
++    qemu_vfree(vmaw->outbuf);
++    g_free(vmaw);
++}
+diff --git a/vma.c b/vma.c
+new file mode 100644
+index 0000000000..2eea2fc281
+--- /dev/null
++++ b/vma.c
+@@ -0,0 +1,839 @@
++/*
++ * VMA: Virtual Machine Archive
++ *
++ * Copyright (C) 2012-2013 Proxmox Server Solutions
++ *
++ * Authors:
++ *  Dietmar Maurer (dietmar@proxmox.com)
++ *
++ * This work is licensed under the terms of the GNU GPL, version 2 or later.
++ * See the COPYING file in the top-level directory.
++ *
++ */
++
++#include "qemu/osdep.h"
++#include <glib.h>
++
++#include "vma.h"
++#include "qemu-common.h"
++#include "qemu/module.h"
++#include "qemu/error-report.h"
++#include "qemu/main-loop.h"
++#include "qemu/cutils.h"
++#include "qapi/qmp/qdict.h"
++#include "sysemu/block-backend.h"
++
++static void help(void)
++{
++    const char *help_msg =
++        "usage: vma command [command options]\n"
++        "\n"
++        "vma list <filename>\n"
++        "vma config <filename> [-c config]\n"
++        "vma create <filename> [-c config] pathname ...\n"
++        "vma extract <filename> [-r <fifo>] <targetdir>\n"
++        "vma verify <filename> [-v]\n"
++        ;
++
++    printf("%s", help_msg);
++    exit(1);
++}
++
++static const char *extract_devname(const char *path, char **devname, int index)
++{
++    assert(path);
++
++    const char *sep = strchr(path, '=');
++
++    if (sep) {
++        *devname = g_strndup(path, sep - path);
++        path = sep + 1;
++    } else {
++        if (index >= 0) {
++            *devname = g_strdup_printf("disk%d", index);
++        } else {
++            *devname = NULL;
++        }
++    }
++
++    return path;
++}
++
++static void print_content(VmaReader *vmar)
++{
++    assert(vmar);
++
++    VmaHeader *head = vma_reader_get_header(vmar);
++
++    GList *l = vma_reader_get_config_data(vmar);
++    while (l && l->data) {
++        VmaConfigData *cdata = (VmaConfigData *)l->data;
++        l = g_list_next(l);
++        printf("CFG: size: %d name: %s\n", cdata->len, cdata->name);
++    }
++
++    int i;
++    VmaDeviceInfo *di;
++    for (i = 1; i < 255; i++) {
++        di = vma_reader_get_device_info(vmar, i);
++        if (di) {
++            if (strcmp(di->devname, "vmstate") == 0) {
++                printf("VMSTATE: dev_id=%d memory: %zd\n", i, di->size);
++            } else {
++                printf("DEV: dev_id=%d size: %zd devname: %s\n",
++                       i, di->size, di->devname);
++            }
++        }
++    }
++    /* ctime is the last entry we print */
++    printf("CTIME: %s", ctime(&head->ctime));
++    fflush(stdout);
++}
++
++static int list_content(int argc, char **argv)
++{
++    int c, ret = 0;
++    const char *filename;
++
++    for (;;) {
++        c = getopt(argc, argv, "h");
++        if (c == -1) {
++            break;
++        }
++        switch (c) {
++        case '?':
++        case 'h':
++            help();
++            break;
++        default:
++            g_assert_not_reached();
++        }
++    }
++
++    /* Get the filename */
++    if ((optind + 1) != argc) {
++        help();
++    }
++    filename = argv[optind++];
++
++    Error *errp = NULL;
++    VmaReader *vmar = vma_reader_create(filename, &errp);
++
++    if (!vmar) {
++        g_error("%s", error_get_pretty(errp));
++    }
++
++    print_content(vmar);
++
++    vma_reader_destroy(vmar);
++
++    return ret;
++}
++
++typedef struct RestoreMap {
++    char *devname;
++    char *path;
++    char *format;
++    uint64_t throttling_bps;
++    char *throttling_group;
++    char *cache;
++    bool write_zero;
++} RestoreMap;
++
++static bool try_parse_option(char **line, const char *optname, char **out, const char *inbuf) {
++    size_t optlen = strlen(optname);
++    if (strncmp(*line, optname, optlen) != 0 || (*line)[optlen] != '=') {
++        return false;
++    }
++    if (*out) {
++        g_error("read map failed - duplicate value for option '%s'", optname);
++    }
++    char *value = (*line) + optlen + 1; /* including a '=' */
++    char *colon = strchr(value, ':');
++    if (!colon) {
++        g_error("read map failed - option '%s' not terminated ('%s')",
++                optname, inbuf);
++    }
++    *line = colon+1;
++    *out = g_strndup(value, colon - value);
++    return true;
++}
++
++static uint64_t verify_u64(const char *text) {
++    uint64_t value;
++    const char *endptr = NULL;
++    if (qemu_strtou64(text, &endptr, 0, &value) != 0 || !endptr || *endptr) {
++        g_error("read map failed - not a number: %s", text);
++    }
++    return value;
++}
++
++static int extract_content(int argc, char **argv)
++{
++    int c, ret = 0;
++    int verbose = 0;
++    const char *filename;
++    const char *dirname;
++    const char *readmap = NULL;
++
++    for (;;) {
++        c = getopt(argc, argv, "hvr:");
++        if (c == -1) {
++            break;
++        }
++        switch (c) {
++        case '?':
++        case 'h':
++            help();
++            break;
++        case 'r':
++            readmap = optarg;
++            break;
++        case 'v':
++            verbose = 1;
++            break;
++        default:
++            help();
++        }
++    }
++
++    /* Get the filename */
++    if ((optind + 2) != argc) {
++        help();
++    }
++    filename = argv[optind++];
++    dirname = argv[optind++];
++
++    Error *errp = NULL;
++    VmaReader *vmar = vma_reader_create(filename, &errp);
++
++    if (!vmar) {
++        g_error("%s", error_get_pretty(errp));
++    }
++
++    if (mkdir(dirname, 0777) < 0) {
++        g_error("unable to create target directory %s - %s",
++                dirname, g_strerror(errno));
++    }
++
++    GList *l = vma_reader_get_config_data(vmar);
++    while (l && l->data) {
++        VmaConfigData *cdata = (VmaConfigData *)l->data;
++        l = g_list_next(l);
++        char *cfgfn = g_strdup_printf("%s/%s", dirname, cdata->name);
++        GError *err = NULL;
++        if (!g_file_set_contents(cfgfn, (gchar *)cdata->data, cdata->len,
++                                 &err)) {
++            g_error("unable to write file: %s", err->message);
++        }
++    }
++
++    GHashTable *devmap = g_hash_table_new(g_str_hash, g_str_equal);
++
++    if (readmap) {
++        print_content(vmar);
++
++        FILE *map = fopen(readmap, "r");
++        if (!map) {
++            g_error("unable to open fifo %s - %s", readmap, g_strerror(errno));
++        }
++
++        while (1) {
++            char inbuf[8192];
++            char *line = fgets(inbuf, sizeof(inbuf), map);
++            char *format = NULL;
++            char *bps = NULL;
++            char *group = NULL;
++            char *cache = NULL;
++            if (!line || line[0] == '\0' || !strcmp(line, "done\n")) {
++                break;
++            }
++            int len = strlen(line);
++            if (line[len - 1] == '\n') {
++                line[len - 1] = '\0';
++                if (len == 1) {
++                    break;
++                }
++            }
++
++            while (1) {
++                if (!try_parse_option(&line, "format", &format, inbuf) &&
++                    !try_parse_option(&line, "throttling.bps", &bps, inbuf) &&
++                    !try_parse_option(&line, "throttling.group", &group, inbuf) &&
++                    !try_parse_option(&line, "cache", &cache, inbuf))
++                {
++                    break;
++                }
++            }
++
++            uint64_t bps_value = 0;
++            if (bps) {
++                bps_value = verify_u64(bps);
++                g_free(bps);
++            }
++
++            const char *path;
++            bool write_zero;
++            if (line[0] == '0' && line[1] == ':') {
++                path = line + 2;
++                write_zero = false;
++            } else if (line[0] == '1' && line[1] == ':') {
++                path = line + 2;
++                write_zero = true;
++            } else {
++                g_error("read map failed - parse error ('%s')", inbuf);
++            }
++
++            char *devname = NULL;
++            path = extract_devname(path, &devname, -1);
++            if (!devname) {
++                g_error("read map failed - no dev name specified ('%s')",
++                        inbuf);
++            }
++
++            RestoreMap *map = g_new0(RestoreMap, 1);
++            map->devname = g_strdup(devname);
++            map->path = g_strdup(path);
++            map->format = format;
++            map->throttling_bps = bps_value;
++            map->throttling_group = group;
++            map->cache = cache;
++            map->write_zero = write_zero;
++
++            g_hash_table_insert(devmap, map->devname, map);
++
++        };
++    }
++
++    int i;
++    int vmstate_fd = -1;
++    guint8 vmstate_stream = 0;
++
++    BlockBackend *blk = NULL;
++
++    for (i = 1; i < 255; i++) {
++        VmaDeviceInfo *di = vma_reader_get_device_info(vmar, i);
++        if (di && (strcmp(di->devname, "vmstate") == 0)) {
++            vmstate_stream = i;
++            char *statefn = g_strdup_printf("%s/vmstate.bin", dirname);
++            vmstate_fd = open(statefn, O_WRONLY|O_CREAT|O_EXCL, 0644);
++            if (vmstate_fd < 0) {
++                g_error("create vmstate file '%s' failed - %s", statefn,
++                        g_strerror(errno));
++            }
++            g_free(statefn);
++        } else if (di) {
++            char *devfn = NULL;
++            const char *format = NULL;
++            uint64_t throttling_bps = 0;
++            const char *throttling_group = NULL;
++            const char *cache = NULL;
++            int flags = BDRV_O_RDWR;
++            bool write_zero = true;
++
++            if (readmap) {
++                RestoreMap *map;
++                map = (RestoreMap *)g_hash_table_lookup(devmap, di->devname);
++                if (map == NULL) {
++                    g_error("no device name mapping for %s", di->devname);
++                }
++                devfn = map->path;
++                format = map->format;
++                throttling_bps = map->throttling_bps;
++                throttling_group = map->throttling_group;
++                cache = map->cache;
++                write_zero = map->write_zero;
++            } else {
++                devfn = g_strdup_printf("%s/tmp-disk-%s.raw",
++                                        dirname, di->devname);
++                printf("DEVINFO %s %zd\n", devfn, di->size);
++
++                bdrv_img_create(devfn, "raw", NULL, NULL, NULL, di->size,
++                                flags, true, &errp);
++                if (errp) {
++                    g_error("can't create file %s: %s", devfn,
++                            error_get_pretty(errp));
++                }
++
++                /* Note: we created an empty file above, so there is no
++                 * need to write zeroes (so we generate a sparse file)
++                 */
++                write_zero = false;
++            }
++
++          size_t devlen = strlen(devfn);
++          QDict *options = NULL;
++            bool writethrough;
++            if (format) {
++                /* explicit format from commandline */
++                options = qdict_new();
++                qdict_put_str(options, "driver", format);
++            } else if ((devlen > 4 && strcmp(devfn+devlen-4, ".raw") == 0) ||
++                     strncmp(devfn, "/dev/", 5) == 0)
++          {
++                /* This part is now deprecated for PVE as well (just as qemu
++                 * deprecated not specifying an explicit raw format, too.
++                 */
++              /* explicit raw format */
++              options = qdict_new();
++              qdict_put_str(options, "driver", "raw");
++          }
++            if (cache && bdrv_parse_cache_mode(cache, &flags, &writethrough)) {
++                g_error("invalid cache option: %s\n", cache);
++            }
++
++          if (errp || !(blk = blk_new_open(devfn, NULL, options, flags, &errp))) {
++                g_error("can't open file %s - %s", devfn,
++                        error_get_pretty(errp));
++            }
++
++            if (cache) {
++                blk_set_enable_write_cache(blk, !writethrough);
++            }
++
++            if (throttling_group) {
++                blk_io_limits_enable(blk, throttling_group);
++            }
++
++            if (throttling_bps) {
++                if (!throttling_group) {
++                    blk_io_limits_enable(blk, devfn);
++                }
++
++                ThrottleConfig cfg;
++                throttle_config_init(&cfg);
++                cfg.buckets[THROTTLE_BPS_WRITE].avg = throttling_bps;
++                Error *err = NULL;
++                if (!throttle_is_valid(&cfg, &err)) {
++                    error_report_err(err);
++                    g_error("failed to apply throttling");
++                }
++                blk_set_io_limits(blk, &cfg);
++            }
++
++            if (vma_reader_register_bs(vmar, i, blk, write_zero, &errp) < 0) {
++                g_error("%s", error_get_pretty(errp));
++            }
++
++            if (!readmap) {
++                g_free(devfn);
++            }
++        }
++    }
++
++    if (vma_reader_restore(vmar, vmstate_fd, verbose, &errp) < 0) {
++        g_error("restore failed - %s", error_get_pretty(errp));
++    }
++
++    if (!readmap) {
++        for (i = 1; i < 255; i++) {
++            VmaDeviceInfo *di = vma_reader_get_device_info(vmar, i);
++            if (di && (i != vmstate_stream)) {
++                char *tmpfn = g_strdup_printf("%s/tmp-disk-%s.raw",
++                                              dirname, di->devname);
++                char *fn = g_strdup_printf("%s/disk-%s.raw",
++                                           dirname, di->devname);
++                if (rename(tmpfn, fn) != 0) {
++                    g_error("rename %s to %s failed - %s",
++                            tmpfn, fn, g_strerror(errno));
++                }
++            }
++        }
++    }
++
++    vma_reader_destroy(vmar);
++
++    blk_unref(blk);
++
++    bdrv_close_all();
++
++    return ret;
++}
++
++static int verify_content(int argc, char **argv)
++{
++    int c, ret = 0;
++    int verbose = 0;
++    const char *filename;
++
++    for (;;) {
++        c = getopt(argc, argv, "hv");
++        if (c == -1) {
++            break;
++        }
++        switch (c) {
++        case '?':
++        case 'h':
++            help();
++            break;
++        case 'v':
++            verbose = 1;
++            break;
++        default:
++            help();
++        }
++    }
++
++    /* Get the filename */
++    if ((optind + 1) != argc) {
++        help();
++    }
++    filename = argv[optind++];
++
++    Error *errp = NULL;
++    VmaReader *vmar = vma_reader_create(filename, &errp);
++
++    if (!vmar) {
++        g_error("%s", error_get_pretty(errp));
++    }
++
++    if (verbose) {
++        print_content(vmar);
++    }
++
++    if (vma_reader_verify(vmar, verbose, &errp) < 0) {
++        g_error("verify failed - %s", error_get_pretty(errp));
++    }
++
++    vma_reader_destroy(vmar);
++
++    bdrv_close_all();
++
++    return ret;
++}
++
++typedef struct BackupJob {
++    BlockBackend *target;
++    int64_t len;
++    VmaWriter *vmaw;
++    uint8_t dev_id;
++} BackupJob;
++
++#define BACKUP_SECTORS_PER_CLUSTER (VMA_CLUSTER_SIZE / BDRV_SECTOR_SIZE)
++
++static void coroutine_fn backup_run_empty(void *opaque)
++{
++    VmaWriter *vmaw = (VmaWriter *)opaque;
++
++    vma_writer_flush_output(vmaw);
++
++    Error *err = NULL;
++    if (vma_writer_close(vmaw, &err) != 0) {
++        g_warning("vma_writer_close failed %s", error_get_pretty(err));
++    }
++}
++
++static void coroutine_fn backup_run(void *opaque)
++{
++    BackupJob *job = (BackupJob *)opaque;
++    struct iovec iov;
++    QEMUIOVector qiov;
++
++    int64_t start, end;
++    int ret = 0;
++
++    unsigned char *buf = blk_blockalign(job->target, VMA_CLUSTER_SIZE);
++
++    start = 0;
++    end = DIV_ROUND_UP(job->len / BDRV_SECTOR_SIZE,
++                       BACKUP_SECTORS_PER_CLUSTER);
++
++    for (; start < end; start++) {
++        iov.iov_base = buf;
++        iov.iov_len = VMA_CLUSTER_SIZE;
++        qemu_iovec_init_external(&qiov, &iov, 1);
++
++        ret = blk_co_preadv(job->target, start * VMA_CLUSTER_SIZE,
++                            VMA_CLUSTER_SIZE, &qiov, 0);
++        if (ret < 0) {
++            vma_writer_set_error(job->vmaw, "read error", -1);
++            goto out;
++        }
++
++        size_t zb = 0;
++        if (vma_writer_write(job->vmaw, job->dev_id, start, buf, &zb) < 0) {
++            vma_writer_set_error(job->vmaw, "backup_dump_cb vma_writer_write failed", -1);
++            goto out;
++        }
++    }
++
++
++out:
++    if (vma_writer_close_stream(job->vmaw, job->dev_id) <= 0) {
++        Error *err = NULL;
++        if (vma_writer_close(job->vmaw, &err) != 0) {
++            g_warning("vma_writer_close failed %s", error_get_pretty(err));
++        }
++    }
++    qemu_vfree(buf);
++}
++
++static int create_archive(int argc, char **argv)
++{
++    int i, c;
++    int verbose = 0;
++    const char *archivename;
++    GList *config_files = NULL;
++
++    for (;;) {
++        c = getopt(argc, argv, "hvc:");
++        if (c == -1) {
++            break;
++        }
++        switch (c) {
++        case '?':
++        case 'h':
++            help();
++            break;
++        case 'c':
++            config_files = g_list_append(config_files, optarg);
++            break;
++        case 'v':
++            verbose = 1;
++            break;
++        default:
++            g_assert_not_reached();
++        }
++    }
++
++
++    /* make sure we an archive name */
++    if ((optind + 1) > argc) {
++        help();
++    }
++
++    archivename = argv[optind++];
++
++    uuid_t uuid;
++    uuid_generate(uuid);
++
++    Error *local_err = NULL;
++    VmaWriter *vmaw = vma_writer_create(archivename, uuid, &local_err);
++
++    if (vmaw == NULL) {
++        g_error("%s", error_get_pretty(local_err));
++    }
++
++    GList *l = config_files;
++    while (l && l->data) {
++        char *name = l->data;
++        char *cdata = NULL;
++        gsize clen = 0;
++        GError *err = NULL;
++        if (!g_file_get_contents(name, &cdata, &clen, &err)) {
++            unlink(archivename);
++            g_error("Unable to read file: %s", err->message);
++        }
++
++        if (vma_writer_add_config(vmaw, name, cdata, clen) != 0) {
++            unlink(archivename);
++            g_error("Unable to append config data %s (len = %zd)",
++                    name, clen);
++        }
++        l = g_list_next(l);
++    }
++
++    int devcount = 0;
++    while (optind < argc) {
++        const char *path = argv[optind++];
++        char *devname = NULL;
++        path = extract_devname(path, &devname, devcount++);
++
++        Error *errp = NULL;
++        BlockBackend *target;
++
++        target = blk_new_open(path, NULL, NULL, 0, &errp);
++        if (!target) {
++            unlink(archivename);
++            g_error("bdrv_open '%s' failed - %s", path, error_get_pretty(errp));
++        }
++        int64_t size = blk_getlength(target);
++        int dev_id = vma_writer_register_stream(vmaw, devname, size);
++        if (dev_id <= 0) {
++            unlink(archivename);
++            g_error("vma_writer_register_stream '%s' failed", devname);
++        }
++
++        BackupJob *job = g_new0(BackupJob, 1);
++        job->len = size;
++        job->target = target;
++        job->vmaw = vmaw;
++        job->dev_id = dev_id;
++
++        Coroutine *co = qemu_coroutine_create(backup_run, job);
++        qemu_coroutine_enter(co);
++    }
++
++    VmaStatus vmastat;
++    int percent = 0;
++    int last_percent = -1;
++
++    if (devcount) {
++        while (1) {
++            main_loop_wait(false);
++            vma_writer_get_status(vmaw, &vmastat);
++
++            if (verbose) {
++
++                uint64_t total = 0;
++                uint64_t transferred = 0;
++                uint64_t zero_bytes = 0;
++
++                int i;
++                for (i = 0; i < 256; i++) {
++                    if (vmastat.stream_info[i].size) {
++                        total += vmastat.stream_info[i].size;
++                        transferred += vmastat.stream_info[i].transferred;
++                        zero_bytes += vmastat.stream_info[i].zero_bytes;
++                    }
++                }
++                percent = (transferred*100)/total;
++                if (percent != last_percent) {
++                    fprintf(stderr, "progress %d%% %zd/%zd %zd\n", percent,
++                            transferred, total, zero_bytes);
++                    fflush(stderr);
++
++                    last_percent = percent;
++                }
++            }
++
++            if (vmastat.closed) {
++                break;
++            }
++        }
++    } else {
++        Coroutine *co = qemu_coroutine_create(backup_run_empty, vmaw);
++        qemu_coroutine_enter(co);
++        while (1) {
++            main_loop_wait(false);
++            vma_writer_get_status(vmaw, &vmastat);
++            if (vmastat.closed) {
++                    break;
++            }
++        }
++    }
++
++    bdrv_drain_all();
++
++    vma_writer_get_status(vmaw, &vmastat);
++
++    if (verbose) {
++        for (i = 0; i < 256; i++) {
++            VmaStreamInfo *si = &vmastat.stream_info[i];
++            if (si->size) {
++                fprintf(stderr, "image %s: size=%zd zeros=%zd saved=%zd\n",
++                        si->devname, si->size, si->zero_bytes,
++                        si->size - si->zero_bytes);
++            }
++        }
++    }
++
++    if (vmastat.status < 0) {
++        unlink(archivename);
++        g_error("creating vma archive failed");
++    }
++
++    vma_writer_destroy(vmaw);
++    return 0;
++}
++
++static int dump_config(int argc, char **argv)
++{
++    int c, ret = 0;
++    const char *filename;
++    const char *config_name = "qemu-server.conf";
++
++    for (;;) {
++        c = getopt(argc, argv, "hc:");
++        if (c == -1) {
++            break;
++        }
++        switch (c) {
++        case '?':
++        case 'h':
++            help();
++            break;
++        case 'c':
++            config_name = optarg;
++            break;
++        default:
++            help();
++        }
++    }
++
++    /* Get the filename */
++    if ((optind + 1) != argc) {
++        help();
++    }
++    filename = argv[optind++];
++
++    Error *errp = NULL;
++    VmaReader *vmar = vma_reader_create(filename, &errp);
++
++    if (!vmar) {
++        g_error("%s", error_get_pretty(errp));
++    }
++
++    int found = 0;
++    GList *l = vma_reader_get_config_data(vmar);
++    while (l && l->data) {
++        VmaConfigData *cdata = (VmaConfigData *)l->data;
++        l = g_list_next(l);
++        if (strcmp(cdata->name, config_name) == 0) {
++            found = 1;
++            fwrite(cdata->data,  cdata->len, 1, stdout);
++            break;
++        }
++    }
++
++    vma_reader_destroy(vmar);
++
++    bdrv_close_all();
++
++    if (!found) {
++        fprintf(stderr, "unable to find configuration data '%s'\n", config_name);
++        return -1;
++    }
++
++    return ret;
++}
++
++int main(int argc, char **argv)
++{
++    const char *cmdname;
++    Error *main_loop_err = NULL;
++
++    error_init(argv[0]);
++    module_call_init(MODULE_INIT_TRACE);
++    qemu_init_exec_dir(argv[0]);
++
++    if (qemu_init_main_loop(&main_loop_err)) {
++        g_error("%s", error_get_pretty(main_loop_err));
++    }
++
++    bdrv_init();
++    module_call_init(MODULE_INIT_QOM);
++
++    if (argc < 2) {
++        help();
++    }
++
++    cmdname = argv[1];
++    argc--; argv++;
++
++
++    if (!strcmp(cmdname, "list")) {
++        return list_content(argc, argv);
++    } else if (!strcmp(cmdname, "create")) {
++        return create_archive(argc, argv);
++    } else if (!strcmp(cmdname, "extract")) {
++        return extract_content(argc, argv);
++    } else if (!strcmp(cmdname, "verify")) {
++        return verify_content(argc, argv);
++    } else if (!strcmp(cmdname, "config")) {
++        return dump_config(argc, argv);
++    }
++
++    help();
++    return 0;
++}
+diff --git a/vma.h b/vma.h
+new file mode 100644
+index 0000000000..c895c97f6d
+--- /dev/null
++++ b/vma.h
+@@ -0,0 +1,150 @@
++/*
++ * VMA: Virtual Machine Archive
++ *
++ * Copyright (C) Proxmox Server Solutions
++ *
++ * Authors:
++ *  Dietmar Maurer (dietmar@proxmox.com)
++ *
++ * This work is licensed under the terms of the GNU GPL, version 2 or later.
++ * See the COPYING file in the top-level directory.
++ *
++ */
++
++#ifndef BACKUP_VMA_H
++#define BACKUP_VMA_H
++
++#include <uuid/uuid.h>
++#include "qapi/error.h"
++#include "block/block.h"
++
++#define VMA_BLOCK_BITS 12
++#define VMA_BLOCK_SIZE (1<<VMA_BLOCK_BITS)
++#define VMA_CLUSTER_BITS (VMA_BLOCK_BITS+4)
++#define VMA_CLUSTER_SIZE (1<<VMA_CLUSTER_BITS)
++
++#if VMA_CLUSTER_SIZE != 65536
++#error unexpected cluster size
++#endif
++
++#define VMA_EXTENT_HEADER_SIZE 512
++#define VMA_BLOCKS_PER_EXTENT 59
++#define VMA_MAX_CONFIGS 256
++
++#define VMA_MAX_EXTENT_SIZE \
++    (VMA_EXTENT_HEADER_SIZE+VMA_CLUSTER_SIZE*VMA_BLOCKS_PER_EXTENT)
++#if VMA_MAX_EXTENT_SIZE != 3867136
++#error unexpected VMA_EXTENT_SIZE
++#endif
++
++/* File Format Definitions */
++
++#define VMA_MAGIC (GUINT32_TO_BE(('V'<<24)|('M'<<16)|('A'<<8)|0x00))
++#define VMA_EXTENT_MAGIC (GUINT32_TO_BE(('V'<<24)|('M'<<16)|('A'<<8)|'E'))
++
++typedef struct VmaDeviceInfoHeader {
++    uint32_t devname_ptr; /* offset into blob_buffer table */
++    uint32_t reserved0;
++    uint64_t size; /* device size in bytes */
++    uint64_t reserved1;
++    uint64_t reserved2;
++} VmaDeviceInfoHeader;
++
++typedef struct VmaHeader {
++    uint32_t magic;
++    uint32_t version;
++    unsigned char uuid[16];
++    int64_t ctime;
++    unsigned char md5sum[16];
++
++    uint32_t blob_buffer_offset;
++    uint32_t blob_buffer_size;
++    uint32_t header_size;
++
++    unsigned char reserved[1984];
++
++    uint32_t config_names[VMA_MAX_CONFIGS]; /* offset into blob_buffer table */
++    uint32_t config_data[VMA_MAX_CONFIGS];  /* offset into blob_buffer table */
++
++    uint32_t reserved1;
++
++    VmaDeviceInfoHeader dev_info[256];
++} VmaHeader;
++
++typedef struct VmaExtentHeader {
++    uint32_t magic;
++    uint16_t reserved1;
++    uint16_t block_count;
++    unsigned char uuid[16];
++    unsigned char md5sum[16];
++    uint64_t blockinfo[VMA_BLOCKS_PER_EXTENT];
++} VmaExtentHeader;
++
++/* functions/definitions to read/write vma files */
++
++typedef struct VmaReader VmaReader;
++
++typedef struct VmaWriter VmaWriter;
++
++typedef struct VmaConfigData {
++    const char *name;
++    const void *data;
++    uint32_t len;
++} VmaConfigData;
++
++typedef struct VmaStreamInfo {
++    uint64_t size;
++    uint64_t cluster_count;
++    uint64_t transferred;
++    uint64_t zero_bytes;
++    int finished;
++    char *devname;
++} VmaStreamInfo;
++
++typedef struct VmaStatus {
++    int status;
++    bool closed;
++    char errmsg[8192];
++    char uuid_str[37];
++    VmaStreamInfo stream_info[256];
++} VmaStatus;
++
++typedef struct VmaDeviceInfo {
++    uint64_t size; /* device size in bytes */
++    const char *devname;
++} VmaDeviceInfo;
++
++VmaWriter *vma_writer_create(const char *filename, uuid_t uuid, Error **errp);
++int vma_writer_close(VmaWriter *vmaw, Error **errp);
++void vma_writer_error_propagate(VmaWriter *vmaw, Error **errp);
++void vma_writer_destroy(VmaWriter *vmaw);
++int vma_writer_add_config(VmaWriter *vmaw, const char *name, gpointer data,
++                          size_t len);
++int vma_writer_register_stream(VmaWriter *vmaw, const char *devname,
++                               size_t size);
++
++int64_t coroutine_fn vma_writer_write(VmaWriter *vmaw, uint8_t dev_id,
++                                      int64_t cluster_num,
++                                      const unsigned char *buf,
++                                      size_t *zero_bytes);
++
++int coroutine_fn vma_writer_close_stream(VmaWriter *vmaw, uint8_t dev_id);
++int coroutine_fn vma_writer_flush_output(VmaWriter *vmaw);
++
++int vma_writer_get_status(VmaWriter *vmaw, VmaStatus *status);
++void vma_writer_set_error(VmaWriter *vmaw, const char *fmt, ...);
++
++
++VmaReader *vma_reader_create(const char *filename, Error **errp);
++void vma_reader_destroy(VmaReader *vmar);
++VmaHeader *vma_reader_get_header(VmaReader *vmar);
++GList *vma_reader_get_config_data(VmaReader *vmar);
++VmaDeviceInfo *vma_reader_get_device_info(VmaReader *vmar, guint8 dev_id);
++int vma_reader_register_bs(VmaReader *vmar, guint8 dev_id,
++                           BlockBackend *target, bool write_zeroes,
++                           Error **errp);
++int vma_reader_restore(VmaReader *vmar, int vmstate_fd, bool verbose,
++                       Error **errp);
++int vma_reader_verify(VmaReader *vmar, bool verbose, Error **errp);
++
++#endif /* BACKUP_VMA_H */
diff --git a/debian/patches/pve/0027-PVE-Backup-modify-job-api.patch b/debian/patches/pve/0027-PVE-Backup-modify-job-api.patch
deleted file mode 100644 (file)
index bd61512..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:56 +0200
-Subject: [PATCH] PVE-Backup: modify job api
-
-Introduce a pause_count parameter to start a backup in
-paused mode. This way backups of multiple drives can be
-started up sequentially via the completion callback while
-having been started at the same point in time.
-
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- block/backup.c            | 3 +++
- block/replication.c       | 2 +-
- blockdev.c                | 3 ++-
- include/block/block_int.h | 1 +
- job.c                     | 2 +-
- 5 files changed, 8 insertions(+), 3 deletions(-)
-
-diff --git a/block/backup.c b/block/backup.c
-index a7a7dcaf4c..ecd93e91e0 100644
---- a/block/backup.c
-+++ b/block/backup.c
-@@ -338,6 +338,7 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
-                   BlockdevOnError on_target_error,
-                   int creation_flags,
-                   BlockCompletionFunc *cb, void *opaque,
-+                  int pause_count,
-                   JobTxn *txn, Error **errp)
- {
-     int64_t len;
-@@ -459,6 +460,8 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
-     block_job_add_bdrv(&job->common, "target", target, 0, BLK_PERM_ALL,
-                        &error_abort);
-+    job->common.job.pause_count += pause_count;
-+
-     return &job->common;
-  error:
-diff --git a/block/replication.c b/block/replication.c
-index da013c2041..17246a822c 100644
---- a/block/replication.c
-+++ b/block/replication.c
-@@ -554,7 +554,7 @@ static void replication_start(ReplicationState *rs, ReplicationMode mode,
-                                 0, MIRROR_SYNC_MODE_NONE, NULL, 0, false, NULL,
-                                 BLOCKDEV_ON_ERROR_REPORT,
-                                 BLOCKDEV_ON_ERROR_REPORT, JOB_INTERNAL,
--                                backup_job_completed, bs, NULL, &local_err);
-+                                backup_job_completed, bs, 0, NULL, &local_err);
-         if (local_err) {
-             error_propagate(errp, local_err);
-             backup_job_cleanup(bs);
-diff --git a/blockdev.c b/blockdev.c
-index 5faddaa705..65c358e4ef 100644
---- a/blockdev.c
-+++ b/blockdev.c
-@@ -3114,7 +3114,8 @@ static BlockJob *do_backup_common(BackupCommon *backup,
-                             backup->filter_node_name,
-                             backup->on_source_error,
-                             backup->on_target_error,
--                            job_flags, NULL, NULL, txn, errp);
-+                            job_flags, NULL, NULL, 0, txn, errp);
-+
-     return job;
- }
-diff --git a/include/block/block_int.h b/include/block/block_int.h
-index 4c3587ea19..336f71e69d 100644
---- a/include/block/block_int.h
-+++ b/include/block/block_int.h
-@@ -1219,6 +1219,7 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
-                             BlockdevOnError on_target_error,
-                             int creation_flags,
-                             BlockCompletionFunc *cb, void *opaque,
-+                            int pause_count,
-                             JobTxn *txn, Error **errp);
- BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
-diff --git a/job.c b/job.c
-index 53be57a3a0..e82253e041 100644
---- a/job.c
-+++ b/job.c
-@@ -918,7 +918,7 @@ void job_start(Job *job)
-     job->co = qemu_coroutine_create(job_co_entry, job);
-     job->pause_count--;
-     job->busy = true;
--    job->paused = false;
-+    job->paused = job->pause_count > 0;
-     job_state_transition(job, JOB_STATUS_RUNNING);
-     aio_co_enter(job->aio_context, job->co);
- }
diff --git a/debian/patches/pve/0028-PVE-Backup-add-backup-dump-block-driver.patch b/debian/patches/pve/0028-PVE-Backup-add-backup-dump-block-driver.patch
new file mode 100644 (file)
index 0000000..57f93ef
--- /dev/null
@@ -0,0 +1,301 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Dietmar Maurer <dietmar@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:58 +0200
+Subject: [PATCH] PVE-Backup: add backup-dump block driver
+
+- add backup-dump block driver block/backup-dump.c
+- move BackupBlockJob declaration from block/backup.c to include/block/block_int.h
+- block/backup.c - backup-job-create: also consider source cluster size
+- job.c: make job_should_pause non-static
+---
+ block/Makefile.objs       |   1 +
+ block/backup-dump.c       | 169 ++++++++++++++++++++++++++++++++++++++
+ block/backup.c            |  23 ++----
+ include/block/block_int.h |  30 +++++++
+ job.c                     |   3 +-
+ 5 files changed, 207 insertions(+), 19 deletions(-)
+ create mode 100644 block/backup-dump.c
+
+diff --git a/block/Makefile.objs b/block/Makefile.objs
+index 1282445672..8af7073c83 100644
+--- a/block/Makefile.objs
++++ b/block/Makefile.objs
+@@ -34,6 +34,7 @@ block-obj-$(CONFIG_RBD) += rbd.o
+ block-obj-$(CONFIG_GLUSTERFS) += gluster.o
+ block-obj-$(CONFIG_VXHS) += vxhs.o
+ block-obj-$(CONFIG_LIBSSH) += ssh.o
++block-obj-y += backup-dump.o
+ block-obj-y += accounting.o dirty-bitmap.o
+ block-obj-y += write-threshold.o
+ block-obj-y += backup.o
+diff --git a/block/backup-dump.c b/block/backup-dump.c
+new file mode 100644
+index 0000000000..3066ab0698
+--- /dev/null
++++ b/block/backup-dump.c
+@@ -0,0 +1,169 @@
++/*
++ * BlockDriver to send backup data stream to a callback function
++ *
++ * Copyright (C) 2020 Proxmox Server Solutions GmbH
++ *
++ * This work is licensed under the terms of the GNU GPL, version 2 or later.
++ * See the COPYING file in the top-level directory.
++ *
++ */
++
++#include "qemu/osdep.h"
++#include "qemu-common.h"
++#include "qom/object_interfaces.h"
++#include "block/block_int.h"
++
++typedef struct {
++    int             dump_cb_block_size;
++    uint64_t        byte_size;
++    BackupDumpFunc *dump_cb;
++    void           *dump_cb_data;
++} BDRVBackupDumpState;
++
++static int qemu_backup_dump_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
++{
++    BDRVBackupDumpState *s = bs->opaque;
++
++    bdi->cluster_size = s->dump_cb_block_size;
++    bdi->unallocated_blocks_are_zero = true;
++    return 0;
++}
++
++static int qemu_backup_dump_check_perm(
++    BlockDriverState *bs,
++    uint64_t perm,
++    uint64_t shared,
++    Error **errp)
++{
++    /* Nothing to do. */
++    return 0;
++}
++
++static void qemu_backup_dump_set_perm(
++    BlockDriverState *bs,
++    uint64_t perm,
++    uint64_t shared)
++{
++    /* Nothing to do. */
++}
++
++static void qemu_backup_dump_abort_perm_update(BlockDriverState *bs)
++{
++    /* Nothing to do. */
++}
++
++static void qemu_backup_dump_refresh_limits(BlockDriverState *bs, Error **errp)
++{
++    bs->bl.request_alignment = BDRV_SECTOR_SIZE; /* No sub-sector I/O */
++}
++
++static void qemu_backup_dump_close(BlockDriverState *bs)
++{
++    /* Nothing to do. */
++}
++
++static int64_t qemu_backup_dump_getlength(BlockDriverState *bs)
++{
++    BDRVBackupDumpState *s = bs->opaque;
++
++    return s->byte_size;
++}
++
++static coroutine_fn int qemu_backup_dump_co_writev(
++    BlockDriverState *bs,
++    int64_t sector_num,
++    int nb_sectors,
++    QEMUIOVector *qiov,
++    int flags)
++{
++    /* flags can be only values we set in supported_write_flags */
++    assert(flags == 0);
++
++    BDRVBackupDumpState *s = bs->opaque;
++    off_t offset = sector_num * BDRV_SECTOR_SIZE;
++
++    uint64_t written = 0;
++
++    for (int i = 0; i < qiov->niov; ++i) {
++        const struct iovec *v = &qiov->iov[i];
++
++        int rc = s->dump_cb(s->dump_cb_data, offset, v->iov_len, v->iov_base);
++        if (rc < 0) {
++            return rc;
++        }
++
++        if (rc != v->iov_len) {
++            return -EIO;
++        }
++
++        written += v->iov_len;
++        offset += v->iov_len;
++    }
++
++    return written;
++}
++
++static void qemu_backup_dump_child_perm(
++    BlockDriverState *bs,
++    BdrvChild *c,
++    const BdrvChildRole *role,
++    BlockReopenQueue *reopen_queue,
++    uint64_t perm, uint64_t shared,
++    uint64_t *nperm, uint64_t *nshared)
++{
++    *nperm = BLK_PERM_ALL;
++    *nshared = BLK_PERM_ALL;
++}
++
++static BlockDriver bdrv_backup_dump_drive = {
++    .format_name                  = "backup-dump-drive",
++    .protocol_name                = "backup-dump",
++    .instance_size                = sizeof(BDRVBackupDumpState),
++
++    .bdrv_close                   = qemu_backup_dump_close,
++    .bdrv_has_zero_init           = bdrv_has_zero_init_1,
++    .bdrv_getlength               = qemu_backup_dump_getlength,
++    .bdrv_get_info                = qemu_backup_dump_get_info,
++
++    .bdrv_co_writev               = qemu_backup_dump_co_writev,
++
++    .bdrv_refresh_limits          = qemu_backup_dump_refresh_limits,
++    .bdrv_check_perm              = qemu_backup_dump_check_perm,
++    .bdrv_set_perm                = qemu_backup_dump_set_perm,
++    .bdrv_abort_perm_update       = qemu_backup_dump_abort_perm_update,
++    .bdrv_child_perm              = qemu_backup_dump_child_perm,
++};
++
++static void bdrv_backup_dump_init(void)
++{
++    bdrv_register(&bdrv_backup_dump_drive);
++}
++
++block_init(bdrv_backup_dump_init);
++
++
++BlockDriverState *bdrv_backup_dump_create(
++    int dump_cb_block_size,
++    uint64_t byte_size,
++    BackupDumpFunc *dump_cb,
++    void *dump_cb_data,
++    Error **errp)
++{
++    BDRVBackupDumpState *state;
++    BlockDriverState *bs = bdrv_new_open_driver(
++        &bdrv_backup_dump_drive, NULL, BDRV_O_RDWR, errp);
++
++    if (!bs) {
++        return NULL;
++    }
++
++    bs->total_sectors = byte_size / BDRV_SECTOR_SIZE;
++    bs->opaque = state = g_new0(BDRVBackupDumpState, 1);
++
++    state->dump_cb_block_size = dump_cb_block_size;
++    state->byte_size = byte_size;
++    state->dump_cb = dump_cb;
++    state->dump_cb_data = dump_cb_data;
++
++    return bs;
++}
+diff --git a/block/backup.c b/block/backup.c
+index ecd93e91e0..cf8f5ad25d 100644
+--- a/block/backup.c
++++ b/block/backup.c
+@@ -32,24 +32,6 @@
+ #define BACKUP_CLUSTER_SIZE_DEFAULT (1 << 16)
+-typedef struct BackupBlockJob {
+-    BlockJob common;
+-    BlockDriverState *backup_top;
+-    BlockDriverState *source_bs;
+-
+-    BdrvDirtyBitmap *sync_bitmap;
+-
+-    MirrorSyncMode sync_mode;
+-    BitmapSyncMode bitmap_mode;
+-    BlockdevOnError on_source_error;
+-    BlockdevOnError on_target_error;
+-    uint64_t len;
+-    uint64_t bytes_read;
+-    int64_t cluster_size;
+-
+-    BlockCopyState *bcs;
+-} BackupBlockJob;
+-
+ static const BlockJobDriver backup_job_driver;
+ static void backup_progress_bytes_callback(int64_t bytes, void *opaque)
+@@ -411,6 +393,11 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
+         goto error;
+     }
++    BlockDriverInfo bdi;
++    if (bdrv_get_info(bs, &bdi) == 0) {
++        cluster_size = MAX(cluster_size, bdi.cluster_size);
++    }
++
+     /*
+      * If source is in backing chain of target assume that target is going to be
+      * used for "image fleecing", i.e. it should represent a kind of snapshot of
+diff --git a/include/block/block_int.h b/include/block/block_int.h
+index 336f71e69d..62e5579723 100644
+--- a/include/block/block_int.h
++++ b/include/block/block_int.h
+@@ -60,6 +60,36 @@
+ #define BLOCK_PROBE_BUF_SIZE        512
++typedef int BackupDumpFunc(void *opaque, uint64_t offset, uint64_t bytes, const void *buf);
++
++BlockDriverState *bdrv_backuo_dump_create(
++    int dump_cb_block_size,
++    uint64_t byte_size,
++    BackupDumpFunc *dump_cb,
++    void *dump_cb_data,
++    Error **errp);
++
++// Needs to be defined here, since it's used in blockdev.c to detect PVE backup
++// jobs with source_bs
++typedef struct BlockCopyState BlockCopyState;
++typedef struct BackupBlockJob {
++    BlockJob common;
++    BlockDriverState *backup_top;
++    BlockDriverState *source_bs;
++
++    BdrvDirtyBitmap *sync_bitmap;
++
++    MirrorSyncMode sync_mode;
++    BitmapSyncMode bitmap_mode;
++    BlockdevOnError on_source_error;
++    BlockdevOnError on_target_error;
++    uint64_t len;
++    uint64_t bytes_read;
++    int64_t cluster_size;
++
++    BlockCopyState *bcs;
++} BackupBlockJob;
++
+ enum BdrvTrackedRequestType {
+     BDRV_TRACKED_READ,
+     BDRV_TRACKED_WRITE,
+diff --git a/job.c b/job.c
+index e82253e041..bcbbb0be02 100644
+--- a/job.c
++++ b/job.c
+@@ -269,7 +269,8 @@ static bool job_started(Job *job)
+     return job->co;
+ }
+-static bool job_should_pause(Job *job)
++bool job_should_pause(Job *job);
++bool job_should_pause(Job *job)
+ {
+     return job->pause_count > 0;
+ }
diff --git a/debian/patches/pve/0028-PVE-Backup-add-vma-backup-format-code.patch b/debian/patches/pve/0028-PVE-Backup-add-vma-backup-format-code.patch
deleted file mode 100644 (file)
index 54245b2..0000000
+++ /dev/null
@@ -1,2690 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Dietmar Maurer <dietmar@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:57 +0200
-Subject: [PATCH] PVE-Backup: add vma backup format code
-
----
- Makefile      |   3 +-
- Makefile.objs |   1 +
- vma-reader.c  | 857 ++++++++++++++++++++++++++++++++++++++++++++++++++
- vma-writer.c  | 771 +++++++++++++++++++++++++++++++++++++++++++++
- vma.c         | 837 ++++++++++++++++++++++++++++++++++++++++++++++++
- vma.h         | 150 +++++++++
- 6 files changed, 2618 insertions(+), 1 deletion(-)
- create mode 100644 vma-reader.c
- create mode 100644 vma-writer.c
- create mode 100644 vma.c
- create mode 100644 vma.h
-
-diff --git a/Makefile b/Makefile
-index 8a9113e666..74c2039005 100644
---- a/Makefile
-+++ b/Makefile
-@@ -479,7 +479,7 @@ dummy := $(call unnest-vars,, \
- include $(SRC_PATH)/tests/Makefile.include
--all: $(DOCS) $(if $(BUILD_DOCS),sphinxdocs) $(TOOLS) $(HELPERS-y) recurse-all modules $(vhost-user-json-y)
-+all: $(DOCS) $(if $(BUILD_DOCS),sphinxdocs) $(TOOLS) vma$(EXESUF) $(HELPERS-y) recurse-all modules $(vhost-user-json-y)
- qemu-version.h: FORCE
-       $(call quiet-command, \
-@@ -608,6 +608,7 @@ qemu-img$(EXESUF): qemu-img.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io
- qemu-nbd$(EXESUF): qemu-nbd.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
- qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
- qemu-storage-daemon$(EXESUF): qemu-storage-daemon.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(chardev-obj-y) $(io-obj-y) $(qom-obj-y) $(storage-daemon-obj-y) $(COMMON_LDADDS)
-+vma$(EXESUF): vma.o vma-reader.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
- qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o $(COMMON_LDADDS)
-diff --git a/Makefile.objs b/Makefile.objs
-index d0b4dde836..05031a3da7 100644
---- a/Makefile.objs
-+++ b/Makefile.objs
-@@ -18,6 +18,7 @@ block-obj-y += block.o blockjob.o job.o
- block-obj-y += block/ scsi/
- block-obj-y += qemu-io-cmds.o
- block-obj-$(CONFIG_REPLICATION) += replication.o
-+block-obj-y += vma-writer.o
- block-obj-m = block/
-diff --git a/vma-reader.c b/vma-reader.c
-new file mode 100644
-index 0000000000..2b1d1cdab3
---- /dev/null
-+++ b/vma-reader.c
-@@ -0,0 +1,857 @@
-+/*
-+ * VMA: Virtual Machine Archive
-+ *
-+ * Copyright (C) 2012 Proxmox Server Solutions
-+ *
-+ * Authors:
-+ *  Dietmar Maurer (dietmar@proxmox.com)
-+ *
-+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
-+ * See the COPYING file in the top-level directory.
-+ *
-+ */
-+
-+#include "qemu/osdep.h"
-+#include <glib.h>
-+#include <uuid/uuid.h>
-+
-+#include "qemu-common.h"
-+#include "qemu/timer.h"
-+#include "qemu/ratelimit.h"
-+#include "vma.h"
-+#include "block/block.h"
-+#include "sysemu/block-backend.h"
-+
-+static unsigned char zero_vma_block[VMA_BLOCK_SIZE];
-+
-+typedef struct VmaRestoreState {
-+    BlockBackend *target;
-+    bool write_zeroes;
-+    unsigned long *bitmap;
-+    int bitmap_size;
-+}  VmaRestoreState;
-+
-+struct VmaReader {
-+    int fd;
-+    GChecksum *md5csum;
-+    GHashTable *blob_hash;
-+    unsigned char *head_data;
-+    VmaDeviceInfo devinfo[256];
-+    VmaRestoreState rstate[256];
-+    GList *cdata_list;
-+    guint8 vmstate_stream;
-+    uint32_t vmstate_clusters;
-+    /* to show restore percentage if run with -v */
-+    time_t start_time;
-+    int64_t cluster_count;
-+    int64_t clusters_read;
-+    int64_t zero_cluster_data;
-+    int64_t partial_zero_cluster_data;
-+    int clusters_read_per;
-+};
-+
-+static guint
-+g_int32_hash(gconstpointer v)
-+{
-+    return *(const uint32_t *)v;
-+}
-+
-+static gboolean
-+g_int32_equal(gconstpointer v1, gconstpointer v2)
-+{
-+    return *((const uint32_t *)v1) == *((const uint32_t *)v2);
-+}
-+
-+static int vma_reader_get_bitmap(VmaRestoreState *rstate, int64_t cluster_num)
-+{
-+    assert(rstate);
-+    assert(rstate->bitmap);
-+
-+    unsigned long val, idx, bit;
-+
-+    idx = cluster_num / BITS_PER_LONG;
-+
-+    assert(rstate->bitmap_size > idx);
-+
-+    bit = cluster_num % BITS_PER_LONG;
-+    val = rstate->bitmap[idx];
-+
-+    return !!(val & (1UL << bit));
-+}
-+
-+static void vma_reader_set_bitmap(VmaRestoreState *rstate, int64_t cluster_num,
-+                                  int dirty)
-+{
-+    assert(rstate);
-+    assert(rstate->bitmap);
-+
-+    unsigned long val, idx, bit;
-+
-+    idx = cluster_num / BITS_PER_LONG;
-+
-+    assert(rstate->bitmap_size > idx);
-+
-+    bit = cluster_num % BITS_PER_LONG;
-+    val = rstate->bitmap[idx];
-+    if (dirty) {
-+        if (!(val & (1UL << bit))) {
-+            val |= 1UL << bit;
-+        }
-+    } else {
-+        if (val & (1UL << bit)) {
-+            val &= ~(1UL << bit);
-+        }
-+    }
-+    rstate->bitmap[idx] = val;
-+}
-+
-+typedef struct VmaBlob {
-+    uint32_t start;
-+    uint32_t len;
-+    void *data;
-+} VmaBlob;
-+
-+static const VmaBlob *get_header_blob(VmaReader *vmar, uint32_t pos)
-+{
-+    assert(vmar);
-+    assert(vmar->blob_hash);
-+
-+    return g_hash_table_lookup(vmar->blob_hash, &pos);
-+}
-+
-+static const char *get_header_str(VmaReader *vmar, uint32_t pos)
-+{
-+    const VmaBlob *blob = get_header_blob(vmar, pos);
-+    if (!blob) {
-+        return NULL;
-+    }
-+    const char *res = (char *)blob->data;
-+    if (res[blob->len-1] != '\0') {
-+        return NULL;
-+    }
-+    return res;
-+}
-+
-+static ssize_t
-+safe_read(int fd, unsigned char *buf, size_t count)
-+{
-+    ssize_t n;
-+
-+    do {
-+        n = read(fd, buf, count);
-+    } while (n < 0 && errno == EINTR);
-+
-+    return n;
-+}
-+
-+static ssize_t
-+full_read(int fd, unsigned char *buf, size_t len)
-+{
-+    ssize_t n;
-+    size_t total;
-+
-+    total = 0;
-+
-+    while (len > 0) {
-+        n = safe_read(fd, buf, len);
-+
-+        if (n == 0) {
-+            return total;
-+        }
-+
-+        if (n <= 0) {
-+            break;
-+        }
-+
-+        buf += n;
-+        total += n;
-+        len -= n;
-+    }
-+
-+    if (len) {
-+        return -1;
-+    }
-+
-+    return total;
-+}
-+
-+void vma_reader_destroy(VmaReader *vmar)
-+{
-+    assert(vmar);
-+
-+    if (vmar->fd >= 0) {
-+        close(vmar->fd);
-+    }
-+
-+    if (vmar->cdata_list) {
-+        g_list_free(vmar->cdata_list);
-+    }
-+
-+    int i;
-+    for (i = 1; i < 256; i++) {
-+        if (vmar->rstate[i].bitmap) {
-+            g_free(vmar->rstate[i].bitmap);
-+        }
-+    }
-+
-+    if (vmar->md5csum) {
-+        g_checksum_free(vmar->md5csum);
-+    }
-+
-+    if (vmar->blob_hash) {
-+        g_hash_table_destroy(vmar->blob_hash);
-+    }
-+
-+    if (vmar->head_data) {
-+        g_free(vmar->head_data);
-+    }
-+
-+    g_free(vmar);
-+
-+};
-+
-+static int vma_reader_read_head(VmaReader *vmar, Error **errp)
-+{
-+    assert(vmar);
-+    assert(errp);
-+    assert(*errp == NULL);
-+
-+    unsigned char md5sum[16];
-+    int i;
-+    int ret = 0;
-+
-+    vmar->head_data = g_malloc(sizeof(VmaHeader));
-+
-+    if (full_read(vmar->fd, vmar->head_data, sizeof(VmaHeader)) !=
-+        sizeof(VmaHeader)) {
-+        error_setg(errp, "can't read vma header - %s",
-+                   errno ? g_strerror(errno) : "got EOF");
-+        return -1;
-+    }
-+
-+    VmaHeader *h = (VmaHeader *)vmar->head_data;
-+
-+    if (h->magic != VMA_MAGIC) {
-+        error_setg(errp, "not a vma file - wrong magic number");
-+        return -1;
-+    }
-+
-+    uint32_t header_size = GUINT32_FROM_BE(h->header_size);
-+    int need = header_size - sizeof(VmaHeader);
-+    if (need <= 0) {
-+        error_setg(errp, "wrong vma header size %d", header_size);
-+        return -1;
-+    }
-+
-+    vmar->head_data = g_realloc(vmar->head_data, header_size);
-+    h = (VmaHeader *)vmar->head_data;
-+
-+    if (full_read(vmar->fd, vmar->head_data + sizeof(VmaHeader), need) !=
-+        need) {
-+        error_setg(errp, "can't read vma header data - %s",
-+                   errno ? g_strerror(errno) : "got EOF");
-+        return -1;
-+    }
-+
-+    memcpy(md5sum, h->md5sum, 16);
-+    memset(h->md5sum, 0, 16);
-+
-+    g_checksum_reset(vmar->md5csum);
-+    g_checksum_update(vmar->md5csum, vmar->head_data, header_size);
-+    gsize csize = 16;
-+    g_checksum_get_digest(vmar->md5csum, (guint8 *)(h->md5sum), &csize);
-+
-+    if (memcmp(md5sum, h->md5sum, 16) != 0) {
-+        error_setg(errp, "wrong vma header chechsum");
-+        return -1;
-+    }
-+
-+    /* we can modify header data after checksum verify */
-+    h->header_size = header_size;
-+
-+    h->version = GUINT32_FROM_BE(h->version);
-+    if (h->version != 1) {
-+        error_setg(errp, "wrong vma version %d", h->version);
-+        return -1;
-+    }
-+
-+    h->ctime = GUINT64_FROM_BE(h->ctime);
-+    h->blob_buffer_offset = GUINT32_FROM_BE(h->blob_buffer_offset);
-+    h->blob_buffer_size = GUINT32_FROM_BE(h->blob_buffer_size);
-+
-+    uint32_t bstart = h->blob_buffer_offset + 1;
-+    uint32_t bend = h->blob_buffer_offset + h->blob_buffer_size;
-+
-+    if (bstart <= sizeof(VmaHeader)) {
-+        error_setg(errp, "wrong vma blob buffer offset %d",
-+                   h->blob_buffer_offset);
-+        return -1;
-+    }
-+
-+    if (bend > header_size) {
-+        error_setg(errp, "wrong vma blob buffer size %d/%d",
-+                   h->blob_buffer_offset, h->blob_buffer_size);
-+        return -1;
-+    }
-+
-+    while ((bstart + 2) <= bend) {
-+        uint32_t size = vmar->head_data[bstart] +
-+            (vmar->head_data[bstart+1] << 8);
-+        if ((bstart + size + 2) <= bend) {
-+            VmaBlob *blob = g_new0(VmaBlob, 1);
-+            blob->start = bstart - h->blob_buffer_offset;
-+            blob->len = size;
-+            blob->data = vmar->head_data + bstart + 2;
-+            g_hash_table_insert(vmar->blob_hash, &blob->start, blob);
-+        }
-+        bstart += size + 2;
-+    }
-+
-+
-+    int count = 0;
-+    for (i = 1; i < 256; i++) {
-+        VmaDeviceInfoHeader *dih = &h->dev_info[i];
-+        uint32_t devname_ptr = GUINT32_FROM_BE(dih->devname_ptr);
-+        uint64_t size = GUINT64_FROM_BE(dih->size);
-+        const char *devname =  get_header_str(vmar, devname_ptr);
-+
-+        if (size && devname) {
-+            count++;
-+            vmar->devinfo[i].size = size;
-+            vmar->devinfo[i].devname = devname;
-+
-+            if (strcmp(devname, "vmstate") == 0) {
-+                vmar->vmstate_stream = i;
-+            }
-+        }
-+    }
-+
-+    for (i = 0; i < VMA_MAX_CONFIGS; i++) {
-+        uint32_t name_ptr = GUINT32_FROM_BE(h->config_names[i]);
-+        uint32_t data_ptr = GUINT32_FROM_BE(h->config_data[i]);
-+
-+        if (!(name_ptr && data_ptr)) {
-+            continue;
-+        }
-+        const char *name =  get_header_str(vmar, name_ptr);
-+        const VmaBlob *blob = get_header_blob(vmar, data_ptr);
-+
-+        if (!(name && blob)) {
-+            error_setg(errp, "vma contains invalid data pointers");
-+            return -1;
-+        }
-+
-+        VmaConfigData *cdata = g_new0(VmaConfigData, 1);
-+        cdata->name = name;
-+        cdata->data = blob->data;
-+        cdata->len = blob->len;
-+
-+        vmar->cdata_list = g_list_append(vmar->cdata_list, cdata);
-+    }
-+
-+    return ret;
-+};
-+
-+VmaReader *vma_reader_create(const char *filename, Error **errp)
-+{
-+    assert(filename);
-+    assert(errp);
-+
-+    VmaReader *vmar = g_new0(VmaReader, 1);
-+
-+    if (strcmp(filename, "-") == 0) {
-+        vmar->fd = dup(0);
-+    } else {
-+        vmar->fd = open(filename, O_RDONLY);
-+    }
-+
-+    if (vmar->fd < 0) {
-+        error_setg(errp, "can't open file %s - %s\n", filename,
-+                   g_strerror(errno));
-+        goto err;
-+    }
-+
-+    vmar->md5csum = g_checksum_new(G_CHECKSUM_MD5);
-+    if (!vmar->md5csum) {
-+        error_setg(errp, "can't allocate cmsum\n");
-+        goto err;
-+    }
-+
-+    vmar->blob_hash = g_hash_table_new_full(g_int32_hash, g_int32_equal,
-+                                            NULL, g_free);
-+
-+    if (vma_reader_read_head(vmar, errp) < 0) {
-+        goto err;
-+    }
-+
-+    return vmar;
-+
-+err:
-+    if (vmar) {
-+        vma_reader_destroy(vmar);
-+    }
-+
-+    return NULL;
-+}
-+
-+VmaHeader *vma_reader_get_header(VmaReader *vmar)
-+{
-+    assert(vmar);
-+    assert(vmar->head_data);
-+
-+    return (VmaHeader *)(vmar->head_data);
-+}
-+
-+GList *vma_reader_get_config_data(VmaReader *vmar)
-+{
-+    assert(vmar);
-+    assert(vmar->head_data);
-+
-+    return vmar->cdata_list;
-+}
-+
-+VmaDeviceInfo *vma_reader_get_device_info(VmaReader *vmar, guint8 dev_id)
-+{
-+    assert(vmar);
-+    assert(dev_id);
-+
-+    if (vmar->devinfo[dev_id].size && vmar->devinfo[dev_id].devname) {
-+        return &vmar->devinfo[dev_id];
-+    }
-+
-+    return NULL;
-+}
-+
-+static void allocate_rstate(VmaReader *vmar,  guint8 dev_id,
-+                            BlockBackend *target, bool write_zeroes)
-+{
-+    assert(vmar);
-+    assert(dev_id);
-+
-+    vmar->rstate[dev_id].target = target;
-+    vmar->rstate[dev_id].write_zeroes = write_zeroes;
-+
-+    int64_t size = vmar->devinfo[dev_id].size;
-+
-+    int64_t bitmap_size = (size/BDRV_SECTOR_SIZE) +
-+        (VMA_CLUSTER_SIZE/BDRV_SECTOR_SIZE) * BITS_PER_LONG - 1;
-+    bitmap_size /= (VMA_CLUSTER_SIZE/BDRV_SECTOR_SIZE) * BITS_PER_LONG;
-+
-+    vmar->rstate[dev_id].bitmap_size = bitmap_size;
-+    vmar->rstate[dev_id].bitmap = g_new0(unsigned long, bitmap_size);
-+
-+    vmar->cluster_count += size/VMA_CLUSTER_SIZE;
-+}
-+
-+int vma_reader_register_bs(VmaReader *vmar, guint8 dev_id, BlockBackend *target,
-+                           bool write_zeroes, Error **errp)
-+{
-+    assert(vmar);
-+    assert(target != NULL);
-+    assert(dev_id);
-+    assert(vmar->rstate[dev_id].target == NULL);
-+
-+    int64_t size = blk_getlength(target);
-+    int64_t size_diff = size - vmar->devinfo[dev_id].size;
-+
-+    /* storage types can have different size restrictions, so it
-+     * is not always possible to create an image with exact size.
-+     * So we tolerate a size difference up to 4MB.
-+     */
-+    if ((size_diff < 0) || (size_diff > 4*1024*1024)) {
-+        error_setg(errp, "vma_reader_register_bs for stream %s failed - "
-+                   "unexpected size %zd != %zd", vmar->devinfo[dev_id].devname,
-+                   size, vmar->devinfo[dev_id].size);
-+        return -1;
-+    }
-+
-+    allocate_rstate(vmar, dev_id, target, write_zeroes);
-+
-+    return 0;
-+}
-+
-+static ssize_t safe_write(int fd, void *buf, size_t count)
-+{
-+    ssize_t n;
-+
-+    do {
-+        n = write(fd, buf, count);
-+    } while (n < 0 && errno == EINTR);
-+
-+    return n;
-+}
-+
-+static size_t full_write(int fd, void *buf, size_t len)
-+{
-+    ssize_t n;
-+    size_t total;
-+
-+    total = 0;
-+
-+    while (len > 0) {
-+        n = safe_write(fd, buf, len);
-+        if (n < 0) {
-+            return n;
-+        }
-+        buf += n;
-+        total += n;
-+        len -= n;
-+    }
-+
-+    if (len) {
-+        /* incomplete write ? */
-+        return -1;
-+    }
-+
-+    return total;
-+}
-+
-+static int restore_write_data(VmaReader *vmar, guint8 dev_id,
-+                              BlockBackend *target, int vmstate_fd,
-+                              unsigned char *buf, int64_t sector_num,
-+                              int nb_sectors, Error **errp)
-+{
-+    assert(vmar);
-+
-+    if (dev_id == vmar->vmstate_stream) {
-+        if (vmstate_fd >= 0) {
-+            int len = nb_sectors * BDRV_SECTOR_SIZE;
-+            int res = full_write(vmstate_fd, buf, len);
-+            if (res < 0) {
-+                error_setg(errp, "write vmstate failed %d", res);
-+                return -1;
-+            }
-+        }
-+    } else {
-+        int res = blk_pwrite(target, sector_num * BDRV_SECTOR_SIZE, buf, nb_sectors * BDRV_SECTOR_SIZE, 0);
-+        if (res < 0) {
-+            error_setg(errp, "blk_pwrite to %s failed (%d)",
-+                       bdrv_get_device_name(blk_bs(target)), res);
-+            return -1;
-+        }
-+    }
-+    return 0;
-+}
-+
-+static int restore_extent(VmaReader *vmar, unsigned char *buf,
-+                          int extent_size, int vmstate_fd,
-+                          bool verbose, bool verify, Error **errp)
-+{
-+    assert(vmar);
-+    assert(buf);
-+
-+    VmaExtentHeader *ehead = (VmaExtentHeader *)buf;
-+    int start = VMA_EXTENT_HEADER_SIZE;
-+    int i;
-+
-+    for (i = 0; i < VMA_BLOCKS_PER_EXTENT; i++) {
-+        uint64_t block_info = GUINT64_FROM_BE(ehead->blockinfo[i]);
-+        uint64_t cluster_num = block_info & 0xffffffff;
-+        uint8_t dev_id = (block_info >> 32) & 0xff;
-+        uint16_t mask = block_info >> (32+16);
-+        int64_t max_sector;
-+
-+        if (!dev_id) {
-+            continue;
-+        }
-+
-+        VmaRestoreState *rstate = &vmar->rstate[dev_id];
-+        BlockBackend *target = NULL;
-+
-+        if (dev_id != vmar->vmstate_stream) {
-+            target = rstate->target;
-+            if (!verify && !target) {
-+                error_setg(errp, "got wrong dev id %d", dev_id);
-+                return -1;
-+            }
-+
-+            if (vma_reader_get_bitmap(rstate, cluster_num)) {
-+                error_setg(errp, "found duplicated cluster %zd for stream %s",
-+                          cluster_num, vmar->devinfo[dev_id].devname);
-+                return -1;
-+            }
-+            vma_reader_set_bitmap(rstate, cluster_num, 1);
-+
-+            max_sector = vmar->devinfo[dev_id].size/BDRV_SECTOR_SIZE;
-+        } else {
-+            max_sector = G_MAXINT64;
-+            if (cluster_num != vmar->vmstate_clusters) {
-+                error_setg(errp, "found out of order vmstate data");
-+                return -1;
-+            }
-+            vmar->vmstate_clusters++;
-+        }
-+
-+        vmar->clusters_read++;
-+
-+        if (verbose) {
-+            time_t duration = time(NULL) - vmar->start_time;
-+            int percent = (vmar->clusters_read*100)/vmar->cluster_count;
-+            if (percent != vmar->clusters_read_per) {
-+                printf("progress %d%% (read %zd bytes, duration %zd sec)\n",
-+                       percent, vmar->clusters_read*VMA_CLUSTER_SIZE,
-+                       duration);
-+                fflush(stdout);
-+                vmar->clusters_read_per = percent;
-+            }
-+        }
-+
-+        /* try to write whole clusters to speedup restore */
-+        if (mask == 0xffff) {
-+            if ((start + VMA_CLUSTER_SIZE) > extent_size) {
-+                error_setg(errp, "short vma extent - too many blocks");
-+                return -1;
-+            }
-+            int64_t sector_num = (cluster_num * VMA_CLUSTER_SIZE) /
-+                BDRV_SECTOR_SIZE;
-+            int64_t end_sector = sector_num +
-+                VMA_CLUSTER_SIZE/BDRV_SECTOR_SIZE;
-+
-+            if (end_sector > max_sector) {
-+                end_sector = max_sector;
-+            }
-+
-+            if (end_sector <= sector_num) {
-+                error_setg(errp, "got wrong block address - write beyond end");
-+                return -1;
-+            }
-+
-+            if (!verify) {
-+                int nb_sectors = end_sector - sector_num;
-+                if (restore_write_data(vmar, dev_id, target, vmstate_fd,
-+                                       buf + start, sector_num, nb_sectors,
-+                                       errp) < 0) {
-+                    return -1;
-+                }
-+            }
-+
-+            start += VMA_CLUSTER_SIZE;
-+        } else {
-+            int j;
-+            int bit = 1;
-+
-+            for (j = 0; j < 16; j++) {
-+                int64_t sector_num = (cluster_num*VMA_CLUSTER_SIZE +
-+                                      j*VMA_BLOCK_SIZE)/BDRV_SECTOR_SIZE;
-+
-+                int64_t end_sector = sector_num +
-+                    VMA_BLOCK_SIZE/BDRV_SECTOR_SIZE;
-+                if (end_sector > max_sector) {
-+                    end_sector = max_sector;
-+                }
-+
-+                if (mask & bit) {
-+                    if ((start + VMA_BLOCK_SIZE) > extent_size) {
-+                        error_setg(errp, "short vma extent - too many blocks");
-+                        return -1;
-+                    }
-+
-+                    if (end_sector <= sector_num) {
-+                        error_setg(errp, "got wrong block address - "
-+                                   "write beyond end");
-+                        return -1;
-+                    }
-+
-+                    if (!verify) {
-+                        int nb_sectors = end_sector - sector_num;
-+                        if (restore_write_data(vmar, dev_id, target, vmstate_fd,
-+                                               buf + start, sector_num,
-+                                               nb_sectors, errp) < 0) {
-+                            return -1;
-+                        }
-+                    }
-+
-+                    start += VMA_BLOCK_SIZE;
-+
-+                } else {
-+
-+
-+                    if (end_sector > sector_num) {
-+                        /* Todo: use bdrv_co_write_zeroes (but that need to
-+                         * be run inside coroutine?)
-+                         */
-+                        int nb_sectors = end_sector - sector_num;
-+                        int zero_size = BDRV_SECTOR_SIZE*nb_sectors;
-+                        vmar->zero_cluster_data += zero_size;
-+                        if (mask != 0) {
-+                            vmar->partial_zero_cluster_data += zero_size;
-+                        }
-+
-+                        if (rstate->write_zeroes && !verify) {
-+                            if (restore_write_data(vmar, dev_id, target, vmstate_fd,
-+                                                   zero_vma_block, sector_num,
-+                                                   nb_sectors, errp) < 0) {
-+                                return -1;
-+                            }
-+                        }
-+                    }
-+                }
-+
-+                bit = bit << 1;
-+            }
-+        }
-+    }
-+
-+    if (start != extent_size) {
-+        error_setg(errp, "vma extent error - missing blocks");
-+        return -1;
-+    }
-+
-+    return 0;
-+}
-+
-+static int vma_reader_restore_full(VmaReader *vmar, int vmstate_fd,
-+                                   bool verbose, bool verify,
-+                                   Error **errp)
-+{
-+    assert(vmar);
-+    assert(vmar->head_data);
-+
-+    int ret = 0;
-+    unsigned char buf[VMA_MAX_EXTENT_SIZE];
-+    int buf_pos = 0;
-+    unsigned char md5sum[16];
-+    VmaHeader *h = (VmaHeader *)vmar->head_data;
-+
-+    vmar->start_time = time(NULL);
-+
-+    while (1) {
-+        int bytes = full_read(vmar->fd, buf + buf_pos, sizeof(buf) - buf_pos);
-+        if (bytes < 0) {
-+            error_setg(errp, "read failed - %s", g_strerror(errno));
-+            return -1;
-+        }
-+
-+        buf_pos += bytes;
-+
-+        if (!buf_pos) {
-+            break; /* EOF */
-+        }
-+
-+        if (buf_pos < VMA_EXTENT_HEADER_SIZE) {
-+            error_setg(errp, "read short extent (%d bytes)", buf_pos);
-+            return -1;
-+        }
-+
-+        VmaExtentHeader *ehead = (VmaExtentHeader *)buf;
-+
-+        /* extract md5sum */
-+        memcpy(md5sum, ehead->md5sum, sizeof(ehead->md5sum));
-+        memset(ehead->md5sum, 0, sizeof(ehead->md5sum));
-+
-+        g_checksum_reset(vmar->md5csum);
-+        g_checksum_update(vmar->md5csum, buf, VMA_EXTENT_HEADER_SIZE);
-+        gsize csize = 16;
-+        g_checksum_get_digest(vmar->md5csum, ehead->md5sum, &csize);
-+
-+        if (memcmp(md5sum, ehead->md5sum, 16) != 0) {
-+            error_setg(errp, "wrong vma extent header chechsum");
-+            return -1;
-+        }
-+
-+        if (memcmp(h->uuid, ehead->uuid, sizeof(ehead->uuid)) != 0) {
-+            error_setg(errp, "wrong vma extent uuid");
-+            return -1;
-+        }
-+
-+        if (ehead->magic != VMA_EXTENT_MAGIC || ehead->reserved1 != 0) {
-+            error_setg(errp, "wrong vma extent header magic");
-+            return -1;
-+        }
-+
-+        int block_count = GUINT16_FROM_BE(ehead->block_count);
-+        int extent_size = VMA_EXTENT_HEADER_SIZE + block_count*VMA_BLOCK_SIZE;
-+
-+        if (buf_pos < extent_size) {
-+            error_setg(errp, "short vma extent (%d < %d)", buf_pos,
-+                       extent_size);
-+            return -1;
-+        }
-+
-+        if (restore_extent(vmar, buf, extent_size, vmstate_fd, verbose,
-+                           verify, errp) < 0) {
-+            return -1;
-+        }
-+
-+        if (buf_pos > extent_size) {
-+            memmove(buf, buf + extent_size, buf_pos - extent_size);
-+            buf_pos = buf_pos - extent_size;
-+        } else {
-+            buf_pos = 0;
-+        }
-+    }
-+
-+    bdrv_drain_all();
-+
-+    int i;
-+    for (i = 1; i < 256; i++) {
-+        VmaRestoreState *rstate = &vmar->rstate[i];
-+        if (!rstate->target) {
-+            continue;
-+        }
-+
-+        if (blk_flush(rstate->target) < 0) {
-+            error_setg(errp, "vma blk_flush %s failed",
-+                       vmar->devinfo[i].devname);
-+            return -1;
-+        }
-+
-+        if (vmar->devinfo[i].size &&
-+            (strcmp(vmar->devinfo[i].devname, "vmstate") != 0)) {
-+            assert(rstate->bitmap);
-+
-+            int64_t cluster_num, end;
-+
-+            end = (vmar->devinfo[i].size + VMA_CLUSTER_SIZE - 1) /
-+                VMA_CLUSTER_SIZE;
-+
-+            for (cluster_num = 0; cluster_num < end; cluster_num++) {
-+                if (!vma_reader_get_bitmap(rstate, cluster_num)) {
-+                    error_setg(errp, "detected missing cluster %zd "
-+                               "for stream %s", cluster_num,
-+                               vmar->devinfo[i].devname);
-+                    return -1;
-+                }
-+            }
-+        }
-+    }
-+
-+    if (verbose) {
-+        if (vmar->clusters_read) {
-+            printf("total bytes read %zd, sparse bytes %zd (%.3g%%)\n",
-+                   vmar->clusters_read*VMA_CLUSTER_SIZE,
-+                   vmar->zero_cluster_data,
-+                   (double)(100.0*vmar->zero_cluster_data)/
-+                   (vmar->clusters_read*VMA_CLUSTER_SIZE));
-+
-+            int64_t datasize = vmar->clusters_read*VMA_CLUSTER_SIZE-vmar->zero_cluster_data;
-+            if (datasize) { // this does not make sense for empty files
-+                printf("space reduction due to 4K zero blocks %.3g%%\n",
-+                       (double)(100.0*vmar->partial_zero_cluster_data) / datasize);
-+            }
-+        } else {
-+            printf("vma archive contains no image data\n");
-+        }
-+    }
-+    return ret;
-+}
-+
-+int vma_reader_restore(VmaReader *vmar, int vmstate_fd, bool verbose,
-+                       Error **errp)
-+{
-+    return vma_reader_restore_full(vmar, vmstate_fd, verbose, false, errp);
-+}
-+
-+int vma_reader_verify(VmaReader *vmar, bool verbose, Error **errp)
-+{
-+    guint8 dev_id;
-+
-+    for (dev_id = 1; dev_id < 255; dev_id++) {
-+        if (vma_reader_get_device_info(vmar, dev_id)) {
-+            allocate_rstate(vmar, dev_id, NULL, false);
-+        }
-+    }
-+
-+    return vma_reader_restore_full(vmar, -1, verbose, true, errp);
-+}
-+
-diff --git a/vma-writer.c b/vma-writer.c
-new file mode 100644
-index 0000000000..fe86b18a60
---- /dev/null
-+++ b/vma-writer.c
-@@ -0,0 +1,771 @@
-+/*
-+ * VMA: Virtual Machine Archive
-+ *
-+ * Copyright (C) 2012 Proxmox Server Solutions
-+ *
-+ * Authors:
-+ *  Dietmar Maurer (dietmar@proxmox.com)
-+ *
-+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
-+ * See the COPYING file in the top-level directory.
-+ *
-+ */
-+
-+#include "qemu/osdep.h"
-+#include <glib.h>
-+#include <uuid/uuid.h>
-+
-+#include "vma.h"
-+#include "block/block.h"
-+#include "monitor/monitor.h"
-+#include "qemu/main-loop.h"
-+#include "qemu/coroutine.h"
-+#include "qemu/cutils.h"
-+
-+#define DEBUG_VMA 0
-+
-+#define DPRINTF(fmt, ...)\
-+    do { if (DEBUG_VMA) { printf("vma: " fmt, ## __VA_ARGS__); } } while (0)
-+
-+#define WRITE_BUFFERS 5
-+#define HEADER_CLUSTERS 8
-+#define HEADERBUF_SIZE (VMA_CLUSTER_SIZE*HEADER_CLUSTERS)
-+
-+struct VmaWriter {
-+    int fd;
-+    FILE *cmd;
-+    int status;
-+    char errmsg[8192];
-+    uuid_t uuid;
-+    bool header_written;
-+    bool closed;
-+
-+    /* we always write extents */
-+    unsigned char *outbuf;
-+    int outbuf_pos; /* in bytes */
-+    int outbuf_count; /* in VMA_BLOCKS */
-+    uint64_t outbuf_block_info[VMA_BLOCKS_PER_EXTENT];
-+
-+    unsigned char *headerbuf;
-+
-+    GChecksum *md5csum;
-+    CoMutex flush_lock;
-+    Coroutine *co_writer;
-+
-+    /* drive informations */
-+    VmaStreamInfo stream_info[256];
-+    guint stream_count;
-+
-+    guint8 vmstate_stream;
-+    uint32_t vmstate_clusters;
-+
-+    /* header blob table */
-+    char *header_blob_table;
-+    uint32_t header_blob_table_size;
-+    uint32_t header_blob_table_pos;
-+
-+    /* store for config blobs */
-+    uint32_t config_names[VMA_MAX_CONFIGS]; /* offset into blob_buffer table */
-+    uint32_t config_data[VMA_MAX_CONFIGS];  /* offset into blob_buffer table */
-+    uint32_t config_count;
-+};
-+
-+void vma_writer_set_error(VmaWriter *vmaw, const char *fmt, ...)
-+{
-+    va_list ap;
-+
-+    if (vmaw->status < 0) {
-+        return;
-+    }
-+
-+    vmaw->status = -1;
-+
-+    va_start(ap, fmt);
-+    g_vsnprintf(vmaw->errmsg, sizeof(vmaw->errmsg), fmt, ap);
-+    va_end(ap);
-+
-+    DPRINTF("vma_writer_set_error: %s\n", vmaw->errmsg);
-+}
-+
-+static uint32_t allocate_header_blob(VmaWriter *vmaw, const char *data,
-+                                     size_t len)
-+{
-+    if (len > 65535) {
-+        return 0;
-+    }
-+
-+    if (!vmaw->header_blob_table ||
-+        (vmaw->header_blob_table_size <
-+         (vmaw->header_blob_table_pos + len + 2))) {
-+        int newsize = vmaw->header_blob_table_size + ((len + 2 + 511)/512)*512;
-+
-+        vmaw->header_blob_table = g_realloc(vmaw->header_blob_table, newsize);
-+        memset(vmaw->header_blob_table + vmaw->header_blob_table_size,
-+               0, newsize - vmaw->header_blob_table_size);
-+        vmaw->header_blob_table_size = newsize;
-+    }
-+
-+    uint32_t cpos = vmaw->header_blob_table_pos;
-+    vmaw->header_blob_table[cpos] = len & 255;
-+    vmaw->header_blob_table[cpos+1] = (len >> 8) & 255;
-+    memcpy(vmaw->header_blob_table + cpos + 2, data, len);
-+    vmaw->header_blob_table_pos += len + 2;
-+    return cpos;
-+}
-+
-+static uint32_t allocate_header_string(VmaWriter *vmaw, const char *str)
-+{
-+    assert(vmaw);
-+
-+    size_t len = strlen(str) + 1;
-+
-+    return allocate_header_blob(vmaw, str, len);
-+}
-+
-+int vma_writer_add_config(VmaWriter *vmaw, const char *name, gpointer data,
-+                          gsize len)
-+{
-+    assert(vmaw);
-+    assert(!vmaw->header_written);
-+    assert(vmaw->config_count < VMA_MAX_CONFIGS);
-+    assert(name);
-+    assert(data);
-+
-+    gchar *basename = g_path_get_basename(name);
-+    uint32_t name_ptr = allocate_header_string(vmaw, basename);
-+    g_free(basename);
-+
-+    if (!name_ptr) {
-+        return -1;
-+    }
-+
-+    uint32_t data_ptr = allocate_header_blob(vmaw, data, len);
-+    if (!data_ptr) {
-+        return -1;
-+    }
-+
-+    vmaw->config_names[vmaw->config_count] = name_ptr;
-+    vmaw->config_data[vmaw->config_count] = data_ptr;
-+
-+    vmaw->config_count++;
-+
-+    return 0;
-+}
-+
-+int vma_writer_register_stream(VmaWriter *vmaw, const char *devname,
-+                               size_t size)
-+{
-+    assert(vmaw);
-+    assert(devname);
-+    assert(!vmaw->status);
-+
-+    if (vmaw->header_written) {
-+        vma_writer_set_error(vmaw, "vma_writer_register_stream: header "
-+                             "already written");
-+        return -1;
-+    }
-+
-+    guint n = vmaw->stream_count + 1;
-+
-+    /* we can have dev_ids form 1 to 255 (0 reserved)
-+     * 255(-1) reseverd for safety
-+     */
-+    if (n > 254) {
-+        vma_writer_set_error(vmaw, "vma_writer_register_stream: "
-+                             "too many drives");
-+        return -1;
-+    }
-+
-+    if (size <= 0) {
-+        vma_writer_set_error(vmaw, "vma_writer_register_stream: "
-+                             "got strange size %zd", size);
-+        return -1;
-+    }
-+
-+    DPRINTF("vma_writer_register_stream %s %zu %d\n", devname, size, n);
-+
-+    vmaw->stream_info[n].devname = g_strdup(devname);
-+    vmaw->stream_info[n].size = size;
-+
-+    vmaw->stream_info[n].cluster_count = (size + VMA_CLUSTER_SIZE - 1) /
-+        VMA_CLUSTER_SIZE;
-+
-+    vmaw->stream_count = n;
-+
-+    if (strcmp(devname, "vmstate") == 0) {
-+        vmaw->vmstate_stream = n;
-+    }
-+
-+    return n;
-+}
-+
-+static void coroutine_fn yield_until_fd_writable(int fd)
-+{
-+    assert(qemu_in_coroutine());
-+    AioContext *ctx = qemu_get_current_aio_context();
-+    aio_set_fd_handler(ctx, fd, false, NULL, (IOHandler *)qemu_coroutine_enter,
-+                       NULL, qemu_coroutine_self());
-+    qemu_coroutine_yield();
-+    aio_set_fd_handler(ctx, fd, false, NULL, NULL, NULL, NULL);
-+}
-+
-+static ssize_t coroutine_fn
-+vma_queue_write(VmaWriter *vmaw, const void *buf, size_t bytes)
-+{
-+    DPRINTF("vma_queue_write enter %zd\n", bytes);
-+
-+    assert(vmaw);
-+    assert(buf);
-+    assert(bytes <= VMA_MAX_EXTENT_SIZE);
-+
-+    size_t done = 0;
-+    ssize_t ret;
-+
-+    assert(vmaw->co_writer == NULL);
-+
-+    vmaw->co_writer = qemu_coroutine_self();
-+
-+    while (done < bytes) {
-+        if (vmaw->status < 0) {
-+            DPRINTF("vma_queue_write detected canceled backup\n");
-+            done = -1;
-+            break;
-+        }
-+        yield_until_fd_writable(vmaw->fd);
-+        ret = write(vmaw->fd, buf + done, bytes - done);
-+        if (ret > 0) {
-+            done += ret;
-+            DPRINTF("vma_queue_write written %zd %zd\n", done, ret);
-+        } else if (ret < 0) {
-+            if (errno == EAGAIN || errno == EWOULDBLOCK) {
-+                /* try again */
-+           } else {
-+                vma_writer_set_error(vmaw, "vma_queue_write: write error - %s",
-+                                     g_strerror(errno));
-+                done = -1; /* always return failure for partial writes */
-+                break;
-+            }
-+        } else if (ret == 0) {
-+            /* should not happen - simply try again */
-+        }
-+    }
-+
-+    vmaw->co_writer = NULL;
-+
-+    return (done == bytes) ? bytes : -1;
-+}
-+
-+VmaWriter *vma_writer_create(const char *filename, uuid_t uuid, Error **errp)
-+{
-+    const char *p;
-+
-+    assert(sizeof(VmaHeader) == (4096 + 8192));
-+    assert(G_STRUCT_OFFSET(VmaHeader, config_names) == 2044);
-+    assert(G_STRUCT_OFFSET(VmaHeader, config_data) == 3068);
-+    assert(G_STRUCT_OFFSET(VmaHeader, dev_info) == 4096);
-+    assert(sizeof(VmaExtentHeader) == 512);
-+
-+    VmaWriter *vmaw = g_new0(VmaWriter, 1);
-+    vmaw->fd = -1;
-+
-+    vmaw->md5csum = g_checksum_new(G_CHECKSUM_MD5);
-+    if (!vmaw->md5csum) {
-+        error_setg(errp, "can't allocate cmsum\n");
-+        goto err;
-+    }
-+
-+    if (strstart(filename, "exec:", &p)) {
-+        vmaw->cmd = popen(p, "w");
-+        if (vmaw->cmd == NULL) {
-+            error_setg(errp, "can't popen command '%s' - %s\n", p,
-+                       g_strerror(errno));
-+            goto err;
-+        }
-+        vmaw->fd = fileno(vmaw->cmd);
-+
-+        /* try to use O_NONBLOCK */
-+        fcntl(vmaw->fd, F_SETFL, fcntl(vmaw->fd, F_GETFL)|O_NONBLOCK);
-+
-+    } else {
-+        struct stat st;
-+        int oflags;
-+        const char *tmp_id_str;
-+
-+        if ((stat(filename, &st) == 0) && S_ISFIFO(st.st_mode)) {
-+            oflags = O_NONBLOCK|O_WRONLY;
-+            vmaw->fd = qemu_open(filename, oflags, 0644);
-+        } else if (strstart(filename, "/dev/fdset/", &tmp_id_str)) {
-+            oflags = O_NONBLOCK|O_WRONLY;
-+            vmaw->fd = qemu_open(filename, oflags, 0644);
-+        } else if (strstart(filename, "/dev/fdname/", &tmp_id_str)) {
-+            vmaw->fd = monitor_get_fd(cur_mon, tmp_id_str, errp);
-+            if (vmaw->fd < 0) {
-+                goto err;
-+            }
-+            /* try to use O_NONBLOCK */
-+            fcntl(vmaw->fd, F_SETFL, fcntl(vmaw->fd, F_GETFL)|O_NONBLOCK);
-+        } else  {
-+            oflags = O_NONBLOCK|O_DIRECT|O_WRONLY|O_CREAT|O_EXCL;
-+            vmaw->fd = qemu_open(filename, oflags, 0644);
-+        }
-+
-+        if (vmaw->fd < 0) {
-+            error_setg(errp, "can't open file %s - %s\n", filename,
-+                       g_strerror(errno));
-+            goto err;
-+        }
-+    }
-+
-+    /* we use O_DIRECT, so we need to align IO buffers */
-+
-+    vmaw->outbuf = qemu_memalign(512, VMA_MAX_EXTENT_SIZE);
-+    vmaw->headerbuf = qemu_memalign(512, HEADERBUF_SIZE);
-+
-+    vmaw->outbuf_count = 0;
-+    vmaw->outbuf_pos = VMA_EXTENT_HEADER_SIZE;
-+
-+    vmaw->header_blob_table_pos = 1; /* start at pos 1 */
-+
-+    qemu_co_mutex_init(&vmaw->flush_lock);
-+
-+    uuid_copy(vmaw->uuid, uuid);
-+
-+    return vmaw;
-+
-+err:
-+    if (vmaw) {
-+        if (vmaw->cmd) {
-+            pclose(vmaw->cmd);
-+        } else if (vmaw->fd >= 0) {
-+            close(vmaw->fd);
-+        }
-+
-+        if (vmaw->md5csum) {
-+            g_checksum_free(vmaw->md5csum);
-+        }
-+
-+        g_free(vmaw);
-+    }
-+
-+    return NULL;
-+}
-+
-+static int coroutine_fn vma_write_header(VmaWriter *vmaw)
-+{
-+    assert(vmaw);
-+    unsigned char *buf = vmaw->headerbuf;
-+    VmaHeader *head = (VmaHeader *)buf;
-+
-+    int i;
-+
-+    DPRINTF("VMA WRITE HEADER\n");
-+
-+    if (vmaw->status < 0) {
-+        return vmaw->status;
-+    }
-+
-+    memset(buf, 0, HEADERBUF_SIZE);
-+
-+    head->magic = VMA_MAGIC;
-+    head->version = GUINT32_TO_BE(1); /* v1 */
-+    memcpy(head->uuid, vmaw->uuid, 16);
-+
-+    time_t ctime = time(NULL);
-+    head->ctime = GUINT64_TO_BE(ctime);
-+
-+    for (i = 0; i < VMA_MAX_CONFIGS; i++) {
-+        head->config_names[i] = GUINT32_TO_BE(vmaw->config_names[i]);
-+        head->config_data[i] = GUINT32_TO_BE(vmaw->config_data[i]);
-+    }
-+
-+    /* 32 bytes per device (12 used currently) = 8192 bytes max */
-+    for (i = 1; i <= 254; i++) {
-+        VmaStreamInfo *si = &vmaw->stream_info[i];
-+        if (si->size) {
-+            assert(si->devname);
-+            uint32_t devname_ptr = allocate_header_string(vmaw, si->devname);
-+            if (!devname_ptr) {
-+                return -1;
-+            }
-+            head->dev_info[i].devname_ptr = GUINT32_TO_BE(devname_ptr);
-+            head->dev_info[i].size = GUINT64_TO_BE(si->size);
-+        }
-+    }
-+
-+    uint32_t header_size = sizeof(VmaHeader) + vmaw->header_blob_table_size;
-+    head->header_size = GUINT32_TO_BE(header_size);
-+
-+    if (header_size > HEADERBUF_SIZE) {
-+        return -1; /* just to be sure */
-+    }
-+
-+    uint32_t blob_buffer_offset = sizeof(VmaHeader);
-+    memcpy(buf + blob_buffer_offset, vmaw->header_blob_table,
-+           vmaw->header_blob_table_size);
-+    head->blob_buffer_offset = GUINT32_TO_BE(blob_buffer_offset);
-+    head->blob_buffer_size = GUINT32_TO_BE(vmaw->header_blob_table_pos);
-+
-+    g_checksum_reset(vmaw->md5csum);
-+    g_checksum_update(vmaw->md5csum, (const guchar *)buf, header_size);
-+    gsize csize = 16;
-+    g_checksum_get_digest(vmaw->md5csum, (guint8 *)(head->md5sum), &csize);
-+
-+    return vma_queue_write(vmaw, buf, header_size);
-+}
-+
-+static int coroutine_fn vma_writer_flush(VmaWriter *vmaw)
-+{
-+    assert(vmaw);
-+
-+    int ret;
-+    int i;
-+
-+    if (vmaw->status < 0) {
-+        return vmaw->status;
-+    }
-+
-+    if (!vmaw->header_written) {
-+        vmaw->header_written = true;
-+        ret = vma_write_header(vmaw);
-+        if (ret < 0) {
-+            vma_writer_set_error(vmaw, "vma_writer_flush: write header failed");
-+            return ret;
-+        }
-+    }
-+
-+    DPRINTF("VMA WRITE FLUSH %d %d\n", vmaw->outbuf_count, vmaw->outbuf_pos);
-+
-+
-+    VmaExtentHeader *ehead = (VmaExtentHeader *)vmaw->outbuf;
-+
-+    ehead->magic = VMA_EXTENT_MAGIC;
-+    ehead->reserved1 = 0;
-+
-+    for (i = 0; i < VMA_BLOCKS_PER_EXTENT; i++) {
-+        ehead->blockinfo[i] = GUINT64_TO_BE(vmaw->outbuf_block_info[i]);
-+    }
-+
-+    guint16 block_count = (vmaw->outbuf_pos - VMA_EXTENT_HEADER_SIZE) /
-+        VMA_BLOCK_SIZE;
-+
-+    ehead->block_count = GUINT16_TO_BE(block_count);
-+
-+    memcpy(ehead->uuid, vmaw->uuid, sizeof(ehead->uuid));
-+    memset(ehead->md5sum, 0, sizeof(ehead->md5sum));
-+
-+    g_checksum_reset(vmaw->md5csum);
-+    g_checksum_update(vmaw->md5csum, vmaw->outbuf, VMA_EXTENT_HEADER_SIZE);
-+    gsize csize = 16;
-+    g_checksum_get_digest(vmaw->md5csum, ehead->md5sum, &csize);
-+
-+    int bytes = vmaw->outbuf_pos;
-+    ret = vma_queue_write(vmaw, vmaw->outbuf, bytes);
-+    if (ret != bytes) {
-+        vma_writer_set_error(vmaw, "vma_writer_flush: failed write");
-+    }
-+
-+    vmaw->outbuf_count = 0;
-+    vmaw->outbuf_pos = VMA_EXTENT_HEADER_SIZE;
-+
-+    for (i = 0; i < VMA_BLOCKS_PER_EXTENT; i++) {
-+        vmaw->outbuf_block_info[i] = 0;
-+    }
-+
-+    return vmaw->status;
-+}
-+
-+static int vma_count_open_streams(VmaWriter *vmaw)
-+{
-+    g_assert(vmaw != NULL);
-+
-+    int i;
-+    int open_drives = 0;
-+    for (i = 0; i <= 255; i++) {
-+        if (vmaw->stream_info[i].size && !vmaw->stream_info[i].finished) {
-+            open_drives++;
-+        }
-+    }
-+
-+    return open_drives;
-+}
-+
-+
-+/**
-+ * You need to call this if the vma archive does not contain
-+ * any data stream.
-+ */
-+int coroutine_fn
-+vma_writer_flush_output(VmaWriter *vmaw)
-+{
-+    qemu_co_mutex_lock(&vmaw->flush_lock);
-+    int ret = vma_writer_flush(vmaw);
-+    qemu_co_mutex_unlock(&vmaw->flush_lock);
-+    if (ret < 0) {
-+        vma_writer_set_error(vmaw, "vma_writer_flush_header failed");
-+    }
-+    return ret;
-+}
-+
-+/**
-+ * all jobs should call this when there is no more data
-+ * Returns: number of remaining stream (0 ==> finished)
-+ */
-+int coroutine_fn
-+vma_writer_close_stream(VmaWriter *vmaw, uint8_t dev_id)
-+{
-+    g_assert(vmaw != NULL);
-+
-+    DPRINTF("vma_writer_set_status %d\n", dev_id);
-+    if (!vmaw->stream_info[dev_id].size) {
-+        vma_writer_set_error(vmaw, "vma_writer_close_stream: "
-+                             "no such stream %d", dev_id);
-+        return -1;
-+    }
-+    if (vmaw->stream_info[dev_id].finished) {
-+        vma_writer_set_error(vmaw, "vma_writer_close_stream: "
-+                             "stream already closed %d", dev_id);
-+        return -1;
-+    }
-+
-+    vmaw->stream_info[dev_id].finished = true;
-+
-+    int open_drives = vma_count_open_streams(vmaw);
-+
-+    if (open_drives <= 0) {
-+        DPRINTF("vma_writer_set_status all drives completed\n");
-+        vma_writer_flush_output(vmaw);
-+    }
-+
-+    return open_drives;
-+}
-+
-+int vma_writer_get_status(VmaWriter *vmaw, VmaStatus *status)
-+{
-+    int i;
-+
-+    g_assert(vmaw != NULL);
-+
-+    if (status) {
-+        status->status = vmaw->status;
-+        g_strlcpy(status->errmsg, vmaw->errmsg, sizeof(status->errmsg));
-+        for (i = 0; i <= 255; i++) {
-+            status->stream_info[i] = vmaw->stream_info[i];
-+        }
-+
-+        uuid_unparse_lower(vmaw->uuid, status->uuid_str);
-+    }
-+
-+    status->closed = vmaw->closed;
-+
-+    return vmaw->status;
-+}
-+
-+static int vma_writer_get_buffer(VmaWriter *vmaw)
-+{
-+    int ret = 0;
-+
-+    qemu_co_mutex_lock(&vmaw->flush_lock);
-+
-+    /* wait until buffer is available */
-+    while (vmaw->outbuf_count >= (VMA_BLOCKS_PER_EXTENT - 1)) {
-+        ret = vma_writer_flush(vmaw);
-+        if (ret < 0) {
-+            vma_writer_set_error(vmaw, "vma_writer_get_buffer: flush failed");
-+            break;
-+        }
-+    }
-+
-+    qemu_co_mutex_unlock(&vmaw->flush_lock);
-+
-+    return ret;
-+}
-+
-+
-+int64_t coroutine_fn
-+vma_writer_write(VmaWriter *vmaw, uint8_t dev_id, int64_t cluster_num,
-+                 const unsigned char *buf, size_t *zero_bytes)
-+{
-+    g_assert(vmaw != NULL);
-+    g_assert(zero_bytes != NULL);
-+
-+    *zero_bytes = 0;
-+
-+    if (vmaw->status < 0) {
-+        return vmaw->status;
-+    }
-+
-+    if (!dev_id || !vmaw->stream_info[dev_id].size) {
-+        vma_writer_set_error(vmaw, "vma_writer_write: "
-+                             "no such stream %d", dev_id);
-+        return -1;
-+    }
-+
-+    if (vmaw->stream_info[dev_id].finished) {
-+        vma_writer_set_error(vmaw, "vma_writer_write: "
-+                             "stream already closed %d", dev_id);
-+        return -1;
-+    }
-+
-+
-+    if (cluster_num >= (((uint64_t)1)<<32)) {
-+        vma_writer_set_error(vmaw, "vma_writer_write: "
-+                             "cluster number out of range");
-+        return -1;
-+    }
-+
-+    if (dev_id == vmaw->vmstate_stream) {
-+        if (cluster_num != vmaw->vmstate_clusters) {
-+            vma_writer_set_error(vmaw, "vma_writer_write: "
-+                                 "non sequential vmstate write");
-+        }
-+        vmaw->vmstate_clusters++;
-+    } else if (cluster_num >= vmaw->stream_info[dev_id].cluster_count) {
-+        vma_writer_set_error(vmaw, "vma_writer_write: cluster number too big");
-+        return -1;
-+    }
-+
-+    /* wait until buffer is available */
-+    if (vma_writer_get_buffer(vmaw) < 0) {
-+        vma_writer_set_error(vmaw, "vma_writer_write: "
-+                             "vma_writer_get_buffer failed");
-+        return -1;
-+    }
-+
-+    DPRINTF("VMA WRITE %d %zd\n", dev_id, cluster_num);
-+
-+    uint16_t mask = 0;
-+
-+    if (buf) {
-+        int i;
-+        int bit = 1;
-+        for (i = 0; i < 16; i++) {
-+            const unsigned char *vmablock = buf + (i*VMA_BLOCK_SIZE);
-+            if (!buffer_is_zero(vmablock, VMA_BLOCK_SIZE)) {
-+                mask |= bit;
-+                memcpy(vmaw->outbuf + vmaw->outbuf_pos, vmablock,
-+                       VMA_BLOCK_SIZE);
-+                vmaw->outbuf_pos += VMA_BLOCK_SIZE;
-+            } else {
-+                DPRINTF("VMA WRITE %zd ZERO BLOCK %d\n", cluster_num, i);
-+                vmaw->stream_info[dev_id].zero_bytes += VMA_BLOCK_SIZE;
-+                *zero_bytes += VMA_BLOCK_SIZE;
-+            }
-+
-+            bit = bit << 1;
-+        }
-+    } else {
-+        DPRINTF("VMA WRITE %zd ZERO CLUSTER\n", cluster_num);
-+        vmaw->stream_info[dev_id].zero_bytes += VMA_CLUSTER_SIZE;
-+        *zero_bytes += VMA_CLUSTER_SIZE;
-+    }
-+
-+    uint64_t block_info = ((uint64_t)mask) << (32+16);
-+    block_info |= ((uint64_t)dev_id) << 32;
-+    block_info |= (cluster_num & 0xffffffff);
-+    vmaw->outbuf_block_info[vmaw->outbuf_count] = block_info;
-+
-+    DPRINTF("VMA WRITE MASK %zd %zx\n", cluster_num, block_info);
-+
-+    vmaw->outbuf_count++;
-+
-+    /** NOTE: We allways write whole clusters, but we correctly set
-+     * transferred bytes. So transferred == size when when everything
-+     * went OK.
-+     */
-+    size_t transferred = VMA_CLUSTER_SIZE;
-+
-+    if (dev_id != vmaw->vmstate_stream) {
-+        uint64_t last = (cluster_num + 1) * VMA_CLUSTER_SIZE;
-+        if (last > vmaw->stream_info[dev_id].size) {
-+            uint64_t diff = last - vmaw->stream_info[dev_id].size;
-+            if (diff >= VMA_CLUSTER_SIZE) {
-+                vma_writer_set_error(vmaw, "vma_writer_write: "
-+                                     "read after last cluster");
-+                return -1;
-+            }
-+            transferred -= diff;
-+        }
-+    }
-+
-+    vmaw->stream_info[dev_id].transferred += transferred;
-+
-+    return transferred;
-+}
-+
-+void vma_writer_error_propagate(VmaWriter *vmaw, Error **errp)
-+{
-+    if (vmaw->status < 0 && *errp == NULL) {
-+        error_setg(errp, "%s", vmaw->errmsg);
-+    }
-+}
-+
-+int vma_writer_close(VmaWriter *vmaw, Error **errp)
-+{
-+    g_assert(vmaw != NULL);
-+
-+    int i;
-+
-+    qemu_co_mutex_lock(&vmaw->flush_lock); // wait for pending writes
-+
-+    assert(vmaw->co_writer == NULL);
-+
-+    if (vmaw->cmd) {
-+        if (pclose(vmaw->cmd) < 0) {
-+            vma_writer_set_error(vmaw, "vma_writer_close: "
-+                                 "pclose failed - %s", g_strerror(errno));
-+        }
-+    } else {
-+        if (close(vmaw->fd) < 0) {
-+            vma_writer_set_error(vmaw, "vma_writer_close: "
-+                                 "close failed - %s", g_strerror(errno));
-+        }
-+    }
-+
-+    for (i = 0; i <= 255; i++) {
-+        VmaStreamInfo *si = &vmaw->stream_info[i];
-+        if (si->size) {
-+            if (!si->finished) {
-+                vma_writer_set_error(vmaw, "vma_writer_close: "
-+                                     "detected open stream '%s'", si->devname);
-+            } else if ((si->transferred != si->size) &&
-+                       (i != vmaw->vmstate_stream)) {
-+                vma_writer_set_error(vmaw, "vma_writer_close: "
-+                                     "incomplete stream '%s' (%zd != %zd)",
-+                                     si->devname, si->transferred, si->size);
-+            }
-+        }
-+    }
-+
-+    for (i = 0; i <= 255; i++) {
-+        vmaw->stream_info[i].finished = 1; /* mark as closed */
-+    }
-+
-+    vmaw->closed = 1;
-+
-+    if (vmaw->status < 0 && *errp == NULL) {
-+        error_setg(errp, "%s", vmaw->errmsg);
-+    }
-+
-+    qemu_co_mutex_unlock(&vmaw->flush_lock);
-+
-+    return vmaw->status;
-+}
-+
-+void vma_writer_destroy(VmaWriter *vmaw)
-+{
-+    assert(vmaw);
-+
-+    int i;
-+
-+    for (i = 0; i <= 255; i++) {
-+        if (vmaw->stream_info[i].devname) {
-+            g_free(vmaw->stream_info[i].devname);
-+        }
-+    }
-+
-+    if (vmaw->md5csum) {
-+        g_checksum_free(vmaw->md5csum);
-+    }
-+
-+    g_free(vmaw);
-+}
-diff --git a/vma.c b/vma.c
-new file mode 100644
-index 0000000000..a82752448a
---- /dev/null
-+++ b/vma.c
-@@ -0,0 +1,837 @@
-+/*
-+ * VMA: Virtual Machine Archive
-+ *
-+ * Copyright (C) 2012-2013 Proxmox Server Solutions
-+ *
-+ * Authors:
-+ *  Dietmar Maurer (dietmar@proxmox.com)
-+ *
-+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
-+ * See the COPYING file in the top-level directory.
-+ *
-+ */
-+
-+#include "qemu/osdep.h"
-+#include <glib.h>
-+
-+#include "vma.h"
-+#include "qemu-common.h"
-+#include "qemu/module.h"
-+#include "qemu/error-report.h"
-+#include "qemu/main-loop.h"
-+#include "qemu/cutils.h"
-+#include "qapi/qmp/qdict.h"
-+#include "sysemu/block-backend.h"
-+
-+static void help(void)
-+{
-+    const char *help_msg =
-+        "usage: vma command [command options]\n"
-+        "\n"
-+        "vma list <filename>\n"
-+        "vma config <filename> [-c config]\n"
-+        "vma create <filename> [-c config] pathname ...\n"
-+        "vma extract <filename> [-r <fifo>] <targetdir>\n"
-+        "vma verify <filename> [-v]\n"
-+        ;
-+
-+    printf("%s", help_msg);
-+    exit(1);
-+}
-+
-+static const char *extract_devname(const char *path, char **devname, int index)
-+{
-+    assert(path);
-+
-+    const char *sep = strchr(path, '=');
-+
-+    if (sep) {
-+        *devname = g_strndup(path, sep - path);
-+        path = sep + 1;
-+    } else {
-+        if (index >= 0) {
-+            *devname = g_strdup_printf("disk%d", index);
-+        } else {
-+            *devname = NULL;
-+        }
-+    }
-+
-+    return path;
-+}
-+
-+static void print_content(VmaReader *vmar)
-+{
-+    assert(vmar);
-+
-+    VmaHeader *head = vma_reader_get_header(vmar);
-+
-+    GList *l = vma_reader_get_config_data(vmar);
-+    while (l && l->data) {
-+        VmaConfigData *cdata = (VmaConfigData *)l->data;
-+        l = g_list_next(l);
-+        printf("CFG: size: %d name: %s\n", cdata->len, cdata->name);
-+    }
-+
-+    int i;
-+    VmaDeviceInfo *di;
-+    for (i = 1; i < 255; i++) {
-+        di = vma_reader_get_device_info(vmar, i);
-+        if (di) {
-+            if (strcmp(di->devname, "vmstate") == 0) {
-+                printf("VMSTATE: dev_id=%d memory: %zd\n", i, di->size);
-+            } else {
-+                printf("DEV: dev_id=%d size: %zd devname: %s\n",
-+                       i, di->size, di->devname);
-+            }
-+        }
-+    }
-+    /* ctime is the last entry we print */
-+    printf("CTIME: %s", ctime(&head->ctime));
-+    fflush(stdout);
-+}
-+
-+static int list_content(int argc, char **argv)
-+{
-+    int c, ret = 0;
-+    const char *filename;
-+
-+    for (;;) {
-+        c = getopt(argc, argv, "h");
-+        if (c == -1) {
-+            break;
-+        }
-+        switch (c) {
-+        case '?':
-+        case 'h':
-+            help();
-+            break;
-+        default:
-+            g_assert_not_reached();
-+        }
-+    }
-+
-+    /* Get the filename */
-+    if ((optind + 1) != argc) {
-+        help();
-+    }
-+    filename = argv[optind++];
-+
-+    Error *errp = NULL;
-+    VmaReader *vmar = vma_reader_create(filename, &errp);
-+
-+    if (!vmar) {
-+        g_error("%s", error_get_pretty(errp));
-+    }
-+
-+    print_content(vmar);
-+
-+    vma_reader_destroy(vmar);
-+
-+    return ret;
-+}
-+
-+typedef struct RestoreMap {
-+    char *devname;
-+    char *path;
-+    char *format;
-+    uint64_t throttling_bps;
-+    char *throttling_group;
-+    char *cache;
-+    bool write_zero;
-+} RestoreMap;
-+
-+static bool try_parse_option(char **line, const char *optname, char **out, const char *inbuf) {
-+    size_t optlen = strlen(optname);
-+    if (strncmp(*line, optname, optlen) != 0 || (*line)[optlen] != '=') {
-+        return false;
-+    }
-+    if (*out) {
-+        g_error("read map failed - duplicate value for option '%s'", optname);
-+    }
-+    char *value = (*line) + optlen + 1; /* including a '=' */
-+    char *colon = strchr(value, ':');
-+    if (!colon) {
-+        g_error("read map failed - option '%s' not terminated ('%s')",
-+                optname, inbuf);
-+    }
-+    *line = colon+1;
-+    *out = g_strndup(value, colon - value);
-+    return true;
-+}
-+
-+static uint64_t verify_u64(const char *text) {
-+    uint64_t value;
-+    const char *endptr = NULL;
-+    if (qemu_strtou64(text, &endptr, 0, &value) != 0 || !endptr || *endptr) {
-+        g_error("read map failed - not a number: %s", text);
-+    }
-+    return value;
-+}
-+
-+static int extract_content(int argc, char **argv)
-+{
-+    int c, ret = 0;
-+    int verbose = 0;
-+    const char *filename;
-+    const char *dirname;
-+    const char *readmap = NULL;
-+
-+    for (;;) {
-+        c = getopt(argc, argv, "hvr:");
-+        if (c == -1) {
-+            break;
-+        }
-+        switch (c) {
-+        case '?':
-+        case 'h':
-+            help();
-+            break;
-+        case 'r':
-+            readmap = optarg;
-+            break;
-+        case 'v':
-+            verbose = 1;
-+            break;
-+        default:
-+            help();
-+        }
-+    }
-+
-+    /* Get the filename */
-+    if ((optind + 2) != argc) {
-+        help();
-+    }
-+    filename = argv[optind++];
-+    dirname = argv[optind++];
-+
-+    Error *errp = NULL;
-+    VmaReader *vmar = vma_reader_create(filename, &errp);
-+
-+    if (!vmar) {
-+        g_error("%s", error_get_pretty(errp));
-+    }
-+
-+    if (mkdir(dirname, 0777) < 0) {
-+        g_error("unable to create target directory %s - %s",
-+                dirname, g_strerror(errno));
-+    }
-+
-+    GList *l = vma_reader_get_config_data(vmar);
-+    while (l && l->data) {
-+        VmaConfigData *cdata = (VmaConfigData *)l->data;
-+        l = g_list_next(l);
-+        char *cfgfn = g_strdup_printf("%s/%s", dirname, cdata->name);
-+        GError *err = NULL;
-+        if (!g_file_set_contents(cfgfn, (gchar *)cdata->data, cdata->len,
-+                                 &err)) {
-+            g_error("unable to write file: %s", err->message);
-+        }
-+    }
-+
-+    GHashTable *devmap = g_hash_table_new(g_str_hash, g_str_equal);
-+
-+    if (readmap) {
-+        print_content(vmar);
-+
-+        FILE *map = fopen(readmap, "r");
-+        if (!map) {
-+            g_error("unable to open fifo %s - %s", readmap, g_strerror(errno));
-+        }
-+
-+        while (1) {
-+            char inbuf[8192];
-+            char *line = fgets(inbuf, sizeof(inbuf), map);
-+            char *format = NULL;
-+            char *bps = NULL;
-+            char *group = NULL;
-+            char *cache = NULL;
-+            if (!line || line[0] == '\0' || !strcmp(line, "done\n")) {
-+                break;
-+            }
-+            int len = strlen(line);
-+            if (line[len - 1] == '\n') {
-+                line[len - 1] = '\0';
-+                if (len == 1) {
-+                    break;
-+                }
-+            }
-+
-+            while (1) {
-+                if (!try_parse_option(&line, "format", &format, inbuf) &&
-+                    !try_parse_option(&line, "throttling.bps", &bps, inbuf) &&
-+                    !try_parse_option(&line, "throttling.group", &group, inbuf) &&
-+                    !try_parse_option(&line, "cache", &cache, inbuf))
-+                {
-+                    break;
-+                }
-+            }
-+
-+            uint64_t bps_value = 0;
-+            if (bps) {
-+                bps_value = verify_u64(bps);
-+                g_free(bps);
-+            }
-+
-+            const char *path;
-+            bool write_zero;
-+            if (line[0] == '0' && line[1] == ':') {
-+                path = line + 2;
-+                write_zero = false;
-+            } else if (line[0] == '1' && line[1] == ':') {
-+                path = line + 2;
-+                write_zero = true;
-+            } else {
-+                g_error("read map failed - parse error ('%s')", inbuf);
-+            }
-+
-+            char *devname = NULL;
-+            path = extract_devname(path, &devname, -1);
-+            if (!devname) {
-+                g_error("read map failed - no dev name specified ('%s')",
-+                        inbuf);
-+            }
-+
-+            RestoreMap *map = g_new0(RestoreMap, 1);
-+            map->devname = g_strdup(devname);
-+            map->path = g_strdup(path);
-+            map->format = format;
-+            map->throttling_bps = bps_value;
-+            map->throttling_group = group;
-+            map->cache = cache;
-+            map->write_zero = write_zero;
-+
-+            g_hash_table_insert(devmap, map->devname, map);
-+
-+        };
-+    }
-+
-+    int i;
-+    int vmstate_fd = -1;
-+    guint8 vmstate_stream = 0;
-+
-+    BlockBackend *blk = NULL;
-+
-+    for (i = 1; i < 255; i++) {
-+        VmaDeviceInfo *di = vma_reader_get_device_info(vmar, i);
-+        if (di && (strcmp(di->devname, "vmstate") == 0)) {
-+            vmstate_stream = i;
-+            char *statefn = g_strdup_printf("%s/vmstate.bin", dirname);
-+            vmstate_fd = open(statefn, O_WRONLY|O_CREAT|O_EXCL, 0644);
-+            if (vmstate_fd < 0) {
-+                g_error("create vmstate file '%s' failed - %s", statefn,
-+                        g_strerror(errno));
-+            }
-+            g_free(statefn);
-+        } else if (di) {
-+            char *devfn = NULL;
-+            const char *format = NULL;
-+            uint64_t throttling_bps = 0;
-+            const char *throttling_group = NULL;
-+            const char *cache = NULL;
-+            int flags = BDRV_O_RDWR;
-+            bool write_zero = true;
-+
-+            if (readmap) {
-+                RestoreMap *map;
-+                map = (RestoreMap *)g_hash_table_lookup(devmap, di->devname);
-+                if (map == NULL) {
-+                    g_error("no device name mapping for %s", di->devname);
-+                }
-+                devfn = map->path;
-+                format = map->format;
-+                throttling_bps = map->throttling_bps;
-+                throttling_group = map->throttling_group;
-+                cache = map->cache;
-+                write_zero = map->write_zero;
-+            } else {
-+                devfn = g_strdup_printf("%s/tmp-disk-%s.raw",
-+                                        dirname, di->devname);
-+                printf("DEVINFO %s %zd\n", devfn, di->size);
-+
-+                bdrv_img_create(devfn, "raw", NULL, NULL, NULL, di->size,
-+                                flags, true, &errp);
-+                if (errp) {
-+                    g_error("can't create file %s: %s", devfn,
-+                            error_get_pretty(errp));
-+                }
-+
-+                /* Note: we created an empty file above, so there is no
-+                 * need to write zeroes (so we generate a sparse file)
-+                 */
-+                write_zero = false;
-+            }
-+
-+          size_t devlen = strlen(devfn);
-+          QDict *options = NULL;
-+            bool writethrough;
-+            if (format) {
-+                /* explicit format from commandline */
-+                options = qdict_new();
-+                qdict_put_str(options, "driver", format);
-+            } else if ((devlen > 4 && strcmp(devfn+devlen-4, ".raw") == 0) ||
-+                     strncmp(devfn, "/dev/", 5) == 0)
-+          {
-+                /* This part is now deprecated for PVE as well (just as qemu
-+                 * deprecated not specifying an explicit raw format, too.
-+                 */
-+              /* explicit raw format */
-+              options = qdict_new();
-+              qdict_put_str(options, "driver", "raw");
-+          }
-+            if (cache && bdrv_parse_cache_mode(cache, &flags, &writethrough)) {
-+                g_error("invalid cache option: %s\n", cache);
-+            }
-+
-+          if (errp || !(blk = blk_new_open(devfn, NULL, options, flags, &errp))) {
-+                g_error("can't open file %s - %s", devfn,
-+                        error_get_pretty(errp));
-+            }
-+
-+            if (cache) {
-+                blk_set_enable_write_cache(blk, !writethrough);
-+            }
-+
-+            if (throttling_group) {
-+                blk_io_limits_enable(blk, throttling_group);
-+            }
-+
-+            if (throttling_bps) {
-+                if (!throttling_group) {
-+                    blk_io_limits_enable(blk, devfn);
-+                }
-+
-+                ThrottleConfig cfg;
-+                throttle_config_init(&cfg);
-+                cfg.buckets[THROTTLE_BPS_WRITE].avg = throttling_bps;
-+                Error *err = NULL;
-+                if (!throttle_is_valid(&cfg, &err)) {
-+                    error_report_err(err);
-+                    g_error("failed to apply throttling");
-+                }
-+                blk_set_io_limits(blk, &cfg);
-+            }
-+
-+            if (vma_reader_register_bs(vmar, i, blk, write_zero, &errp) < 0) {
-+                g_error("%s", error_get_pretty(errp));
-+            }
-+
-+            if (!readmap) {
-+                g_free(devfn);
-+            }
-+        }
-+    }
-+
-+    if (vma_reader_restore(vmar, vmstate_fd, verbose, &errp) < 0) {
-+        g_error("restore failed - %s", error_get_pretty(errp));
-+    }
-+
-+    if (!readmap) {
-+        for (i = 1; i < 255; i++) {
-+            VmaDeviceInfo *di = vma_reader_get_device_info(vmar, i);
-+            if (di && (i != vmstate_stream)) {
-+                char *tmpfn = g_strdup_printf("%s/tmp-disk-%s.raw",
-+                                              dirname, di->devname);
-+                char *fn = g_strdup_printf("%s/disk-%s.raw",
-+                                           dirname, di->devname);
-+                if (rename(tmpfn, fn) != 0) {
-+                    g_error("rename %s to %s failed - %s",
-+                            tmpfn, fn, g_strerror(errno));
-+                }
-+            }
-+        }
-+    }
-+
-+    vma_reader_destroy(vmar);
-+
-+    blk_unref(blk);
-+
-+    bdrv_close_all();
-+
-+    return ret;
-+}
-+
-+static int verify_content(int argc, char **argv)
-+{
-+    int c, ret = 0;
-+    int verbose = 0;
-+    const char *filename;
-+
-+    for (;;) {
-+        c = getopt(argc, argv, "hv");
-+        if (c == -1) {
-+            break;
-+        }
-+        switch (c) {
-+        case '?':
-+        case 'h':
-+            help();
-+            break;
-+        case 'v':
-+            verbose = 1;
-+            break;
-+        default:
-+            help();
-+        }
-+    }
-+
-+    /* Get the filename */
-+    if ((optind + 1) != argc) {
-+        help();
-+    }
-+    filename = argv[optind++];
-+
-+    Error *errp = NULL;
-+    VmaReader *vmar = vma_reader_create(filename, &errp);
-+
-+    if (!vmar) {
-+        g_error("%s", error_get_pretty(errp));
-+    }
-+
-+    if (verbose) {
-+        print_content(vmar);
-+    }
-+
-+    if (vma_reader_verify(vmar, verbose, &errp) < 0) {
-+        g_error("verify failed - %s", error_get_pretty(errp));
-+    }
-+
-+    vma_reader_destroy(vmar);
-+
-+    bdrv_close_all();
-+
-+    return ret;
-+}
-+
-+typedef struct BackupJob {
-+    BlockBackend *target;
-+    int64_t len;
-+    VmaWriter *vmaw;
-+    uint8_t dev_id;
-+} BackupJob;
-+
-+#define BACKUP_SECTORS_PER_CLUSTER (VMA_CLUSTER_SIZE / BDRV_SECTOR_SIZE)
-+
-+static void coroutine_fn backup_run_empty(void *opaque)
-+{
-+    VmaWriter *vmaw = (VmaWriter *)opaque;
-+
-+    vma_writer_flush_output(vmaw);
-+
-+    Error *err = NULL;
-+    if (vma_writer_close(vmaw, &err) != 0) {
-+        g_warning("vma_writer_close failed %s", error_get_pretty(err));
-+    }
-+}
-+
-+static void coroutine_fn backup_run(void *opaque)
-+{
-+    BackupJob *job = (BackupJob *)opaque;
-+    struct iovec iov;
-+    QEMUIOVector qiov;
-+
-+    int64_t start, end;
-+    int ret = 0;
-+
-+    unsigned char *buf = blk_blockalign(job->target, VMA_CLUSTER_SIZE);
-+
-+    start = 0;
-+    end = DIV_ROUND_UP(job->len / BDRV_SECTOR_SIZE,
-+                       BACKUP_SECTORS_PER_CLUSTER);
-+
-+    for (; start < end; start++) {
-+        iov.iov_base = buf;
-+        iov.iov_len = VMA_CLUSTER_SIZE;
-+        qemu_iovec_init_external(&qiov, &iov, 1);
-+
-+        ret = blk_co_preadv(job->target, start * VMA_CLUSTER_SIZE,
-+                            VMA_CLUSTER_SIZE, &qiov, 0);
-+        if (ret < 0) {
-+            vma_writer_set_error(job->vmaw, "read error", -1);
-+            goto out;
-+        }
-+
-+        size_t zb = 0;
-+        if (vma_writer_write(job->vmaw, job->dev_id, start, buf, &zb) < 0) {
-+            vma_writer_set_error(job->vmaw, "backup_dump_cb vma_writer_write failed", -1);
-+            goto out;
-+        }
-+    }
-+
-+
-+out:
-+    if (vma_writer_close_stream(job->vmaw, job->dev_id) <= 0) {
-+        Error *err = NULL;
-+        if (vma_writer_close(job->vmaw, &err) != 0) {
-+            g_warning("vma_writer_close failed %s", error_get_pretty(err));
-+        }
-+    }
-+}
-+
-+static int create_archive(int argc, char **argv)
-+{
-+    int i, c;
-+    int verbose = 0;
-+    const char *archivename;
-+    GList *config_files = NULL;
-+
-+    for (;;) {
-+        c = getopt(argc, argv, "hvc:");
-+        if (c == -1) {
-+            break;
-+        }
-+        switch (c) {
-+        case '?':
-+        case 'h':
-+            help();
-+            break;
-+        case 'c':
-+            config_files = g_list_append(config_files, optarg);
-+            break;
-+        case 'v':
-+            verbose = 1;
-+            break;
-+        default:
-+            g_assert_not_reached();
-+        }
-+    }
-+
-+
-+    /* make sure we an archive name */
-+    if ((optind + 1) > argc) {
-+        help();
-+    }
-+
-+    archivename = argv[optind++];
-+
-+    uuid_t uuid;
-+    uuid_generate(uuid);
-+
-+    Error *local_err = NULL;
-+    VmaWriter *vmaw = vma_writer_create(archivename, uuid, &local_err);
-+
-+    if (vmaw == NULL) {
-+        g_error("%s", error_get_pretty(local_err));
-+    }
-+
-+    GList *l = config_files;
-+    while (l && l->data) {
-+        char *name = l->data;
-+        char *cdata = NULL;
-+        gsize clen = 0;
-+        GError *err = NULL;
-+        if (!g_file_get_contents(name, &cdata, &clen, &err)) {
-+            unlink(archivename);
-+            g_error("Unable to read file: %s", err->message);
-+        }
-+
-+        if (vma_writer_add_config(vmaw, name, cdata, clen) != 0) {
-+            unlink(archivename);
-+            g_error("Unable to append config data %s (len = %zd)",
-+                    name, clen);
-+        }
-+        l = g_list_next(l);
-+    }
-+
-+    int devcount = 0;
-+    while (optind < argc) {
-+        const char *path = argv[optind++];
-+        char *devname = NULL;
-+        path = extract_devname(path, &devname, devcount++);
-+
-+        Error *errp = NULL;
-+        BlockBackend *target;
-+
-+        target = blk_new_open(path, NULL, NULL, 0, &errp);
-+        if (!target) {
-+            unlink(archivename);
-+            g_error("bdrv_open '%s' failed - %s", path, error_get_pretty(errp));
-+        }
-+        int64_t size = blk_getlength(target);
-+        int dev_id = vma_writer_register_stream(vmaw, devname, size);
-+        if (dev_id <= 0) {
-+            unlink(archivename);
-+            g_error("vma_writer_register_stream '%s' failed", devname);
-+        }
-+
-+        BackupJob *job = g_new0(BackupJob, 1);
-+        job->len = size;
-+        job->target = target;
-+        job->vmaw = vmaw;
-+        job->dev_id = dev_id;
-+
-+        Coroutine *co = qemu_coroutine_create(backup_run, job);
-+        qemu_coroutine_enter(co);
-+    }
-+
-+    VmaStatus vmastat;
-+    int percent = 0;
-+    int last_percent = -1;
-+
-+    if (devcount) {
-+        while (1) {
-+            main_loop_wait(false);
-+            vma_writer_get_status(vmaw, &vmastat);
-+
-+            if (verbose) {
-+
-+                uint64_t total = 0;
-+                uint64_t transferred = 0;
-+                uint64_t zero_bytes = 0;
-+
-+                int i;
-+                for (i = 0; i < 256; i++) {
-+                    if (vmastat.stream_info[i].size) {
-+                        total += vmastat.stream_info[i].size;
-+                        transferred += vmastat.stream_info[i].transferred;
-+                        zero_bytes += vmastat.stream_info[i].zero_bytes;
-+                    }
-+                }
-+                percent = (transferred*100)/total;
-+                if (percent != last_percent) {
-+                    fprintf(stderr, "progress %d%% %zd/%zd %zd\n", percent,
-+                            transferred, total, zero_bytes);
-+                    fflush(stderr);
-+
-+                    last_percent = percent;
-+                }
-+            }
-+
-+            if (vmastat.closed) {
-+                break;
-+            }
-+        }
-+    } else {
-+        Coroutine *co = qemu_coroutine_create(backup_run_empty, vmaw);
-+        qemu_coroutine_enter(co);
-+        while (1) {
-+            main_loop_wait(false);
-+            vma_writer_get_status(vmaw, &vmastat);
-+            if (vmastat.closed) {
-+                    break;
-+            }
-+        }
-+    }
-+
-+    bdrv_drain_all();
-+
-+    vma_writer_get_status(vmaw, &vmastat);
-+
-+    if (verbose) {
-+        for (i = 0; i < 256; i++) {
-+            VmaStreamInfo *si = &vmastat.stream_info[i];
-+            if (si->size) {
-+                fprintf(stderr, "image %s: size=%zd zeros=%zd saved=%zd\n",
-+                        si->devname, si->size, si->zero_bytes,
-+                        si->size - si->zero_bytes);
-+            }
-+        }
-+    }
-+
-+    if (vmastat.status < 0) {
-+        unlink(archivename);
-+        g_error("creating vma archive failed");
-+    }
-+
-+    return 0;
-+}
-+
-+static int dump_config(int argc, char **argv)
-+{
-+    int c, ret = 0;
-+    const char *filename;
-+    const char *config_name = "qemu-server.conf";
-+
-+    for (;;) {
-+        c = getopt(argc, argv, "hc:");
-+        if (c == -1) {
-+            break;
-+        }
-+        switch (c) {
-+        case '?':
-+        case 'h':
-+            help();
-+            break;
-+        case 'c':
-+            config_name = optarg;
-+            break;
-+        default:
-+            help();
-+        }
-+    }
-+
-+    /* Get the filename */
-+    if ((optind + 1) != argc) {
-+        help();
-+    }
-+    filename = argv[optind++];
-+
-+    Error *errp = NULL;
-+    VmaReader *vmar = vma_reader_create(filename, &errp);
-+
-+    if (!vmar) {
-+        g_error("%s", error_get_pretty(errp));
-+    }
-+
-+    int found = 0;
-+    GList *l = vma_reader_get_config_data(vmar);
-+    while (l && l->data) {
-+        VmaConfigData *cdata = (VmaConfigData *)l->data;
-+        l = g_list_next(l);
-+        if (strcmp(cdata->name, config_name) == 0) {
-+            found = 1;
-+            fwrite(cdata->data,  cdata->len, 1, stdout);
-+            break;
-+        }
-+    }
-+
-+    vma_reader_destroy(vmar);
-+
-+    bdrv_close_all();
-+
-+    if (!found) {
-+        fprintf(stderr, "unable to find configuration data '%s'\n", config_name);
-+        return -1;
-+    }
-+
-+    return ret;
-+}
-+
-+int main(int argc, char **argv)
-+{
-+    const char *cmdname;
-+    Error *main_loop_err = NULL;
-+
-+    error_init(argv[0]);
-+    module_call_init(MODULE_INIT_TRACE);
-+    qemu_init_exec_dir(argv[0]);
-+
-+    if (qemu_init_main_loop(&main_loop_err)) {
-+        g_error("%s", error_get_pretty(main_loop_err));
-+    }
-+
-+    bdrv_init();
-+    module_call_init(MODULE_INIT_QOM);
-+
-+    if (argc < 2) {
-+        help();
-+    }
-+
-+    cmdname = argv[1];
-+    argc--; argv++;
-+
-+
-+    if (!strcmp(cmdname, "list")) {
-+        return list_content(argc, argv);
-+    } else if (!strcmp(cmdname, "create")) {
-+        return create_archive(argc, argv);
-+    } else if (!strcmp(cmdname, "extract")) {
-+        return extract_content(argc, argv);
-+    } else if (!strcmp(cmdname, "verify")) {
-+        return verify_content(argc, argv);
-+    } else if (!strcmp(cmdname, "config")) {
-+        return dump_config(argc, argv);
-+    }
-+
-+    help();
-+    return 0;
-+}
-diff --git a/vma.h b/vma.h
-new file mode 100644
-index 0000000000..c895c97f6d
---- /dev/null
-+++ b/vma.h
-@@ -0,0 +1,150 @@
-+/*
-+ * VMA: Virtual Machine Archive
-+ *
-+ * Copyright (C) Proxmox Server Solutions
-+ *
-+ * Authors:
-+ *  Dietmar Maurer (dietmar@proxmox.com)
-+ *
-+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
-+ * See the COPYING file in the top-level directory.
-+ *
-+ */
-+
-+#ifndef BACKUP_VMA_H
-+#define BACKUP_VMA_H
-+
-+#include <uuid/uuid.h>
-+#include "qapi/error.h"
-+#include "block/block.h"
-+
-+#define VMA_BLOCK_BITS 12
-+#define VMA_BLOCK_SIZE (1<<VMA_BLOCK_BITS)
-+#define VMA_CLUSTER_BITS (VMA_BLOCK_BITS+4)
-+#define VMA_CLUSTER_SIZE (1<<VMA_CLUSTER_BITS)
-+
-+#if VMA_CLUSTER_SIZE != 65536
-+#error unexpected cluster size
-+#endif
-+
-+#define VMA_EXTENT_HEADER_SIZE 512
-+#define VMA_BLOCKS_PER_EXTENT 59
-+#define VMA_MAX_CONFIGS 256
-+
-+#define VMA_MAX_EXTENT_SIZE \
-+    (VMA_EXTENT_HEADER_SIZE+VMA_CLUSTER_SIZE*VMA_BLOCKS_PER_EXTENT)
-+#if VMA_MAX_EXTENT_SIZE != 3867136
-+#error unexpected VMA_EXTENT_SIZE
-+#endif
-+
-+/* File Format Definitions */
-+
-+#define VMA_MAGIC (GUINT32_TO_BE(('V'<<24)|('M'<<16)|('A'<<8)|0x00))
-+#define VMA_EXTENT_MAGIC (GUINT32_TO_BE(('V'<<24)|('M'<<16)|('A'<<8)|'E'))
-+
-+typedef struct VmaDeviceInfoHeader {
-+    uint32_t devname_ptr; /* offset into blob_buffer table */
-+    uint32_t reserved0;
-+    uint64_t size; /* device size in bytes */
-+    uint64_t reserved1;
-+    uint64_t reserved2;
-+} VmaDeviceInfoHeader;
-+
-+typedef struct VmaHeader {
-+    uint32_t magic;
-+    uint32_t version;
-+    unsigned char uuid[16];
-+    int64_t ctime;
-+    unsigned char md5sum[16];
-+
-+    uint32_t blob_buffer_offset;
-+    uint32_t blob_buffer_size;
-+    uint32_t header_size;
-+
-+    unsigned char reserved[1984];
-+
-+    uint32_t config_names[VMA_MAX_CONFIGS]; /* offset into blob_buffer table */
-+    uint32_t config_data[VMA_MAX_CONFIGS];  /* offset into blob_buffer table */
-+
-+    uint32_t reserved1;
-+
-+    VmaDeviceInfoHeader dev_info[256];
-+} VmaHeader;
-+
-+typedef struct VmaExtentHeader {
-+    uint32_t magic;
-+    uint16_t reserved1;
-+    uint16_t block_count;
-+    unsigned char uuid[16];
-+    unsigned char md5sum[16];
-+    uint64_t blockinfo[VMA_BLOCKS_PER_EXTENT];
-+} VmaExtentHeader;
-+
-+/* functions/definitions to read/write vma files */
-+
-+typedef struct VmaReader VmaReader;
-+
-+typedef struct VmaWriter VmaWriter;
-+
-+typedef struct VmaConfigData {
-+    const char *name;
-+    const void *data;
-+    uint32_t len;
-+} VmaConfigData;
-+
-+typedef struct VmaStreamInfo {
-+    uint64_t size;
-+    uint64_t cluster_count;
-+    uint64_t transferred;
-+    uint64_t zero_bytes;
-+    int finished;
-+    char *devname;
-+} VmaStreamInfo;
-+
-+typedef struct VmaStatus {
-+    int status;
-+    bool closed;
-+    char errmsg[8192];
-+    char uuid_str[37];
-+    VmaStreamInfo stream_info[256];
-+} VmaStatus;
-+
-+typedef struct VmaDeviceInfo {
-+    uint64_t size; /* device size in bytes */
-+    const char *devname;
-+} VmaDeviceInfo;
-+
-+VmaWriter *vma_writer_create(const char *filename, uuid_t uuid, Error **errp);
-+int vma_writer_close(VmaWriter *vmaw, Error **errp);
-+void vma_writer_error_propagate(VmaWriter *vmaw, Error **errp);
-+void vma_writer_destroy(VmaWriter *vmaw);
-+int vma_writer_add_config(VmaWriter *vmaw, const char *name, gpointer data,
-+                          size_t len);
-+int vma_writer_register_stream(VmaWriter *vmaw, const char *devname,
-+                               size_t size);
-+
-+int64_t coroutine_fn vma_writer_write(VmaWriter *vmaw, uint8_t dev_id,
-+                                      int64_t cluster_num,
-+                                      const unsigned char *buf,
-+                                      size_t *zero_bytes);
-+
-+int coroutine_fn vma_writer_close_stream(VmaWriter *vmaw, uint8_t dev_id);
-+int coroutine_fn vma_writer_flush_output(VmaWriter *vmaw);
-+
-+int vma_writer_get_status(VmaWriter *vmaw, VmaStatus *status);
-+void vma_writer_set_error(VmaWriter *vmaw, const char *fmt, ...);
-+
-+
-+VmaReader *vma_reader_create(const char *filename, Error **errp);
-+void vma_reader_destroy(VmaReader *vmar);
-+VmaHeader *vma_reader_get_header(VmaReader *vmar);
-+GList *vma_reader_get_config_data(VmaReader *vmar);
-+VmaDeviceInfo *vma_reader_get_device_info(VmaReader *vmar, guint8 dev_id);
-+int vma_reader_register_bs(VmaReader *vmar, guint8 dev_id,
-+                           BlockBackend *target, bool write_zeroes,
-+                           Error **errp);
-+int vma_reader_restore(VmaReader *vmar, int vmstate_fd, bool verbose,
-+                       Error **errp);
-+int vma_reader_verify(VmaReader *vmar, bool verbose, Error **errp);
-+
-+#endif /* BACKUP_VMA_H */
diff --git a/debian/patches/pve/0029-PVE-Backup-add-backup-dump-block-driver.patch b/debian/patches/pve/0029-PVE-Backup-add-backup-dump-block-driver.patch
deleted file mode 100644 (file)
index 57f93ef..0000000
+++ /dev/null
@@ -1,301 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Dietmar Maurer <dietmar@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:58 +0200
-Subject: [PATCH] PVE-Backup: add backup-dump block driver
-
-- add backup-dump block driver block/backup-dump.c
-- move BackupBlockJob declaration from block/backup.c to include/block/block_int.h
-- block/backup.c - backup-job-create: also consider source cluster size
-- job.c: make job_should_pause non-static
----
- block/Makefile.objs       |   1 +
- block/backup-dump.c       | 169 ++++++++++++++++++++++++++++++++++++++
- block/backup.c            |  23 ++----
- include/block/block_int.h |  30 +++++++
- job.c                     |   3 +-
- 5 files changed, 207 insertions(+), 19 deletions(-)
- create mode 100644 block/backup-dump.c
-
-diff --git a/block/Makefile.objs b/block/Makefile.objs
-index 1282445672..8af7073c83 100644
---- a/block/Makefile.objs
-+++ b/block/Makefile.objs
-@@ -34,6 +34,7 @@ block-obj-$(CONFIG_RBD) += rbd.o
- block-obj-$(CONFIG_GLUSTERFS) += gluster.o
- block-obj-$(CONFIG_VXHS) += vxhs.o
- block-obj-$(CONFIG_LIBSSH) += ssh.o
-+block-obj-y += backup-dump.o
- block-obj-y += accounting.o dirty-bitmap.o
- block-obj-y += write-threshold.o
- block-obj-y += backup.o
-diff --git a/block/backup-dump.c b/block/backup-dump.c
-new file mode 100644
-index 0000000000..3066ab0698
---- /dev/null
-+++ b/block/backup-dump.c
-@@ -0,0 +1,169 @@
-+/*
-+ * BlockDriver to send backup data stream to a callback function
-+ *
-+ * Copyright (C) 2020 Proxmox Server Solutions GmbH
-+ *
-+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
-+ * See the COPYING file in the top-level directory.
-+ *
-+ */
-+
-+#include "qemu/osdep.h"
-+#include "qemu-common.h"
-+#include "qom/object_interfaces.h"
-+#include "block/block_int.h"
-+
-+typedef struct {
-+    int             dump_cb_block_size;
-+    uint64_t        byte_size;
-+    BackupDumpFunc *dump_cb;
-+    void           *dump_cb_data;
-+} BDRVBackupDumpState;
-+
-+static int qemu_backup_dump_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
-+{
-+    BDRVBackupDumpState *s = bs->opaque;
-+
-+    bdi->cluster_size = s->dump_cb_block_size;
-+    bdi->unallocated_blocks_are_zero = true;
-+    return 0;
-+}
-+
-+static int qemu_backup_dump_check_perm(
-+    BlockDriverState *bs,
-+    uint64_t perm,
-+    uint64_t shared,
-+    Error **errp)
-+{
-+    /* Nothing to do. */
-+    return 0;
-+}
-+
-+static void qemu_backup_dump_set_perm(
-+    BlockDriverState *bs,
-+    uint64_t perm,
-+    uint64_t shared)
-+{
-+    /* Nothing to do. */
-+}
-+
-+static void qemu_backup_dump_abort_perm_update(BlockDriverState *bs)
-+{
-+    /* Nothing to do. */
-+}
-+
-+static void qemu_backup_dump_refresh_limits(BlockDriverState *bs, Error **errp)
-+{
-+    bs->bl.request_alignment = BDRV_SECTOR_SIZE; /* No sub-sector I/O */
-+}
-+
-+static void qemu_backup_dump_close(BlockDriverState *bs)
-+{
-+    /* Nothing to do. */
-+}
-+
-+static int64_t qemu_backup_dump_getlength(BlockDriverState *bs)
-+{
-+    BDRVBackupDumpState *s = bs->opaque;
-+
-+    return s->byte_size;
-+}
-+
-+static coroutine_fn int qemu_backup_dump_co_writev(
-+    BlockDriverState *bs,
-+    int64_t sector_num,
-+    int nb_sectors,
-+    QEMUIOVector *qiov,
-+    int flags)
-+{
-+    /* flags can be only values we set in supported_write_flags */
-+    assert(flags == 0);
-+
-+    BDRVBackupDumpState *s = bs->opaque;
-+    off_t offset = sector_num * BDRV_SECTOR_SIZE;
-+
-+    uint64_t written = 0;
-+
-+    for (int i = 0; i < qiov->niov; ++i) {
-+        const struct iovec *v = &qiov->iov[i];
-+
-+        int rc = s->dump_cb(s->dump_cb_data, offset, v->iov_len, v->iov_base);
-+        if (rc < 0) {
-+            return rc;
-+        }
-+
-+        if (rc != v->iov_len) {
-+            return -EIO;
-+        }
-+
-+        written += v->iov_len;
-+        offset += v->iov_len;
-+    }
-+
-+    return written;
-+}
-+
-+static void qemu_backup_dump_child_perm(
-+    BlockDriverState *bs,
-+    BdrvChild *c,
-+    const BdrvChildRole *role,
-+    BlockReopenQueue *reopen_queue,
-+    uint64_t perm, uint64_t shared,
-+    uint64_t *nperm, uint64_t *nshared)
-+{
-+    *nperm = BLK_PERM_ALL;
-+    *nshared = BLK_PERM_ALL;
-+}
-+
-+static BlockDriver bdrv_backup_dump_drive = {
-+    .format_name                  = "backup-dump-drive",
-+    .protocol_name                = "backup-dump",
-+    .instance_size                = sizeof(BDRVBackupDumpState),
-+
-+    .bdrv_close                   = qemu_backup_dump_close,
-+    .bdrv_has_zero_init           = bdrv_has_zero_init_1,
-+    .bdrv_getlength               = qemu_backup_dump_getlength,
-+    .bdrv_get_info                = qemu_backup_dump_get_info,
-+
-+    .bdrv_co_writev               = qemu_backup_dump_co_writev,
-+
-+    .bdrv_refresh_limits          = qemu_backup_dump_refresh_limits,
-+    .bdrv_check_perm              = qemu_backup_dump_check_perm,
-+    .bdrv_set_perm                = qemu_backup_dump_set_perm,
-+    .bdrv_abort_perm_update       = qemu_backup_dump_abort_perm_update,
-+    .bdrv_child_perm              = qemu_backup_dump_child_perm,
-+};
-+
-+static void bdrv_backup_dump_init(void)
-+{
-+    bdrv_register(&bdrv_backup_dump_drive);
-+}
-+
-+block_init(bdrv_backup_dump_init);
-+
-+
-+BlockDriverState *bdrv_backup_dump_create(
-+    int dump_cb_block_size,
-+    uint64_t byte_size,
-+    BackupDumpFunc *dump_cb,
-+    void *dump_cb_data,
-+    Error **errp)
-+{
-+    BDRVBackupDumpState *state;
-+    BlockDriverState *bs = bdrv_new_open_driver(
-+        &bdrv_backup_dump_drive, NULL, BDRV_O_RDWR, errp);
-+
-+    if (!bs) {
-+        return NULL;
-+    }
-+
-+    bs->total_sectors = byte_size / BDRV_SECTOR_SIZE;
-+    bs->opaque = state = g_new0(BDRVBackupDumpState, 1);
-+
-+    state->dump_cb_block_size = dump_cb_block_size;
-+    state->byte_size = byte_size;
-+    state->dump_cb = dump_cb;
-+    state->dump_cb_data = dump_cb_data;
-+
-+    return bs;
-+}
-diff --git a/block/backup.c b/block/backup.c
-index ecd93e91e0..cf8f5ad25d 100644
---- a/block/backup.c
-+++ b/block/backup.c
-@@ -32,24 +32,6 @@
- #define BACKUP_CLUSTER_SIZE_DEFAULT (1 << 16)
--typedef struct BackupBlockJob {
--    BlockJob common;
--    BlockDriverState *backup_top;
--    BlockDriverState *source_bs;
--
--    BdrvDirtyBitmap *sync_bitmap;
--
--    MirrorSyncMode sync_mode;
--    BitmapSyncMode bitmap_mode;
--    BlockdevOnError on_source_error;
--    BlockdevOnError on_target_error;
--    uint64_t len;
--    uint64_t bytes_read;
--    int64_t cluster_size;
--
--    BlockCopyState *bcs;
--} BackupBlockJob;
--
- static const BlockJobDriver backup_job_driver;
- static void backup_progress_bytes_callback(int64_t bytes, void *opaque)
-@@ -411,6 +393,11 @@ BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
-         goto error;
-     }
-+    BlockDriverInfo bdi;
-+    if (bdrv_get_info(bs, &bdi) == 0) {
-+        cluster_size = MAX(cluster_size, bdi.cluster_size);
-+    }
-+
-     /*
-      * If source is in backing chain of target assume that target is going to be
-      * used for "image fleecing", i.e. it should represent a kind of snapshot of
-diff --git a/include/block/block_int.h b/include/block/block_int.h
-index 336f71e69d..62e5579723 100644
---- a/include/block/block_int.h
-+++ b/include/block/block_int.h
-@@ -60,6 +60,36 @@
- #define BLOCK_PROBE_BUF_SIZE        512
-+typedef int BackupDumpFunc(void *opaque, uint64_t offset, uint64_t bytes, const void *buf);
-+
-+BlockDriverState *bdrv_backuo_dump_create(
-+    int dump_cb_block_size,
-+    uint64_t byte_size,
-+    BackupDumpFunc *dump_cb,
-+    void *dump_cb_data,
-+    Error **errp);
-+
-+// Needs to be defined here, since it's used in blockdev.c to detect PVE backup
-+// jobs with source_bs
-+typedef struct BlockCopyState BlockCopyState;
-+typedef struct BackupBlockJob {
-+    BlockJob common;
-+    BlockDriverState *backup_top;
-+    BlockDriverState *source_bs;
-+
-+    BdrvDirtyBitmap *sync_bitmap;
-+
-+    MirrorSyncMode sync_mode;
-+    BitmapSyncMode bitmap_mode;
-+    BlockdevOnError on_source_error;
-+    BlockdevOnError on_target_error;
-+    uint64_t len;
-+    uint64_t bytes_read;
-+    int64_t cluster_size;
-+
-+    BlockCopyState *bcs;
-+} BackupBlockJob;
-+
- enum BdrvTrackedRequestType {
-     BDRV_TRACKED_READ,
-     BDRV_TRACKED_WRITE,
-diff --git a/job.c b/job.c
-index e82253e041..bcbbb0be02 100644
---- a/job.c
-+++ b/job.c
-@@ -269,7 +269,8 @@ static bool job_started(Job *job)
-     return job->co;
- }
--static bool job_should_pause(Job *job)
-+bool job_should_pause(Job *job);
-+bool job_should_pause(Job *job)
- {
-     return job->pause_count > 0;
- }
diff --git a/debian/patches/pve/0029-PVE-Backup-proxmox-backup-patches-for-qemu.patch b/debian/patches/pve/0029-PVE-Backup-proxmox-backup-patches-for-qemu.patch
new file mode 100644 (file)
index 0000000..56161cc
--- /dev/null
@@ -0,0 +1,1654 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Dietmar Maurer <dietmar@proxmox.com>
+Date: Mon, 6 Apr 2020 12:16:59 +0200
+Subject: [PATCH] PVE-Backup: proxmox backup patches for qemu
+
+---
+ Makefile                       |   1 +
+ Makefile.objs                  |   2 +
+ Makefile.target                |   2 +-
+ block/monitor/block-hmp-cmds.c |  33 ++
+ blockdev.c                     |   1 +
+ hmp-commands-info.hx           |  13 +
+ hmp-commands.hx                |  29 +
+ include/block/block_int.h      |   2 +-
+ include/monitor/hmp.h          |   3 +
+ monitor/hmp-cmds.c             |  44 ++
+ proxmox-backup-client.c        | 182 +++++++
+ proxmox-backup-client.h        |  52 ++
+ pve-backup.c                   | 959 +++++++++++++++++++++++++++++++++
+ qapi/block-core.json           | 109 ++++
+ qapi/common.json               |  13 +
+ qapi/misc.json                 |  13 -
+ 16 files changed, 1443 insertions(+), 15 deletions(-)
+ create mode 100644 proxmox-backup-client.c
+ create mode 100644 proxmox-backup-client.h
+ create mode 100644 pve-backup.c
+
+diff --git a/Makefile b/Makefile
+index 74c2039005..dbd9542ae4 100644
+--- a/Makefile
++++ b/Makefile
+@@ -608,6 +608,7 @@ qemu-img$(EXESUF): qemu-img.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io
+ qemu-nbd$(EXESUF): qemu-nbd.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+ qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+ qemu-storage-daemon$(EXESUF): qemu-storage-daemon.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(chardev-obj-y) $(io-obj-y) $(qom-obj-y) $(storage-daemon-obj-y) $(COMMON_LDADDS)
++qemu-storage-daemon$(EXESUF): LIBS += -lproxmox_backup_qemu
+ vma$(EXESUF): vma.o vma-reader.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
+ qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o $(COMMON_LDADDS)
+diff --git a/Makefile.objs b/Makefile.objs
+index 05031a3da7..b7d58e592e 100644
+--- a/Makefile.objs
++++ b/Makefile.objs
+@@ -34,6 +34,7 @@ endif # CONFIG_SOFTMMU or CONFIG_TOOLS
+ storage-daemon-obj-y = block/ monitor/ qapi/ qom/ storage-daemon/
+ storage-daemon-obj-y += blockdev.o blockdev-nbd.o iothread.o job-qmp.o
++storage-daemon-obj-y += proxmox-backup-client.o pve-backup.o
+ storage-daemon-obj-$(CONFIG_WIN32) += os-win32.o
+ storage-daemon-obj-$(CONFIG_POSIX) += os-posix.o
+@@ -45,6 +46,7 @@ storage-daemon-obj-$(CONFIG_POSIX) += os-posix.o
+ ifeq ($(CONFIG_SOFTMMU),y)
+ common-obj-y = blockdev.o blockdev-nbd.o block/
+ common-obj-y += bootdevice.o iothread.o
++common-obj-y += proxmox-backup-client.o pve-backup.o
+ common-obj-y += dump/
+ common-obj-y += job-qmp.o
+ common-obj-y += monitor/
+diff --git a/Makefile.target b/Makefile.target
+index 8ed1eba95b..f453a95efc 100644
+--- a/Makefile.target
++++ b/Makefile.target
+@@ -162,7 +162,7 @@ obj-y += memory.o
+ obj-y += memory_mapping.o
+ obj-y += migration/ram.o
+ obj-y += softmmu/
+-LIBS := $(libs_softmmu) $(LIBS)
++LIBS := $(libs_softmmu) $(LIBS)  -lproxmox_backup_qemu
+ # Hardware support
+ ifeq ($(TARGET_NAME), sparc64)
+diff --git a/block/monitor/block-hmp-cmds.c b/block/monitor/block-hmp-cmds.c
+index 4c8c375172..d485c3ac79 100644
+--- a/block/monitor/block-hmp-cmds.c
++++ b/block/monitor/block-hmp-cmds.c
+@@ -1011,3 +1011,36 @@ void hmp_info_snapshots(Monitor *mon, const QDict *qdict)
+     g_free(sn_tab);
+     g_free(global_snapshots);
+ }
++
++void hmp_backup_cancel(Monitor *mon, const QDict *qdict)
++{
++    Error *error = NULL;
++
++    qmp_backup_cancel(&error);
++
++    hmp_handle_error(mon, error);
++}
++
++void hmp_backup(Monitor *mon, const QDict *qdict)
++{
++    Error *error = NULL;
++
++    int dir = qdict_get_try_bool(qdict, "directory", 0);
++    const char *backup_file = qdict_get_str(qdict, "backupfile");
++    const char *devlist = qdict_get_try_str(qdict, "devlist");
++    int64_t speed = qdict_get_try_int(qdict, "speed", 0);
++
++    qmp_backup(
++        backup_file,
++        false, NULL, // PBS password
++        false, NULL, // PBS keyfile
++        false, NULL, // PBS key_password
++        false, NULL, // PBS fingerprint
++        false, NULL, // PBS backup-id
++        false, 0, // PBS backup-time
++        true, dir ? BACKUP_FORMAT_DIR : BACKUP_FORMAT_VMA,
++        false, NULL, false, NULL, !!devlist,
++        devlist, qdict_haskey(qdict, "speed"), speed, &error);
++
++    hmp_handle_error(mon, error);
++}
+diff --git a/blockdev.c b/blockdev.c
+index 65c358e4ef..f391c3b3c7 100644
+--- a/blockdev.c
++++ b/blockdev.c
+@@ -36,6 +36,7 @@
+ #include "hw/block/block.h"
+ #include "block/blockjob.h"
+ #include "block/qdict.h"
++#include "block/blockjob_int.h"
+ #include "block/throttle-groups.h"
+ #include "monitor/monitor.h"
+ #include "qemu/error-report.h"
+diff --git a/hmp-commands-info.hx b/hmp-commands-info.hx
+index 89fea71972..64995443d4 100644
+--- a/hmp-commands-info.hx
++++ b/hmp-commands-info.hx
+@@ -512,6 +512,19 @@ SRST
+     Show CPU statistics.
+ ERST
++    {
++        .name       = "backup",
++        .args_type  = "",
++        .params     = "",
++        .help       = "show backup status",
++        .cmd        = hmp_info_backup,
++    },
++
++SRST
++  ``info backup``
++    Show backup status.
++ERST
++
+ #if defined(CONFIG_SLIRP)
+     {
+         .name       = "usernet",
+diff --git a/hmp-commands.hx b/hmp-commands.hx
+index 81fe305d07..8a03b45c44 100644
+--- a/hmp-commands.hx
++++ b/hmp-commands.hx
+@@ -97,6 +97,35 @@ ERST
+ SRST
+ ``block_stream``
+   Copy data from a backing file into a block device.
++ERST
++
++   {
++        .name       = "backup",
++        .args_type  = "directory:-d,backupfile:s,speed:o?,devlist:s?",
++        .params     = "[-d] backupfile [speed [devlist]]",
++        .help       = "create a VM Backup."
++                  "\n\t\t\t Use -d to dump data into a directory instead"
++                  "\n\t\t\t of using VMA format.",
++        .cmd = hmp_backup,
++    },
++
++SRST
++``backup``
++  Create a VM backup.
++ERST
++
++    {
++        .name       = "backup_cancel",
++        .args_type  = "",
++        .params     = "",
++        .help       = "cancel the current VM backup",
++        .cmd        = hmp_backup_cancel,
++    },
++
++SRST
++``backup_cancel``
++  Cancel the current VM backup.
++
+ ERST
+     {
+diff --git a/include/block/block_int.h b/include/block/block_int.h
+index 62e5579723..6d234f1de9 100644
+--- a/include/block/block_int.h
++++ b/include/block/block_int.h
+@@ -62,7 +62,7 @@
+ typedef int BackupDumpFunc(void *opaque, uint64_t offset, uint64_t bytes, const void *buf);
+-BlockDriverState *bdrv_backuo_dump_create(
++BlockDriverState *bdrv_backup_dump_create(
+     int dump_cb_block_size,
+     uint64_t byte_size,
+     BackupDumpFunc *dump_cb,
+diff --git a/include/monitor/hmp.h b/include/monitor/hmp.h
+index 601827d43f..6653d04c3c 100644
+--- a/include/monitor/hmp.h
++++ b/include/monitor/hmp.h
+@@ -30,6 +30,7 @@ void hmp_info_migrate(Monitor *mon, const QDict *qdict);
+ void hmp_info_migrate_capabilities(Monitor *mon, const QDict *qdict);
+ void hmp_info_migrate_parameters(Monitor *mon, const QDict *qdict);
+ void hmp_info_migrate_cache_size(Monitor *mon, const QDict *qdict);
++void hmp_info_backup(Monitor *mon, const QDict *qdict);
+ void hmp_info_cpus(Monitor *mon, const QDict *qdict);
+ void hmp_info_vnc(Monitor *mon, const QDict *qdict);
+ void hmp_info_spice(Monitor *mon, const QDict *qdict);
+@@ -76,6 +77,8 @@ void hmp_x_colo_lost_heartbeat(Monitor *mon, const QDict *qdict);
+ void hmp_set_password(Monitor *mon, const QDict *qdict);
+ void hmp_expire_password(Monitor *mon, const QDict *qdict);
+ void hmp_change(Monitor *mon, const QDict *qdict);
++void hmp_backup(Monitor *mon, const QDict *qdict);
++void hmp_backup_cancel(Monitor *mon, const QDict *qdict);
+ void hmp_migrate(Monitor *mon, const QDict *qdict);
+ void hmp_device_add(Monitor *mon, const QDict *qdict);
+ void hmp_device_del(Monitor *mon, const QDict *qdict);
+diff --git a/monitor/hmp-cmds.c b/monitor/hmp-cmds.c
+index 39c7474cea..7fd59b1c22 100644
+--- a/monitor/hmp-cmds.c
++++ b/monitor/hmp-cmds.c
+@@ -192,6 +192,50 @@ void hmp_info_mice(Monitor *mon, const QDict *qdict)
+     qapi_free_MouseInfoList(mice_list);
+ }
++void hmp_info_backup(Monitor *mon, const QDict *qdict)
++{
++    BackupStatus *info;
++
++    info = qmp_query_backup(NULL);
++
++    if (!info) {
++       monitor_printf(mon, "Backup status: not initialized\n");
++       return;
++    }
++
++    if (info->has_status) {
++        if (info->has_errmsg) {
++            monitor_printf(mon, "Backup status: %s - %s\n",
++                           info->status, info->errmsg);
++        } else {
++            monitor_printf(mon, "Backup status: %s\n", info->status);
++        }
++    }
++
++    if (info->has_backup_file) {
++        monitor_printf(mon, "Start time: %s", ctime(&info->start_time));
++        if (info->end_time) {
++            monitor_printf(mon, "End time: %s", ctime(&info->end_time));
++        }
++
++        int per = (info->has_total && info->total &&
++            info->has_transferred && info->transferred) ?
++            (info->transferred * 100)/info->total : 0;
++        int zero_per = (info->has_total && info->total &&
++                        info->has_zero_bytes && info->zero_bytes) ?
++            (info->zero_bytes * 100)/info->total : 0;
++        monitor_printf(mon, "Backup file: %s\n", info->backup_file);
++        monitor_printf(mon, "Backup uuid: %s\n", info->uuid);
++        monitor_printf(mon, "Total size: %zd\n", info->total);
++        monitor_printf(mon, "Transferred bytes: %zd (%d%%)\n",
++                       info->transferred, per);
++        monitor_printf(mon, "Zero bytes: %zd (%d%%)\n",
++                       info->zero_bytes, zero_per);
++    }
++
++    qapi_free_BackupStatus(info);
++}
++
+ static char *SocketAddress_to_str(SocketAddress *addr)
+ {
+     switch (addr->type) {
+diff --git a/proxmox-backup-client.c b/proxmox-backup-client.c
+new file mode 100644
+index 0000000000..b7bc7f2574
+--- /dev/null
++++ b/proxmox-backup-client.c
+@@ -0,0 +1,182 @@
++#include "proxmox-backup-client.h"
++#include "qemu/main-loop.h"
++#include "block/aio-wait.h"
++#include "qapi/error.h"
++
++/* Proxmox Backup Server client bindings using coroutines */
++
++typedef struct BlockOnCoroutineWrapper {
++    AioContext *ctx;
++    CoroutineEntry *entry;
++    void *entry_arg;
++    bool finished;
++} BlockOnCoroutineWrapper;
++
++// Waker implementaion to syncronice with proxmox backup rust code
++typedef struct ProxmoxBackupWaker {
++    Coroutine *co;
++    AioContext *ctx;
++} ProxmoxBackupWaker;
++
++static void coroutine_fn block_on_coroutine_wrapper(void *opaque)
++{
++    BlockOnCoroutineWrapper *wrapper = opaque;
++    wrapper->entry(wrapper->entry_arg);
++    wrapper->finished = true;
++    aio_wait_kick();
++}
++
++void block_on_coroutine_fn(CoroutineEntry *entry, void *entry_arg)
++{
++    assert(!qemu_in_coroutine());
++
++    AioContext *ctx = qemu_get_current_aio_context();
++    BlockOnCoroutineWrapper wrapper = {
++        .finished = false,
++        .entry = entry,
++        .entry_arg = entry_arg,
++        .ctx = ctx,
++    };
++    Coroutine *wrapper_co = qemu_coroutine_create(block_on_coroutine_wrapper, &wrapper);
++    aio_co_enter(ctx, wrapper_co);
++    AIO_WAIT_WHILE(ctx, !wrapper.finished);
++}
++
++// This is called from another thread, so we use aio_co_schedule()
++static void proxmox_backup_schedule_wake(void *data) {
++    ProxmoxBackupWaker *waker = (ProxmoxBackupWaker *)data;
++    aio_co_schedule(waker->ctx, waker->co);
++}
++
++int coroutine_fn
++proxmox_backup_co_connect(ProxmoxBackupHandle *pbs, Error **errp)
++{
++    Coroutine *co = qemu_coroutine_self();
++    AioContext *ctx = qemu_get_current_aio_context();
++    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
++    char *pbs_err = NULL;
++    int pbs_res = -1;
++
++    proxmox_backup_connect_async(pbs, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
++    qemu_coroutine_yield();
++    if (pbs_res < 0) {
++        if (errp) error_setg(errp, "backup connect failed: %s", pbs_err ? pbs_err : "unknown error");
++        if (pbs_err) proxmox_backup_free_error(pbs_err);
++    }
++    return pbs_res;
++}
++
++int coroutine_fn
++proxmox_backup_co_add_config(
++    ProxmoxBackupHandle *pbs,
++    const char *name,
++    const uint8_t *data,
++    uint64_t size,
++    Error **errp)
++{
++    Coroutine *co = qemu_coroutine_self();
++    AioContext *ctx = qemu_get_current_aio_context();
++    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
++    char *pbs_err = NULL;
++    int pbs_res = -1;
++
++    proxmox_backup_add_config_async(
++        pbs, name, data, size ,proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
++    qemu_coroutine_yield();
++    if (pbs_res < 0) {
++        if (errp) error_setg(errp, "backup add_config %s failed: %s", name, pbs_err ? pbs_err : "unknown error");
++        if (pbs_err) proxmox_backup_free_error(pbs_err);
++    }
++    return pbs_res;
++}
++
++int coroutine_fn
++proxmox_backup_co_register_image(
++    ProxmoxBackupHandle *pbs,
++    const char *device_name,
++    uint64_t size,
++    Error **errp)
++{
++    Coroutine *co = qemu_coroutine_self();
++    AioContext *ctx = qemu_get_current_aio_context();
++    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
++    char *pbs_err = NULL;
++    int pbs_res = -1;
++
++    proxmox_backup_register_image_async(
++        pbs, device_name, size ,proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
++    qemu_coroutine_yield();
++    if (pbs_res < 0) {
++        if (errp) error_setg(errp, "backup register image failed: %s", pbs_err ? pbs_err : "unknown error");
++        if (pbs_err) proxmox_backup_free_error(pbs_err);
++    }
++    return pbs_res;
++}
++
++int coroutine_fn
++proxmox_backup_co_finish(
++    ProxmoxBackupHandle *pbs,
++    Error **errp)
++{
++    Coroutine *co = qemu_coroutine_self();
++    AioContext *ctx = qemu_get_current_aio_context();
++    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
++    char *pbs_err = NULL;
++    int pbs_res = -1;
++
++    proxmox_backup_finish_async(
++        pbs, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
++    qemu_coroutine_yield();
++    if (pbs_res < 0) {
++        if (errp) error_setg(errp, "backup finish failed: %s", pbs_err ? pbs_err : "unknown error");
++        if (pbs_err) proxmox_backup_free_error(pbs_err);
++    }
++    return pbs_res;
++}
++
++int coroutine_fn
++proxmox_backup_co_close_image(
++    ProxmoxBackupHandle *pbs,
++    uint8_t dev_id,
++    Error **errp)
++{
++    Coroutine *co = qemu_coroutine_self();
++    AioContext *ctx = qemu_get_current_aio_context();
++    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
++    char *pbs_err = NULL;
++    int pbs_res = -1;
++
++    proxmox_backup_close_image_async(
++        pbs, dev_id, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
++    qemu_coroutine_yield();
++    if (pbs_res < 0) {
++        if (errp) error_setg(errp, "backup close image failed: %s", pbs_err ? pbs_err : "unknown error");
++        if (pbs_err) proxmox_backup_free_error(pbs_err);
++    }
++    return pbs_res;
++}
++
++int coroutine_fn
++proxmox_backup_co_write_data(
++    ProxmoxBackupHandle *pbs,
++    uint8_t dev_id,
++    const uint8_t *data,
++    uint64_t offset,
++    uint64_t size,
++    Error **errp)
++{
++    Coroutine *co = qemu_coroutine_self();
++    AioContext *ctx = qemu_get_current_aio_context();
++    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
++    char *pbs_err = NULL;
++    int pbs_res = -1;
++
++    proxmox_backup_write_data_async(
++        pbs, dev_id, data, offset, size, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
++    qemu_coroutine_yield();
++    if (pbs_res < 0) {
++        if (errp) error_setg(errp, "backup write data failed: %s", pbs_err ? pbs_err : "unknown error");
++        if (pbs_err) proxmox_backup_free_error(pbs_err);
++    }
++    return pbs_res;
++}
+diff --git a/proxmox-backup-client.h b/proxmox-backup-client.h
+new file mode 100644
+index 0000000000..b311bf8de8
+--- /dev/null
++++ b/proxmox-backup-client.h
+@@ -0,0 +1,52 @@
++#ifndef PROXMOX_BACKUP_CLIENT_H
++#define PROXMOX_BACKUP_CLIENT_H
++
++#include "qemu/osdep.h"
++#include "qemu/coroutine.h"
++#include "proxmox-backup-qemu.h"
++
++void block_on_coroutine_fn(CoroutineEntry *entry, void *entry_arg);
++
++int coroutine_fn
++proxmox_backup_co_connect(
++    ProxmoxBackupHandle *pbs,
++    Error **errp);
++
++int coroutine_fn
++proxmox_backup_co_add_config(
++    ProxmoxBackupHandle *pbs,
++    const char *name,
++    const uint8_t *data,
++    uint64_t size,
++    Error **errp);
++
++int coroutine_fn
++proxmox_backup_co_register_image(
++    ProxmoxBackupHandle *pbs,
++    const char *device_name,
++    uint64_t size,
++    Error **errp);
++
++
++int coroutine_fn
++proxmox_backup_co_finish(
++    ProxmoxBackupHandle *pbs,
++    Error **errp);
++
++int coroutine_fn
++proxmox_backup_co_close_image(
++    ProxmoxBackupHandle *pbs,
++    uint8_t dev_id,
++    Error **errp);
++
++int coroutine_fn
++proxmox_backup_co_write_data(
++    ProxmoxBackupHandle *pbs,
++    uint8_t dev_id,
++    const uint8_t *data,
++    uint64_t offset,
++    uint64_t size,
++    Error **errp);
++
++
++#endif /* PROXMOX_BACKUP_CLIENT_H */
+diff --git a/pve-backup.c b/pve-backup.c
+new file mode 100644
+index 0000000000..9ae89fb679
+--- /dev/null
++++ b/pve-backup.c
+@@ -0,0 +1,959 @@
++#include "proxmox-backup-client.h"
++#include "vma.h"
++
++#include "qemu/osdep.h"
++#include "qemu/module.h"
++#include "sysemu/block-backend.h"
++#include "sysemu/blockdev.h"
++#include "block/blockjob.h"
++#include "qapi/qapi-commands-block.h"
++#include "qapi/qmp/qerror.h"
++
++/* PVE backup state and related function */
++
++
++static struct PVEBackupState {
++    struct {
++        // Everithing accessed from qmp command, protected using rwlock
++        CoRwlock rwlock;
++        Error *error;
++        time_t start_time;
++        time_t end_time;
++        char *backup_file;
++        uuid_t uuid;
++        char uuid_str[37];
++        size_t total;
++        size_t transferred;
++        size_t zero_bytes;
++        bool cancel;
++    } stat;
++    int64_t speed;
++    VmaWriter *vmaw;
++    ProxmoxBackupHandle *pbs;
++    GList *di_list;
++    CoMutex backup_mutex;
++} backup_state;
++
++static void pvebackup_init(void)
++{
++    qemu_co_rwlock_init(&backup_state.stat.rwlock);
++    qemu_co_mutex_init(&backup_state.backup_mutex);
++}
++
++// initialize PVEBackupState at startup
++opts_init(pvebackup_init);
++
++typedef struct PVEBackupDevInfo {
++    BlockDriverState *bs;
++    size_t size;
++    uint8_t dev_id;
++    bool completed;
++    char targetfile[PATH_MAX];
++    BlockDriverState *target;
++} PVEBackupDevInfo;
++
++static void pvebackup_co_run_next_job(void);
++
++static int coroutine_fn
++pvebackup_co_dump_cb(
++    void *opaque,
++    uint64_t start,
++    uint64_t bytes,
++    const void *pbuf)
++{
++    assert(qemu_in_coroutine());
++
++    const uint64_t size = bytes;
++    const unsigned char *buf = pbuf;
++    PVEBackupDevInfo *di = opaque;
++
++    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++    bool cancel = backup_state.stat.cancel;
++    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++    if (cancel) {
++        return size; // return success
++    }
++
++    qemu_co_mutex_lock(&backup_state.backup_mutex);
++
++    int ret = -1;
++
++    if (backup_state.vmaw) {
++        size_t zero_bytes = 0;
++        uint64_t remaining = size;
++
++        uint64_t cluster_num = start / VMA_CLUSTER_SIZE;
++        if ((cluster_num * VMA_CLUSTER_SIZE) != start) {
++            qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++            if (!backup_state.stat.error) {
++                qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
++                error_setg(&backup_state.stat.error,
++                           "got unaligned write inside backup dump "
++                           "callback (sector %ld)", start);
++            }
++            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++            qemu_co_mutex_unlock(&backup_state.backup_mutex);
++            return -1; // not aligned to cluster size
++        }
++
++        while (remaining > 0) {
++            ret = vma_writer_write(backup_state.vmaw, di->dev_id, cluster_num,
++                                   buf, &zero_bytes);
++            ++cluster_num;
++            if (buf) {
++                buf += VMA_CLUSTER_SIZE;
++            }
++            if (ret < 0) {
++                qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++                if (!backup_state.stat.error) {
++                    qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
++                    vma_writer_error_propagate(backup_state.vmaw, &backup_state.stat.error);
++                }
++                qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++                qemu_co_mutex_unlock(&backup_state.backup_mutex);
++                return ret;
++            } else {
++                qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++                backup_state.stat.zero_bytes += zero_bytes;
++                if (remaining >= VMA_CLUSTER_SIZE) {
++                    backup_state.stat.transferred += VMA_CLUSTER_SIZE;
++                    remaining -= VMA_CLUSTER_SIZE;
++                } else {
++                    backup_state.stat.transferred += remaining;
++                    remaining = 0;
++                }
++                qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++            }
++        }
++    } else if (backup_state.pbs) {
++        Error *local_err = NULL;
++        int pbs_res = -1;
++
++        pbs_res = proxmox_backup_co_write_data(backup_state.pbs, di->dev_id, buf, start, size, &local_err);
++
++        qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++
++        if (pbs_res < 0) {
++            error_propagate(&backup_state.stat.error, local_err);
++            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++            qemu_co_mutex_unlock(&backup_state.backup_mutex);
++            return pbs_res;
++        } else {
++            if (!buf) {
++                backup_state.stat.zero_bytes += size;
++            }
++            backup_state.stat.transferred += size;
++        }
++
++        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++    } else {
++        qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++        if (!buf) {
++            backup_state.stat.zero_bytes += size;
++        }
++        backup_state.stat.transferred += size;
++        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++    }
++
++    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++
++    return size;
++}
++
++static void coroutine_fn pvebackup_co_cleanup(void)
++{
++    assert(qemu_in_coroutine());
++
++    qemu_co_mutex_lock(&backup_state.backup_mutex);
++
++    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++    backup_state.stat.end_time = time(NULL);
++    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++    if (backup_state.vmaw) {
++        Error *local_err = NULL;
++        vma_writer_close(backup_state.vmaw, &local_err);
++
++        if (local_err != NULL) {
++            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++            error_propagate(&backup_state.stat.error, local_err);
++            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++        }
++
++        backup_state.vmaw = NULL;
++    }
++
++    if (backup_state.pbs) {
++        qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++        bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
++        if (!error_or_canceled) {
++            Error *local_err = NULL;
++            proxmox_backup_co_finish(backup_state.pbs, &local_err);
++            if (local_err != NULL) {
++                qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
++                error_propagate(&backup_state.stat.error, local_err);
++             }
++        }
++        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++        proxmox_backup_disconnect(backup_state.pbs);
++        backup_state.pbs = NULL;
++    }
++
++    g_list_free(backup_state.di_list);
++    backup_state.di_list = NULL;
++    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++}
++
++typedef struct PVEBackupCompeteCallbackData {
++    PVEBackupDevInfo *di;
++    int result;
++} PVEBackupCompeteCallbackData;
++
++static void coroutine_fn pvebackup_co_complete_cb(void *opaque)
++{
++    assert(qemu_in_coroutine());
++
++    PVEBackupCompeteCallbackData *cb_data = opaque;
++
++    qemu_co_mutex_lock(&backup_state.backup_mutex);
++
++    PVEBackupDevInfo *di = cb_data->di;
++    int ret = cb_data->result;
++
++    di->completed = true;
++
++    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++    bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
++
++    if (ret < 0 && !backup_state.stat.error) {
++        qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
++        error_setg(&backup_state.stat.error, "job failed with err %d - %s",
++                   ret, strerror(-ret));
++    }
++    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++    di->bs = NULL;
++
++    if (di->target) {
++        bdrv_unref(di->target);
++        di->target = NULL;
++    }
++
++    if (backup_state.vmaw) {
++        vma_writer_close_stream(backup_state.vmaw, di->dev_id);
++    }
++
++    if (backup_state.pbs && !error_or_canceled) {
++        Error *local_err = NULL;
++        proxmox_backup_co_close_image(backup_state.pbs, di->dev_id, &local_err);
++        if (local_err != NULL) {
++            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++            error_propagate(&backup_state.stat.error, local_err);
++            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++        }
++    }
++
++    // remove self from job queue
++    backup_state.di_list = g_list_remove(backup_state.di_list, di);
++    g_free(di);
++
++    int pending_jobs = g_list_length(backup_state.di_list);
++
++    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++
++    if (pending_jobs > 0) {
++        pvebackup_co_run_next_job();
++    } else {
++        pvebackup_co_cleanup();
++    }
++}
++
++static void pvebackup_complete_cb(void *opaque, int ret)
++{
++    // This can be called from the main loop, or from a coroutine
++    PVEBackupCompeteCallbackData cb_data = {
++        .di = opaque,
++        .result = ret,
++    };
++
++    if (qemu_in_coroutine()) {
++        pvebackup_co_complete_cb(&cb_data);
++    } else {
++        block_on_coroutine_fn(pvebackup_co_complete_cb, &cb_data);
++    }
++}
++
++static void coroutine_fn pvebackup_co_cancel(void *opaque)
++{
++    assert(qemu_in_coroutine());
++
++    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++    backup_state.stat.cancel = true;
++    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++    qemu_co_mutex_lock(&backup_state.backup_mutex);
++
++    // Avoid race between block jobs and backup-cancel command:
++    if (!(backup_state.vmaw || backup_state.pbs)) {
++        qemu_co_mutex_unlock(&backup_state.backup_mutex);
++        return;
++    }
++
++    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++    if (!backup_state.stat.error) {
++        qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
++        error_setg(&backup_state.stat.error, "backup cancelled");
++    }
++    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++    if (backup_state.vmaw) {
++        /* make sure vma writer does not block anymore */
++        vma_writer_set_error(backup_state.vmaw, "backup cancelled");
++    }
++
++    if (backup_state.pbs) {
++        proxmox_backup_abort(backup_state.pbs, "backup cancelled");
++    }
++
++    bool running_jobs = 0;
++    GList *l = backup_state.di_list;
++    while (l) {
++        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++        l = g_list_next(l);
++        if (!di->completed && di->bs) {
++            for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
++                if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
++                    continue;
++                }
++
++                BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
++                if (bjob && bjob->source_bs == di->bs) {
++                    AioContext *aio_context = job->job.aio_context;
++                    aio_context_acquire(aio_context);
++
++                    if (!di->completed) {
++                        running_jobs += 1;
++                        job_cancel(&job->job, false);
++                    }
++                    aio_context_release(aio_context);
++                }
++            }
++        }
++    }
++
++    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++
++    if (running_jobs == 0) pvebackup_co_cleanup(); // else job will call completion handler
++}
++
++void qmp_backup_cancel(Error **errp)
++{
++    block_on_coroutine_fn(pvebackup_co_cancel, NULL);
++}
++
++static int coroutine_fn pvebackup_co_add_config(
++    const char *file,
++    const char *name,
++    BackupFormat format,
++    const char *backup_dir,
++    VmaWriter *vmaw,
++    ProxmoxBackupHandle *pbs,
++    Error **errp)
++{
++    int res = 0;
++
++    char *cdata = NULL;
++    gsize clen = 0;
++    GError *err = NULL;
++    if (!g_file_get_contents(file, &cdata, &clen, &err)) {
++        error_setg(errp, "unable to read file '%s'", file);
++        return 1;
++    }
++
++    char *basename = g_path_get_basename(file);
++    if (name == NULL) name = basename;
++
++    if (format == BACKUP_FORMAT_VMA) {
++        if (vma_writer_add_config(vmaw, name, cdata, clen) != 0) {
++            error_setg(errp, "unable to add %s config data to vma archive", file);
++            goto err;
++        }
++    } else if (format == BACKUP_FORMAT_PBS) {
++        if (proxmox_backup_co_add_config(pbs, name, (unsigned char *)cdata, clen, errp) < 0)
++            goto err;
++    } else if (format == BACKUP_FORMAT_DIR) {
++        char config_path[PATH_MAX];
++        snprintf(config_path, PATH_MAX, "%s/%s", backup_dir, name);
++        if (!g_file_set_contents(config_path, cdata, clen, &err)) {
++            error_setg(errp, "unable to write config file '%s'", config_path);
++            goto err;
++        }
++    }
++
++ out:
++    g_free(basename);
++    g_free(cdata);
++    return res;
++
++ err:
++    res = -1;
++    goto out;
++}
++
++bool job_should_pause(Job *job);
++
++static void coroutine_fn pvebackup_co_run_next_job(void)
++{
++    assert(qemu_in_coroutine());
++
++    qemu_co_mutex_lock(&backup_state.backup_mutex);
++
++    GList *l = backup_state.di_list;
++    while (l) {
++        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++        l = g_list_next(l);
++        if (!di->completed && di->bs) {
++            for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
++                if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
++                    continue;
++                }
++
++                BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
++                if (bjob && bjob->source_bs == di->bs) {
++                    AioContext *aio_context = job->job.aio_context;
++                    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++                    aio_context_acquire(aio_context);
++
++                    if (job_should_pause(&job->job)) {
++                        qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++                        bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
++                        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++                        if (error_or_canceled) {
++                            job_cancel(&job->job, false);
++                        } else {
++                            job_resume(&job->job);
++                        }
++                    }
++                    aio_context_release(aio_context);
++                    return;
++                }
++            }
++        }
++    }
++    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++}
++
++typedef struct QmpBackupTask {
++    const char *backup_file;
++    bool has_password;
++    const char *password;
++    bool has_keyfile;
++    const char *keyfile;
++    bool has_key_password;
++    const char *key_password;
++    bool has_backup_id;
++    const char *backup_id;
++    bool has_backup_time;
++    const char *fingerprint;
++    bool has_fingerprint;
++    int64_t backup_time;
++    bool has_format;
++    BackupFormat format;
++    bool has_config_file;
++    const char *config_file;
++    bool has_firewall_file;
++    const char *firewall_file;
++    bool has_devlist;
++    const char *devlist;
++    bool has_speed;
++    int64_t speed;
++    Error **errp;
++    UuidInfo *result;
++} QmpBackupTask;
++
++static void coroutine_fn pvebackup_co_start(void *opaque)
++{
++    assert(qemu_in_coroutine());
++
++    QmpBackupTask *task = opaque;
++
++    task->result = NULL; // just to be sure
++
++    BlockBackend *blk;
++    BlockDriverState *bs = NULL;
++    const char *backup_dir = NULL;
++    Error *local_err = NULL;
++    uuid_t uuid;
++    VmaWriter *vmaw = NULL;
++    ProxmoxBackupHandle *pbs = NULL;
++    gchar **devs = NULL;
++    GList *di_list = NULL;
++    GList *l;
++    UuidInfo *uuid_info;
++    BlockJob *job;
++
++    const char *config_name = "qemu-server.conf";
++    const char *firewall_name = "qemu-server.fw";
++
++    qemu_co_mutex_lock(&backup_state.backup_mutex);
++
++    if (backup_state.di_list) {
++        qemu_co_mutex_unlock(&backup_state.backup_mutex);
++        error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
++                  "previous backup not finished");
++        return;
++    }
++
++    /* Todo: try to auto-detect format based on file name */
++    BackupFormat format = task->has_format ? task->format : BACKUP_FORMAT_VMA;
++
++    if (task->has_devlist) {
++        devs = g_strsplit_set(task->devlist, ",;:", -1);
++
++        gchar **d = devs;
++        while (d && *d) {
++            blk = blk_by_name(*d);
++            if (blk) {
++                bs = blk_bs(blk);
++                if (bdrv_is_read_only(bs)) {
++                    error_setg(task->errp, "Node '%s' is read only", *d);
++                    goto err;
++                }
++                if (!bdrv_is_inserted(bs)) {
++                    error_setg(task->errp, QERR_DEVICE_HAS_NO_MEDIUM, *d);
++                    goto err;
++                }
++                PVEBackupDevInfo *di = g_new0(PVEBackupDevInfo, 1);
++                di->bs = bs;
++                di_list = g_list_append(di_list, di);
++            } else {
++                error_set(task->errp, ERROR_CLASS_DEVICE_NOT_FOUND,
++                          "Device '%s' not found", *d);
++                goto err;
++            }
++            d++;
++        }
++
++    } else {
++        BdrvNextIterator it;
++
++        bs = NULL;
++        for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
++            if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
++                continue;
++            }
++
++            PVEBackupDevInfo *di = g_new0(PVEBackupDevInfo, 1);
++            di->bs = bs;
++            di_list = g_list_append(di_list, di);
++        }
++    }
++
++    if (!di_list) {
++        error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "empty device list");
++        goto err;
++    }
++
++    size_t total = 0;
++
++    l = di_list;
++    while (l) {
++        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++        l = g_list_next(l);
++        if (bdrv_op_is_blocked(di->bs, BLOCK_OP_TYPE_BACKUP_SOURCE, task->errp)) {
++            goto err;
++        }
++
++        ssize_t size = bdrv_getlength(di->bs);
++        if (size < 0) {
++            error_setg_errno(task->errp, -di->size, "bdrv_getlength failed");
++            goto err;
++        }
++        di->size = size;
++        total += size;
++    }
++
++    uuid_generate(uuid);
++
++    if (format == BACKUP_FORMAT_PBS) {
++        if (!task->has_password) {
++            error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'password'");
++            goto err;
++        }
++        if (!task->has_backup_id) {
++            error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'backup-id'");
++            goto err;
++        }
++        if (!task->has_backup_time) {
++            error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'backup-time'");
++            goto err;
++        }
++
++        int dump_cb_block_size = PROXMOX_BACKUP_DEFAULT_CHUNK_SIZE; // Hardcoded (4M)
++        firewall_name = "fw.conf";
++
++        char *pbs_err = NULL;
++        pbs = proxmox_backup_new(
++            task->backup_file,
++            task->backup_id,
++            task->backup_time,
++            dump_cb_block_size,
++            task->has_password ? task->password : NULL,
++            task->has_keyfile ? task->keyfile : NULL,
++            task->has_key_password ? task->key_password : NULL,
++            task->has_fingerprint ? task->fingerprint : NULL,
++            &pbs_err);
++
++        if (!pbs) {
++            error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
++                      "proxmox_backup_new failed: %s", pbs_err);
++            proxmox_backup_free_error(pbs_err);
++            goto err;
++        }
++
++        if (proxmox_backup_co_connect(pbs, task->errp) < 0)
++            goto err;
++
++        /* register all devices */
++        l = di_list;
++        while (l) {
++            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++            l = g_list_next(l);
++
++            const char *devname = bdrv_get_device_name(di->bs);
++
++            int dev_id = proxmox_backup_co_register_image(pbs, devname, di->size, task->errp);
++            if (dev_id < 0)
++                goto err;
++
++            if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_cb, di, task->errp))) {
++                goto err;
++            }
++
++            di->dev_id = dev_id;
++        }
++    } else if (format == BACKUP_FORMAT_VMA) {
++        vmaw = vma_writer_create(task->backup_file, uuid, &local_err);
++        if (!vmaw) {
++            if (local_err) {
++                error_propagate(task->errp, local_err);
++            }
++            goto err;
++        }
++
++        /* register all devices for vma writer */
++        l = di_list;
++        while (l) {
++            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++            l = g_list_next(l);
++
++            if (!(di->target = bdrv_backup_dump_create(VMA_CLUSTER_SIZE, di->size, pvebackup_co_dump_cb, di, task->errp))) {
++                goto err;
++            }
++
++            const char *devname = bdrv_get_device_name(di->bs);
++            di->dev_id = vma_writer_register_stream(vmaw, devname, di->size);
++            if (di->dev_id <= 0) {
++                error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
++                          "register_stream failed");
++                goto err;
++            }
++        }
++    } else if (format == BACKUP_FORMAT_DIR) {
++        if (mkdir(task->backup_file, 0640) != 0) {
++            error_setg_errno(task->errp, errno, "can't create directory '%s'\n",
++                             task->backup_file);
++            goto err;
++        }
++        backup_dir = task->backup_file;
++
++        l = di_list;
++        while (l) {
++            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++            l = g_list_next(l);
++
++            const char *devname = bdrv_get_device_name(di->bs);
++            snprintf(di->targetfile, PATH_MAX, "%s/%s.raw", backup_dir, devname);
++
++            int flags = BDRV_O_RDWR;
++            bdrv_img_create(di->targetfile, "raw", NULL, NULL, NULL,
++                            di->size, flags, false, &local_err);
++            if (local_err) {
++                error_propagate(task->errp, local_err);
++                goto err;
++            }
++
++            di->target = bdrv_open(di->targetfile, NULL, NULL, flags, &local_err);
++            if (!di->target) {
++                error_propagate(task->errp, local_err);
++                goto err;
++            }
++        }
++    } else {
++        error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "unknown backup format");
++        goto err;
++    }
++
++
++    /* add configuration file to archive */
++    if (task->has_config_file) {
++        if (pvebackup_co_add_config(task->config_file, config_name, format, backup_dir,
++                                    vmaw, pbs, task->errp) != 0) {
++            goto err;
++        }
++    }
++
++    /* add firewall file to archive */
++    if (task->has_firewall_file) {
++        if (pvebackup_co_add_config(task->firewall_file, firewall_name, format, backup_dir,
++                                    vmaw, pbs, task->errp) != 0) {
++            goto err;
++        }
++    }
++    /* initialize global backup_state now */
++
++    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++
++    backup_state.stat.cancel = false;
++
++    if (backup_state.stat.error) {
++        error_free(backup_state.stat.error);
++        backup_state.stat.error = NULL;
++    }
++
++    backup_state.stat.start_time = time(NULL);
++    backup_state.stat.end_time = 0;
++
++    if (backup_state.stat.backup_file) {
++        g_free(backup_state.stat.backup_file);
++    }
++    backup_state.stat.backup_file = g_strdup(task->backup_file);
++
++    uuid_copy(backup_state.stat.uuid, uuid);
++    uuid_unparse_lower(uuid, backup_state.stat.uuid_str);
++    char *uuid_str = g_strdup(backup_state.stat.uuid_str);
++
++    backup_state.stat.total = total;
++    backup_state.stat.transferred = 0;
++    backup_state.stat.zero_bytes = 0;
++
++    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++    backup_state.speed = (task->has_speed && task->speed > 0) ? task->speed : 0;
++
++    backup_state.vmaw = vmaw;
++    backup_state.pbs = pbs;
++
++    backup_state.di_list = di_list;
++
++    /* start all jobs (paused state) */
++    l = di_list;
++    while (l) {
++        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++        l = g_list_next(l);
++
++        // make sure target runs in same aoi_context as source
++        AioContext *aio_context = bdrv_get_aio_context(di->bs);
++        aio_context_acquire(aio_context);
++        GSList *ignore = NULL;
++        bdrv_set_aio_context_ignore(di->target, aio_context, &ignore);
++        g_slist_free(ignore);
++        aio_context_release(aio_context);
++
++        job = backup_job_create(NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
++                                BITMAP_SYNC_MODE_NEVER, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
++                                JOB_DEFAULT, pvebackup_complete_cb, di, 1, NULL, &local_err);
++        if (!job || local_err != NULL) {
++            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++            error_setg(&backup_state.stat.error, "backup_job_create failed");
++            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++            break;
++        }
++        job_start(&job->job);
++        if (di->target) {
++            bdrv_unref(di->target);
++            di->target = NULL;
++        }
++    }
++
++    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++
++    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++    bool no_errors = !backup_state.stat.error;
++    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++
++    if (no_errors) {
++        pvebackup_co_run_next_job(); // run one job
++    } else {
++        pvebackup_co_cancel(NULL);
++    }
++
++    uuid_info = g_malloc0(sizeof(*uuid_info));
++    uuid_info->UUID = uuid_str;
++
++    task->result = uuid_info;
++    return;
++
++err:
++
++    l = di_list;
++    while (l) {
++        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++        l = g_list_next(l);
++
++        if (di->target) {
++            bdrv_unref(di->target);
++        }
++
++        if (di->targetfile[0]) {
++            unlink(di->targetfile);
++        }
++        g_free(di);
++    }
++    g_list_free(di_list);
++
++    if (devs) {
++        g_strfreev(devs);
++    }
++
++    if (vmaw) {
++        Error *err = NULL;
++        vma_writer_close(vmaw, &err);
++        unlink(task->backup_file);
++    }
++
++    if (pbs) {
++        proxmox_backup_disconnect(pbs);
++    }
++
++    if (backup_dir) {
++        rmdir(backup_dir);
++    }
++
++    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++
++    task->result = NULL;
++    return;
++}
++
++UuidInfo *qmp_backup(
++    const char *backup_file,
++    bool has_password, const char *password,
++    bool has_keyfile, const char *keyfile,
++    bool has_key_password, const char *key_password,
++    bool has_fingerprint, const char *fingerprint,
++    bool has_backup_id, const char *backup_id,
++    bool has_backup_time, int64_t backup_time,
++    bool has_format, BackupFormat format,
++    bool has_config_file, const char *config_file,
++    bool has_firewall_file, const char *firewall_file,
++    bool has_devlist, const char *devlist,
++    bool has_speed, int64_t speed, Error **errp)
++{
++    QmpBackupTask task = {
++        .backup_file = backup_file,
++        .has_password = has_password,
++        .password = password,
++        .has_key_password = has_key_password,
++        .key_password = key_password,
++        .has_fingerprint = has_fingerprint,
++        .fingerprint = fingerprint,
++        .has_backup_id = has_backup_id,
++        .backup_id = backup_id,
++        .has_backup_time = has_backup_time,
++        .backup_time = backup_time,
++        .has_format = has_format,
++        .format = format,
++        .has_config_file = has_config_file,
++        .config_file = config_file,
++        .has_firewall_file = has_firewall_file,
++        .firewall_file = firewall_file,
++        .has_devlist = has_devlist,
++        .devlist = devlist,
++        .has_speed = has_speed,
++        .speed = speed,
++        .errp = errp,
++    };
++
++    block_on_coroutine_fn(pvebackup_co_start, &task);
++
++    return task.result;
++}
++
++
++typedef struct QmpQueryBackupTask {
++    Error **errp;
++    BackupStatus *result;
++} QmpQueryBackupTask;
++
++static void coroutine_fn pvebackup_co_query(void *opaque)
++{
++    assert(qemu_in_coroutine());
++
++    QmpQueryBackupTask *task = opaque;
++
++    BackupStatus *info = g_malloc0(sizeof(*info));
++
++    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++
++    if (!backup_state.stat.start_time) {
++        /* not started, return {} */
++        task->result = info;
++        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++        return;
++    }
++
++    info->has_status = true;
++    info->has_start_time = true;
++    info->start_time = backup_state.stat.start_time;
++
++    if (backup_state.stat.backup_file) {
++        info->has_backup_file = true;
++        info->backup_file = g_strdup(backup_state.stat.backup_file);
++    }
++
++    info->has_uuid = true;
++    info->uuid = g_strdup(backup_state.stat.uuid_str);
++
++    if (backup_state.stat.end_time) {
++        if (backup_state.stat.error) {
++            info->status = g_strdup("error");
++            info->has_errmsg = true;
++            info->errmsg = g_strdup(error_get_pretty(backup_state.stat.error));
++        } else {
++            info->status = g_strdup("done");
++        }
++        info->has_end_time = true;
++        info->end_time = backup_state.stat.end_time;
++    } else {
++        info->status = g_strdup("active");
++    }
++
++    info->has_total = true;
++    info->total = backup_state.stat.total;
++    info->has_zero_bytes = true;
++    info->zero_bytes = backup_state.stat.zero_bytes;
++    info->has_transferred = true;
++    info->transferred = backup_state.stat.transferred;
++
++    task->result = info;
++
++    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++}
++
++BackupStatus *qmp_query_backup(Error **errp)
++{
++    QmpQueryBackupTask task = {
++        .errp = errp,
++        .result = NULL,
++    };
++
++    block_on_coroutine_fn(pvebackup_co_query, &task);
++
++    return task.result;
++}
+diff --git a/qapi/block-core.json b/qapi/block-core.json
+index 4c55464f86..97d1f64636 100644
+--- a/qapi/block-core.json
++++ b/qapi/block-core.json
+@@ -744,6 +744,115 @@
+ { 'command': 'query-block', 'returns': ['BlockInfo'] }
++##
++# @BackupStatus:
++#
++# Detailed backup status.
++#
++# @status: string describing the current backup status.
++#          This can be 'active', 'done', 'error'. If this field is not
++#          returned, no backup process has been initiated
++#
++# @errmsg: error message (only returned if status is 'error')
++#
++# @total: total amount of bytes involved in the backup process
++#
++# @transferred: amount of bytes already backed up.
++#
++# @zero-bytes: amount of 'zero' bytes detected.
++#
++# @start-time: time (epoch) when backup job started.
++#
++# @end-time: time (epoch) when backup job finished.
++#
++# @backup-file: backup file name
++#
++# @uuid: uuid for this backup job
++#
++##
++{ 'struct': 'BackupStatus',
++  'data': {'*status': 'str', '*errmsg': 'str', '*total': 'int',
++           '*transferred': 'int', '*zero-bytes': 'int',
++           '*start-time': 'int', '*end-time': 'int',
++           '*backup-file': 'str', '*uuid': 'str' } }
++
++##
++# @BackupFormat:
++#
++# An enumeration of supported backup formats.
++#
++# @vma: Proxmox vma backup format
++##
++{ 'enum': 'BackupFormat',
++  'data': [ 'vma', 'dir', 'pbs' ] }
++
++##
++# @backup:
++#
++# Starts a VM backup.
++#
++# @backup-file: the backup file name
++#
++# @format: format of the backup file
++#
++# @config-file: a configuration file to include into
++# the backup archive.
++#
++# @speed: the maximum speed, in bytes per second
++#
++# @devlist: list of block device names (separated by ',', ';'
++# or ':'). By default the backup includes all writable block devices.
++#
++# @password: backup server passsword (required for format 'pbs')
++#
++# @keyfile: keyfile used for encryption (optional for format 'pbs')
++#
++# @key-password: password for keyfile (optional for format 'pbs')
++#
++# @fingerprint: server cert fingerprint (optional for format 'pbs')
++#
++# @backup-id: backup ID (required for format 'pbs')
++#
++# @backup-time: backup timestamp (Unix epoch, required for format 'pbs')
++#
++# Returns: the uuid of the backup job
++#
++##
++{ 'command': 'backup', 'data': { 'backup-file': 'str',
++                                    '*password': 'str',
++                                    '*keyfile': 'str',
++                                    '*key-password': 'str',
++                                    '*fingerprint': 'str',
++                                    '*backup-id': 'str',
++                                    '*backup-time': 'int',
++                                    '*format': 'BackupFormat',
++                                    '*config-file': 'str',
++                                    '*firewall-file': 'str',
++                                    '*devlist': 'str', '*speed': 'int' },
++  'returns': 'UuidInfo' }
++
++##
++# @query-backup:
++#
++# Returns information about current/last backup task.
++#
++# Returns: @BackupStatus
++#
++##
++{ 'command': 'query-backup', 'returns': 'BackupStatus' }
++
++##
++# @backup-cancel:
++#
++# Cancel the current executing backup process.
++#
++# Returns: nothing on success
++#
++# Notes: This command succeeds even if there is no backup process running.
++#
++##
++{ 'command': 'backup-cancel' }
++
+ ##
+ # @BlockDeviceTimedStats:
+ #
+diff --git a/qapi/common.json b/qapi/common.json
+index 7b9cbcd97b..c3b8bb7b48 100644
+--- a/qapi/common.json
++++ b/qapi/common.json
+@@ -144,3 +144,16 @@
+ ##
+ { 'enum': 'PCIELinkWidth',
+   'data': [ '1', '2', '4', '8', '12', '16', '32' ] }
++
++##
++# @UuidInfo:
++#
++# Guest UUID information (Universally Unique Identifier).
++#
++# @UUID: the UUID of the guest
++#
++# Since: 0.14.0
++#
++# Notes: If no UUID was specified for the guest, a null UUID is returned.
++##
++{ 'struct': 'UuidInfo', 'data': {'UUID': 'str'} }
+diff --git a/qapi/misc.json b/qapi/misc.json
+index 0868de22b7..c690a3707d 100644
+--- a/qapi/misc.json
++++ b/qapi/misc.json
+@@ -129,19 +129,6 @@
+ ##
+ { 'command': 'query-kvm', 'returns': 'KvmInfo' }
+-##
+-# @UuidInfo:
+-#
+-# Guest UUID information (Universally Unique Identifier).
+-#
+-# @UUID: the UUID of the guest
+-#
+-# Since: 0.14.0
+-#
+-# Notes: If no UUID was specified for the guest, a null UUID is returned.
+-##
+-{ 'struct': 'UuidInfo', 'data': {'UUID': 'str'} }
+-
+ ##
+ # @query-uuid:
+ #
diff --git a/debian/patches/pve/0030-PVE-Backup-pbs-restore-new-command-to-restore-from-p.patch b/debian/patches/pve/0030-PVE-Backup-pbs-restore-new-command-to-restore-from-p.patch
new file mode 100644 (file)
index 0000000..2652bcf
--- /dev/null
@@ -0,0 +1,258 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Dietmar Maurer <dietmar@proxmox.com>
+Date: Mon, 6 Apr 2020 12:17:01 +0200
+Subject: [PATCH] PVE-Backup: pbs-restore - new command to restore from proxmox
+ backup server
+
+Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
+---
+ Makefile      |   4 +-
+ pbs-restore.c | 217 ++++++++++++++++++++++++++++++++++++++++++++++++++
+ 2 files changed, 220 insertions(+), 1 deletion(-)
+ create mode 100644 pbs-restore.c
+
+diff --git a/Makefile b/Makefile
+index dbd9542ae4..7c1fb58e18 100644
+--- a/Makefile
++++ b/Makefile
+@@ -479,7 +479,7 @@ dummy := $(call unnest-vars,, \
+ include $(SRC_PATH)/tests/Makefile.include
+-all: $(DOCS) $(if $(BUILD_DOCS),sphinxdocs) $(TOOLS) vma$(EXESUF) $(HELPERS-y) recurse-all modules $(vhost-user-json-y)
++all: $(DOCS) $(if $(BUILD_DOCS),sphinxdocs) $(TOOLS) vma$(EXESUF) pbs-restore$(EXESUF) $(HELPERS-y) recurse-all modules $(vhost-user-json-y)
+ qemu-version.h: FORCE
+       $(call quiet-command, \
+@@ -610,6 +610,8 @@ qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-o
+ qemu-storage-daemon$(EXESUF): qemu-storage-daemon.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(chardev-obj-y) $(io-obj-y) $(qom-obj-y) $(storage-daemon-obj-y) $(COMMON_LDADDS)
+ qemu-storage-daemon$(EXESUF): LIBS += -lproxmox_backup_qemu
+ vma$(EXESUF): vma.o vma-reader.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
++pbs-restore$(EXESUF): pbs-restore.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
++pbs-restore$(EXESUF): LIBS += -lproxmox_backup_qemu
+ qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o $(COMMON_LDADDS)
+diff --git a/pbs-restore.c b/pbs-restore.c
+new file mode 100644
+index 0000000000..4bf37ef1fa
+--- /dev/null
++++ b/pbs-restore.c
+@@ -0,0 +1,217 @@
++/*
++ * Qemu image restore helper for Proxmox Backup
++ *
++ * Copyright (C) 2019 Proxmox Server Solutions
++ *
++ * Authors:
++ *  Dietmar Maurer (dietmar@proxmox.com)
++ *
++ * This work is licensed under the terms of the GNU GPL, version 2 or later.
++ * See the COPYING file in the top-level directory.
++ *
++ */
++
++#include "qemu/osdep.h"
++#include <glib.h>
++#include <getopt.h>
++#include <string.h>
++
++#include "qemu-common.h"
++#include "qemu/module.h"
++#include "qemu/error-report.h"
++#include "qemu/main-loop.h"
++#include "qemu/cutils.h"
++#include "qapi/error.h"
++#include "qapi/qmp/qdict.h"
++#include "sysemu/block-backend.h"
++
++#include <proxmox-backup-qemu.h>
++
++static void help(void)
++{
++    const char *help_msg =
++        "usage: pbs-restore [--repository <repo>] snapshot archive-name target [command options]\n"
++        ;
++
++    printf("%s", help_msg);
++    exit(1);
++}
++
++typedef struct CallbackData {
++    BlockBackend *target;
++    uint64_t last_offset;
++    bool skip_zero;
++} CallbackData;
++
++static int write_callback(
++    void *callback_data_ptr,
++    uint64_t offset,
++    const unsigned char *data,
++    uint64_t data_len)
++{
++    int res = -1;
++
++    CallbackData *callback_data = (CallbackData *)callback_data_ptr;
++
++    uint64_t last_offset = callback_data->last_offset;
++    if (offset > last_offset) callback_data->last_offset = offset;
++
++    if (data == NULL) {
++        if (callback_data->skip_zero && offset > last_offset) {
++            return 0;
++        }
++        res = blk_pwrite_zeroes(callback_data->target, offset, data_len, 0);
++    } else {
++        res = blk_pwrite(callback_data->target, offset, data, data_len, 0);
++    }
++
++    if (res < 0) {
++        fprintf(stderr, "blk_pwrite failed at offset %ld length %ld (%d) - %s\n", offset, data_len, res, strerror(-res));
++        return res;
++    }
++
++    return 0;
++}
++
++int main(int argc, char **argv)
++{
++    Error *main_loop_err = NULL;
++    const char *format = "raw";
++    const char *repository = NULL;
++    const char *keyfile = NULL;
++    int verbose = false;
++    bool skip_zero = false;
++
++    error_init(argv[0]);
++
++    for (;;) {
++        static const struct option long_options[] = {
++            {"help", no_argument, 0, 'h'},
++            {"skip-zero", no_argument, 0, 'S'},
++            {"verbose", no_argument, 0, 'v'},
++            {"format", required_argument, 0, 'f'},
++            {"repository", required_argument, 0, 'r'},
++            {"keyfile", required_argument, 0, 'k'},
++            {0, 0, 0, 0}
++        };
++        int c = getopt_long(argc, argv, "hvf:r:k:", long_options, NULL);
++        if (c == -1) {
++            break;
++        }
++        switch (c) {
++            case ':':
++                fprintf(stderr, "missing argument for option '%s'\n", argv[optind - 1]);
++                return -1;
++            case '?':
++                fprintf(stderr, "unrecognized option '%s'\n", argv[optind - 1]);
++                return -1;
++            case 'f':
++                format = g_strdup(argv[optind - 1]);
++                break;
++            case 'r':
++                repository = g_strdup(argv[optind - 1]);
++                break;
++            case 'k':
++                keyfile = g_strdup(argv[optind - 1]);
++                break;
++            case 'v':
++                verbose = true;
++                break;
++            case 'S':
++                skip_zero = true;
++                break;
++            case 'h':
++                help();
++                return 0;
++        }
++    }
++
++    if (optind >= argc - 2) {
++        fprintf(stderr, "missing arguments\n");
++        help();
++        return -1;
++    }
++
++    if (repository == NULL) {
++        repository = getenv("PBS_REPOSITORY");
++    }
++
++    if (repository == NULL) {
++        fprintf(stderr, "no repository specified\n");
++        help();
++        return -1;
++    }
++
++    char *snapshot = argv[optind++];
++    char *archive_name = argv[optind++];
++    char *target = argv[optind++];
++
++    const char *password = getenv("PBS_PASSWORD");
++    const char *fingerprint = getenv("PBS_FINGERPRINT");
++    const char *key_password = getenv("PBS_ENCRYPTION_PASSWORD");
++
++    if (qemu_init_main_loop(&main_loop_err)) {
++        g_error("%s", error_get_pretty(main_loop_err));
++    }
++
++    bdrv_init();
++    module_call_init(MODULE_INIT_QOM);
++
++    if (verbose) {
++        fprintf(stderr, "connecting to repository '%s'\n", repository);
++    }
++    char *pbs_error = NULL;
++    ProxmoxRestoreHandle *conn = proxmox_restore_connect(
++        repository, snapshot, password, keyfile, key_password, fingerprint, &pbs_error);
++    if (conn == NULL) {
++        fprintf(stderr, "restore failed: %s\n", pbs_error);
++        return -1;
++    }
++
++    QDict *options = qdict_new();
++
++    if (format) {
++        qdict_put_str(options, "driver", format);
++    }
++
++
++    if (verbose) {
++        fprintf(stderr, "open block backend for target '%s'\n", target);
++    }
++    Error *local_err = NULL;
++    int flags = BDRV_O_RDWR;
++    BlockBackend *blk = blk_new_open(target, NULL, options, flags, &local_err);
++    if (!blk) {
++        fprintf(stderr, "%s\n", error_get_pretty(local_err));
++        return -1;
++    }
++
++    CallbackData *callback_data = calloc(sizeof(CallbackData), 1);
++
++    callback_data->target = blk;
++    callback_data->skip_zero = skip_zero;
++    callback_data->last_offset = 0;
++
++    // blk_set_enable_write_cache(blk, !writethrough);
++
++    if (verbose) {
++        fprintf(stderr, "starting to restore snapshot '%s'\n", snapshot);
++        fflush(stderr); // ensure we do not get printed after the progress log
++    }
++    int res = proxmox_restore_image(
++        conn,
++        archive_name,
++        write_callback,
++        callback_data,
++        &pbs_error,
++        verbose);
++
++    proxmox_restore_disconnect(conn);
++
++    if (res < 0) {
++        fprintf(stderr, "restore failed: %s\n", pbs_error);
++        return -1;
++    }
++
++    return 0;
++}
diff --git a/debian/patches/pve/0030-PVE-Backup-proxmox-backup-patches-for-qemu.patch b/debian/patches/pve/0030-PVE-Backup-proxmox-backup-patches-for-qemu.patch
deleted file mode 100644 (file)
index 3d5dc1a..0000000
+++ /dev/null
@@ -1,1654 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Dietmar Maurer <dietmar@proxmox.com>
-Date: Mon, 6 Apr 2020 12:16:59 +0200
-Subject: [PATCH] PVE-Backup: proxmox backup patches for qemu
-
----
- Makefile                       |   1 +
- Makefile.objs                  |   2 +
- Makefile.target                |   2 +-
- block/monitor/block-hmp-cmds.c |  33 ++
- blockdev.c                     |   1 +
- hmp-commands-info.hx           |  13 +
- hmp-commands.hx                |  29 +
- include/block/block_int.h      |   2 +-
- include/monitor/hmp.h          |   3 +
- monitor/hmp-cmds.c             |  44 ++
- proxmox-backup-client.c        | 182 +++++++
- proxmox-backup-client.h        |  52 ++
- pve-backup.c                   | 959 +++++++++++++++++++++++++++++++++
- qapi/block-core.json           | 109 ++++
- qapi/common.json               |  13 +
- qapi/misc.json                 |  13 -
- 16 files changed, 1443 insertions(+), 15 deletions(-)
- create mode 100644 proxmox-backup-client.c
- create mode 100644 proxmox-backup-client.h
- create mode 100644 pve-backup.c
-
-diff --git a/Makefile b/Makefile
-index 74c2039005..dbd9542ae4 100644
---- a/Makefile
-+++ b/Makefile
-@@ -608,6 +608,7 @@ qemu-img$(EXESUF): qemu-img.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io
- qemu-nbd$(EXESUF): qemu-nbd.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
- qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
- qemu-storage-daemon$(EXESUF): qemu-storage-daemon.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(chardev-obj-y) $(io-obj-y) $(qom-obj-y) $(storage-daemon-obj-y) $(COMMON_LDADDS)
-+qemu-storage-daemon$(EXESUF): LIBS += -lproxmox_backup_qemu
- vma$(EXESUF): vma.o vma-reader.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
- qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o $(COMMON_LDADDS)
-diff --git a/Makefile.objs b/Makefile.objs
-index 05031a3da7..b7d58e592e 100644
---- a/Makefile.objs
-+++ b/Makefile.objs
-@@ -34,6 +34,7 @@ endif # CONFIG_SOFTMMU or CONFIG_TOOLS
- storage-daemon-obj-y = block/ monitor/ qapi/ qom/ storage-daemon/
- storage-daemon-obj-y += blockdev.o blockdev-nbd.o iothread.o job-qmp.o
-+storage-daemon-obj-y += proxmox-backup-client.o pve-backup.o
- storage-daemon-obj-$(CONFIG_WIN32) += os-win32.o
- storage-daemon-obj-$(CONFIG_POSIX) += os-posix.o
-@@ -45,6 +46,7 @@ storage-daemon-obj-$(CONFIG_POSIX) += os-posix.o
- ifeq ($(CONFIG_SOFTMMU),y)
- common-obj-y = blockdev.o blockdev-nbd.o block/
- common-obj-y += bootdevice.o iothread.o
-+common-obj-y += proxmox-backup-client.o pve-backup.o
- common-obj-y += dump/
- common-obj-y += job-qmp.o
- common-obj-y += monitor/
-diff --git a/Makefile.target b/Makefile.target
-index 8ed1eba95b..f453a95efc 100644
---- a/Makefile.target
-+++ b/Makefile.target
-@@ -162,7 +162,7 @@ obj-y += memory.o
- obj-y += memory_mapping.o
- obj-y += migration/ram.o
- obj-y += softmmu/
--LIBS := $(libs_softmmu) $(LIBS)
-+LIBS := $(libs_softmmu) $(LIBS)  -lproxmox_backup_qemu
- # Hardware support
- ifeq ($(TARGET_NAME), sparc64)
-diff --git a/block/monitor/block-hmp-cmds.c b/block/monitor/block-hmp-cmds.c
-index 4c8c375172..4f03881286 100644
---- a/block/monitor/block-hmp-cmds.c
-+++ b/block/monitor/block-hmp-cmds.c
-@@ -1011,3 +1011,36 @@ void hmp_info_snapshots(Monitor *mon, const QDict *qdict)
-     g_free(sn_tab);
-     g_free(global_snapshots);
- }
-+
-+void hmp_backup_cancel(Monitor *mon, const QDict *qdict)
-+{
-+    Error *error = NULL;
-+
-+    qmp_backup_cancel(&error);
-+
-+    hmp_handle_error(mon, error);
-+}
-+
-+void hmp_backup(Monitor *mon, const QDict *qdict)
-+{
-+    Error *error = NULL;
-+
-+    int dir = qdict_get_try_bool(qdict, "directory", 0);
-+    const char *backup_file = qdict_get_str(qdict, "backupfile");
-+    const char *devlist = qdict_get_try_str(qdict, "devlist");
-+    int64_t speed = qdict_get_try_int(qdict, "speed", 0);
-+
-+    qmp_backup(
-+        backup_file,
-+        false, NULL, // PBS password
-+        false, NULL, // PBS keyfile
-+        false, NULL, // PBS key_password
-+        false, NULL, // PBS fingerprint
-+        false, NULL, // PBS backup-id
-+        false, 0, // PBS backup-time
-+        true, dir ? BACKUP_FORMAT_DIR : BACKUP_FORMAT_VMA,
-+        false, NULL, false, NULL, !!devlist,
-+        devlist, qdict_haskey(qdict, "speed"), speed, &error);
-+
-+    hmp_handle_error(mon, error);
-+}
-diff --git a/blockdev.c b/blockdev.c
-index 65c358e4ef..f391c3b3c7 100644
---- a/blockdev.c
-+++ b/blockdev.c
-@@ -36,6 +36,7 @@
- #include "hw/block/block.h"
- #include "block/blockjob.h"
- #include "block/qdict.h"
-+#include "block/blockjob_int.h"
- #include "block/throttle-groups.h"
- #include "monitor/monitor.h"
- #include "qemu/error-report.h"
-diff --git a/hmp-commands-info.hx b/hmp-commands-info.hx
-index 89fea71972..64995443d4 100644
---- a/hmp-commands-info.hx
-+++ b/hmp-commands-info.hx
-@@ -512,6 +512,19 @@ SRST
-     Show CPU statistics.
- ERST
-+    {
-+        .name       = "backup",
-+        .args_type  = "",
-+        .params     = "",
-+        .help       = "show backup status",
-+        .cmd        = hmp_info_backup,
-+    },
-+
-+SRST
-+  ``info backup``
-+    Show backup status.
-+ERST
-+
- #if defined(CONFIG_SLIRP)
-     {
-         .name       = "usernet",
-diff --git a/hmp-commands.hx b/hmp-commands.hx
-index 81fe305d07..8a03b45c44 100644
---- a/hmp-commands.hx
-+++ b/hmp-commands.hx
-@@ -97,6 +97,35 @@ ERST
- SRST
- ``block_stream``
-   Copy data from a backing file into a block device.
-+ERST
-+
-+   {
-+        .name       = "backup",
-+        .args_type  = "directory:-d,backupfile:s,speed:o?,devlist:s?",
-+        .params     = "[-d] backupfile [speed [devlist]]",
-+        .help       = "create a VM Backup."
-+                  "\n\t\t\t Use -d to dump data into a directory instead"
-+                  "\n\t\t\t of using VMA format.",
-+        .cmd = hmp_backup,
-+    },
-+
-+SRST
-+``backup``
-+  Create a VM backup.
-+ERST
-+
-+    {
-+        .name       = "backup_cancel",
-+        .args_type  = "",
-+        .params     = "",
-+        .help       = "cancel the current VM backup",
-+        .cmd        = hmp_backup_cancel,
-+    },
-+
-+SRST
-+``backup_cancel``
-+  Cancel the current VM backup.
-+
- ERST
-     {
-diff --git a/include/block/block_int.h b/include/block/block_int.h
-index 62e5579723..6d234f1de9 100644
---- a/include/block/block_int.h
-+++ b/include/block/block_int.h
-@@ -62,7 +62,7 @@
- typedef int BackupDumpFunc(void *opaque, uint64_t offset, uint64_t bytes, const void *buf);
--BlockDriverState *bdrv_backuo_dump_create(
-+BlockDriverState *bdrv_backup_dump_create(
-     int dump_cb_block_size,
-     uint64_t byte_size,
-     BackupDumpFunc *dump_cb,
-diff --git a/include/monitor/hmp.h b/include/monitor/hmp.h
-index 601827d43f..6653d04c3c 100644
---- a/include/monitor/hmp.h
-+++ b/include/monitor/hmp.h
-@@ -30,6 +30,7 @@ void hmp_info_migrate(Monitor *mon, const QDict *qdict);
- void hmp_info_migrate_capabilities(Monitor *mon, const QDict *qdict);
- void hmp_info_migrate_parameters(Monitor *mon, const QDict *qdict);
- void hmp_info_migrate_cache_size(Monitor *mon, const QDict *qdict);
-+void hmp_info_backup(Monitor *mon, const QDict *qdict);
- void hmp_info_cpus(Monitor *mon, const QDict *qdict);
- void hmp_info_vnc(Monitor *mon, const QDict *qdict);
- void hmp_info_spice(Monitor *mon, const QDict *qdict);
-@@ -76,6 +77,8 @@ void hmp_x_colo_lost_heartbeat(Monitor *mon, const QDict *qdict);
- void hmp_set_password(Monitor *mon, const QDict *qdict);
- void hmp_expire_password(Monitor *mon, const QDict *qdict);
- void hmp_change(Monitor *mon, const QDict *qdict);
-+void hmp_backup(Monitor *mon, const QDict *qdict);
-+void hmp_backup_cancel(Monitor *mon, const QDict *qdict);
- void hmp_migrate(Monitor *mon, const QDict *qdict);
- void hmp_device_add(Monitor *mon, const QDict *qdict);
- void hmp_device_del(Monitor *mon, const QDict *qdict);
-diff --git a/monitor/hmp-cmds.c b/monitor/hmp-cmds.c
-index 39c7474cea..7fd59b1c22 100644
---- a/monitor/hmp-cmds.c
-+++ b/monitor/hmp-cmds.c
-@@ -192,6 +192,50 @@ void hmp_info_mice(Monitor *mon, const QDict *qdict)
-     qapi_free_MouseInfoList(mice_list);
- }
-+void hmp_info_backup(Monitor *mon, const QDict *qdict)
-+{
-+    BackupStatus *info;
-+
-+    info = qmp_query_backup(NULL);
-+
-+    if (!info) {
-+       monitor_printf(mon, "Backup status: not initialized\n");
-+       return;
-+    }
-+
-+    if (info->has_status) {
-+        if (info->has_errmsg) {
-+            monitor_printf(mon, "Backup status: %s - %s\n",
-+                           info->status, info->errmsg);
-+        } else {
-+            monitor_printf(mon, "Backup status: %s\n", info->status);
-+        }
-+    }
-+
-+    if (info->has_backup_file) {
-+        monitor_printf(mon, "Start time: %s", ctime(&info->start_time));
-+        if (info->end_time) {
-+            monitor_printf(mon, "End time: %s", ctime(&info->end_time));
-+        }
-+
-+        int per = (info->has_total && info->total &&
-+            info->has_transferred && info->transferred) ?
-+            (info->transferred * 100)/info->total : 0;
-+        int zero_per = (info->has_total && info->total &&
-+                        info->has_zero_bytes && info->zero_bytes) ?
-+            (info->zero_bytes * 100)/info->total : 0;
-+        monitor_printf(mon, "Backup file: %s\n", info->backup_file);
-+        monitor_printf(mon, "Backup uuid: %s\n", info->uuid);
-+        monitor_printf(mon, "Total size: %zd\n", info->total);
-+        monitor_printf(mon, "Transferred bytes: %zd (%d%%)\n",
-+                       info->transferred, per);
-+        monitor_printf(mon, "Zero bytes: %zd (%d%%)\n",
-+                       info->zero_bytes, zero_per);
-+    }
-+
-+    qapi_free_BackupStatus(info);
-+}
-+
- static char *SocketAddress_to_str(SocketAddress *addr)
- {
-     switch (addr->type) {
-diff --git a/proxmox-backup-client.c b/proxmox-backup-client.c
-new file mode 100644
-index 0000000000..b7bc7f2574
---- /dev/null
-+++ b/proxmox-backup-client.c
-@@ -0,0 +1,182 @@
-+#include "proxmox-backup-client.h"
-+#include "qemu/main-loop.h"
-+#include "block/aio-wait.h"
-+#include "qapi/error.h"
-+
-+/* Proxmox Backup Server client bindings using coroutines */
-+
-+typedef struct BlockOnCoroutineWrapper {
-+    AioContext *ctx;
-+    CoroutineEntry *entry;
-+    void *entry_arg;
-+    bool finished;
-+} BlockOnCoroutineWrapper;
-+
-+// Waker implementaion to syncronice with proxmox backup rust code
-+typedef struct ProxmoxBackupWaker {
-+    Coroutine *co;
-+    AioContext *ctx;
-+} ProxmoxBackupWaker;
-+
-+static void coroutine_fn block_on_coroutine_wrapper(void *opaque)
-+{
-+    BlockOnCoroutineWrapper *wrapper = opaque;
-+    wrapper->entry(wrapper->entry_arg);
-+    wrapper->finished = true;
-+    aio_wait_kick();
-+}
-+
-+void block_on_coroutine_fn(CoroutineEntry *entry, void *entry_arg)
-+{
-+    assert(!qemu_in_coroutine());
-+
-+    AioContext *ctx = qemu_get_current_aio_context();
-+    BlockOnCoroutineWrapper wrapper = {
-+        .finished = false,
-+        .entry = entry,
-+        .entry_arg = entry_arg,
-+        .ctx = ctx,
-+    };
-+    Coroutine *wrapper_co = qemu_coroutine_create(block_on_coroutine_wrapper, &wrapper);
-+    aio_co_enter(ctx, wrapper_co);
-+    AIO_WAIT_WHILE(ctx, !wrapper.finished);
-+}
-+
-+// This is called from another thread, so we use aio_co_schedule()
-+static void proxmox_backup_schedule_wake(void *data) {
-+    ProxmoxBackupWaker *waker = (ProxmoxBackupWaker *)data;
-+    aio_co_schedule(waker->ctx, waker->co);
-+}
-+
-+int coroutine_fn
-+proxmox_backup_co_connect(ProxmoxBackupHandle *pbs, Error **errp)
-+{
-+    Coroutine *co = qemu_coroutine_self();
-+    AioContext *ctx = qemu_get_current_aio_context();
-+    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
-+    char *pbs_err = NULL;
-+    int pbs_res = -1;
-+
-+    proxmox_backup_connect_async(pbs, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
-+    qemu_coroutine_yield();
-+    if (pbs_res < 0) {
-+        if (errp) error_setg(errp, "backup connect failed: %s", pbs_err ? pbs_err : "unknown error");
-+        if (pbs_err) proxmox_backup_free_error(pbs_err);
-+    }
-+    return pbs_res;
-+}
-+
-+int coroutine_fn
-+proxmox_backup_co_add_config(
-+    ProxmoxBackupHandle *pbs,
-+    const char *name,
-+    const uint8_t *data,
-+    uint64_t size,
-+    Error **errp)
-+{
-+    Coroutine *co = qemu_coroutine_self();
-+    AioContext *ctx = qemu_get_current_aio_context();
-+    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
-+    char *pbs_err = NULL;
-+    int pbs_res = -1;
-+
-+    proxmox_backup_add_config_async(
-+        pbs, name, data, size ,proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
-+    qemu_coroutine_yield();
-+    if (pbs_res < 0) {
-+        if (errp) error_setg(errp, "backup add_config %s failed: %s", name, pbs_err ? pbs_err : "unknown error");
-+        if (pbs_err) proxmox_backup_free_error(pbs_err);
-+    }
-+    return pbs_res;
-+}
-+
-+int coroutine_fn
-+proxmox_backup_co_register_image(
-+    ProxmoxBackupHandle *pbs,
-+    const char *device_name,
-+    uint64_t size,
-+    Error **errp)
-+{
-+    Coroutine *co = qemu_coroutine_self();
-+    AioContext *ctx = qemu_get_current_aio_context();
-+    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
-+    char *pbs_err = NULL;
-+    int pbs_res = -1;
-+
-+    proxmox_backup_register_image_async(
-+        pbs, device_name, size ,proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
-+    qemu_coroutine_yield();
-+    if (pbs_res < 0) {
-+        if (errp) error_setg(errp, "backup register image failed: %s", pbs_err ? pbs_err : "unknown error");
-+        if (pbs_err) proxmox_backup_free_error(pbs_err);
-+    }
-+    return pbs_res;
-+}
-+
-+int coroutine_fn
-+proxmox_backup_co_finish(
-+    ProxmoxBackupHandle *pbs,
-+    Error **errp)
-+{
-+    Coroutine *co = qemu_coroutine_self();
-+    AioContext *ctx = qemu_get_current_aio_context();
-+    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
-+    char *pbs_err = NULL;
-+    int pbs_res = -1;
-+
-+    proxmox_backup_finish_async(
-+        pbs, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
-+    qemu_coroutine_yield();
-+    if (pbs_res < 0) {
-+        if (errp) error_setg(errp, "backup finish failed: %s", pbs_err ? pbs_err : "unknown error");
-+        if (pbs_err) proxmox_backup_free_error(pbs_err);
-+    }
-+    return pbs_res;
-+}
-+
-+int coroutine_fn
-+proxmox_backup_co_close_image(
-+    ProxmoxBackupHandle *pbs,
-+    uint8_t dev_id,
-+    Error **errp)
-+{
-+    Coroutine *co = qemu_coroutine_self();
-+    AioContext *ctx = qemu_get_current_aio_context();
-+    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
-+    char *pbs_err = NULL;
-+    int pbs_res = -1;
-+
-+    proxmox_backup_close_image_async(
-+        pbs, dev_id, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
-+    qemu_coroutine_yield();
-+    if (pbs_res < 0) {
-+        if (errp) error_setg(errp, "backup close image failed: %s", pbs_err ? pbs_err : "unknown error");
-+        if (pbs_err) proxmox_backup_free_error(pbs_err);
-+    }
-+    return pbs_res;
-+}
-+
-+int coroutine_fn
-+proxmox_backup_co_write_data(
-+    ProxmoxBackupHandle *pbs,
-+    uint8_t dev_id,
-+    const uint8_t *data,
-+    uint64_t offset,
-+    uint64_t size,
-+    Error **errp)
-+{
-+    Coroutine *co = qemu_coroutine_self();
-+    AioContext *ctx = qemu_get_current_aio_context();
-+    ProxmoxBackupWaker waker = { .co = co, .ctx = ctx };
-+    char *pbs_err = NULL;
-+    int pbs_res = -1;
-+
-+    proxmox_backup_write_data_async(
-+        pbs, dev_id, data, offset, size, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
-+    qemu_coroutine_yield();
-+    if (pbs_res < 0) {
-+        if (errp) error_setg(errp, "backup write data failed: %s", pbs_err ? pbs_err : "unknown error");
-+        if (pbs_err) proxmox_backup_free_error(pbs_err);
-+    }
-+    return pbs_res;
-+}
-diff --git a/proxmox-backup-client.h b/proxmox-backup-client.h
-new file mode 100644
-index 0000000000..b311bf8de8
---- /dev/null
-+++ b/proxmox-backup-client.h
-@@ -0,0 +1,52 @@
-+#ifndef PROXMOX_BACKUP_CLIENT_H
-+#define PROXMOX_BACKUP_CLIENT_H
-+
-+#include "qemu/osdep.h"
-+#include "qemu/coroutine.h"
-+#include "proxmox-backup-qemu.h"
-+
-+void block_on_coroutine_fn(CoroutineEntry *entry, void *entry_arg);
-+
-+int coroutine_fn
-+proxmox_backup_co_connect(
-+    ProxmoxBackupHandle *pbs,
-+    Error **errp);
-+
-+int coroutine_fn
-+proxmox_backup_co_add_config(
-+    ProxmoxBackupHandle *pbs,
-+    const char *name,
-+    const uint8_t *data,
-+    uint64_t size,
-+    Error **errp);
-+
-+int coroutine_fn
-+proxmox_backup_co_register_image(
-+    ProxmoxBackupHandle *pbs,
-+    const char *device_name,
-+    uint64_t size,
-+    Error **errp);
-+
-+
-+int coroutine_fn
-+proxmox_backup_co_finish(
-+    ProxmoxBackupHandle *pbs,
-+    Error **errp);
-+
-+int coroutine_fn
-+proxmox_backup_co_close_image(
-+    ProxmoxBackupHandle *pbs,
-+    uint8_t dev_id,
-+    Error **errp);
-+
-+int coroutine_fn
-+proxmox_backup_co_write_data(
-+    ProxmoxBackupHandle *pbs,
-+    uint8_t dev_id,
-+    const uint8_t *data,
-+    uint64_t offset,
-+    uint64_t size,
-+    Error **errp);
-+
-+
-+#endif /* PROXMOX_BACKUP_CLIENT_H */
-diff --git a/pve-backup.c b/pve-backup.c
-new file mode 100644
-index 0000000000..9ae89fb679
---- /dev/null
-+++ b/pve-backup.c
-@@ -0,0 +1,959 @@
-+#include "proxmox-backup-client.h"
-+#include "vma.h"
-+
-+#include "qemu/osdep.h"
-+#include "qemu/module.h"
-+#include "sysemu/block-backend.h"
-+#include "sysemu/blockdev.h"
-+#include "block/blockjob.h"
-+#include "qapi/qapi-commands-block.h"
-+#include "qapi/qmp/qerror.h"
-+
-+/* PVE backup state and related function */
-+
-+
-+static struct PVEBackupState {
-+    struct {
-+        // Everithing accessed from qmp command, protected using rwlock
-+        CoRwlock rwlock;
-+        Error *error;
-+        time_t start_time;
-+        time_t end_time;
-+        char *backup_file;
-+        uuid_t uuid;
-+        char uuid_str[37];
-+        size_t total;
-+        size_t transferred;
-+        size_t zero_bytes;
-+        bool cancel;
-+    } stat;
-+    int64_t speed;
-+    VmaWriter *vmaw;
-+    ProxmoxBackupHandle *pbs;
-+    GList *di_list;
-+    CoMutex backup_mutex;
-+} backup_state;
-+
-+static void pvebackup_init(void)
-+{
-+    qemu_co_rwlock_init(&backup_state.stat.rwlock);
-+    qemu_co_mutex_init(&backup_state.backup_mutex);
-+}
-+
-+// initialize PVEBackupState at startup
-+opts_init(pvebackup_init);
-+
-+typedef struct PVEBackupDevInfo {
-+    BlockDriverState *bs;
-+    size_t size;
-+    uint8_t dev_id;
-+    bool completed;
-+    char targetfile[PATH_MAX];
-+    BlockDriverState *target;
-+} PVEBackupDevInfo;
-+
-+static void pvebackup_co_run_next_job(void);
-+
-+static int coroutine_fn
-+pvebackup_co_dump_cb(
-+    void *opaque,
-+    uint64_t start,
-+    uint64_t bytes,
-+    const void *pbuf)
-+{
-+    assert(qemu_in_coroutine());
-+
-+    const uint64_t size = bytes;
-+    const unsigned char *buf = pbuf;
-+    PVEBackupDevInfo *di = opaque;
-+
-+    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+    bool cancel = backup_state.stat.cancel;
-+    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+    if (cancel) {
-+        return size; // return success
-+    }
-+
-+    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+
-+    int ret = -1;
-+
-+    if (backup_state.vmaw) {
-+        size_t zero_bytes = 0;
-+        uint64_t remaining = size;
-+
-+        uint64_t cluster_num = start / VMA_CLUSTER_SIZE;
-+        if ((cluster_num * VMA_CLUSTER_SIZE) != start) {
-+            qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+            if (!backup_state.stat.error) {
-+                qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
-+                error_setg(&backup_state.stat.error,
-+                           "got unaligned write inside backup dump "
-+                           "callback (sector %ld)", start);
-+            }
-+            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+            qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+            return -1; // not aligned to cluster size
-+        }
-+
-+        while (remaining > 0) {
-+            ret = vma_writer_write(backup_state.vmaw, di->dev_id, cluster_num,
-+                                   buf, &zero_bytes);
-+            ++cluster_num;
-+            if (buf) {
-+                buf += VMA_CLUSTER_SIZE;
-+            }
-+            if (ret < 0) {
-+                qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+                if (!backup_state.stat.error) {
-+                    qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
-+                    vma_writer_error_propagate(backup_state.vmaw, &backup_state.stat.error);
-+                }
-+                qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+                qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+                return ret;
-+            } else {
-+                qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+                backup_state.stat.zero_bytes += zero_bytes;
-+                if (remaining >= VMA_CLUSTER_SIZE) {
-+                    backup_state.stat.transferred += VMA_CLUSTER_SIZE;
-+                    remaining -= VMA_CLUSTER_SIZE;
-+                } else {
-+                    backup_state.stat.transferred += remaining;
-+                    remaining = 0;
-+                }
-+                qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+            }
-+        }
-+    } else if (backup_state.pbs) {
-+        Error *local_err = NULL;
-+        int pbs_res = -1;
-+
-+        pbs_res = proxmox_backup_co_write_data(backup_state.pbs, di->dev_id, buf, start, size, &local_err);
-+
-+        qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+
-+        if (pbs_res < 0) {
-+            error_propagate(&backup_state.stat.error, local_err);
-+            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+            qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+            return pbs_res;
-+        } else {
-+            if (!buf) {
-+                backup_state.stat.zero_bytes += size;
-+            }
-+            backup_state.stat.transferred += size;
-+        }
-+
-+        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+    } else {
-+        qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+        if (!buf) {
-+            backup_state.stat.zero_bytes += size;
-+        }
-+        backup_state.stat.transferred += size;
-+        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+    }
-+
-+    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+
-+    return size;
-+}
-+
-+static void coroutine_fn pvebackup_co_cleanup(void)
-+{
-+    assert(qemu_in_coroutine());
-+
-+    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+
-+    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+    backup_state.stat.end_time = time(NULL);
-+    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+    if (backup_state.vmaw) {
-+        Error *local_err = NULL;
-+        vma_writer_close(backup_state.vmaw, &local_err);
-+
-+        if (local_err != NULL) {
-+            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+            error_propagate(&backup_state.stat.error, local_err);
-+            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+        }
-+
-+        backup_state.vmaw = NULL;
-+    }
-+
-+    if (backup_state.pbs) {
-+        qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+        bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
-+        if (!error_or_canceled) {
-+            Error *local_err = NULL;
-+            proxmox_backup_co_finish(backup_state.pbs, &local_err);
-+            if (local_err != NULL) {
-+                qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
-+                error_propagate(&backup_state.stat.error, local_err);
-+             }
-+        }
-+        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+        proxmox_backup_disconnect(backup_state.pbs);
-+        backup_state.pbs = NULL;
-+    }
-+
-+    g_list_free(backup_state.di_list);
-+    backup_state.di_list = NULL;
-+    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+}
-+
-+typedef struct PVEBackupCompeteCallbackData {
-+    PVEBackupDevInfo *di;
-+    int result;
-+} PVEBackupCompeteCallbackData;
-+
-+static void coroutine_fn pvebackup_co_complete_cb(void *opaque)
-+{
-+    assert(qemu_in_coroutine());
-+
-+    PVEBackupCompeteCallbackData *cb_data = opaque;
-+
-+    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+
-+    PVEBackupDevInfo *di = cb_data->di;
-+    int ret = cb_data->result;
-+
-+    di->completed = true;
-+
-+    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+    bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
-+
-+    if (ret < 0 && !backup_state.stat.error) {
-+        qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
-+        error_setg(&backup_state.stat.error, "job failed with err %d - %s",
-+                   ret, strerror(-ret));
-+    }
-+    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+    di->bs = NULL;
-+
-+    if (di->target) {
-+        bdrv_unref(di->target);
-+        di->target = NULL;
-+    }
-+
-+    if (backup_state.vmaw) {
-+        vma_writer_close_stream(backup_state.vmaw, di->dev_id);
-+    }
-+
-+    if (backup_state.pbs && !error_or_canceled) {
-+        Error *local_err = NULL;
-+        proxmox_backup_co_close_image(backup_state.pbs, di->dev_id, &local_err);
-+        if (local_err != NULL) {
-+            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+            error_propagate(&backup_state.stat.error, local_err);
-+            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+        }
-+    }
-+
-+    // remove self from job queue
-+    backup_state.di_list = g_list_remove(backup_state.di_list, di);
-+    g_free(di);
-+
-+    int pending_jobs = g_list_length(backup_state.di_list);
-+
-+    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+
-+    if (pending_jobs > 0) {
-+        pvebackup_co_run_next_job();
-+    } else {
-+        pvebackup_co_cleanup();
-+    }
-+}
-+
-+static void pvebackup_complete_cb(void *opaque, int ret)
-+{
-+    // This can be called from the main loop, or from a coroutine
-+    PVEBackupCompeteCallbackData cb_data = {
-+        .di = opaque,
-+        .result = ret,
-+    };
-+
-+    if (qemu_in_coroutine()) {
-+        pvebackup_co_complete_cb(&cb_data);
-+    } else {
-+        block_on_coroutine_fn(pvebackup_co_complete_cb, &cb_data);
-+    }
-+}
-+
-+static void coroutine_fn pvebackup_co_cancel(void *opaque)
-+{
-+    assert(qemu_in_coroutine());
-+
-+    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+    backup_state.stat.cancel = true;
-+    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+
-+    // Avoid race between block jobs and backup-cancel command:
-+    if (!(backup_state.vmaw || backup_state.pbs)) {
-+        qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+        return;
-+    }
-+
-+    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+    if (!backup_state.stat.error) {
-+        qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
-+        error_setg(&backup_state.stat.error, "backup cancelled");
-+    }
-+    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+    if (backup_state.vmaw) {
-+        /* make sure vma writer does not block anymore */
-+        vma_writer_set_error(backup_state.vmaw, "backup cancelled");
-+    }
-+
-+    if (backup_state.pbs) {
-+        proxmox_backup_abort(backup_state.pbs, "backup cancelled");
-+    }
-+
-+    bool running_jobs = 0;
-+    GList *l = backup_state.di_list;
-+    while (l) {
-+        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+        l = g_list_next(l);
-+        if (!di->completed && di->bs) {
-+            for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
-+                if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
-+                    continue;
-+                }
-+
-+                BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
-+                if (bjob && bjob->source_bs == di->bs) {
-+                    AioContext *aio_context = job->job.aio_context;
-+                    aio_context_acquire(aio_context);
-+
-+                    if (!di->completed) {
-+                        running_jobs += 1;
-+                        job_cancel(&job->job, false);
-+                    }
-+                    aio_context_release(aio_context);
-+                }
-+            }
-+        }
-+    }
-+
-+    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+
-+    if (running_jobs == 0) pvebackup_co_cleanup(); // else job will call completion handler
-+}
-+
-+void qmp_backup_cancel(Error **errp)
-+{
-+    block_on_coroutine_fn(pvebackup_co_cancel, NULL);
-+}
-+
-+static int coroutine_fn pvebackup_co_add_config(
-+    const char *file,
-+    const char *name,
-+    BackupFormat format,
-+    const char *backup_dir,
-+    VmaWriter *vmaw,
-+    ProxmoxBackupHandle *pbs,
-+    Error **errp)
-+{
-+    int res = 0;
-+
-+    char *cdata = NULL;
-+    gsize clen = 0;
-+    GError *err = NULL;
-+    if (!g_file_get_contents(file, &cdata, &clen, &err)) {
-+        error_setg(errp, "unable to read file '%s'", file);
-+        return 1;
-+    }
-+
-+    char *basename = g_path_get_basename(file);
-+    if (name == NULL) name = basename;
-+
-+    if (format == BACKUP_FORMAT_VMA) {
-+        if (vma_writer_add_config(vmaw, name, cdata, clen) != 0) {
-+            error_setg(errp, "unable to add %s config data to vma archive", file);
-+            goto err;
-+        }
-+    } else if (format == BACKUP_FORMAT_PBS) {
-+        if (proxmox_backup_co_add_config(pbs, name, (unsigned char *)cdata, clen, errp) < 0)
-+            goto err;
-+    } else if (format == BACKUP_FORMAT_DIR) {
-+        char config_path[PATH_MAX];
-+        snprintf(config_path, PATH_MAX, "%s/%s", backup_dir, name);
-+        if (!g_file_set_contents(config_path, cdata, clen, &err)) {
-+            error_setg(errp, "unable to write config file '%s'", config_path);
-+            goto err;
-+        }
-+    }
-+
-+ out:
-+    g_free(basename);
-+    g_free(cdata);
-+    return res;
-+
-+ err:
-+    res = -1;
-+    goto out;
-+}
-+
-+bool job_should_pause(Job *job);
-+
-+static void coroutine_fn pvebackup_co_run_next_job(void)
-+{
-+    assert(qemu_in_coroutine());
-+
-+    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+
-+    GList *l = backup_state.di_list;
-+    while (l) {
-+        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+        l = g_list_next(l);
-+        if (!di->completed && di->bs) {
-+            for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
-+                if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
-+                    continue;
-+                }
-+
-+                BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
-+                if (bjob && bjob->source_bs == di->bs) {
-+                    AioContext *aio_context = job->job.aio_context;
-+                    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+                    aio_context_acquire(aio_context);
-+
-+                    if (job_should_pause(&job->job)) {
-+                        qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+                        bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
-+                        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+                        if (error_or_canceled) {
-+                            job_cancel(&job->job, false);
-+                        } else {
-+                            job_resume(&job->job);
-+                        }
-+                    }
-+                    aio_context_release(aio_context);
-+                    return;
-+                }
-+            }
-+        }
-+    }
-+    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+}
-+
-+typedef struct QmpBackupTask {
-+    const char *backup_file;
-+    bool has_password;
-+    const char *password;
-+    bool has_keyfile;
-+    const char *keyfile;
-+    bool has_key_password;
-+    const char *key_password;
-+    bool has_backup_id;
-+    const char *backup_id;
-+    bool has_backup_time;
-+    const char *fingerprint;
-+    bool has_fingerprint;
-+    int64_t backup_time;
-+    bool has_format;
-+    BackupFormat format;
-+    bool has_config_file;
-+    const char *config_file;
-+    bool has_firewall_file;
-+    const char *firewall_file;
-+    bool has_devlist;
-+    const char *devlist;
-+    bool has_speed;
-+    int64_t speed;
-+    Error **errp;
-+    UuidInfo *result;
-+} QmpBackupTask;
-+
-+static void coroutine_fn pvebackup_co_start(void *opaque)
-+{
-+    assert(qemu_in_coroutine());
-+
-+    QmpBackupTask *task = opaque;
-+
-+    task->result = NULL; // just to be sure
-+
-+    BlockBackend *blk;
-+    BlockDriverState *bs = NULL;
-+    const char *backup_dir = NULL;
-+    Error *local_err = NULL;
-+    uuid_t uuid;
-+    VmaWriter *vmaw = NULL;
-+    ProxmoxBackupHandle *pbs = NULL;
-+    gchar **devs = NULL;
-+    GList *di_list = NULL;
-+    GList *l;
-+    UuidInfo *uuid_info;
-+    BlockJob *job;
-+
-+    const char *config_name = "qemu-server.conf";
-+    const char *firewall_name = "qemu-server.fw";
-+
-+    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+
-+    if (backup_state.di_list) {
-+        qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+        error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
-+                  "previous backup not finished");
-+        return;
-+    }
-+
-+    /* Todo: try to auto-detect format based on file name */
-+    BackupFormat format = task->has_format ? task->format : BACKUP_FORMAT_VMA;
-+
-+    if (task->has_devlist) {
-+        devs = g_strsplit_set(task->devlist, ",;:", -1);
-+
-+        gchar **d = devs;
-+        while (d && *d) {
-+            blk = blk_by_name(*d);
-+            if (blk) {
-+                bs = blk_bs(blk);
-+                if (bdrv_is_read_only(bs)) {
-+                    error_setg(task->errp, "Node '%s' is read only", *d);
-+                    goto err;
-+                }
-+                if (!bdrv_is_inserted(bs)) {
-+                    error_setg(task->errp, QERR_DEVICE_HAS_NO_MEDIUM, *d);
-+                    goto err;
-+                }
-+                PVEBackupDevInfo *di = g_new0(PVEBackupDevInfo, 1);
-+                di->bs = bs;
-+                di_list = g_list_append(di_list, di);
-+            } else {
-+                error_set(task->errp, ERROR_CLASS_DEVICE_NOT_FOUND,
-+                          "Device '%s' not found", *d);
-+                goto err;
-+            }
-+            d++;
-+        }
-+
-+    } else {
-+        BdrvNextIterator it;
-+
-+        bs = NULL;
-+        for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
-+            if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
-+                continue;
-+            }
-+
-+            PVEBackupDevInfo *di = g_new0(PVEBackupDevInfo, 1);
-+            di->bs = bs;
-+            di_list = g_list_append(di_list, di);
-+        }
-+    }
-+
-+    if (!di_list) {
-+        error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "empty device list");
-+        goto err;
-+    }
-+
-+    size_t total = 0;
-+
-+    l = di_list;
-+    while (l) {
-+        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+        l = g_list_next(l);
-+        if (bdrv_op_is_blocked(di->bs, BLOCK_OP_TYPE_BACKUP_SOURCE, task->errp)) {
-+            goto err;
-+        }
-+
-+        ssize_t size = bdrv_getlength(di->bs);
-+        if (size < 0) {
-+            error_setg_errno(task->errp, -di->size, "bdrv_getlength failed");
-+            goto err;
-+        }
-+        di->size = size;
-+        total += size;
-+    }
-+
-+    uuid_generate(uuid);
-+
-+    if (format == BACKUP_FORMAT_PBS) {
-+        if (!task->has_password) {
-+            error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'password'");
-+            goto err;
-+        }
-+        if (!task->has_backup_id) {
-+            error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'backup-id'");
-+            goto err;
-+        }
-+        if (!task->has_backup_time) {
-+            error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "missing parameter 'backup-time'");
-+            goto err;
-+        }
-+
-+        int dump_cb_block_size = PROXMOX_BACKUP_DEFAULT_CHUNK_SIZE; // Hardcoded (4M)
-+        firewall_name = "fw.conf";
-+
-+        char *pbs_err = NULL;
-+        pbs = proxmox_backup_new(
-+            task->backup_file,
-+            task->backup_id,
-+            task->backup_time,
-+            dump_cb_block_size,
-+            task->has_password ? task->password : NULL,
-+            task->has_keyfile ? task->keyfile : NULL,
-+            task->has_key_password ? task->key_password : NULL,
-+            task->has_fingerprint ? task->fingerprint : NULL,
-+            &pbs_err);
-+
-+        if (!pbs) {
-+            error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
-+                      "proxmox_backup_new failed: %s", pbs_err);
-+            proxmox_backup_free_error(pbs_err);
-+            goto err;
-+        }
-+
-+        if (proxmox_backup_co_connect(pbs, task->errp) < 0)
-+            goto err;
-+
-+        /* register all devices */
-+        l = di_list;
-+        while (l) {
-+            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+            l = g_list_next(l);
-+
-+            const char *devname = bdrv_get_device_name(di->bs);
-+
-+            int dev_id = proxmox_backup_co_register_image(pbs, devname, di->size, task->errp);
-+            if (dev_id < 0)
-+                goto err;
-+
-+            if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_cb, di, task->errp))) {
-+                goto err;
-+            }
-+
-+            di->dev_id = dev_id;
-+        }
-+    } else if (format == BACKUP_FORMAT_VMA) {
-+        vmaw = vma_writer_create(task->backup_file, uuid, &local_err);
-+        if (!vmaw) {
-+            if (local_err) {
-+                error_propagate(task->errp, local_err);
-+            }
-+            goto err;
-+        }
-+
-+        /* register all devices for vma writer */
-+        l = di_list;
-+        while (l) {
-+            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+            l = g_list_next(l);
-+
-+            if (!(di->target = bdrv_backup_dump_create(VMA_CLUSTER_SIZE, di->size, pvebackup_co_dump_cb, di, task->errp))) {
-+                goto err;
-+            }
-+
-+            const char *devname = bdrv_get_device_name(di->bs);
-+            di->dev_id = vma_writer_register_stream(vmaw, devname, di->size);
-+            if (di->dev_id <= 0) {
-+                error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
-+                          "register_stream failed");
-+                goto err;
-+            }
-+        }
-+    } else if (format == BACKUP_FORMAT_DIR) {
-+        if (mkdir(task->backup_file, 0640) != 0) {
-+            error_setg_errno(task->errp, errno, "can't create directory '%s'\n",
-+                             task->backup_file);
-+            goto err;
-+        }
-+        backup_dir = task->backup_file;
-+
-+        l = di_list;
-+        while (l) {
-+            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+            l = g_list_next(l);
-+
-+            const char *devname = bdrv_get_device_name(di->bs);
-+            snprintf(di->targetfile, PATH_MAX, "%s/%s.raw", backup_dir, devname);
-+
-+            int flags = BDRV_O_RDWR;
-+            bdrv_img_create(di->targetfile, "raw", NULL, NULL, NULL,
-+                            di->size, flags, false, &local_err);
-+            if (local_err) {
-+                error_propagate(task->errp, local_err);
-+                goto err;
-+            }
-+
-+            di->target = bdrv_open(di->targetfile, NULL, NULL, flags, &local_err);
-+            if (!di->target) {
-+                error_propagate(task->errp, local_err);
-+                goto err;
-+            }
-+        }
-+    } else {
-+        error_set(task->errp, ERROR_CLASS_GENERIC_ERROR, "unknown backup format");
-+        goto err;
-+    }
-+
-+
-+    /* add configuration file to archive */
-+    if (task->has_config_file) {
-+        if (pvebackup_co_add_config(task->config_file, config_name, format, backup_dir,
-+                                    vmaw, pbs, task->errp) != 0) {
-+            goto err;
-+        }
-+    }
-+
-+    /* add firewall file to archive */
-+    if (task->has_firewall_file) {
-+        if (pvebackup_co_add_config(task->firewall_file, firewall_name, format, backup_dir,
-+                                    vmaw, pbs, task->errp) != 0) {
-+            goto err;
-+        }
-+    }
-+    /* initialize global backup_state now */
-+
-+    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+
-+    backup_state.stat.cancel = false;
-+
-+    if (backup_state.stat.error) {
-+        error_free(backup_state.stat.error);
-+        backup_state.stat.error = NULL;
-+    }
-+
-+    backup_state.stat.start_time = time(NULL);
-+    backup_state.stat.end_time = 0;
-+
-+    if (backup_state.stat.backup_file) {
-+        g_free(backup_state.stat.backup_file);
-+    }
-+    backup_state.stat.backup_file = g_strdup(task->backup_file);
-+
-+    uuid_copy(backup_state.stat.uuid, uuid);
-+    uuid_unparse_lower(uuid, backup_state.stat.uuid_str);
-+    char *uuid_str = g_strdup(backup_state.stat.uuid_str);
-+
-+    backup_state.stat.total = total;
-+    backup_state.stat.transferred = 0;
-+    backup_state.stat.zero_bytes = 0;
-+
-+    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+    backup_state.speed = (task->has_speed && task->speed > 0) ? task->speed : 0;
-+
-+    backup_state.vmaw = vmaw;
-+    backup_state.pbs = pbs;
-+
-+    backup_state.di_list = di_list;
-+
-+    /* start all jobs (paused state) */
-+    l = di_list;
-+    while (l) {
-+        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+        l = g_list_next(l);
-+
-+        // make sure target runs in same aoi_context as source
-+        AioContext *aio_context = bdrv_get_aio_context(di->bs);
-+        aio_context_acquire(aio_context);
-+        GSList *ignore = NULL;
-+        bdrv_set_aio_context_ignore(di->target, aio_context, &ignore);
-+        g_slist_free(ignore);
-+        aio_context_release(aio_context);
-+
-+        job = backup_job_create(NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
-+                                BITMAP_SYNC_MODE_NEVER, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
-+                                JOB_DEFAULT, pvebackup_complete_cb, di, 1, NULL, &local_err);
-+        if (!job || local_err != NULL) {
-+            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+            error_setg(&backup_state.stat.error, "backup_job_create failed");
-+            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+            break;
-+        }
-+        job_start(&job->job);
-+        if (di->target) {
-+            bdrv_unref(di->target);
-+            di->target = NULL;
-+        }
-+    }
-+
-+    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+
-+    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+    bool no_errors = !backup_state.stat.error;
-+    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+
-+    if (no_errors) {
-+        pvebackup_co_run_next_job(); // run one job
-+    } else {
-+        pvebackup_co_cancel(NULL);
-+    }
-+
-+    uuid_info = g_malloc0(sizeof(*uuid_info));
-+    uuid_info->UUID = uuid_str;
-+
-+    task->result = uuid_info;
-+    return;
-+
-+err:
-+
-+    l = di_list;
-+    while (l) {
-+        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+        l = g_list_next(l);
-+
-+        if (di->target) {
-+            bdrv_unref(di->target);
-+        }
-+
-+        if (di->targetfile[0]) {
-+            unlink(di->targetfile);
-+        }
-+        g_free(di);
-+    }
-+    g_list_free(di_list);
-+
-+    if (devs) {
-+        g_strfreev(devs);
-+    }
-+
-+    if (vmaw) {
-+        Error *err = NULL;
-+        vma_writer_close(vmaw, &err);
-+        unlink(task->backup_file);
-+    }
-+
-+    if (pbs) {
-+        proxmox_backup_disconnect(pbs);
-+    }
-+
-+    if (backup_dir) {
-+        rmdir(backup_dir);
-+    }
-+
-+    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+
-+    task->result = NULL;
-+    return;
-+}
-+
-+UuidInfo *qmp_backup(
-+    const char *backup_file,
-+    bool has_password, const char *password,
-+    bool has_keyfile, const char *keyfile,
-+    bool has_key_password, const char *key_password,
-+    bool has_fingerprint, const char *fingerprint,
-+    bool has_backup_id, const char *backup_id,
-+    bool has_backup_time, int64_t backup_time,
-+    bool has_format, BackupFormat format,
-+    bool has_config_file, const char *config_file,
-+    bool has_firewall_file, const char *firewall_file,
-+    bool has_devlist, const char *devlist,
-+    bool has_speed, int64_t speed, Error **errp)
-+{
-+    QmpBackupTask task = {
-+        .backup_file = backup_file,
-+        .has_password = has_password,
-+        .password = password,
-+        .has_key_password = has_key_password,
-+        .key_password = key_password,
-+        .has_fingerprint = has_fingerprint,
-+        .fingerprint = fingerprint,
-+        .has_backup_id = has_backup_id,
-+        .backup_id = backup_id,
-+        .has_backup_time = has_backup_time,
-+        .backup_time = backup_time,
-+        .has_format = has_format,
-+        .format = format,
-+        .has_config_file = has_config_file,
-+        .config_file = config_file,
-+        .has_firewall_file = has_firewall_file,
-+        .firewall_file = firewall_file,
-+        .has_devlist = has_devlist,
-+        .devlist = devlist,
-+        .has_speed = has_speed,
-+        .speed = speed,
-+        .errp = errp,
-+    };
-+
-+    block_on_coroutine_fn(pvebackup_co_start, &task);
-+
-+    return task.result;
-+}
-+
-+
-+typedef struct QmpQueryBackupTask {
-+    Error **errp;
-+    BackupStatus *result;
-+} QmpQueryBackupTask;
-+
-+static void coroutine_fn pvebackup_co_query(void *opaque)
-+{
-+    assert(qemu_in_coroutine());
-+
-+    QmpQueryBackupTask *task = opaque;
-+
-+    BackupStatus *info = g_malloc0(sizeof(*info));
-+
-+    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+
-+    if (!backup_state.stat.start_time) {
-+        /* not started, return {} */
-+        task->result = info;
-+        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+        return;
-+    }
-+
-+    info->has_status = true;
-+    info->has_start_time = true;
-+    info->start_time = backup_state.stat.start_time;
-+
-+    if (backup_state.stat.backup_file) {
-+        info->has_backup_file = true;
-+        info->backup_file = g_strdup(backup_state.stat.backup_file);
-+    }
-+
-+    info->has_uuid = true;
-+    info->uuid = g_strdup(backup_state.stat.uuid_str);
-+
-+    if (backup_state.stat.end_time) {
-+        if (backup_state.stat.error) {
-+            info->status = g_strdup("error");
-+            info->has_errmsg = true;
-+            info->errmsg = g_strdup(error_get_pretty(backup_state.stat.error));
-+        } else {
-+            info->status = g_strdup("done");
-+        }
-+        info->has_end_time = true;
-+        info->end_time = backup_state.stat.end_time;
-+    } else {
-+        info->status = g_strdup("active");
-+    }
-+
-+    info->has_total = true;
-+    info->total = backup_state.stat.total;
-+    info->has_zero_bytes = true;
-+    info->zero_bytes = backup_state.stat.zero_bytes;
-+    info->has_transferred = true;
-+    info->transferred = backup_state.stat.transferred;
-+
-+    task->result = info;
-+
-+    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+}
-+
-+BackupStatus *qmp_query_backup(Error **errp)
-+{
-+    QmpQueryBackupTask task = {
-+        .errp = errp,
-+        .result = NULL,
-+    };
-+
-+    block_on_coroutine_fn(pvebackup_co_query, &task);
-+
-+    return task.result;
-+}
-diff --git a/qapi/block-core.json b/qapi/block-core.json
-index 4c55464f86..97d1f64636 100644
---- a/qapi/block-core.json
-+++ b/qapi/block-core.json
-@@ -744,6 +744,115 @@
- { 'command': 'query-block', 'returns': ['BlockInfo'] }
-+##
-+# @BackupStatus:
-+#
-+# Detailed backup status.
-+#
-+# @status: string describing the current backup status.
-+#          This can be 'active', 'done', 'error'. If this field is not
-+#          returned, no backup process has been initiated
-+#
-+# @errmsg: error message (only returned if status is 'error')
-+#
-+# @total: total amount of bytes involved in the backup process
-+#
-+# @transferred: amount of bytes already backed up.
-+#
-+# @zero-bytes: amount of 'zero' bytes detected.
-+#
-+# @start-time: time (epoch) when backup job started.
-+#
-+# @end-time: time (epoch) when backup job finished.
-+#
-+# @backup-file: backup file name
-+#
-+# @uuid: uuid for this backup job
-+#
-+##
-+{ 'struct': 'BackupStatus',
-+  'data': {'*status': 'str', '*errmsg': 'str', '*total': 'int',
-+           '*transferred': 'int', '*zero-bytes': 'int',
-+           '*start-time': 'int', '*end-time': 'int',
-+           '*backup-file': 'str', '*uuid': 'str' } }
-+
-+##
-+# @BackupFormat:
-+#
-+# An enumeration of supported backup formats.
-+#
-+# @vma: Proxmox vma backup format
-+##
-+{ 'enum': 'BackupFormat',
-+  'data': [ 'vma', 'dir', 'pbs' ] }
-+
-+##
-+# @backup:
-+#
-+# Starts a VM backup.
-+#
-+# @backup-file: the backup file name
-+#
-+# @format: format of the backup file
-+#
-+# @config-file: a configuration file to include into
-+# the backup archive.
-+#
-+# @speed: the maximum speed, in bytes per second
-+#
-+# @devlist: list of block device names (separated by ',', ';'
-+# or ':'). By default the backup includes all writable block devices.
-+#
-+# @password: backup server passsword (required for format 'pbs')
-+#
-+# @keyfile: keyfile used for encryption (optional for format 'pbs')
-+#
-+# @key-password: password for keyfile (optional for format 'pbs')
-+#
-+# @fingerprint: server cert fingerprint (optional for format 'pbs')
-+#
-+# @backup-id: backup ID (required for format 'pbs')
-+#
-+# @backup-time: backup timestamp (Unix epoch, required for format 'pbs')
-+#
-+# Returns: the uuid of the backup job
-+#
-+##
-+{ 'command': 'backup', 'data': { 'backup-file': 'str',
-+                                    '*password': 'str',
-+                                    '*keyfile': 'str',
-+                                    '*key-password': 'str',
-+                                    '*fingerprint': 'str',
-+                                    '*backup-id': 'str',
-+                                    '*backup-time': 'int',
-+                                    '*format': 'BackupFormat',
-+                                    '*config-file': 'str',
-+                                    '*firewall-file': 'str',
-+                                    '*devlist': 'str', '*speed': 'int' },
-+  'returns': 'UuidInfo' }
-+
-+##
-+# @query-backup:
-+#
-+# Returns information about current/last backup task.
-+#
-+# Returns: @BackupStatus
-+#
-+##
-+{ 'command': 'query-backup', 'returns': 'BackupStatus' }
-+
-+##
-+# @backup-cancel:
-+#
-+# Cancel the current executing backup process.
-+#
-+# Returns: nothing on success
-+#
-+# Notes: This command succeeds even if there is no backup process running.
-+#
-+##
-+{ 'command': 'backup-cancel' }
-+
- ##
- # @BlockDeviceTimedStats:
- #
-diff --git a/qapi/common.json b/qapi/common.json
-index 7b9cbcd97b..c3b8bb7b48 100644
---- a/qapi/common.json
-+++ b/qapi/common.json
-@@ -144,3 +144,16 @@
- ##
- { 'enum': 'PCIELinkWidth',
-   'data': [ '1', '2', '4', '8', '12', '16', '32' ] }
-+
-+##
-+# @UuidInfo:
-+#
-+# Guest UUID information (Universally Unique Identifier).
-+#
-+# @UUID: the UUID of the guest
-+#
-+# Since: 0.14.0
-+#
-+# Notes: If no UUID was specified for the guest, a null UUID is returned.
-+##
-+{ 'struct': 'UuidInfo', 'data': {'UUID': 'str'} }
-diff --git a/qapi/misc.json b/qapi/misc.json
-index 0868de22b7..c690a3707d 100644
---- a/qapi/misc.json
-+++ b/qapi/misc.json
-@@ -129,19 +129,6 @@
- ##
- { 'command': 'query-kvm', 'returns': 'KvmInfo' }
--##
--# @UuidInfo:
--#
--# Guest UUID information (Universally Unique Identifier).
--#
--# @UUID: the UUID of the guest
--#
--# Since: 0.14.0
--#
--# Notes: If no UUID was specified for the guest, a null UUID is returned.
--##
--{ 'struct': 'UuidInfo', 'data': {'UUID': 'str'} }
--
- ##
- # @query-uuid:
- #
diff --git a/debian/patches/pve/0031-PVE-Backup-aquire-aio_context-before-calling-backup_.patch b/debian/patches/pve/0031-PVE-Backup-aquire-aio_context-before-calling-backup_.patch
deleted file mode 100644 (file)
index 4b0e14e..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Dietmar Maurer <dietmar@proxmox.com>
-Date: Mon, 6 Apr 2020 12:17:00 +0200
-Subject: [PATCH] PVE-Backup: aquire aio_context before calling
- backup_job_create
-
-And do not set target in same aoi_context as source, because
-this is already done in bdrv_backup_top_append ...
-
-Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
----
- pve-backup.c | 8 +++-----
- 1 file changed, 3 insertions(+), 5 deletions(-)
-
-diff --git a/pve-backup.c b/pve-backup.c
-index 9ae89fb679..38dd33e28b 100644
---- a/pve-backup.c
-+++ b/pve-backup.c
-@@ -757,17 +757,15 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
-         PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-         l = g_list_next(l);
--        // make sure target runs in same aoi_context as source
-         AioContext *aio_context = bdrv_get_aio_context(di->bs);
-         aio_context_acquire(aio_context);
--        GSList *ignore = NULL;
--        bdrv_set_aio_context_ignore(di->target, aio_context, &ignore);
--        g_slist_free(ignore);
--        aio_context_release(aio_context);
-         job = backup_job_create(NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
-                                 BITMAP_SYNC_MODE_NEVER, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
-                                 JOB_DEFAULT, pvebackup_complete_cb, di, 1, NULL, &local_err);
-+
-+        aio_context_release(aio_context);
-+
-         if (!job || local_err != NULL) {
-             qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-             error_setg(&backup_state.stat.error, "backup_job_create failed");
diff --git a/debian/patches/pve/0031-PVE-Backup-avoid-coroutines-to-fix-AIO-freeze-cleanu.patch b/debian/patches/pve/0031-PVE-Backup-avoid-coroutines-to-fix-AIO-freeze-cleanu.patch
new file mode 100644 (file)
index 0000000..6f29231
--- /dev/null
@@ -0,0 +1,914 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Dietmar Maurer <dietmar@proxmox.com>
+Date: Mon, 6 Apr 2020 12:17:00 +0200
+Subject: [PATCH] PVE-Backup: avoid coroutines to fix AIO freeze, cleanups
+
+We observed various AIO pool loop freezes, so we decided to avoid
+coroutines and restrict ourselfes using similar code as upstream
+(see blockdev.c: do_backup_common).
+
+* avoid coroutine for job related code (causes hangs with iothreads)
+    - We then acquire/release all mutexes outside coroutines now, so we can now
+      correctly use a normal mutex.
+
+* split pvebackup_co_dump_cb into:
+    - pvebackup_co_dump_pbs_cb and
+    - pvebackup_co_dump_pbs_cb
+
+* new helper functions
+    - pvebackup_propagate_error
+    - pvebackup_error_or_canceled
+    - pvebackup_add_transfered_bytes
+
+* avoid cancel flag (not needed)
+
+* simplify backup_cancel logic
+
+There is progress on upstream to support running qmp commands inside
+coroutines, see:
+https://lists.gnu.org/archive/html/qemu-devel/2020-02/msg04852.html
+
+We should consider using that when it is available in upstream qemu.
+
+Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
+---
+ pve-backup.c | 638 ++++++++++++++++++++++++++-------------------------
+ 1 file changed, 320 insertions(+), 318 deletions(-)
+
+diff --git a/pve-backup.c b/pve-backup.c
+index 9ae89fb679..bb917ee972 100644
+--- a/pve-backup.c
++++ b/pve-backup.c
+@@ -11,11 +11,27 @@
+ /* PVE backup state and related function */
++/*
++ * Note: A resume from a qemu_coroutine_yield can happen in a different thread,
++ * so you may not use normal mutexes within coroutines:
++ *
++ * ---bad-example---
++ * qemu_rec_mutex_lock(lock)
++ * ...
++ * qemu_coroutine_yield() // wait for something
++ * // we are now inside a different thread
++ * qemu_rec_mutex_unlock(lock) // Crash - wrong thread!!
++ * ---end-bad-example--
++ *
++ * ==> Always use CoMutext inside coroutines.
++ * ==> Never acquire/release AioContext withing coroutines (because that use QemuRecMutex)
++ *
++ */
+ static struct PVEBackupState {
+     struct {
+-        // Everithing accessed from qmp command, protected using rwlock
+-        CoRwlock rwlock;
++        // Everithing accessed from qmp_backup_query command is protected using lock
++        QemuMutex lock;
+         Error *error;
+         time_t start_time;
+         time_t end_time;
+@@ -25,19 +41,20 @@ static struct PVEBackupState {
+         size_t total;
+         size_t transferred;
+         size_t zero_bytes;
+-        bool cancel;
+     } stat;
+     int64_t speed;
+     VmaWriter *vmaw;
+     ProxmoxBackupHandle *pbs;
+     GList *di_list;
+-    CoMutex backup_mutex;
++    QemuMutex backup_mutex;
++    CoMutex dump_callback_mutex;
+ } backup_state;
+ static void pvebackup_init(void)
+ {
+-    qemu_co_rwlock_init(&backup_state.stat.rwlock);
+-    qemu_co_mutex_init(&backup_state.backup_mutex);
++    qemu_mutex_init(&backup_state.stat.lock);
++    qemu_mutex_init(&backup_state.backup_mutex);
++    qemu_co_mutex_init(&backup_state.dump_callback_mutex);
+ }
+ // initialize PVEBackupState at startup
+@@ -52,10 +69,54 @@ typedef struct PVEBackupDevInfo {
+     BlockDriverState *target;
+ } PVEBackupDevInfo;
+-static void pvebackup_co_run_next_job(void);
++static void pvebackup_run_next_job(void);
++static BlockJob *
++lookup_active_block_job(PVEBackupDevInfo *di)
++{
++    if (!di->completed && di->bs) {
++        for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
++            if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
++                continue;
++            }
++
++            BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
++            if (bjob && bjob->source_bs == di->bs) {
++                return job;
++            }
++        }
++    }
++    return NULL;
++}
++
++static void pvebackup_propagate_error(Error *err)
++{
++    qemu_mutex_lock(&backup_state.stat.lock);
++    error_propagate(&backup_state.stat.error, err);
++    qemu_mutex_unlock(&backup_state.stat.lock);
++}
++
++static bool pvebackup_error_or_canceled(void)
++{
++    qemu_mutex_lock(&backup_state.stat.lock);
++    bool error_or_canceled = !!backup_state.stat.error;
++    qemu_mutex_unlock(&backup_state.stat.lock);
++
++    return error_or_canceled;
++}
++
++static void pvebackup_add_transfered_bytes(size_t transferred, size_t zero_bytes)
++{
++    qemu_mutex_lock(&backup_state.stat.lock);
++    backup_state.stat.zero_bytes += zero_bytes;
++    backup_state.stat.transferred += transferred;
++    qemu_mutex_unlock(&backup_state.stat.lock);
++}
++
++// This may get called from multiple coroutines in multiple io-threads
++// Note1: this may get called after job_cancel()
+ static int coroutine_fn
+-pvebackup_co_dump_cb(
++pvebackup_co_dump_pbs_cb(
+     void *opaque,
+     uint64_t start,
+     uint64_t bytes,
+@@ -67,137 +128,127 @@ pvebackup_co_dump_cb(
+     const unsigned char *buf = pbuf;
+     PVEBackupDevInfo *di = opaque;
+-    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
+-    bool cancel = backup_state.stat.cancel;
+-    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++    assert(backup_state.pbs);
++
++    Error *local_err = NULL;
++    int pbs_res = -1;
++
++    qemu_co_mutex_lock(&backup_state.dump_callback_mutex);
+-    if (cancel) {
+-        return size; // return success
++    // avoid deadlock if job is cancelled
++    if (pvebackup_error_or_canceled()) {
++        qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
++        return -1;
+     }
+-    qemu_co_mutex_lock(&backup_state.backup_mutex);
++    pbs_res = proxmox_backup_co_write_data(backup_state.pbs, di->dev_id, buf, start, size, &local_err);
++    qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
+-    int ret = -1;
++    if (pbs_res < 0) {
++        pvebackup_propagate_error(local_err);
++        return pbs_res;
++    } else {
++        pvebackup_add_transfered_bytes(size, !buf ? size : 0);
++    }
+-    if (backup_state.vmaw) {
+-        size_t zero_bytes = 0;
+-        uint64_t remaining = size;
+-
+-        uint64_t cluster_num = start / VMA_CLUSTER_SIZE;
+-        if ((cluster_num * VMA_CLUSTER_SIZE) != start) {
+-            qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
+-            if (!backup_state.stat.error) {
+-                qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
+-                error_setg(&backup_state.stat.error,
+-                           "got unaligned write inside backup dump "
+-                           "callback (sector %ld)", start);
+-            }
+-            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-            qemu_co_mutex_unlock(&backup_state.backup_mutex);
+-            return -1; // not aligned to cluster size
+-        }
++    return size;
++}
+-        while (remaining > 0) {
+-            ret = vma_writer_write(backup_state.vmaw, di->dev_id, cluster_num,
+-                                   buf, &zero_bytes);
+-            ++cluster_num;
+-            if (buf) {
+-                buf += VMA_CLUSTER_SIZE;
+-            }
+-            if (ret < 0) {
+-                qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
+-                if (!backup_state.stat.error) {
+-                    qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
+-                    vma_writer_error_propagate(backup_state.vmaw, &backup_state.stat.error);
+-                }
+-                qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++// This may get called from multiple coroutines in multiple io-threads
++static int coroutine_fn
++pvebackup_co_dump_vma_cb(
++    void *opaque,
++    uint64_t start,
++    uint64_t bytes,
++    const void *pbuf)
++{
++    assert(qemu_in_coroutine());
+-                qemu_co_mutex_unlock(&backup_state.backup_mutex);
+-                return ret;
+-            } else {
+-                qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
+-                backup_state.stat.zero_bytes += zero_bytes;
+-                if (remaining >= VMA_CLUSTER_SIZE) {
+-                    backup_state.stat.transferred += VMA_CLUSTER_SIZE;
+-                    remaining -= VMA_CLUSTER_SIZE;
+-                } else {
+-                    backup_state.stat.transferred += remaining;
+-                    remaining = 0;
+-                }
+-                qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-            }
+-        }
+-    } else if (backup_state.pbs) {
+-        Error *local_err = NULL;
+-        int pbs_res = -1;
++    const uint64_t size = bytes;
++    const unsigned char *buf = pbuf;
++    PVEBackupDevInfo *di = opaque;
+-        pbs_res = proxmox_backup_co_write_data(backup_state.pbs, di->dev_id, buf, start, size, &local_err);
++    int ret = -1;
+-        qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++    assert(backup_state.vmaw);
+-        if (pbs_res < 0) {
+-            error_propagate(&backup_state.stat.error, local_err);
+-            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-            qemu_co_mutex_unlock(&backup_state.backup_mutex);
+-            return pbs_res;
+-        } else {
+-            if (!buf) {
+-                backup_state.stat.zero_bytes += size;
+-            }
+-            backup_state.stat.transferred += size;
++    uint64_t remaining = size;
++
++    uint64_t cluster_num = start / VMA_CLUSTER_SIZE;
++    if ((cluster_num * VMA_CLUSTER_SIZE) != start) {
++        Error *local_err = NULL;
++        error_setg(&local_err,
++                   "got unaligned write inside backup dump "
++                   "callback (sector %ld)", start);
++        pvebackup_propagate_error(local_err);
++        return -1; // not aligned to cluster size
++    }
++
++    while (remaining > 0) {
++        qemu_co_mutex_lock(&backup_state.dump_callback_mutex);
++        // avoid deadlock if job is cancelled
++        if (pvebackup_error_or_canceled()) {
++            qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
++            return -1;
+         }
+-        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++        size_t zero_bytes = 0;
++        ret = vma_writer_write(backup_state.vmaw, di->dev_id, cluster_num, buf, &zero_bytes);
++        qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
+-    } else {
+-        qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
+-        if (!buf) {
+-            backup_state.stat.zero_bytes += size;
++        ++cluster_num;
++        if (buf) {
++            buf += VMA_CLUSTER_SIZE;
++        }
++        if (ret < 0) {
++            Error *local_err = NULL;
++            vma_writer_error_propagate(backup_state.vmaw, &local_err);
++            pvebackup_propagate_error(local_err);
++            return ret;
++        } else {
++            if (remaining >= VMA_CLUSTER_SIZE) {
++                assert(ret == VMA_CLUSTER_SIZE);
++                pvebackup_add_transfered_bytes(VMA_CLUSTER_SIZE, zero_bytes);
++                remaining -= VMA_CLUSTER_SIZE;
++            } else {
++                assert(ret == remaining);
++                pvebackup_add_transfered_bytes(remaining, zero_bytes);
++                remaining = 0;
++            }
+         }
+-        backup_state.stat.transferred += size;
+-        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+     }
+-    qemu_co_mutex_unlock(&backup_state.backup_mutex);
+-
+     return size;
+ }
+-static void coroutine_fn pvebackup_co_cleanup(void)
++// assumes the caller holds backup_mutex
++static void coroutine_fn pvebackup_co_cleanup(void *unused)
+ {
+     assert(qemu_in_coroutine());
+-    qemu_co_mutex_lock(&backup_state.backup_mutex);
+-
+-    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
++    qemu_mutex_lock(&backup_state.stat.lock);
+     backup_state.stat.end_time = time(NULL);
+-    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++    qemu_mutex_unlock(&backup_state.stat.lock);
+     if (backup_state.vmaw) {
+         Error *local_err = NULL;
+         vma_writer_close(backup_state.vmaw, &local_err);
+         if (local_err != NULL) {
+-            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
+-            error_propagate(&backup_state.stat.error, local_err);
+-            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-        }
++            pvebackup_propagate_error(local_err);
++         }
+         backup_state.vmaw = NULL;
+     }
+     if (backup_state.pbs) {
+-        qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
+-        bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
+-        if (!error_or_canceled) {
++        if (!pvebackup_error_or_canceled()) {
+             Error *local_err = NULL;
+             proxmox_backup_co_finish(backup_state.pbs, &local_err);
+             if (local_err != NULL) {
+-                qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
+-                error_propagate(&backup_state.stat.error, local_err);
+-             }
++                pvebackup_propagate_error(local_err);
++            }
+         }
+-        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+         proxmox_backup_disconnect(backup_state.pbs);
+         backup_state.pbs = NULL;
+@@ -205,43 +256,14 @@ static void coroutine_fn pvebackup_co_cleanup(void)
+     g_list_free(backup_state.di_list);
+     backup_state.di_list = NULL;
+-    qemu_co_mutex_unlock(&backup_state.backup_mutex);
+ }
+-typedef struct PVEBackupCompeteCallbackData {
+-    PVEBackupDevInfo *di;
+-    int result;
+-} PVEBackupCompeteCallbackData;
+-
+-static void coroutine_fn pvebackup_co_complete_cb(void *opaque)
++// assumes the caller holds backup_mutex
++static void coroutine_fn pvebackup_complete_stream(void *opaque)
+ {
+-    assert(qemu_in_coroutine());
+-
+-    PVEBackupCompeteCallbackData *cb_data = opaque;
+-
+-    qemu_co_mutex_lock(&backup_state.backup_mutex);
+-
+-    PVEBackupDevInfo *di = cb_data->di;
+-    int ret = cb_data->result;
+-
+-    di->completed = true;
+-
+-    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
+-    bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
+-
+-    if (ret < 0 && !backup_state.stat.error) {
+-        qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
+-        error_setg(&backup_state.stat.error, "job failed with err %d - %s",
+-                   ret, strerror(-ret));
+-    }
+-    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-
+-    di->bs = NULL;
++    PVEBackupDevInfo *di = opaque;
+-    if (di->target) {
+-        bdrv_unref(di->target);
+-        di->target = NULL;
+-    }
++    bool error_or_canceled = pvebackup_error_or_canceled();
+     if (backup_state.vmaw) {
+         vma_writer_close_stream(backup_state.vmaw, di->dev_id);
+@@ -251,110 +273,101 @@ static void coroutine_fn pvebackup_co_complete_cb(void *opaque)
+         Error *local_err = NULL;
+         proxmox_backup_co_close_image(backup_state.pbs, di->dev_id, &local_err);
+         if (local_err != NULL) {
+-            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
+-            error_propagate(&backup_state.stat.error, local_err);
+-            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++            pvebackup_propagate_error(local_err);
+         }
+     }
++}
+-    // remove self from job queue
+-    backup_state.di_list = g_list_remove(backup_state.di_list, di);
+-    g_free(di);
++static void pvebackup_complete_cb(void *opaque, int ret)
++{
++    assert(!qemu_in_coroutine());
+-    int pending_jobs = g_list_length(backup_state.di_list);
++    PVEBackupDevInfo *di = opaque;
+-    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++    qemu_mutex_lock(&backup_state.backup_mutex);
+-    if (pending_jobs > 0) {
+-        pvebackup_co_run_next_job();
+-    } else {
+-        pvebackup_co_cleanup();
++    di->completed = true;
++
++    if (ret < 0) {
++        Error *local_err = NULL;
++        error_setg(&local_err, "job failed with err %d - %s", ret, strerror(-ret));
++        pvebackup_propagate_error(local_err);
+     }
+-}
+-static void pvebackup_complete_cb(void *opaque, int ret)
+-{
+-    // This can be called from the main loop, or from a coroutine
+-    PVEBackupCompeteCallbackData cb_data = {
+-        .di = opaque,
+-        .result = ret,
+-    };
++    di->bs = NULL;
+-    if (qemu_in_coroutine()) {
+-        pvebackup_co_complete_cb(&cb_data);
+-    } else {
+-        block_on_coroutine_fn(pvebackup_co_complete_cb, &cb_data);
+-    }
+-}
++    assert(di->target == NULL);
+-static void coroutine_fn pvebackup_co_cancel(void *opaque)
+-{
+-    assert(qemu_in_coroutine());
++    block_on_coroutine_fn(pvebackup_complete_stream, di);
+-    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
+-    backup_state.stat.cancel = true;
+-    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++    // remove self from job queue
++    backup_state.di_list = g_list_remove(backup_state.di_list, di);
+-    qemu_co_mutex_lock(&backup_state.backup_mutex);
++    g_free(di);
+-    // Avoid race between block jobs and backup-cancel command:
+-    if (!(backup_state.vmaw || backup_state.pbs)) {
+-        qemu_co_mutex_unlock(&backup_state.backup_mutex);
+-        return;
+-    }
++    qemu_mutex_unlock(&backup_state.backup_mutex);
+-    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
+-    if (!backup_state.stat.error) {
+-        qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
+-        error_setg(&backup_state.stat.error, "backup cancelled");
+-    }
+-    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++    pvebackup_run_next_job();
++}
++
++static void pvebackup_cancel(void)
++{
++    assert(!qemu_in_coroutine());
++
++    Error *cancel_err = NULL;
++    error_setg(&cancel_err, "backup canceled");
++    pvebackup_propagate_error(cancel_err);
++
++    qemu_mutex_lock(&backup_state.backup_mutex);
+     if (backup_state.vmaw) {
+         /* make sure vma writer does not block anymore */
+-        vma_writer_set_error(backup_state.vmaw, "backup cancelled");
++        vma_writer_set_error(backup_state.vmaw, "backup canceled");
+     }
+     if (backup_state.pbs) {
+-        proxmox_backup_abort(backup_state.pbs, "backup cancelled");
++        proxmox_backup_abort(backup_state.pbs, "backup canceled");
+     }
+-    bool running_jobs = 0;
+-    GList *l = backup_state.di_list;
+-    while (l) {
+-        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
+-        l = g_list_next(l);
+-        if (!di->completed && di->bs) {
+-            for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
+-                if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
+-                    continue;
+-                }
++    qemu_mutex_unlock(&backup_state.backup_mutex);
+-                BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
+-                if (bjob && bjob->source_bs == di->bs) {
+-                    AioContext *aio_context = job->job.aio_context;
+-                    aio_context_acquire(aio_context);
++    for(;;) {
+-                    if (!di->completed) {
+-                        running_jobs += 1;
+-                        job_cancel(&job->job, false);
+-                    }
+-                    aio_context_release(aio_context);
+-                }
++        BlockJob *next_job = NULL;
++
++        qemu_mutex_lock(&backup_state.backup_mutex);
++
++        GList *l = backup_state.di_list;
++        while (l) {
++            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++            l = g_list_next(l);
++
++            BlockJob *job = lookup_active_block_job(di);
++            if (job != NULL) {
++                next_job = job;
++                break;
+             }
+         }
+-    }
+-    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++        qemu_mutex_unlock(&backup_state.backup_mutex);
+-    if (running_jobs == 0) pvebackup_co_cleanup(); // else job will call completion handler
++        if (next_job) {
++            AioContext *aio_context = next_job->job.aio_context;
++            aio_context_acquire(aio_context);
++            job_cancel_sync(&next_job->job);
++            aio_context_release(aio_context);
++        } else {
++            break;
++        }
++    }
+ }
+ void qmp_backup_cancel(Error **errp)
+ {
+-    block_on_coroutine_fn(pvebackup_co_cancel, NULL);
++    pvebackup_cancel();
+ }
++// assumes the caller holds backup_mutex
+ static int coroutine_fn pvebackup_co_add_config(
+     const char *file,
+     const char *name,
+@@ -406,46 +419,97 @@ static int coroutine_fn pvebackup_co_add_config(
+ bool job_should_pause(Job *job);
+-static void coroutine_fn pvebackup_co_run_next_job(void)
++static void pvebackup_run_next_job(void)
+ {
+-    assert(qemu_in_coroutine());
++    assert(!qemu_in_coroutine());
+-    qemu_co_mutex_lock(&backup_state.backup_mutex);
++    qemu_mutex_lock(&backup_state.backup_mutex);
+     GList *l = backup_state.di_list;
+     while (l) {
+         PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
+         l = g_list_next(l);
+-        if (!di->completed && di->bs) {
+-            for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
+-                if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
+-                    continue;
+-                }
+-                BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
+-                if (bjob && bjob->source_bs == di->bs) {
+-                    AioContext *aio_context = job->job.aio_context;
+-                    qemu_co_mutex_unlock(&backup_state.backup_mutex);
+-                    aio_context_acquire(aio_context);
+-
+-                    if (job_should_pause(&job->job)) {
+-                        qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
+-                        bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
+-                        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-
+-                        if (error_or_canceled) {
+-                            job_cancel(&job->job, false);
+-                        } else {
+-                            job_resume(&job->job);
+-                        }
+-                    }
+-                    aio_context_release(aio_context);
+-                    return;
++        BlockJob *job = lookup_active_block_job(di);
++
++        if (job) {
++            qemu_mutex_unlock(&backup_state.backup_mutex);
++
++            AioContext *aio_context = job->job.aio_context;
++            aio_context_acquire(aio_context);
++
++            if (job_should_pause(&job->job)) {
++                bool error_or_canceled = pvebackup_error_or_canceled();
++                if (error_or_canceled) {
++                    job_cancel_sync(&job->job);
++                } else {
++                    job_resume(&job->job);
+                 }
+             }
++            aio_context_release(aio_context);
++            return;
++        }
++    }
++
++    block_on_coroutine_fn(pvebackup_co_cleanup, NULL); // no more jobs, run cleanup
++
++    qemu_mutex_unlock(&backup_state.backup_mutex);
++}
++
++static bool create_backup_jobs(void) {
++
++    assert(!qemu_in_coroutine());
++
++    Error *local_err = NULL;
++
++    /* create and start all jobs (paused state) */
++    GList *l =  backup_state.di_list;
++    while (l) {
++        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++        l = g_list_next(l);
++
++        assert(di->target != NULL);
++
++        AioContext *aio_context = bdrv_get_aio_context(di->bs);
++        aio_context_acquire(aio_context);
++
++        BlockJob *job = backup_job_create(
++            NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
++            BITMAP_SYNC_MODE_NEVER, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
++            JOB_DEFAULT, pvebackup_complete_cb, di, 1, NULL, &local_err);
++
++        aio_context_release(aio_context);
++
++        if (!job || local_err != NULL) {
++            Error *create_job_err = NULL;
++            error_setg(&create_job_err, "backup_job_create failed: %s",
++                       local_err ? error_get_pretty(local_err) : "null");
++
++            pvebackup_propagate_error(create_job_err);
++            break;
++        }
++        job_start(&job->job);
++
++        bdrv_unref(di->target);
++        di->target = NULL;
++    }
++
++    bool errors = pvebackup_error_or_canceled();
++
++    if (errors) {
++        l = backup_state.di_list;
++        while (l) {
++            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++            l = g_list_next(l);
++
++            if (di->target) {
++                bdrv_unref(di->target);
++                di->target = NULL;
++            }
+         }
+     }
+-    qemu_co_mutex_unlock(&backup_state.backup_mutex);
++
++    return errors;
+ }
+ typedef struct QmpBackupTask {
+@@ -476,7 +540,8 @@ typedef struct QmpBackupTask {
+     UuidInfo *result;
+ } QmpBackupTask;
+-static void coroutine_fn pvebackup_co_start(void *opaque)
++// assumes the caller holds backup_mutex
++static void coroutine_fn pvebackup_co_prepare(void *opaque)
+ {
+     assert(qemu_in_coroutine());
+@@ -495,16 +560,12 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
+     GList *di_list = NULL;
+     GList *l;
+     UuidInfo *uuid_info;
+-    BlockJob *job;
+     const char *config_name = "qemu-server.conf";
+     const char *firewall_name = "qemu-server.fw";
+-    qemu_co_mutex_lock(&backup_state.backup_mutex);
+-
+     if (backup_state.di_list) {
+-        qemu_co_mutex_unlock(&backup_state.backup_mutex);
+-        error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
++         error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
+                   "previous backup not finished");
+         return;
+     }
+@@ -631,7 +692,7 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
+             if (dev_id < 0)
+                 goto err;
+-            if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_cb, di, task->errp))) {
++            if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_pbs_cb, di, task->errp))) {
+                 goto err;
+             }
+@@ -652,7 +713,7 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
+             PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
+             l = g_list_next(l);
+-            if (!(di->target = bdrv_backup_dump_create(VMA_CLUSTER_SIZE, di->size, pvebackup_co_dump_cb, di, task->errp))) {
++            if (!(di->target = bdrv_backup_dump_create(VMA_CLUSTER_SIZE, di->size, pvebackup_co_dump_vma_cb, di, task->errp))) {
+                 goto err;
+             }
+@@ -717,9 +778,7 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
+     }
+     /* initialize global backup_state now */
+-    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
+-
+-    backup_state.stat.cancel = false;
++    qemu_mutex_lock(&backup_state.stat.lock);
+     if (backup_state.stat.error) {
+         error_free(backup_state.stat.error);
+@@ -742,7 +801,7 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
+     backup_state.stat.transferred = 0;
+     backup_state.stat.zero_bytes = 0;
+-    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
++    qemu_mutex_unlock(&backup_state.stat.lock);
+     backup_state.speed = (task->has_speed && task->speed > 0) ? task->speed : 0;
+@@ -751,48 +810,6 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
+     backup_state.di_list = di_list;
+-    /* start all jobs (paused state) */
+-    l = di_list;
+-    while (l) {
+-        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
+-        l = g_list_next(l);
+-
+-        // make sure target runs in same aoi_context as source
+-        AioContext *aio_context = bdrv_get_aio_context(di->bs);
+-        aio_context_acquire(aio_context);
+-        GSList *ignore = NULL;
+-        bdrv_set_aio_context_ignore(di->target, aio_context, &ignore);
+-        g_slist_free(ignore);
+-        aio_context_release(aio_context);
+-
+-        job = backup_job_create(NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
+-                                BITMAP_SYNC_MODE_NEVER, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
+-                                JOB_DEFAULT, pvebackup_complete_cb, di, 1, NULL, &local_err);
+-        if (!job || local_err != NULL) {
+-            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
+-            error_setg(&backup_state.stat.error, "backup_job_create failed");
+-            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-            break;
+-        }
+-        job_start(&job->job);
+-        if (di->target) {
+-            bdrv_unref(di->target);
+-            di->target = NULL;
+-        }
+-    }
+-
+-    qemu_co_mutex_unlock(&backup_state.backup_mutex);
+-
+-    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
+-    bool no_errors = !backup_state.stat.error;
+-    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-
+-    if (no_errors) {
+-        pvebackup_co_run_next_job(); // run one job
+-    } else {
+-        pvebackup_co_cancel(NULL);
+-    }
+-
+     uuid_info = g_malloc0(sizeof(*uuid_info));
+     uuid_info->UUID = uuid_str;
+@@ -835,8 +852,6 @@ err:
+         rmdir(backup_dir);
+     }
+-    qemu_co_mutex_unlock(&backup_state.backup_mutex);
+-
+     task->result = NULL;
+     return;
+ }
+@@ -880,32 +895,31 @@ UuidInfo *qmp_backup(
+         .errp = errp,
+     };
+-    block_on_coroutine_fn(pvebackup_co_start, &task);
++    qemu_mutex_lock(&backup_state.backup_mutex);
+-    return task.result;
+-}
++    block_on_coroutine_fn(pvebackup_co_prepare, &task);
++    if (*errp == NULL) {
++        create_backup_jobs();
++        qemu_mutex_unlock(&backup_state.backup_mutex);
++        pvebackup_run_next_job();
++    } else {
++        qemu_mutex_unlock(&backup_state.backup_mutex);
++    }
+-typedef struct QmpQueryBackupTask {
+-    Error **errp;
+-    BackupStatus *result;
+-} QmpQueryBackupTask;
++    return task.result;
++}
+-static void coroutine_fn pvebackup_co_query(void *opaque)
++BackupStatus *qmp_query_backup(Error **errp)
+ {
+-    assert(qemu_in_coroutine());
+-
+-    QmpQueryBackupTask *task = opaque;
+-
+     BackupStatus *info = g_malloc0(sizeof(*info));
+-    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
++    qemu_mutex_lock(&backup_state.stat.lock);
+     if (!backup_state.stat.start_time) {
+         /* not started, return {} */
+-        task->result = info;
+-        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-        return;
++        qemu_mutex_unlock(&backup_state.stat.lock);
++        return info;
+     }
+     info->has_status = true;
+@@ -941,19 +955,7 @@ static void coroutine_fn pvebackup_co_query(void *opaque)
+     info->has_transferred = true;
+     info->transferred = backup_state.stat.transferred;
+-    task->result = info;
++    qemu_mutex_unlock(&backup_state.stat.lock);
+-    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
+-}
+-
+-BackupStatus *qmp_query_backup(Error **errp)
+-{
+-    QmpQueryBackupTask task = {
+-        .errp = errp,
+-        .result = NULL,
+-    };
+-
+-    block_on_coroutine_fn(pvebackup_co_query, &task);
+-
+-    return task.result;
++    return info;
+ }
diff --git a/debian/patches/pve/0032-PVE-Backup-pbs-restore-new-command-to-restore-from-p.patch b/debian/patches/pve/0032-PVE-Backup-pbs-restore-new-command-to-restore-from-p.patch
deleted file mode 100644 (file)
index 2652bcf..0000000
+++ /dev/null
@@ -1,258 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Dietmar Maurer <dietmar@proxmox.com>
-Date: Mon, 6 Apr 2020 12:17:01 +0200
-Subject: [PATCH] PVE-Backup: pbs-restore - new command to restore from proxmox
- backup server
-
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- Makefile      |   4 +-
- pbs-restore.c | 217 ++++++++++++++++++++++++++++++++++++++++++++++++++
- 2 files changed, 220 insertions(+), 1 deletion(-)
- create mode 100644 pbs-restore.c
-
-diff --git a/Makefile b/Makefile
-index dbd9542ae4..7c1fb58e18 100644
---- a/Makefile
-+++ b/Makefile
-@@ -479,7 +479,7 @@ dummy := $(call unnest-vars,, \
- include $(SRC_PATH)/tests/Makefile.include
--all: $(DOCS) $(if $(BUILD_DOCS),sphinxdocs) $(TOOLS) vma$(EXESUF) $(HELPERS-y) recurse-all modules $(vhost-user-json-y)
-+all: $(DOCS) $(if $(BUILD_DOCS),sphinxdocs) $(TOOLS) vma$(EXESUF) pbs-restore$(EXESUF) $(HELPERS-y) recurse-all modules $(vhost-user-json-y)
- qemu-version.h: FORCE
-       $(call quiet-command, \
-@@ -610,6 +610,8 @@ qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-o
- qemu-storage-daemon$(EXESUF): qemu-storage-daemon.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(chardev-obj-y) $(io-obj-y) $(qom-obj-y) $(storage-daemon-obj-y) $(COMMON_LDADDS)
- qemu-storage-daemon$(EXESUF): LIBS += -lproxmox_backup_qemu
- vma$(EXESUF): vma.o vma-reader.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
-+pbs-restore$(EXESUF): pbs-restore.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS)
-+pbs-restore$(EXESUF): LIBS += -lproxmox_backup_qemu
- qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o $(COMMON_LDADDS)
-diff --git a/pbs-restore.c b/pbs-restore.c
-new file mode 100644
-index 0000000000..4bf37ef1fa
---- /dev/null
-+++ b/pbs-restore.c
-@@ -0,0 +1,217 @@
-+/*
-+ * Qemu image restore helper for Proxmox Backup
-+ *
-+ * Copyright (C) 2019 Proxmox Server Solutions
-+ *
-+ * Authors:
-+ *  Dietmar Maurer (dietmar@proxmox.com)
-+ *
-+ * This work is licensed under the terms of the GNU GPL, version 2 or later.
-+ * See the COPYING file in the top-level directory.
-+ *
-+ */
-+
-+#include "qemu/osdep.h"
-+#include <glib.h>
-+#include <getopt.h>
-+#include <string.h>
-+
-+#include "qemu-common.h"
-+#include "qemu/module.h"
-+#include "qemu/error-report.h"
-+#include "qemu/main-loop.h"
-+#include "qemu/cutils.h"
-+#include "qapi/error.h"
-+#include "qapi/qmp/qdict.h"
-+#include "sysemu/block-backend.h"
-+
-+#include <proxmox-backup-qemu.h>
-+
-+static void help(void)
-+{
-+    const char *help_msg =
-+        "usage: pbs-restore [--repository <repo>] snapshot archive-name target [command options]\n"
-+        ;
-+
-+    printf("%s", help_msg);
-+    exit(1);
-+}
-+
-+typedef struct CallbackData {
-+    BlockBackend *target;
-+    uint64_t last_offset;
-+    bool skip_zero;
-+} CallbackData;
-+
-+static int write_callback(
-+    void *callback_data_ptr,
-+    uint64_t offset,
-+    const unsigned char *data,
-+    uint64_t data_len)
-+{
-+    int res = -1;
-+
-+    CallbackData *callback_data = (CallbackData *)callback_data_ptr;
-+
-+    uint64_t last_offset = callback_data->last_offset;
-+    if (offset > last_offset) callback_data->last_offset = offset;
-+
-+    if (data == NULL) {
-+        if (callback_data->skip_zero && offset > last_offset) {
-+            return 0;
-+        }
-+        res = blk_pwrite_zeroes(callback_data->target, offset, data_len, 0);
-+    } else {
-+        res = blk_pwrite(callback_data->target, offset, data, data_len, 0);
-+    }
-+
-+    if (res < 0) {
-+        fprintf(stderr, "blk_pwrite failed at offset %ld length %ld (%d) - %s\n", offset, data_len, res, strerror(-res));
-+        return res;
-+    }
-+
-+    return 0;
-+}
-+
-+int main(int argc, char **argv)
-+{
-+    Error *main_loop_err = NULL;
-+    const char *format = "raw";
-+    const char *repository = NULL;
-+    const char *keyfile = NULL;
-+    int verbose = false;
-+    bool skip_zero = false;
-+
-+    error_init(argv[0]);
-+
-+    for (;;) {
-+        static const struct option long_options[] = {
-+            {"help", no_argument, 0, 'h'},
-+            {"skip-zero", no_argument, 0, 'S'},
-+            {"verbose", no_argument, 0, 'v'},
-+            {"format", required_argument, 0, 'f'},
-+            {"repository", required_argument, 0, 'r'},
-+            {"keyfile", required_argument, 0, 'k'},
-+            {0, 0, 0, 0}
-+        };
-+        int c = getopt_long(argc, argv, "hvf:r:k:", long_options, NULL);
-+        if (c == -1) {
-+            break;
-+        }
-+        switch (c) {
-+            case ':':
-+                fprintf(stderr, "missing argument for option '%s'\n", argv[optind - 1]);
-+                return -1;
-+            case '?':
-+                fprintf(stderr, "unrecognized option '%s'\n", argv[optind - 1]);
-+                return -1;
-+            case 'f':
-+                format = g_strdup(argv[optind - 1]);
-+                break;
-+            case 'r':
-+                repository = g_strdup(argv[optind - 1]);
-+                break;
-+            case 'k':
-+                keyfile = g_strdup(argv[optind - 1]);
-+                break;
-+            case 'v':
-+                verbose = true;
-+                break;
-+            case 'S':
-+                skip_zero = true;
-+                break;
-+            case 'h':
-+                help();
-+                return 0;
-+        }
-+    }
-+
-+    if (optind >= argc - 2) {
-+        fprintf(stderr, "missing arguments\n");
-+        help();
-+        return -1;
-+    }
-+
-+    if (repository == NULL) {
-+        repository = getenv("PBS_REPOSITORY");
-+    }
-+
-+    if (repository == NULL) {
-+        fprintf(stderr, "no repository specified\n");
-+        help();
-+        return -1;
-+    }
-+
-+    char *snapshot = argv[optind++];
-+    char *archive_name = argv[optind++];
-+    char *target = argv[optind++];
-+
-+    const char *password = getenv("PBS_PASSWORD");
-+    const char *fingerprint = getenv("PBS_FINGERPRINT");
-+    const char *key_password = getenv("PBS_ENCRYPTION_PASSWORD");
-+
-+    if (qemu_init_main_loop(&main_loop_err)) {
-+        g_error("%s", error_get_pretty(main_loop_err));
-+    }
-+
-+    bdrv_init();
-+    module_call_init(MODULE_INIT_QOM);
-+
-+    if (verbose) {
-+        fprintf(stderr, "connecting to repository '%s'\n", repository);
-+    }
-+    char *pbs_error = NULL;
-+    ProxmoxRestoreHandle *conn = proxmox_restore_connect(
-+        repository, snapshot, password, keyfile, key_password, fingerprint, &pbs_error);
-+    if (conn == NULL) {
-+        fprintf(stderr, "restore failed: %s\n", pbs_error);
-+        return -1;
-+    }
-+
-+    QDict *options = qdict_new();
-+
-+    if (format) {
-+        qdict_put_str(options, "driver", format);
-+    }
-+
-+
-+    if (verbose) {
-+        fprintf(stderr, "open block backend for target '%s'\n", target);
-+    }
-+    Error *local_err = NULL;
-+    int flags = BDRV_O_RDWR;
-+    BlockBackend *blk = blk_new_open(target, NULL, options, flags, &local_err);
-+    if (!blk) {
-+        fprintf(stderr, "%s\n", error_get_pretty(local_err));
-+        return -1;
-+    }
-+
-+    CallbackData *callback_data = calloc(sizeof(CallbackData), 1);
-+
-+    callback_data->target = blk;
-+    callback_data->skip_zero = skip_zero;
-+    callback_data->last_offset = 0;
-+
-+    // blk_set_enable_write_cache(blk, !writethrough);
-+
-+    if (verbose) {
-+        fprintf(stderr, "starting to restore snapshot '%s'\n", snapshot);
-+        fflush(stderr); // ensure we do not get printed after the progress log
-+    }
-+    int res = proxmox_restore_image(
-+        conn,
-+        archive_name,
-+        write_callback,
-+        callback_data,
-+        &pbs_error,
-+        verbose);
-+
-+    proxmox_restore_disconnect(conn);
-+
-+    if (res < 0) {
-+        fprintf(stderr, "restore failed: %s\n", pbs_error);
-+        return -1;
-+    }
-+
-+    return 0;
-+}
diff --git a/debian/patches/pve/0032-drive-mirror-add-support-for-sync-bitmap-mode-never.patch b/debian/patches/pve/0032-drive-mirror-add-support-for-sync-bitmap-mode-never.patch
new file mode 100644 (file)
index 0000000..7cd4d76
--- /dev/null
@@ -0,0 +1,439 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: John Snow <jsnow@redhat.com>
+Date: Mon, 6 Apr 2020 12:17:03 +0200
+Subject: [PATCH] drive-mirror: add support for sync=bitmap mode=never
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+This patch adds support for the "BITMAP" sync mode to drive-mirror and
+blockdev-mirror. It adds support only for the BitmapSyncMode "never,"
+because it's the simplest mode.
+
+This mode simply uses a user-provided bitmap as an initial copy
+manifest, and then does not clear any bits in the bitmap at the
+conclusion of the operation.
+
+Any new writes dirtied during the operation are copied out, in contrast
+to backup. Note that whether these writes are reflected in the bitmap
+at the conclusion of the operation depends on whether that bitmap is
+actually recording!
+
+This patch was originally based on one by Ma Haocong, but it has since
+been modified pretty heavily.
+
+Suggested-by: Ma Haocong <mahaocong@didichuxing.com>
+Signed-off-by: Ma Haocong <mahaocong@didichuxing.com>
+Signed-off-by: John Snow <jsnow@redhat.com>
+Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
+---
+ block/mirror.c              | 98 ++++++++++++++++++++++++++++++-------
+ blockdev.c                  | 39 +++++++++++++--
+ include/block/block_int.h   |  4 +-
+ qapi/block-core.json        | 29 +++++++++--
+ tests/test-block-iothread.c |  4 +-
+ 5 files changed, 145 insertions(+), 29 deletions(-)
+
+diff --git a/block/mirror.c b/block/mirror.c
+index c26fd9260d..3c9cd42c50 100644
+--- a/block/mirror.c
++++ b/block/mirror.c
+@@ -49,7 +49,7 @@ typedef struct MirrorBlockJob {
+     BlockDriverState *to_replace;
+     /* Used to block operations on the drive-mirror-replace target */
+     Error *replace_blocker;
+-    bool is_none_mode;
++    MirrorSyncMode sync_mode;
+     BlockMirrorBackingMode backing_mode;
+     /* Whether the target image requires explicit zero-initialization */
+     bool zero_target;
+@@ -64,6 +64,8 @@ typedef struct MirrorBlockJob {
+     size_t buf_size;
+     int64_t bdev_length;
+     unsigned long *cow_bitmap;
++    BdrvDirtyBitmap *sync_bitmap;
++    BitmapSyncMode bitmap_mode;
+     BdrvDirtyBitmap *dirty_bitmap;
+     BdrvDirtyBitmapIter *dbi;
+     uint8_t *buf;
+@@ -676,7 +678,8 @@ static int mirror_exit_common(Job *job)
+     bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
+                              &error_abort);
+     if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
+-        BlockDriverState *backing = s->is_none_mode ? src : s->base;
++        BlockDriverState *backing;
++        backing = s->sync_mode == MIRROR_SYNC_MODE_NONE ? src : s->base;
+         if (backing_bs(target_bs) != backing) {
+             bdrv_set_backing_hd(target_bs, backing, &local_err);
+             if (local_err) {
+@@ -771,6 +774,16 @@ static void mirror_abort(Job *job)
+     assert(ret == 0);
+ }
++/* Always called after commit/abort. */
++static void mirror_clean(Job *job)
++{
++    MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
++
++    if (s->sync_bitmap) {
++        bdrv_dirty_bitmap_set_busy(s->sync_bitmap, false);
++    }
++}
++
+ static void coroutine_fn mirror_throttle(MirrorBlockJob *s)
+ {
+     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
+@@ -949,7 +962,8 @@ static int coroutine_fn mirror_run(Job *job, Error **errp)
+     mirror_free_init(s);
+     s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
+-    if (!s->is_none_mode) {
++    if ((s->sync_mode == MIRROR_SYNC_MODE_TOP) ||
++        (s->sync_mode == MIRROR_SYNC_MODE_FULL)) {
+         ret = mirror_dirty_init(s);
+         if (ret < 0 || job_is_cancelled(&s->common.job)) {
+             goto immediate_exit;
+@@ -1181,6 +1195,7 @@ static const BlockJobDriver mirror_job_driver = {
+         .run                    = mirror_run,
+         .prepare                = mirror_prepare,
+         .abort                  = mirror_abort,
++        .clean                  = mirror_clean,
+         .pause                  = mirror_pause,
+         .complete               = mirror_complete,
+     },
+@@ -1196,6 +1211,7 @@ static const BlockJobDriver commit_active_job_driver = {
+         .run                    = mirror_run,
+         .prepare                = mirror_prepare,
+         .abort                  = mirror_abort,
++        .clean                  = mirror_clean,
+         .pause                  = mirror_pause,
+         .complete               = mirror_complete,
+     },
+@@ -1542,7 +1558,10 @@ static BlockJob *mirror_start_job(
+                              BlockCompletionFunc *cb,
+                              void *opaque,
+                              const BlockJobDriver *driver,
+-                             bool is_none_mode, BlockDriverState *base,
++                             MirrorSyncMode sync_mode,
++                             BdrvDirtyBitmap *bitmap,
++                             BitmapSyncMode bitmap_mode,
++                             BlockDriverState *base,
+                              bool auto_complete, const char *filter_node_name,
+                              bool is_mirror, MirrorCopyMode copy_mode,
+                              Error **errp)
+@@ -1555,10 +1574,39 @@ static BlockJob *mirror_start_job(
+     Error *local_err = NULL;
+     int ret;
+-    if (granularity == 0) {
+-        granularity = bdrv_get_default_bitmap_granularity(target);
++    if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
++        error_setg(errp, "Sync mode '%s' not supported",
++                   MirrorSyncMode_str(sync_mode));
++        return NULL;
++    } else if (sync_mode == MIRROR_SYNC_MODE_BITMAP) {
++        if (!bitmap) {
++            error_setg(errp, "Must provide a valid bitmap name for '%s'"
++                       " sync mode",
++                       MirrorSyncMode_str(sync_mode));
++            return NULL;
++        } else if (bitmap_mode != BITMAP_SYNC_MODE_NEVER) {
++            error_setg(errp,
++                       "Bitmap Sync Mode '%s' is not supported by Mirror",
++                       BitmapSyncMode_str(bitmap_mode));
++        }
++    } else if (bitmap) {
++        error_setg(errp,
++                   "sync mode '%s' is not compatible with bitmaps",
++                   MirrorSyncMode_str(sync_mode));
++        return NULL;
+     }
++    if (bitmap) {
++        if (granularity) {
++            error_setg(errp, "granularity (%d)"
++                       "cannot be specified when a bitmap is provided",
++                       granularity);
++            return NULL;
++        }
++        granularity = bdrv_dirty_bitmap_granularity(bitmap);
++    } else if (granularity == 0) {
++        granularity = bdrv_get_default_bitmap_granularity(target);
++    }
+     assert(is_power_of_2(granularity));
+     if (buf_size < 0) {
+@@ -1662,7 +1710,9 @@ static BlockJob *mirror_start_job(
+     s->replaces = g_strdup(replaces);
+     s->on_source_error = on_source_error;
+     s->on_target_error = on_target_error;
+-    s->is_none_mode = is_none_mode;
++    s->sync_mode = sync_mode;
++    s->sync_bitmap = bitmap;
++    s->bitmap_mode = bitmap_mode;
+     s->backing_mode = backing_mode;
+     s->zero_target = zero_target;
+     s->copy_mode = copy_mode;
+@@ -1682,6 +1732,18 @@ static BlockJob *mirror_start_job(
+         bdrv_disable_dirty_bitmap(s->dirty_bitmap);
+     }
++    if (s->sync_bitmap) {
++        bdrv_dirty_bitmap_set_busy(s->sync_bitmap, true);
++    }
++
++    if (s->sync_mode == MIRROR_SYNC_MODE_BITMAP) {
++        bdrv_merge_dirty_bitmap(s->dirty_bitmap, s->sync_bitmap,
++                                NULL, &local_err);
++        if (local_err) {
++            goto fail;
++        }
++    }
++
+     ret = block_job_add_bdrv(&s->common, "source", bs, 0,
+                              BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE |
+                              BLK_PERM_CONSISTENT_READ,
+@@ -1735,6 +1797,9 @@ fail:
+         if (s->dirty_bitmap) {
+             bdrv_release_dirty_bitmap(s->dirty_bitmap);
+         }
++        if (s->sync_bitmap) {
++            bdrv_dirty_bitmap_set_busy(s->sync_bitmap, false);
++        }
+         job_early_fail(&s->common.job);
+     }
+@@ -1752,29 +1817,23 @@ void mirror_start(const char *job_id, BlockDriverState *bs,
+                   BlockDriverState *target, const char *replaces,
+                   int creation_flags, int64_t speed,
+                   uint32_t granularity, int64_t buf_size,
+-                  MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
++                  MirrorSyncMode mode, BdrvDirtyBitmap *bitmap,
++                  BitmapSyncMode bitmap_mode,
++                  BlockMirrorBackingMode backing_mode,
+                   bool zero_target,
+                   BlockdevOnError on_source_error,
+                   BlockdevOnError on_target_error,
+                   bool unmap, const char *filter_node_name,
+                   MirrorCopyMode copy_mode, Error **errp)
+ {
+-    bool is_none_mode;
+     BlockDriverState *base;
+-    if ((mode == MIRROR_SYNC_MODE_INCREMENTAL) ||
+-        (mode == MIRROR_SYNC_MODE_BITMAP)) {
+-        error_setg(errp, "Sync mode '%s' not supported",
+-                   MirrorSyncMode_str(mode));
+-        return;
+-    }
+-    is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
+     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
+     mirror_start_job(job_id, bs, creation_flags, target, replaces,
+                      speed, granularity, buf_size, backing_mode, zero_target,
+                      on_source_error, on_target_error, unmap, NULL, NULL,
+-                     &mirror_job_driver, is_none_mode, base, false,
+-                     filter_node_name, true, copy_mode, errp);
++                     &mirror_job_driver, mode, bitmap, bitmap_mode, base,
++                     false, filter_node_name, true, copy_mode, errp);
+ }
+ BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
+@@ -1800,7 +1859,8 @@ BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
+                      job_id, bs, creation_flags, base, NULL, speed, 0, 0,
+                      MIRROR_LEAVE_BACKING_CHAIN, false,
+                      on_error, on_error, true, cb, opaque,
+-                     &commit_active_job_driver, false, base, auto_complete,
++                     &commit_active_job_driver, MIRROR_SYNC_MODE_FULL,
++                     NULL, 0, base, auto_complete,
+                      filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
+                      &local_err);
+     if (local_err) {
+diff --git a/blockdev.c b/blockdev.c
+index f391c3b3c7..bbeff9c439 100644
+--- a/blockdev.c
++++ b/blockdev.c
+@@ -3159,6 +3159,10 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
+                                    BlockDriverState *target,
+                                    bool has_replaces, const char *replaces,
+                                    enum MirrorSyncMode sync,
++                                   bool has_bitmap,
++                                   const char *bitmap_name,
++                                   bool has_bitmap_mode,
++                                   BitmapSyncMode bitmap_mode,
+                                    BlockMirrorBackingMode backing_mode,
+                                    bool zero_target,
+                                    bool has_speed, int64_t speed,
+@@ -3177,6 +3181,7 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
+                                    Error **errp)
+ {
+     int job_flags = JOB_DEFAULT;
++    BdrvDirtyBitmap *bitmap = NULL;
+     if (!has_speed) {
+         speed = 0;
+@@ -3231,6 +3236,29 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
+         sync = MIRROR_SYNC_MODE_FULL;
+     }
++    if (has_bitmap) {
++        if (granularity) {
++            error_setg(errp, "Granularity and bitmap cannot both be set");
++            return;
++        }
++
++        if (!has_bitmap_mode) {
++            error_setg(errp, "bitmap-mode must be specified if"
++                       " a bitmap is provided");
++            return;
++        }
++
++        bitmap = bdrv_find_dirty_bitmap(bs, bitmap_name);
++        if (!bitmap) {
++            error_setg(errp, "Dirty bitmap '%s' not found", bitmap_name);
++            return;
++        }
++
++        if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
++            return;
++        }
++    }
++
+     if (has_replaces) {
+         BlockDriverState *to_replace_bs;
+         AioContext *replace_aio_context;
+@@ -3268,8 +3296,8 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
+      * and will allow to check whether the node still exist at mirror completion
+      */
+     mirror_start(job_id, bs, target,
+-                 has_replaces ? replaces : NULL, job_flags,
+-                 speed, granularity, buf_size, sync, backing_mode, zero_target,
++                 has_replaces ? replaces : NULL, job_flags, speed, granularity,
++                 buf_size, sync, bitmap, bitmap_mode, backing_mode, zero_target,
+                  on_source_error, on_target_error, unmap, filter_node_name,
+                  copy_mode, errp);
+ }
+@@ -3410,6 +3438,8 @@ void qmp_drive_mirror(DriveMirror *arg, Error **errp)
+     blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
+                            arg->has_replaces, arg->replaces, arg->sync,
++                           arg->has_bitmap, arg->bitmap,
++                           arg->has_bitmap_mode, arg->bitmap_mode,
+                            backing_mode, zero_target,
+                            arg->has_speed, arg->speed,
+                            arg->has_granularity, arg->granularity,
+@@ -3432,6 +3462,8 @@ void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
+                          const char *device, const char *target,
+                          bool has_replaces, const char *replaces,
+                          MirrorSyncMode sync,
++                         bool has_bitmap, const char *bitmap,
++                         bool has_bitmap_mode, BitmapSyncMode bitmap_mode,
+                          bool has_speed, int64_t speed,
+                          bool has_granularity, uint32_t granularity,
+                          bool has_buf_size, int64_t buf_size,
+@@ -3482,7 +3514,8 @@ void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
+     }
+     blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
+-                           has_replaces, replaces, sync, backing_mode,
++                           has_replaces, replaces, sync, has_bitmap,
++                           bitmap, has_bitmap_mode, bitmap_mode, backing_mode,
+                            zero_target, has_speed, speed,
+                            has_granularity, granularity,
+                            has_buf_size, buf_size,
+diff --git a/include/block/block_int.h b/include/block/block_int.h
+index 6d234f1de9..180a5e00fd 100644
+--- a/include/block/block_int.h
++++ b/include/block/block_int.h
+@@ -1210,7 +1210,9 @@ void mirror_start(const char *job_id, BlockDriverState *bs,
+                   BlockDriverState *target, const char *replaces,
+                   int creation_flags, int64_t speed,
+                   uint32_t granularity, int64_t buf_size,
+-                  MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
++                  MirrorSyncMode mode, BdrvDirtyBitmap *bitmap,
++                  BitmapSyncMode bitmap_mode,
++                  BlockMirrorBackingMode backing_mode,
+                   bool zero_target,
+                   BlockdevOnError on_source_error,
+                   BlockdevOnError on_target_error,
+diff --git a/qapi/block-core.json b/qapi/block-core.json
+index 97d1f64636..8bdbccb397 100644
+--- a/qapi/block-core.json
++++ b/qapi/block-core.json
+@@ -2054,10 +2054,19 @@
+ #        (all the disk, only the sectors allocated in the topmost image, or
+ #        only new I/O).
+ #
++# @bitmap: The name of a bitmap to use for sync=bitmap mode. This argument must
++#          be present for bitmap mode and absent otherwise. The bitmap's
++#          granularity is used instead of @granularity (since 4.1).
++#
++# @bitmap-mode: Specifies the type of data the bitmap should contain after
++#               the operation concludes. Must be present if sync is "bitmap".
++#               Must NOT be present otherwise. (Since 4.1)
++#
+ # @granularity: granularity of the dirty bitmap, default is 64K
+ #               if the image format doesn't have clusters, 4K if the clusters
+ #               are smaller than that, else the cluster size.  Must be a
+-#               power of 2 between 512 and 64M (since 1.4).
++#               power of 2 between 512 and 64M. Must not be specified if
++#               @bitmap is present (since 1.4).
+ #
+ # @buf-size: maximum amount of data in flight from source to
+ #            target (since 1.4).
+@@ -2095,7 +2104,9 @@
+ { 'struct': 'DriveMirror',
+   'data': { '*job-id': 'str', 'device': 'str', 'target': 'str',
+             '*format': 'str', '*node-name': 'str', '*replaces': 'str',
+-            'sync': 'MirrorSyncMode', '*mode': 'NewImageMode',
++            'sync': 'MirrorSyncMode', '*bitmap': 'str',
++            '*bitmap-mode': 'BitmapSyncMode',
++            '*mode': 'NewImageMode',
+             '*speed': 'int', '*granularity': 'uint32',
+             '*buf-size': 'int', '*on-source-error': 'BlockdevOnError',
+             '*on-target-error': 'BlockdevOnError',
+@@ -2362,10 +2373,19 @@
+ #        (all the disk, only the sectors allocated in the topmost image, or
+ #        only new I/O).
+ #
++# @bitmap: The name of a bitmap to use for sync=bitmap mode. This argument must
++#          be present for bitmap mode and absent otherwise. The bitmap's
++#          granularity is used instead of @granularity (since 4.1).
++#
++# @bitmap-mode: Specifies the type of data the bitmap should contain after
++#               the operation concludes. Must be present if sync is "bitmap".
++#               Must NOT be present otherwise. (Since 4.1)
++#
+ # @granularity: granularity of the dirty bitmap, default is 64K
+ #               if the image format doesn't have clusters, 4K if the clusters
+ #               are smaller than that, else the cluster size.  Must be a
+-#               power of 2 between 512 and 64M
++#               power of 2 between 512 and 64M . Must not be specified if
++#               @bitmap is present.
+ #
+ # @buf-size: maximum amount of data in flight from source to
+ #            target
+@@ -2414,7 +2434,8 @@
+ { 'command': 'blockdev-mirror',
+   'data': { '*job-id': 'str', 'device': 'str', 'target': 'str',
+             '*replaces': 'str',
+-            'sync': 'MirrorSyncMode',
++            'sync': 'MirrorSyncMode', '*bitmap': 'str',
++            '*bitmap-mode': 'BitmapSyncMode',
+             '*speed': 'int', '*granularity': 'uint32',
+             '*buf-size': 'int', '*on-source-error': 'BlockdevOnError',
+             '*on-target-error': 'BlockdevOnError',
+diff --git a/tests/test-block-iothread.c b/tests/test-block-iothread.c
+index 0c861809f0..da87a67a57 100644
+--- a/tests/test-block-iothread.c
++++ b/tests/test-block-iothread.c
+@@ -611,8 +611,8 @@ static void test_propagate_mirror(void)
+     /* Start a mirror job */
+     mirror_start("job0", src, target, NULL, JOB_DEFAULT, 0, 0, 0,
+-                 MIRROR_SYNC_MODE_NONE, MIRROR_OPEN_BACKING_CHAIN, false,
+-                 BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
++                 MIRROR_SYNC_MODE_NONE, NULL, 0, MIRROR_OPEN_BACKING_CHAIN,
++                 false, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
+                  false, "filter_node", MIRROR_COPY_MODE_BACKGROUND,
+                  &error_abort);
+     job = job_get("job0");
diff --git a/debian/patches/pve/0033-PVE-Backup-avoid-coroutines-to-fix-AIO-freeze-cleanu.patch b/debian/patches/pve/0033-PVE-Backup-avoid-coroutines-to-fix-AIO-freeze-cleanu.patch
deleted file mode 100644 (file)
index 9ebf8f2..0000000
+++ /dev/null
@@ -1,884 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Dietmar Maurer <dietmar@proxmox.com>
-Date: Mon, 6 Apr 2020 12:17:02 +0200
-Subject: [PATCH] PVE-Backup: avoid coroutines to fix AIO freeze, cleanups
-
-We observed various AIO pool loop freezes, so we decided to avoid
-coroutines and restrict ourselfes using similar code as upstream
-(see blockdev.c: do_backup_common).
-
-* avoid coroutine for job related code (causes hangs with iothreads)
-    - this imply to use normal QemuRecMutex instead of CoMutex
-
-* split pvebackup_co_dump_cb into:
-    - pvebackup_co_dump_pbs_cb and
-    - pvebackup_co_dump_pbs_cb
-
-* new helper functions
-    - pvebackup_propagate_error
-    - pvebackup_error_or_canceled
-    - pvebackup_add_transfered_bytes
-
-* avoid cancel flag (not needed)
-
-* simplify backup_cancel logic
-
-There is progress on upstream to support running qmp commands inside
-coroutines, see:
-
-https://lists.gnu.org/archive/html/qemu-devel/2020-02/msg04852.html
-
-We should consider using that when it is available in upstream qemu.
----
- pve-backup.c | 611 +++++++++++++++++++++++++--------------------------
- 1 file changed, 299 insertions(+), 312 deletions(-)
-
-diff --git a/pve-backup.c b/pve-backup.c
-index 38dd33e28b..169f0c68d0 100644
---- a/pve-backup.c
-+++ b/pve-backup.c
-@@ -11,11 +11,10 @@
- /* PVE backup state and related function */
--
- static struct PVEBackupState {
-     struct {
--        // Everithing accessed from qmp command, protected using rwlock
--        CoRwlock rwlock;
-+        // Everithing accessed from qmp_backup_query command is protected using lock
-+        QemuRecMutex lock;
-         Error *error;
-         time_t start_time;
-         time_t end_time;
-@@ -25,19 +24,18 @@ static struct PVEBackupState {
-         size_t total;
-         size_t transferred;
-         size_t zero_bytes;
--        bool cancel;
-     } stat;
-     int64_t speed;
-     VmaWriter *vmaw;
-     ProxmoxBackupHandle *pbs;
-     GList *di_list;
--    CoMutex backup_mutex;
-+    QemuRecMutex backup_mutex;
- } backup_state;
- static void pvebackup_init(void)
- {
--    qemu_co_rwlock_init(&backup_state.stat.rwlock);
--    qemu_co_mutex_init(&backup_state.backup_mutex);
-+    qemu_rec_mutex_init(&backup_state.stat.lock);
-+    qemu_rec_mutex_init(&backup_state.backup_mutex);
- }
- // initialize PVEBackupState at startup
-@@ -52,10 +50,54 @@ typedef struct PVEBackupDevInfo {
-     BlockDriverState *target;
- } PVEBackupDevInfo;
--static void pvebackup_co_run_next_job(void);
-+static void pvebackup_run_next_job(void);
-+
-+static BlockJob *
-+lookup_active_block_job(PVEBackupDevInfo *di)
-+{
-+    if (!di->completed && di->bs) {
-+        for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
-+            if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
-+                continue;
-+            }
-+
-+            BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
-+            if (bjob && bjob->source_bs == di->bs) {
-+                return job;
-+            }
-+        }
-+    }
-+    return NULL;
-+}
-+
-+static void pvebackup_propagate_error(Error *err)
-+{
-+    qemu_rec_mutex_lock(&backup_state.stat.lock);
-+    error_propagate(&backup_state.stat.error, err);
-+    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+}
-+
-+static bool pvebackup_error_or_canceled(void)
-+{
-+    qemu_rec_mutex_lock(&backup_state.stat.lock);
-+    bool error_or_canceled = !!backup_state.stat.error;
-+    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+
-+    return error_or_canceled;
-+}
-+static void pvebackup_add_transfered_bytes(size_t transferred, size_t zero_bytes)
-+{
-+    qemu_rec_mutex_lock(&backup_state.stat.lock);
-+    backup_state.stat.zero_bytes += zero_bytes;
-+    backup_state.stat.transferred += transferred;
-+    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+}
-+
-+// This may get called from multiple coroutines in multiple io-threads
-+// Note1: this may get called after job_cancel()
- static int coroutine_fn
--pvebackup_co_dump_cb(
-+pvebackup_co_dump_pbs_cb(
-     void *opaque,
-     uint64_t start,
-     uint64_t bytes,
-@@ -67,137 +109,129 @@ pvebackup_co_dump_cb(
-     const unsigned char *buf = pbuf;
-     PVEBackupDevInfo *di = opaque;
--    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
--    bool cancel = backup_state.stat.cancel;
--    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+    assert(backup_state.pbs);
-+
-+    Error *local_err = NULL;
-+    int pbs_res = -1;
-+
-+    qemu_rec_mutex_lock(&backup_state.backup_mutex);
--    if (cancel) {
--        return size; // return success
-+    // avoid deadlock if job is cancelled
-+    if (pvebackup_error_or_canceled()) {
-+        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+        return -1;
-     }
--    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+    pbs_res = proxmox_backup_co_write_data(backup_state.pbs, di->dev_id, buf, start, size, &local_err);
-+    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
--    int ret = -1;
-+    if (pbs_res < 0) {
-+        pvebackup_propagate_error(local_err);
-+        return pbs_res;
-+    } else {
-+        pvebackup_add_transfered_bytes(size, !buf ? size : 0);
-+    }
--    if (backup_state.vmaw) {
--        size_t zero_bytes = 0;
--        uint64_t remaining = size;
--
--        uint64_t cluster_num = start / VMA_CLUSTER_SIZE;
--        if ((cluster_num * VMA_CLUSTER_SIZE) != start) {
--            qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
--            if (!backup_state.stat.error) {
--                qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
--                error_setg(&backup_state.stat.error,
--                           "got unaligned write inside backup dump "
--                           "callback (sector %ld)", start);
--            }
--            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--            qemu_co_mutex_unlock(&backup_state.backup_mutex);
--            return -1; // not aligned to cluster size
--        }
-+    return size;
-+}
--        while (remaining > 0) {
--            ret = vma_writer_write(backup_state.vmaw, di->dev_id, cluster_num,
--                                   buf, &zero_bytes);
--            ++cluster_num;
--            if (buf) {
--                buf += VMA_CLUSTER_SIZE;
--            }
--            if (ret < 0) {
--                qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
--                if (!backup_state.stat.error) {
--                    qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
--                    vma_writer_error_propagate(backup_state.vmaw, &backup_state.stat.error);
--                }
--                qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+// This may get called from multiple coroutines in multiple io-threads
-+static int coroutine_fn
-+pvebackup_co_dump_vma_cb(
-+    void *opaque,
-+    uint64_t start,
-+    uint64_t bytes,
-+    const void *pbuf)
-+{
-+    assert(qemu_in_coroutine());
--                qemu_co_mutex_unlock(&backup_state.backup_mutex);
--                return ret;
--            } else {
--                qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
--                backup_state.stat.zero_bytes += zero_bytes;
--                if (remaining >= VMA_CLUSTER_SIZE) {
--                    backup_state.stat.transferred += VMA_CLUSTER_SIZE;
--                    remaining -= VMA_CLUSTER_SIZE;
--                } else {
--                    backup_state.stat.transferred += remaining;
--                    remaining = 0;
--                }
--                qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--            }
--        }
--    } else if (backup_state.pbs) {
--        Error *local_err = NULL;
--        int pbs_res = -1;
-+    const uint64_t size = bytes;
-+    const unsigned char *buf = pbuf;
-+    PVEBackupDevInfo *di = opaque;
--        pbs_res = proxmox_backup_co_write_data(backup_state.pbs, di->dev_id, buf, start, size, &local_err);
--        qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+    int ret = -1;
--        if (pbs_res < 0) {
--            error_propagate(&backup_state.stat.error, local_err);
--            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--            qemu_co_mutex_unlock(&backup_state.backup_mutex);
--            return pbs_res;
--        } else {
--            if (!buf) {
--                backup_state.stat.zero_bytes += size;
--            }
--            backup_state.stat.transferred += size;
-+    assert(backup_state.vmaw);
-+
-+    uint64_t remaining = size;
-+
-+    uint64_t cluster_num = start / VMA_CLUSTER_SIZE;
-+    if ((cluster_num * VMA_CLUSTER_SIZE) != start) {
-+        Error *local_err = NULL;
-+        error_setg(&local_err,
-+                   "got unaligned write inside backup dump "
-+                   "callback (sector %ld)", start);
-+        pvebackup_propagate_error(local_err);
-+        return -1; // not aligned to cluster size
-+    }
-+
-+    while (remaining > 0) {
-+        qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+        // avoid deadlock if job is cancelled
-+        if (pvebackup_error_or_canceled()) {
-+            qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+            return -1;
-         }
--        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+        size_t zero_bytes = 0;
-+        ret = vma_writer_write(backup_state.vmaw, di->dev_id, cluster_num, buf, &zero_bytes);
-+        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
--    } else {
--        qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
--        if (!buf) {
--            backup_state.stat.zero_bytes += size;
-+        ++cluster_num;
-+        if (buf) {
-+            buf += VMA_CLUSTER_SIZE;
-+        }
-+        if (ret < 0) {
-+            Error *local_err = NULL;
-+            vma_writer_error_propagate(backup_state.vmaw, &local_err);
-+            pvebackup_propagate_error(local_err);
-+            return ret;
-+        } else {
-+            if (remaining >= VMA_CLUSTER_SIZE) {
-+                assert(ret == VMA_CLUSTER_SIZE);
-+                pvebackup_add_transfered_bytes(VMA_CLUSTER_SIZE, zero_bytes);
-+                remaining -= VMA_CLUSTER_SIZE;
-+            } else {
-+                assert(ret == remaining);
-+                pvebackup_add_transfered_bytes(remaining, zero_bytes);
-+                remaining = 0;
-+            }
-         }
--        backup_state.stat.transferred += size;
--        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-     }
--    qemu_co_mutex_unlock(&backup_state.backup_mutex);
--
-     return size;
- }
--static void coroutine_fn pvebackup_co_cleanup(void)
-+static void coroutine_fn pvebackup_co_cleanup(void *unused)
- {
-     assert(qemu_in_coroutine());
--    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+    qemu_rec_mutex_lock(&backup_state.backup_mutex);
--    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
-+    qemu_rec_mutex_lock(&backup_state.stat.lock);
-     backup_state.stat.end_time = time(NULL);
--    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-     if (backup_state.vmaw) {
-         Error *local_err = NULL;
-         vma_writer_close(backup_state.vmaw, &local_err);
-         if (local_err != NULL) {
--            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
--            error_propagate(&backup_state.stat.error, local_err);
--            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--        }
-+            pvebackup_propagate_error(local_err);
-+         }
-         backup_state.vmaw = NULL;
-     }
-     if (backup_state.pbs) {
--        qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
--        bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
--        if (!error_or_canceled) {
-+        if (!pvebackup_error_or_canceled()) {
-             Error *local_err = NULL;
-             proxmox_backup_co_finish(backup_state.pbs, &local_err);
-             if (local_err != NULL) {
--                qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
--                error_propagate(&backup_state.stat.error, local_err);
--             }
-+                pvebackup_propagate_error(local_err);
-+            }
-         }
--        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-         proxmox_backup_disconnect(backup_state.pbs);
-         backup_state.pbs = NULL;
-@@ -205,43 +239,14 @@ static void coroutine_fn pvebackup_co_cleanup(void)
-     g_list_free(backup_state.di_list);
-     backup_state.di_list = NULL;
--    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
- }
--typedef struct PVEBackupCompeteCallbackData {
--    PVEBackupDevInfo *di;
--    int result;
--} PVEBackupCompeteCallbackData;
--
--static void coroutine_fn pvebackup_co_complete_cb(void *opaque)
-+static void coroutine_fn pvebackup_complete_stream(void *opaque)
- {
--    assert(qemu_in_coroutine());
--
--    PVEBackupCompeteCallbackData *cb_data = opaque;
--
--    qemu_co_mutex_lock(&backup_state.backup_mutex);
--
--    PVEBackupDevInfo *di = cb_data->di;
--    int ret = cb_data->result;
--
--    di->completed = true;
--
--    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
--    bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
--
--    if (ret < 0 && !backup_state.stat.error) {
--        qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
--        error_setg(&backup_state.stat.error, "job failed with err %d - %s",
--                   ret, strerror(-ret));
--    }
--    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--
--    di->bs = NULL;
-+    PVEBackupDevInfo *di = opaque;
--    if (di->target) {
--        bdrv_unref(di->target);
--        di->target = NULL;
--    }
-+    bool error_or_canceled = pvebackup_error_or_canceled();
-     if (backup_state.vmaw) {
-         vma_writer_close_stream(backup_state.vmaw, di->dev_id);
-@@ -251,108 +256,96 @@ static void coroutine_fn pvebackup_co_complete_cb(void *opaque)
-         Error *local_err = NULL;
-         proxmox_backup_co_close_image(backup_state.pbs, di->dev_id, &local_err);
-         if (local_err != NULL) {
--            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
--            error_propagate(&backup_state.stat.error, local_err);
--            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+            pvebackup_propagate_error(local_err);
-         }
-     }
-+}
--    // remove self from job queue
--    backup_state.di_list = g_list_remove(backup_state.di_list, di);
--    g_free(di);
-+static void pvebackup_complete_cb(void *opaque, int ret)
-+{
-+    assert(!qemu_in_coroutine());
-+
-+    PVEBackupDevInfo *di = opaque;
--    int pending_jobs = g_list_length(backup_state.di_list);
-+    qemu_rec_mutex_lock(&backup_state.backup_mutex);
--    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+    di->completed = true;
--    if (pending_jobs > 0) {
--        pvebackup_co_run_next_job();
--    } else {
--        pvebackup_co_cleanup();
-+    if (ret < 0) {
-+        Error *local_err = NULL;
-+        error_setg(&local_err, "job failed with err %d - %s", ret, strerror(-ret));
-+        pvebackup_propagate_error(local_err);
-     }
--}
--static void pvebackup_complete_cb(void *opaque, int ret)
--{
--    // This can be called from the main loop, or from a coroutine
--    PVEBackupCompeteCallbackData cb_data = {
--        .di = opaque,
--        .result = ret,
--    };
-+    di->bs = NULL;
--    if (qemu_in_coroutine()) {
--        pvebackup_co_complete_cb(&cb_data);
--    } else {
--        block_on_coroutine_fn(pvebackup_co_complete_cb, &cb_data);
--    }
--}
-+    assert(di->target == NULL);
--static void coroutine_fn pvebackup_co_cancel(void *opaque)
--{
--    assert(qemu_in_coroutine());
-+    block_on_coroutine_fn(pvebackup_complete_stream, di);
--    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
--    backup_state.stat.cancel = true;
--    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+    // remove self from job queue
-+    backup_state.di_list = g_list_remove(backup_state.di_list, di);
--    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+    g_free(di);
--    // Avoid race between block jobs and backup-cancel command:
--    if (!(backup_state.vmaw || backup_state.pbs)) {
--        qemu_co_mutex_unlock(&backup_state.backup_mutex);
--        return;
--    }
-+    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
--    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
--    if (!backup_state.stat.error) {
--        qemu_co_rwlock_upgrade(&backup_state.stat.rwlock);
--        error_setg(&backup_state.stat.error, "backup cancelled");
--    }
--    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+    pvebackup_run_next_job();
-+}
-+
-+static void pvebackup_cancel(void)
-+{
-+    Error *cancel_err = NULL;
-+    error_setg(&cancel_err, "backup canceled");
-+    pvebackup_propagate_error(cancel_err);
-+
-+    qemu_rec_mutex_lock(&backup_state.backup_mutex);
-     if (backup_state.vmaw) {
-         /* make sure vma writer does not block anymore */
--        vma_writer_set_error(backup_state.vmaw, "backup cancelled");
-+        vma_writer_set_error(backup_state.vmaw, "backup canceled");
-     }
-     if (backup_state.pbs) {
--        proxmox_backup_abort(backup_state.pbs, "backup cancelled");
-+        proxmox_backup_abort(backup_state.pbs, "backup canceled");
-     }
--    bool running_jobs = 0;
--    GList *l = backup_state.di_list;
--    while (l) {
--        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
--        l = g_list_next(l);
--        if (!di->completed && di->bs) {
--            for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
--                if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
--                    continue;
--                }
-+    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
--                BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
--                if (bjob && bjob->source_bs == di->bs) {
--                    AioContext *aio_context = job->job.aio_context;
--                    aio_context_acquire(aio_context);
-+    for(;;) {
--                    if (!di->completed) {
--                        running_jobs += 1;
--                        job_cancel(&job->job, false);
--                    }
--                    aio_context_release(aio_context);
--                }
-+        BlockJob *next_job = NULL;
-+
-+        qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+
-+        GList *l = backup_state.di_list;
-+        while (l) {
-+            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+            l = g_list_next(l);
-+
-+            BlockJob *job = lookup_active_block_job(di);
-+            if (job != NULL) {
-+                next_job = job;
-+                break;
-             }
-         }
--    }
--    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
--    if (running_jobs == 0) pvebackup_co_cleanup(); // else job will call completion handler
-+        if (next_job) {
-+            AioContext *aio_context = next_job->job.aio_context;
-+            aio_context_acquire(aio_context);
-+            job_cancel_sync(&next_job->job);
-+            aio_context_release(aio_context);
-+        } else {
-+            break;
-+        }
-+    }
- }
- void qmp_backup_cancel(Error **errp)
- {
--    block_on_coroutine_fn(pvebackup_co_cancel, NULL);
-+    pvebackup_cancel();
- }
- static int coroutine_fn pvebackup_co_add_config(
-@@ -406,46 +399,97 @@ static int coroutine_fn pvebackup_co_add_config(
- bool job_should_pause(Job *job);
--static void coroutine_fn pvebackup_co_run_next_job(void)
-+static void pvebackup_run_next_job(void)
- {
--    assert(qemu_in_coroutine());
-+    assert(!qemu_in_coroutine());
--    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+    qemu_rec_mutex_lock(&backup_state.backup_mutex);
-     GList *l = backup_state.di_list;
-     while (l) {
-         PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-         l = g_list_next(l);
--        if (!di->completed && di->bs) {
--            for (BlockJob *job = block_job_next(NULL); job; job = block_job_next(job)) {
--                if (job->job.driver->job_type != JOB_TYPE_BACKUP) {
--                    continue;
--                }
--                BackupBlockJob *bjob = container_of(job, BackupBlockJob, common);
--                if (bjob && bjob->source_bs == di->bs) {
--                    AioContext *aio_context = job->job.aio_context;
--                    qemu_co_mutex_unlock(&backup_state.backup_mutex);
--                    aio_context_acquire(aio_context);
--
--                    if (job_should_pause(&job->job)) {
--                        qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
--                        bool error_or_canceled = backup_state.stat.error || backup_state.stat.cancel;
--                        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--
--                        if (error_or_canceled) {
--                            job_cancel(&job->job, false);
--                        } else {
--                            job_resume(&job->job);
--                        }
--                    }
--                    aio_context_release(aio_context);
--                    return;
-+        BlockJob *job = lookup_active_block_job(di);
-+
-+        if (job) {
-+            qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+
-+            AioContext *aio_context = job->job.aio_context;
-+            aio_context_acquire(aio_context);
-+
-+            if (job_should_pause(&job->job)) {
-+                bool error_or_canceled = pvebackup_error_or_canceled();
-+                if (error_or_canceled) {
-+                    job_cancel_sync(&job->job);
-+                } else {
-+                    job_resume(&job->job);
-                 }
-             }
-+            aio_context_release(aio_context);
-+            return;
-         }
-     }
--    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+
-+    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+
-+    block_on_coroutine_fn(pvebackup_co_cleanup, NULL); // no more jobs, run cleanup
-+}
-+
-+static bool create_backup_jobs(void) {
-+
-+    assert(!qemu_in_coroutine());
-+
-+    Error *local_err = NULL;
-+
-+    /* create and start all jobs (paused state) */
-+    GList *l =  backup_state.di_list;
-+    while (l) {
-+        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+        l = g_list_next(l);
-+
-+        assert(di->target != NULL);
-+
-+        AioContext *aio_context = bdrv_get_aio_context(di->bs);
-+        aio_context_acquire(aio_context);
-+
-+        BlockJob *job = backup_job_create(
-+            NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
-+            BITMAP_SYNC_MODE_NEVER, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
-+            JOB_DEFAULT, pvebackup_complete_cb, di, 1, NULL, &local_err);
-+
-+        aio_context_release(aio_context);
-+
-+        if (!job || local_err != NULL) {
-+            Error *create_job_err = NULL;
-+            error_setg(&create_job_err, "backup_job_create failed: %s",
-+                       local_err ? error_get_pretty(local_err) : "null");
-+
-+            pvebackup_propagate_error(create_job_err);
-+            break;
-+        }
-+        job_start(&job->job);
-+
-+        bdrv_unref(di->target);
-+        di->target = NULL;
-+    }
-+
-+    bool errors = pvebackup_error_or_canceled();
-+
-+    if (errors) {
-+        l = backup_state.di_list;
-+        while (l) {
-+            PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+            l = g_list_next(l);
-+
-+            if (di->target) {
-+                bdrv_unref(di->target);
-+                di->target = NULL;
-+            }
-+        }
-+    }
-+
-+    return errors;
- }
- typedef struct QmpBackupTask {
-@@ -476,7 +520,7 @@ typedef struct QmpBackupTask {
-     UuidInfo *result;
- } QmpBackupTask;
--static void coroutine_fn pvebackup_co_start(void *opaque)
-+static void coroutine_fn pvebackup_co_prepare(void *opaque)
- {
-     assert(qemu_in_coroutine());
-@@ -495,15 +539,14 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
-     GList *di_list = NULL;
-     GList *l;
-     UuidInfo *uuid_info;
--    BlockJob *job;
-     const char *config_name = "qemu-server.conf";
-     const char *firewall_name = "qemu-server.fw";
--    qemu_co_mutex_lock(&backup_state.backup_mutex);
-+    qemu_rec_mutex_lock(&backup_state.backup_mutex);
-     if (backup_state.di_list) {
--        qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-         error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
-                   "previous backup not finished");
-         return;
-@@ -631,7 +674,7 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
-             if (dev_id < 0)
-                 goto err;
--            if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_cb, di, task->errp))) {
-+            if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_pbs_cb, di, task->errp))) {
-                 goto err;
-             }
-@@ -652,7 +695,7 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
-             PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-             l = g_list_next(l);
--            if (!(di->target = bdrv_backup_dump_create(VMA_CLUSTER_SIZE, di->size, pvebackup_co_dump_cb, di, task->errp))) {
-+            if (!(di->target = bdrv_backup_dump_create(VMA_CLUSTER_SIZE, di->size, pvebackup_co_dump_vma_cb, di, task->errp))) {
-                 goto err;
-             }
-@@ -717,9 +760,7 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
-     }
-     /* initialize global backup_state now */
--    qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
--
--    backup_state.stat.cancel = false;
-+    qemu_rec_mutex_lock(&backup_state.stat.lock);
-     if (backup_state.stat.error) {
-         error_free(backup_state.stat.error);
-@@ -742,7 +783,7 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
-     backup_state.stat.transferred = 0;
-     backup_state.stat.zero_bytes = 0;
--    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
-+    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-     backup_state.speed = (task->has_speed && task->speed > 0) ? task->speed : 0;
-@@ -751,45 +792,7 @@ static void coroutine_fn pvebackup_co_start(void *opaque)
-     backup_state.di_list = di_list;
--    /* start all jobs (paused state) */
--    l = di_list;
--    while (l) {
--        PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
--        l = g_list_next(l);
--
--        AioContext *aio_context = bdrv_get_aio_context(di->bs);
--        aio_context_acquire(aio_context);
--
--        job = backup_job_create(NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
--                                BITMAP_SYNC_MODE_NEVER, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
--                                JOB_DEFAULT, pvebackup_complete_cb, di, 1, NULL, &local_err);
--
--        aio_context_release(aio_context);
--
--        if (!job || local_err != NULL) {
--            qemu_co_rwlock_wrlock(&backup_state.stat.rwlock);
--            error_setg(&backup_state.stat.error, "backup_job_create failed");
--            qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--            break;
--        }
--        job_start(&job->job);
--        if (di->target) {
--            bdrv_unref(di->target);
--            di->target = NULL;
--        }
--    }
--
--    qemu_co_mutex_unlock(&backup_state.backup_mutex);
--
--    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
--    bool no_errors = !backup_state.stat.error;
--    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--
--    if (no_errors) {
--        pvebackup_co_run_next_job(); // run one job
--    } else {
--        pvebackup_co_cancel(NULL);
--    }
-+    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-     uuid_info = g_malloc0(sizeof(*uuid_info));
-     uuid_info->UUID = uuid_str;
-@@ -833,7 +836,7 @@ err:
-         rmdir(backup_dir);
-     }
--    qemu_co_mutex_unlock(&backup_state.backup_mutex);
-+    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-     task->result = NULL;
-     return;
-@@ -878,32 +881,28 @@ UuidInfo *qmp_backup(
-         .errp = errp,
-     };
--    block_on_coroutine_fn(pvebackup_co_start, &task);
-+    block_on_coroutine_fn(pvebackup_co_prepare, &task);
-+
-+    if (*errp == NULL) {
-+        qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+        create_backup_jobs();
-+        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+        pvebackup_run_next_job();
-+    }
-     return task.result;
- }
--
--typedef struct QmpQueryBackupTask {
--    Error **errp;
--    BackupStatus *result;
--} QmpQueryBackupTask;
--
--static void coroutine_fn pvebackup_co_query(void *opaque)
-+BackupStatus *qmp_query_backup(Error **errp)
- {
--    assert(qemu_in_coroutine());
--
--    QmpQueryBackupTask *task = opaque;
--
-     BackupStatus *info = g_malloc0(sizeof(*info));
--    qemu_co_rwlock_rdlock(&backup_state.stat.rwlock);
-+    qemu_rec_mutex_lock(&backup_state.stat.lock);
-     if (!backup_state.stat.start_time) {
-         /* not started, return {} */
--        task->result = info;
--        qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--        return;
-+        qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+        return info;
-     }
-     info->has_status = true;
-@@ -939,19 +938,7 @@ static void coroutine_fn pvebackup_co_query(void *opaque)
-     info->has_transferred = true;
-     info->transferred = backup_state.stat.transferred;
--    task->result = info;
-+    qemu_rec_mutex_unlock(&backup_state.stat.lock);
--    qemu_co_rwlock_unlock(&backup_state.stat.rwlock);
--}
--
--BackupStatus *qmp_query_backup(Error **errp)
--{
--    QmpQueryBackupTask task = {
--        .errp = errp,
--        .result = NULL,
--    };
--
--    block_on_coroutine_fn(pvebackup_co_query, &task);
--
--    return task.result;
-+    return info;
- }
diff --git a/debian/patches/pve/0033-drive-mirror-add-support-for-conditional-and-always-.patch b/debian/patches/pve/0033-drive-mirror-add-support-for-conditional-and-always-.patch
new file mode 100644 (file)
index 0000000..a6aee66
--- /dev/null
@@ -0,0 +1,80 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: John Snow <jsnow@redhat.com>
+Date: Mon, 6 Apr 2020 12:17:04 +0200
+Subject: [PATCH] drive-mirror: add support for conditional and always bitmap
+ sync modes
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+Teach mirror two new tricks for using bitmaps:
+
+Always: no matter what, we synchronize the copy_bitmap back to the
+sync_bitmap. In effect, this allows us resume a failed mirror at a later
+date.
+
+Conditional: On success only, we sync the bitmap. This is akin to
+incremental backup modes; we can use this bitmap to later refresh a
+successfully created mirror.
+
+Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
+---
+ block/mirror.c | 24 ++++++++++++++++++------
+ 1 file changed, 18 insertions(+), 6 deletions(-)
+
+diff --git a/block/mirror.c b/block/mirror.c
+index 3c9cd42c50..08ac9827f2 100644
+--- a/block/mirror.c
++++ b/block/mirror.c
+@@ -653,8 +653,6 @@ static int mirror_exit_common(Job *job)
+         bdrv_unfreeze_backing_chain(mirror_top_bs, target_bs);
+     }
+-    bdrv_release_dirty_bitmap(s->dirty_bitmap);
+-
+     /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
+      * before we can call bdrv_drained_end */
+     bdrv_ref(src);
+@@ -752,6 +750,18 @@ static int mirror_exit_common(Job *job)
+     blk_set_perm(bjob->blk, 0, BLK_PERM_ALL, &error_abort);
+     blk_insert_bs(bjob->blk, mirror_top_bs, &error_abort);
++    if (s->sync_bitmap) {
++        if (s->bitmap_mode == BITMAP_SYNC_MODE_ALWAYS ||
++            (s->bitmap_mode == BITMAP_SYNC_MODE_ON_SUCCESS &&
++             job->ret == 0 && ret == 0)) {
++            /* Success; synchronize copy back to sync. */
++            bdrv_clear_dirty_bitmap(s->sync_bitmap, NULL);
++            bdrv_merge_dirty_bitmap(s->sync_bitmap, s->dirty_bitmap,
++                                    NULL, &error_abort);
++        }
++    }
++    bdrv_release_dirty_bitmap(s->dirty_bitmap);
++
+     bs_opaque->job = NULL;
+     bdrv_drained_end(src);
+@@ -1584,10 +1594,6 @@ static BlockJob *mirror_start_job(
+                        " sync mode",
+                        MirrorSyncMode_str(sync_mode));
+             return NULL;
+-        } else if (bitmap_mode != BITMAP_SYNC_MODE_NEVER) {
+-            error_setg(errp,
+-                       "Bitmap Sync Mode '%s' is not supported by Mirror",
+-                       BitmapSyncMode_str(bitmap_mode));
+         }
+     } else if (bitmap) {
+         error_setg(errp,
+@@ -1604,6 +1610,12 @@ static BlockJob *mirror_start_job(
+             return NULL;
+         }
+         granularity = bdrv_dirty_bitmap_granularity(bitmap);
++
++        if (bitmap_mode != BITMAP_SYNC_MODE_NEVER) {
++            if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_DEFAULT, errp)) {
++                return NULL;
++            }
++        }
+     } else if (granularity == 0) {
+         granularity = bdrv_get_default_bitmap_granularity(target);
+     }
diff --git a/debian/patches/pve/0034-drive-mirror-add-support-for-sync-bitmap-mode-never.patch b/debian/patches/pve/0034-drive-mirror-add-support-for-sync-bitmap-mode-never.patch
deleted file mode 100644 (file)
index 7cd4d76..0000000
+++ /dev/null
@@ -1,439 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: John Snow <jsnow@redhat.com>
-Date: Mon, 6 Apr 2020 12:17:03 +0200
-Subject: [PATCH] drive-mirror: add support for sync=bitmap mode=never
-MIME-Version: 1.0
-Content-Type: text/plain; charset=UTF-8
-Content-Transfer-Encoding: 8bit
-
-This patch adds support for the "BITMAP" sync mode to drive-mirror and
-blockdev-mirror. It adds support only for the BitmapSyncMode "never,"
-because it's the simplest mode.
-
-This mode simply uses a user-provided bitmap as an initial copy
-manifest, and then does not clear any bits in the bitmap at the
-conclusion of the operation.
-
-Any new writes dirtied during the operation are copied out, in contrast
-to backup. Note that whether these writes are reflected in the bitmap
-at the conclusion of the operation depends on whether that bitmap is
-actually recording!
-
-This patch was originally based on one by Ma Haocong, but it has since
-been modified pretty heavily.
-
-Suggested-by: Ma Haocong <mahaocong@didichuxing.com>
-Signed-off-by: Ma Haocong <mahaocong@didichuxing.com>
-Signed-off-by: John Snow <jsnow@redhat.com>
-Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
----
- block/mirror.c              | 98 ++++++++++++++++++++++++++++++-------
- blockdev.c                  | 39 +++++++++++++--
- include/block/block_int.h   |  4 +-
- qapi/block-core.json        | 29 +++++++++--
- tests/test-block-iothread.c |  4 +-
- 5 files changed, 145 insertions(+), 29 deletions(-)
-
-diff --git a/block/mirror.c b/block/mirror.c
-index c26fd9260d..3c9cd42c50 100644
---- a/block/mirror.c
-+++ b/block/mirror.c
-@@ -49,7 +49,7 @@ typedef struct MirrorBlockJob {
-     BlockDriverState *to_replace;
-     /* Used to block operations on the drive-mirror-replace target */
-     Error *replace_blocker;
--    bool is_none_mode;
-+    MirrorSyncMode sync_mode;
-     BlockMirrorBackingMode backing_mode;
-     /* Whether the target image requires explicit zero-initialization */
-     bool zero_target;
-@@ -64,6 +64,8 @@ typedef struct MirrorBlockJob {
-     size_t buf_size;
-     int64_t bdev_length;
-     unsigned long *cow_bitmap;
-+    BdrvDirtyBitmap *sync_bitmap;
-+    BitmapSyncMode bitmap_mode;
-     BdrvDirtyBitmap *dirty_bitmap;
-     BdrvDirtyBitmapIter *dbi;
-     uint8_t *buf;
-@@ -676,7 +678,8 @@ static int mirror_exit_common(Job *job)
-     bdrv_child_refresh_perms(mirror_top_bs, mirror_top_bs->backing,
-                              &error_abort);
-     if (!abort && s->backing_mode == MIRROR_SOURCE_BACKING_CHAIN) {
--        BlockDriverState *backing = s->is_none_mode ? src : s->base;
-+        BlockDriverState *backing;
-+        backing = s->sync_mode == MIRROR_SYNC_MODE_NONE ? src : s->base;
-         if (backing_bs(target_bs) != backing) {
-             bdrv_set_backing_hd(target_bs, backing, &local_err);
-             if (local_err) {
-@@ -771,6 +774,16 @@ static void mirror_abort(Job *job)
-     assert(ret == 0);
- }
-+/* Always called after commit/abort. */
-+static void mirror_clean(Job *job)
-+{
-+    MirrorBlockJob *s = container_of(job, MirrorBlockJob, common.job);
-+
-+    if (s->sync_bitmap) {
-+        bdrv_dirty_bitmap_set_busy(s->sync_bitmap, false);
-+    }
-+}
-+
- static void coroutine_fn mirror_throttle(MirrorBlockJob *s)
- {
-     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
-@@ -949,7 +962,8 @@ static int coroutine_fn mirror_run(Job *job, Error **errp)
-     mirror_free_init(s);
-     s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
--    if (!s->is_none_mode) {
-+    if ((s->sync_mode == MIRROR_SYNC_MODE_TOP) ||
-+        (s->sync_mode == MIRROR_SYNC_MODE_FULL)) {
-         ret = mirror_dirty_init(s);
-         if (ret < 0 || job_is_cancelled(&s->common.job)) {
-             goto immediate_exit;
-@@ -1181,6 +1195,7 @@ static const BlockJobDriver mirror_job_driver = {
-         .run                    = mirror_run,
-         .prepare                = mirror_prepare,
-         .abort                  = mirror_abort,
-+        .clean                  = mirror_clean,
-         .pause                  = mirror_pause,
-         .complete               = mirror_complete,
-     },
-@@ -1196,6 +1211,7 @@ static const BlockJobDriver commit_active_job_driver = {
-         .run                    = mirror_run,
-         .prepare                = mirror_prepare,
-         .abort                  = mirror_abort,
-+        .clean                  = mirror_clean,
-         .pause                  = mirror_pause,
-         .complete               = mirror_complete,
-     },
-@@ -1542,7 +1558,10 @@ static BlockJob *mirror_start_job(
-                              BlockCompletionFunc *cb,
-                              void *opaque,
-                              const BlockJobDriver *driver,
--                             bool is_none_mode, BlockDriverState *base,
-+                             MirrorSyncMode sync_mode,
-+                             BdrvDirtyBitmap *bitmap,
-+                             BitmapSyncMode bitmap_mode,
-+                             BlockDriverState *base,
-                              bool auto_complete, const char *filter_node_name,
-                              bool is_mirror, MirrorCopyMode copy_mode,
-                              Error **errp)
-@@ -1555,10 +1574,39 @@ static BlockJob *mirror_start_job(
-     Error *local_err = NULL;
-     int ret;
--    if (granularity == 0) {
--        granularity = bdrv_get_default_bitmap_granularity(target);
-+    if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
-+        error_setg(errp, "Sync mode '%s' not supported",
-+                   MirrorSyncMode_str(sync_mode));
-+        return NULL;
-+    } else if (sync_mode == MIRROR_SYNC_MODE_BITMAP) {
-+        if (!bitmap) {
-+            error_setg(errp, "Must provide a valid bitmap name for '%s'"
-+                       " sync mode",
-+                       MirrorSyncMode_str(sync_mode));
-+            return NULL;
-+        } else if (bitmap_mode != BITMAP_SYNC_MODE_NEVER) {
-+            error_setg(errp,
-+                       "Bitmap Sync Mode '%s' is not supported by Mirror",
-+                       BitmapSyncMode_str(bitmap_mode));
-+        }
-+    } else if (bitmap) {
-+        error_setg(errp,
-+                   "sync mode '%s' is not compatible with bitmaps",
-+                   MirrorSyncMode_str(sync_mode));
-+        return NULL;
-     }
-+    if (bitmap) {
-+        if (granularity) {
-+            error_setg(errp, "granularity (%d)"
-+                       "cannot be specified when a bitmap is provided",
-+                       granularity);
-+            return NULL;
-+        }
-+        granularity = bdrv_dirty_bitmap_granularity(bitmap);
-+    } else if (granularity == 0) {
-+        granularity = bdrv_get_default_bitmap_granularity(target);
-+    }
-     assert(is_power_of_2(granularity));
-     if (buf_size < 0) {
-@@ -1662,7 +1710,9 @@ static BlockJob *mirror_start_job(
-     s->replaces = g_strdup(replaces);
-     s->on_source_error = on_source_error;
-     s->on_target_error = on_target_error;
--    s->is_none_mode = is_none_mode;
-+    s->sync_mode = sync_mode;
-+    s->sync_bitmap = bitmap;
-+    s->bitmap_mode = bitmap_mode;
-     s->backing_mode = backing_mode;
-     s->zero_target = zero_target;
-     s->copy_mode = copy_mode;
-@@ -1682,6 +1732,18 @@ static BlockJob *mirror_start_job(
-         bdrv_disable_dirty_bitmap(s->dirty_bitmap);
-     }
-+    if (s->sync_bitmap) {
-+        bdrv_dirty_bitmap_set_busy(s->sync_bitmap, true);
-+    }
-+
-+    if (s->sync_mode == MIRROR_SYNC_MODE_BITMAP) {
-+        bdrv_merge_dirty_bitmap(s->dirty_bitmap, s->sync_bitmap,
-+                                NULL, &local_err);
-+        if (local_err) {
-+            goto fail;
-+        }
-+    }
-+
-     ret = block_job_add_bdrv(&s->common, "source", bs, 0,
-                              BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE |
-                              BLK_PERM_CONSISTENT_READ,
-@@ -1735,6 +1797,9 @@ fail:
-         if (s->dirty_bitmap) {
-             bdrv_release_dirty_bitmap(s->dirty_bitmap);
-         }
-+        if (s->sync_bitmap) {
-+            bdrv_dirty_bitmap_set_busy(s->sync_bitmap, false);
-+        }
-         job_early_fail(&s->common.job);
-     }
-@@ -1752,29 +1817,23 @@ void mirror_start(const char *job_id, BlockDriverState *bs,
-                   BlockDriverState *target, const char *replaces,
-                   int creation_flags, int64_t speed,
-                   uint32_t granularity, int64_t buf_size,
--                  MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
-+                  MirrorSyncMode mode, BdrvDirtyBitmap *bitmap,
-+                  BitmapSyncMode bitmap_mode,
-+                  BlockMirrorBackingMode backing_mode,
-                   bool zero_target,
-                   BlockdevOnError on_source_error,
-                   BlockdevOnError on_target_error,
-                   bool unmap, const char *filter_node_name,
-                   MirrorCopyMode copy_mode, Error **errp)
- {
--    bool is_none_mode;
-     BlockDriverState *base;
--    if ((mode == MIRROR_SYNC_MODE_INCREMENTAL) ||
--        (mode == MIRROR_SYNC_MODE_BITMAP)) {
--        error_setg(errp, "Sync mode '%s' not supported",
--                   MirrorSyncMode_str(mode));
--        return;
--    }
--    is_none_mode = mode == MIRROR_SYNC_MODE_NONE;
-     base = mode == MIRROR_SYNC_MODE_TOP ? backing_bs(bs) : NULL;
-     mirror_start_job(job_id, bs, creation_flags, target, replaces,
-                      speed, granularity, buf_size, backing_mode, zero_target,
-                      on_source_error, on_target_error, unmap, NULL, NULL,
--                     &mirror_job_driver, is_none_mode, base, false,
--                     filter_node_name, true, copy_mode, errp);
-+                     &mirror_job_driver, mode, bitmap, bitmap_mode, base,
-+                     false, filter_node_name, true, copy_mode, errp);
- }
- BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
-@@ -1800,7 +1859,8 @@ BlockJob *commit_active_start(const char *job_id, BlockDriverState *bs,
-                      job_id, bs, creation_flags, base, NULL, speed, 0, 0,
-                      MIRROR_LEAVE_BACKING_CHAIN, false,
-                      on_error, on_error, true, cb, opaque,
--                     &commit_active_job_driver, false, base, auto_complete,
-+                     &commit_active_job_driver, MIRROR_SYNC_MODE_FULL,
-+                     NULL, 0, base, auto_complete,
-                      filter_node_name, false, MIRROR_COPY_MODE_BACKGROUND,
-                      &local_err);
-     if (local_err) {
-diff --git a/blockdev.c b/blockdev.c
-index f391c3b3c7..bbeff9c439 100644
---- a/blockdev.c
-+++ b/blockdev.c
-@@ -3159,6 +3159,10 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
-                                    BlockDriverState *target,
-                                    bool has_replaces, const char *replaces,
-                                    enum MirrorSyncMode sync,
-+                                   bool has_bitmap,
-+                                   const char *bitmap_name,
-+                                   bool has_bitmap_mode,
-+                                   BitmapSyncMode bitmap_mode,
-                                    BlockMirrorBackingMode backing_mode,
-                                    bool zero_target,
-                                    bool has_speed, int64_t speed,
-@@ -3177,6 +3181,7 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
-                                    Error **errp)
- {
-     int job_flags = JOB_DEFAULT;
-+    BdrvDirtyBitmap *bitmap = NULL;
-     if (!has_speed) {
-         speed = 0;
-@@ -3231,6 +3236,29 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
-         sync = MIRROR_SYNC_MODE_FULL;
-     }
-+    if (has_bitmap) {
-+        if (granularity) {
-+            error_setg(errp, "Granularity and bitmap cannot both be set");
-+            return;
-+        }
-+
-+        if (!has_bitmap_mode) {
-+            error_setg(errp, "bitmap-mode must be specified if"
-+                       " a bitmap is provided");
-+            return;
-+        }
-+
-+        bitmap = bdrv_find_dirty_bitmap(bs, bitmap_name);
-+        if (!bitmap) {
-+            error_setg(errp, "Dirty bitmap '%s' not found", bitmap_name);
-+            return;
-+        }
-+
-+        if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
-+            return;
-+        }
-+    }
-+
-     if (has_replaces) {
-         BlockDriverState *to_replace_bs;
-         AioContext *replace_aio_context;
-@@ -3268,8 +3296,8 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
-      * and will allow to check whether the node still exist at mirror completion
-      */
-     mirror_start(job_id, bs, target,
--                 has_replaces ? replaces : NULL, job_flags,
--                 speed, granularity, buf_size, sync, backing_mode, zero_target,
-+                 has_replaces ? replaces : NULL, job_flags, speed, granularity,
-+                 buf_size, sync, bitmap, bitmap_mode, backing_mode, zero_target,
-                  on_source_error, on_target_error, unmap, filter_node_name,
-                  copy_mode, errp);
- }
-@@ -3410,6 +3438,8 @@ void qmp_drive_mirror(DriveMirror *arg, Error **errp)
-     blockdev_mirror_common(arg->has_job_id ? arg->job_id : NULL, bs, target_bs,
-                            arg->has_replaces, arg->replaces, arg->sync,
-+                           arg->has_bitmap, arg->bitmap,
-+                           arg->has_bitmap_mode, arg->bitmap_mode,
-                            backing_mode, zero_target,
-                            arg->has_speed, arg->speed,
-                            arg->has_granularity, arg->granularity,
-@@ -3432,6 +3462,8 @@ void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
-                          const char *device, const char *target,
-                          bool has_replaces, const char *replaces,
-                          MirrorSyncMode sync,
-+                         bool has_bitmap, const char *bitmap,
-+                         bool has_bitmap_mode, BitmapSyncMode bitmap_mode,
-                          bool has_speed, int64_t speed,
-                          bool has_granularity, uint32_t granularity,
-                          bool has_buf_size, int64_t buf_size,
-@@ -3482,7 +3514,8 @@ void qmp_blockdev_mirror(bool has_job_id, const char *job_id,
-     }
-     blockdev_mirror_common(has_job_id ? job_id : NULL, bs, target_bs,
--                           has_replaces, replaces, sync, backing_mode,
-+                           has_replaces, replaces, sync, has_bitmap,
-+                           bitmap, has_bitmap_mode, bitmap_mode, backing_mode,
-                            zero_target, has_speed, speed,
-                            has_granularity, granularity,
-                            has_buf_size, buf_size,
-diff --git a/include/block/block_int.h b/include/block/block_int.h
-index 6d234f1de9..180a5e00fd 100644
---- a/include/block/block_int.h
-+++ b/include/block/block_int.h
-@@ -1210,7 +1210,9 @@ void mirror_start(const char *job_id, BlockDriverState *bs,
-                   BlockDriverState *target, const char *replaces,
-                   int creation_flags, int64_t speed,
-                   uint32_t granularity, int64_t buf_size,
--                  MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
-+                  MirrorSyncMode mode, BdrvDirtyBitmap *bitmap,
-+                  BitmapSyncMode bitmap_mode,
-+                  BlockMirrorBackingMode backing_mode,
-                   bool zero_target,
-                   BlockdevOnError on_source_error,
-                   BlockdevOnError on_target_error,
-diff --git a/qapi/block-core.json b/qapi/block-core.json
-index 97d1f64636..8bdbccb397 100644
---- a/qapi/block-core.json
-+++ b/qapi/block-core.json
-@@ -2054,10 +2054,19 @@
- #        (all the disk, only the sectors allocated in the topmost image, or
- #        only new I/O).
- #
-+# @bitmap: The name of a bitmap to use for sync=bitmap mode. This argument must
-+#          be present for bitmap mode and absent otherwise. The bitmap's
-+#          granularity is used instead of @granularity (since 4.1).
-+#
-+# @bitmap-mode: Specifies the type of data the bitmap should contain after
-+#               the operation concludes. Must be present if sync is "bitmap".
-+#               Must NOT be present otherwise. (Since 4.1)
-+#
- # @granularity: granularity of the dirty bitmap, default is 64K
- #               if the image format doesn't have clusters, 4K if the clusters
- #               are smaller than that, else the cluster size.  Must be a
--#               power of 2 between 512 and 64M (since 1.4).
-+#               power of 2 between 512 and 64M. Must not be specified if
-+#               @bitmap is present (since 1.4).
- #
- # @buf-size: maximum amount of data in flight from source to
- #            target (since 1.4).
-@@ -2095,7 +2104,9 @@
- { 'struct': 'DriveMirror',
-   'data': { '*job-id': 'str', 'device': 'str', 'target': 'str',
-             '*format': 'str', '*node-name': 'str', '*replaces': 'str',
--            'sync': 'MirrorSyncMode', '*mode': 'NewImageMode',
-+            'sync': 'MirrorSyncMode', '*bitmap': 'str',
-+            '*bitmap-mode': 'BitmapSyncMode',
-+            '*mode': 'NewImageMode',
-             '*speed': 'int', '*granularity': 'uint32',
-             '*buf-size': 'int', '*on-source-error': 'BlockdevOnError',
-             '*on-target-error': 'BlockdevOnError',
-@@ -2362,10 +2373,19 @@
- #        (all the disk, only the sectors allocated in the topmost image, or
- #        only new I/O).
- #
-+# @bitmap: The name of a bitmap to use for sync=bitmap mode. This argument must
-+#          be present for bitmap mode and absent otherwise. The bitmap's
-+#          granularity is used instead of @granularity (since 4.1).
-+#
-+# @bitmap-mode: Specifies the type of data the bitmap should contain after
-+#               the operation concludes. Must be present if sync is "bitmap".
-+#               Must NOT be present otherwise. (Since 4.1)
-+#
- # @granularity: granularity of the dirty bitmap, default is 64K
- #               if the image format doesn't have clusters, 4K if the clusters
- #               are smaller than that, else the cluster size.  Must be a
--#               power of 2 between 512 and 64M
-+#               power of 2 between 512 and 64M . Must not be specified if
-+#               @bitmap is present.
- #
- # @buf-size: maximum amount of data in flight from source to
- #            target
-@@ -2414,7 +2434,8 @@
- { 'command': 'blockdev-mirror',
-   'data': { '*job-id': 'str', 'device': 'str', 'target': 'str',
-             '*replaces': 'str',
--            'sync': 'MirrorSyncMode',
-+            'sync': 'MirrorSyncMode', '*bitmap': 'str',
-+            '*bitmap-mode': 'BitmapSyncMode',
-             '*speed': 'int', '*granularity': 'uint32',
-             '*buf-size': 'int', '*on-source-error': 'BlockdevOnError',
-             '*on-target-error': 'BlockdevOnError',
-diff --git a/tests/test-block-iothread.c b/tests/test-block-iothread.c
-index 0c861809f0..da87a67a57 100644
---- a/tests/test-block-iothread.c
-+++ b/tests/test-block-iothread.c
-@@ -611,8 +611,8 @@ static void test_propagate_mirror(void)
-     /* Start a mirror job */
-     mirror_start("job0", src, target, NULL, JOB_DEFAULT, 0, 0, 0,
--                 MIRROR_SYNC_MODE_NONE, MIRROR_OPEN_BACKING_CHAIN, false,
--                 BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
-+                 MIRROR_SYNC_MODE_NONE, NULL, 0, MIRROR_OPEN_BACKING_CHAIN,
-+                 false, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
-                  false, "filter_node", MIRROR_COPY_MODE_BACKGROUND,
-                  &error_abort);
-     job = job_get("job0");
diff --git a/debian/patches/pve/0034-mirror-add-check-for-bitmap-mode-without-bitmap.patch b/debian/patches/pve/0034-mirror-add-check-for-bitmap-mode-without-bitmap.patch
new file mode 100644 (file)
index 0000000..d8682bb
--- /dev/null
@@ -0,0 +1,30 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Fabian=20Gr=C3=BCnbichler?= <f.gruenbichler@proxmox.com>
+Date: Mon, 6 Apr 2020 12:17:05 +0200
+Subject: [PATCH] mirror: add check for bitmap-mode without bitmap
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+as one without the other does not make much sense with the current set
+of modes.
+
+Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
+---
+ blockdev.c | 3 +++
+ 1 file changed, 3 insertions(+)
+
+diff --git a/blockdev.c b/blockdev.c
+index bbeff9c439..fa3c2f5548 100644
+--- a/blockdev.c
++++ b/blockdev.c
+@@ -3257,6 +3257,9 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
+         if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
+             return;
+         }
++    } else if (has_bitmap_mode) {
++        error_setg(errp, "Cannot specify bitmap sync mode without a bitmap");
++        return;
+     }
+     if (has_replaces) {
diff --git a/debian/patches/pve/0035-drive-mirror-add-support-for-conditional-and-always-.patch b/debian/patches/pve/0035-drive-mirror-add-support-for-conditional-and-always-.patch
deleted file mode 100644 (file)
index a6aee66..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: John Snow <jsnow@redhat.com>
-Date: Mon, 6 Apr 2020 12:17:04 +0200
-Subject: [PATCH] drive-mirror: add support for conditional and always bitmap
- sync modes
-MIME-Version: 1.0
-Content-Type: text/plain; charset=UTF-8
-Content-Transfer-Encoding: 8bit
-
-Teach mirror two new tricks for using bitmaps:
-
-Always: no matter what, we synchronize the copy_bitmap back to the
-sync_bitmap. In effect, this allows us resume a failed mirror at a later
-date.
-
-Conditional: On success only, we sync the bitmap. This is akin to
-incremental backup modes; we can use this bitmap to later refresh a
-successfully created mirror.
-
-Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
----
- block/mirror.c | 24 ++++++++++++++++++------
- 1 file changed, 18 insertions(+), 6 deletions(-)
-
-diff --git a/block/mirror.c b/block/mirror.c
-index 3c9cd42c50..08ac9827f2 100644
---- a/block/mirror.c
-+++ b/block/mirror.c
-@@ -653,8 +653,6 @@ static int mirror_exit_common(Job *job)
-         bdrv_unfreeze_backing_chain(mirror_top_bs, target_bs);
-     }
--    bdrv_release_dirty_bitmap(s->dirty_bitmap);
--
-     /* Make sure that the source BDS doesn't go away during bdrv_replace_node,
-      * before we can call bdrv_drained_end */
-     bdrv_ref(src);
-@@ -752,6 +750,18 @@ static int mirror_exit_common(Job *job)
-     blk_set_perm(bjob->blk, 0, BLK_PERM_ALL, &error_abort);
-     blk_insert_bs(bjob->blk, mirror_top_bs, &error_abort);
-+    if (s->sync_bitmap) {
-+        if (s->bitmap_mode == BITMAP_SYNC_MODE_ALWAYS ||
-+            (s->bitmap_mode == BITMAP_SYNC_MODE_ON_SUCCESS &&
-+             job->ret == 0 && ret == 0)) {
-+            /* Success; synchronize copy back to sync. */
-+            bdrv_clear_dirty_bitmap(s->sync_bitmap, NULL);
-+            bdrv_merge_dirty_bitmap(s->sync_bitmap, s->dirty_bitmap,
-+                                    NULL, &error_abort);
-+        }
-+    }
-+    bdrv_release_dirty_bitmap(s->dirty_bitmap);
-+
-     bs_opaque->job = NULL;
-     bdrv_drained_end(src);
-@@ -1584,10 +1594,6 @@ static BlockJob *mirror_start_job(
-                        " sync mode",
-                        MirrorSyncMode_str(sync_mode));
-             return NULL;
--        } else if (bitmap_mode != BITMAP_SYNC_MODE_NEVER) {
--            error_setg(errp,
--                       "Bitmap Sync Mode '%s' is not supported by Mirror",
--                       BitmapSyncMode_str(bitmap_mode));
-         }
-     } else if (bitmap) {
-         error_setg(errp,
-@@ -1604,6 +1610,12 @@ static BlockJob *mirror_start_job(
-             return NULL;
-         }
-         granularity = bdrv_dirty_bitmap_granularity(bitmap);
-+
-+        if (bitmap_mode != BITMAP_SYNC_MODE_NEVER) {
-+            if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_DEFAULT, errp)) {
-+                return NULL;
-+            }
-+        }
-     } else if (granularity == 0) {
-         granularity = bdrv_get_default_bitmap_granularity(target);
-     }
diff --git a/debian/patches/pve/0035-mirror-switch-to-bdrv_dirty_bitmap_merge_internal.patch b/debian/patches/pve/0035-mirror-switch-to-bdrv_dirty_bitmap_merge_internal.patch
new file mode 100644 (file)
index 0000000..15bebef
--- /dev/null
@@ -0,0 +1,42 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Fabian=20Gr=C3=BCnbichler?= <f.gruenbichler@proxmox.com>
+Date: Mon, 6 Apr 2020 12:17:06 +0200
+Subject: [PATCH] mirror: switch to bdrv_dirty_bitmap_merge_internal
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+since sync_bitmap is busy at the point of merging, and we checked access
+beforehand.
+
+Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
+---
+ block/mirror.c | 8 ++++----
+ 1 file changed, 4 insertions(+), 4 deletions(-)
+
+diff --git a/block/mirror.c b/block/mirror.c
+index 08ac9827f2..c56b0f87e3 100644
+--- a/block/mirror.c
++++ b/block/mirror.c
+@@ -756,8 +756,8 @@ static int mirror_exit_common(Job *job)
+              job->ret == 0 && ret == 0)) {
+             /* Success; synchronize copy back to sync. */
+             bdrv_clear_dirty_bitmap(s->sync_bitmap, NULL);
+-            bdrv_merge_dirty_bitmap(s->sync_bitmap, s->dirty_bitmap,
+-                                    NULL, &error_abort);
++            bdrv_dirty_bitmap_merge_internal(s->sync_bitmap, s->dirty_bitmap,
++                                             NULL, true);
+         }
+     }
+     bdrv_release_dirty_bitmap(s->dirty_bitmap);
+@@ -1749,8 +1749,8 @@ static BlockJob *mirror_start_job(
+     }
+     if (s->sync_mode == MIRROR_SYNC_MODE_BITMAP) {
+-        bdrv_merge_dirty_bitmap(s->dirty_bitmap, s->sync_bitmap,
+-                                NULL, &local_err);
++        bdrv_dirty_bitmap_merge_internal(s->dirty_bitmap, s->sync_bitmap,
++                                         NULL, true);
+         if (local_err) {
+             goto fail;
+         }
diff --git a/debian/patches/pve/0036-iotests-add-test-for-bitmap-mirror.patch b/debian/patches/pve/0036-iotests-add-test-for-bitmap-mirror.patch
new file mode 100644 (file)
index 0000000..71ddcd4
--- /dev/null
@@ -0,0 +1,3447 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Fabian=20Gr=C3=BCnbichler?= <f.gruenbichler@proxmox.com>
+Date: Mon, 6 Apr 2020 12:17:07 +0200
+Subject: [PATCH] iotests: add test for bitmap mirror
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+heavily based on/practically forked off iotest 257 for bitmap backups,
+but:
+
+- no writes to filter node 'mirror-top' between completion and
+finalization, as those seem to deadlock?
+- no inclusion of not-yet-available full/top sync modes in combination
+with bitmaps
+- extra set of reference/test mirrors to verify that writes in parallel
+with active mirror work
+
+intentionally keeping copyright and ownership of original test case to
+honor provenance.
+
+Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
+---
+ tests/qemu-iotests/384     |  547 +++++++
+ tests/qemu-iotests/384.out | 2846 ++++++++++++++++++++++++++++++++++++
+ tests/qemu-iotests/group   |    1 +
+ 3 files changed, 3394 insertions(+)
+ create mode 100755 tests/qemu-iotests/384
+ create mode 100644 tests/qemu-iotests/384.out
+
+diff --git a/tests/qemu-iotests/384 b/tests/qemu-iotests/384
+new file mode 100755
+index 0000000000..b04a8e651a
+--- /dev/null
++++ b/tests/qemu-iotests/384
+@@ -0,0 +1,547 @@
++#!/usr/bin/env python3
++#
++# Test bitmap-sync mirrors (incremental, differential, and partials)
++#
++# Copyright (c) 2019 John Snow for Red Hat, Inc.
++#
++# This program is free software; you can redistribute it and/or modify
++# it under the terms of the GNU General Public License as published by
++# the Free Software Foundation; either version 2 of the License, or
++# (at your option) any later version.
++#
++# This program is distributed in the hope that it will be useful,
++# but WITHOUT ANY WARRANTY; without even the implied warranty of
++# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
++# GNU General Public License for more details.
++#
++# You should have received a copy of the GNU General Public License
++# along with this program.  If not, see <http://www.gnu.org/licenses/>.
++#
++# owner=jsnow@redhat.com
++
++import math
++import os
++
++import iotests
++from iotests import log, qemu_img
++
++SIZE = 64 * 1024 * 1024
++GRANULARITY = 64 * 1024
++
++
++class Pattern:
++    def __init__(self, byte, offset, size=GRANULARITY):
++        self.byte = byte
++        self.offset = offset
++        self.size = size
++
++    def bits(self, granularity):
++        lower = self.offset // granularity
++        upper = (self.offset + self.size - 1) // granularity
++        return set(range(lower, upper + 1))
++
++
++class PatternGroup:
++    """Grouping of Pattern objects. Initialize with an iterable of Patterns."""
++    def __init__(self, patterns):
++        self.patterns = patterns
++
++    def bits(self, granularity):
++        """Calculate the unique bits dirtied by this pattern grouping"""
++        res = set()
++        for pattern in self.patterns:
++            res |= pattern.bits(granularity)
++        return res
++
++
++GROUPS = [
++    PatternGroup([
++        # Batch 0: 4 clusters
++        Pattern('0x49', 0x0000000),
++        Pattern('0x6c', 0x0100000),   # 1M
++        Pattern('0x6f', 0x2000000),   # 32M
++        Pattern('0x76', 0x3ff0000)]), # 64M - 64K
++    PatternGroup([
++        # Batch 1: 6 clusters (3 new)
++        Pattern('0x65', 0x0000000),   # Full overwrite
++        Pattern('0x77', 0x00f8000),   # Partial-left (1M-32K)
++        Pattern('0x72', 0x2008000),   # Partial-right (32M+32K)
++        Pattern('0x69', 0x3fe0000)]), # Adjacent-left (64M - 128K)
++    PatternGroup([
++        # Batch 2: 7 clusters (3 new)
++        Pattern('0x74', 0x0010000),   # Adjacent-right
++        Pattern('0x69', 0x00e8000),   # Partial-left  (1M-96K)
++        Pattern('0x6e', 0x2018000),   # Partial-right (32M+96K)
++        Pattern('0x67', 0x3fe0000,
++                2*GRANULARITY)]),     # Overwrite [(64M-128K)-64M)
++    PatternGroup([
++        # Batch 3: 8 clusters (5 new)
++        # Carefully chosen such that nothing re-dirties the one cluster
++        # that copies out successfully before failure in Group #1.
++        Pattern('0xaa', 0x0010000,
++                3*GRANULARITY),       # Overwrite and 2x Adjacent-right
++        Pattern('0xbb', 0x00d8000),   # Partial-left (1M-160K)
++        Pattern('0xcc', 0x2028000),   # Partial-right (32M+160K)
++        Pattern('0xdd', 0x3fc0000)]), # New; leaving a gap to the right
++]
++
++
++class EmulatedBitmap:
++    def __init__(self, granularity=GRANULARITY):
++        self._bits = set()
++        self.granularity = granularity
++
++    def dirty_bits(self, bits):
++        self._bits |= set(bits)
++
++    def dirty_group(self, n):
++        self.dirty_bits(GROUPS[n].bits(self.granularity))
++
++    def clear(self):
++        self._bits = set()
++
++    def clear_bits(self, bits):
++        self._bits -= set(bits)
++
++    def clear_bit(self, bit):
++        self.clear_bits({bit})
++
++    def clear_group(self, n):
++        self.clear_bits(GROUPS[n].bits(self.granularity))
++
++    @property
++    def first_bit(self):
++        return sorted(self.bits)[0]
++
++    @property
++    def bits(self):
++        return self._bits
++
++    @property
++    def count(self):
++        return len(self.bits)
++
++    def compare(self, qmp_bitmap):
++        """
++        Print a nice human-readable message checking that a bitmap as reported
++        by the QMP interface has as many bits set as we expect it to.
++        """
++
++        name = qmp_bitmap.get('name', '(anonymous)')
++        log("= Checking Bitmap {:s} =".format(name))
++
++        want = self.count
++        have = qmp_bitmap['count'] // qmp_bitmap['granularity']
++
++        log("expecting {:d} dirty sectors; have {:d}. {:s}".format(
++            want, have, "OK!" if want == have else "ERROR!"))
++        log('')
++
++
++class Drive:
++    """Represents, vaguely, a drive attached to a VM.
++    Includes format, graph, and device information."""
++
++    def __init__(self, path, vm=None):
++        self.path = path
++        self.vm = vm
++        self.fmt = None
++        self.size = None
++        self.node = None
++
++    def img_create(self, fmt, size):
++        self.fmt = fmt
++        self.size = size
++        iotests.qemu_img_create('-f', self.fmt, self.path, str(self.size))
++
++    def create_target(self, name, fmt, size):
++        basename = os.path.basename(self.path)
++        file_node_name = "file_{}".format(basename)
++        vm = self.vm
++
++        log(vm.command('blockdev-create', job_id='bdc-file-job',
++                       options={
++                           'driver': 'file',
++                           'filename': self.path,
++                           'size': 0,
++                       }))
++        vm.run_job('bdc-file-job')
++        log(vm.command('blockdev-add', driver='file',
++                       node_name=file_node_name, filename=self.path))
++
++        log(vm.command('blockdev-create', job_id='bdc-fmt-job',
++                       options={
++                           'driver': fmt,
++                           'file': file_node_name,
++                           'size': size,
++                       }))
++        vm.run_job('bdc-fmt-job')
++        log(vm.command('blockdev-add', driver=fmt,
++                       node_name=name,
++                       file=file_node_name))
++        self.fmt = fmt
++        self.size = size
++        self.node = name
++
++def blockdev_mirror(vm, device, target, sync, **kwargs):
++    # Strip any arguments explicitly nulled by the caller:
++    kwargs = {key: val for key, val in kwargs.items() if val is not None}
++    result = vm.qmp_log('blockdev-mirror',
++                        device=device,
++                        target=target,
++                        sync=sync,
++                        filter_node_name='mirror-top',
++                        **kwargs)
++    return result
++
++def blockdev_mirror_mktarget(drive, target_id, filepath, sync, **kwargs):
++    target_drive = Drive(filepath, vm=drive.vm)
++    target_drive.create_target(target_id, drive.fmt, drive.size)
++    blockdev_mirror(drive.vm, drive.node, target_id, sync, **kwargs)
++
++def reference_mirror(drive, n, filepath):
++    log("--- Reference mirror #{:d} ---\n".format(n))
++    target_id = "ref_target_{:d}".format(n)
++    job_id = "ref_mirror_{:d}".format(n)
++    blockdev_mirror_mktarget(drive, target_id, filepath, "full",
++                             job_id=job_id)
++    drive.vm.run_job(job_id, auto_dismiss=True)
++    log('')
++
++def mirror(drive, n, filepath, sync, **kwargs):
++    log("--- Test mirror #{:d} ---\n".format(n))
++    target_id = "mirror_target_{:d}".format(n)
++    job_id = "mirror_{:d}".format(n)
++    kwargs.setdefault('auto-finalize', False)
++    blockdev_mirror_mktarget(drive, target_id, filepath, sync,
++                             job_id=job_id, **kwargs)
++    return job_id
++
++def perform_writes(drive, n, filter_node_name=None):
++    log("--- Write #{:d} ---\n".format(n))
++    for pattern in GROUPS[n].patterns:
++        cmd = "write -P{:s} 0x{:07x} 0x{:x}".format(
++            pattern.byte,
++            pattern.offset,
++            pattern.size)
++        log(cmd)
++        log(drive.vm.hmp_qemu_io(filter_node_name or drive.node, cmd))
++    bitmaps = drive.vm.query_bitmaps()
++    log({'bitmaps': bitmaps}, indent=2)
++    log('')
++    return bitmaps
++
++
++def compare_images(image, reference, baseimg=None, expected_match=True):
++    """
++    Print a nice human-readable message comparing these images.
++    """
++    expected_ret = 0 if expected_match else 1
++    if baseimg:
++        assert qemu_img("rebase", "-u", "-b", baseimg, image) == 0
++    ret = qemu_img("compare", image, reference)
++    log('qemu_img compare "{:s}" "{:s}" ==> {:s}, {:s}'.format(
++        image, reference,
++        "Identical" if ret == 0 else "Mismatch",
++        "OK!" if ret == expected_ret else "ERROR!"),
++        filters=[iotests.filter_testfiles])
++
++def test_bitmap_sync(bsync_mode, msync_mode='bitmap', failure=None):
++    """
++    Test bitmap mirror routines.
++
++    :param bsync_mode: Is the Bitmap Sync mode, and can be any of:
++        - on-success: This is the "incremental" style mode. Bitmaps are
++                      synchronized to what was copied out only on success.
++                      (Partial images must be discarded.)
++        - never:      This is the "differential" style mode.
++                      Bitmaps are never synchronized.
++        - always:     This is a "best effort" style mode.
++                      Bitmaps are always synchronized, regardless of failure.
++                      (Partial images must be kept.)
++
++    :param msync_mode: The mirror sync mode to use for the first mirror.
++                       Can be any one of:
++        - bitmap: mirrors based on bitmap manifest.
++        - full:   Full mirrors.
++        - top:    Full mirrors of the top layer only.
++
++    :param failure: Is the (optional) failure mode, and can be any of:
++        - None:         No failure. Test the normative path. Default.
++        - simulated:    Cancel the job right before it completes.
++                        This also tests writes "during" the job.
++        - intermediate: This tests a job that fails mid-process and produces
++                        an incomplete mirror. Testing limitations prevent
++                        testing competing writes.
++    """
++    with iotests.FilePaths(['img', 'bsync1', 'bsync2', 'bsync3',
++                            'fmirror0', 'fmirror1', 'fmirror2', 'fmirror3']) as \
++                            (img_path, bsync1, bsync2, bsync3,
++                             fmirror0, fmirror1, fmirror2, fmirror3), \
++         iotests.VM() as vm:
++
++        mode = "Mode {:s}; Bitmap Sync {:s}".format(msync_mode, bsync_mode)
++        preposition = "with" if failure else "without"
++        cond = "{:s} {:s}".format(preposition,
++                                  "{:s} failure".format(failure) if failure
++                                  else "failure")
++        log("\n=== {:s} {:s} ===\n".format(mode, cond))
++
++        log('--- Preparing image & VM ---\n')
++        drive0 = Drive(img_path, vm=vm)
++        drive0.img_create(iotests.imgfmt, SIZE)
++        vm.add_device("{},id=scsi0".format(iotests.get_virtio_scsi_device()))
++        vm.launch()
++
++        file_config = {
++            'driver': 'file',
++            'filename': drive0.path
++        }
++
++        if failure == 'intermediate':
++            file_config = {
++                'driver': 'blkdebug',
++                'image': file_config,
++                'set-state': [{
++                    'event': 'flush_to_disk',
++                    'state': 1,
++                    'new_state': 2
++                }, {
++                    'event': 'read_aio',
++                    'state': 2,
++                    'new_state': 3
++                }, {
++                    'event': 'read_aio',
++                    'state': 3,
++                    'new_state': 4
++                }],
++                'inject-error': [{
++                    'event': 'read_aio',
++                    'errno': 5,
++                    'state': 3,
++                    'immediately': False,
++                    'once': True
++                }, {
++                    'event': 'read_aio',
++                    'errno': 5,
++                    'state': 4,
++                    'immediately': False,
++                    'once': True
++                }]
++            }
++
++        drive0.node = 'drive0'
++        vm.qmp_log('blockdev-add',
++                   filters=[iotests.filter_qmp_testfiles],
++                   node_name=drive0.node,
++                   driver=drive0.fmt,
++                   file=file_config)
++        log('')
++
++        # 0 - Writes and Reference mirror
++        perform_writes(drive0, 0)
++        reference_mirror(drive0, 0, fmirror0)
++        log('--- Add Bitmap ---\n')
++        vm.qmp_log("block-dirty-bitmap-add", node=drive0.node,
++                   name="bitmap0", granularity=GRANULARITY)
++        log('')
++        ebitmap = EmulatedBitmap()
++
++        # 1 - Writes and Reference mirror
++        bitmaps = perform_writes(drive0, 1)
++        ebitmap.dirty_group(1)
++        bitmap = vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps)
++        ebitmap.compare(bitmap)
++        reference_mirror(drive0, 1, fmirror1)
++
++        # 1 - Test mirror (w/ Optional induced failure)
++        if failure == 'intermediate':
++            # Activate blkdebug induced failure for second-to-next read
++            log(vm.hmp_qemu_io(drive0.node, 'flush'))
++            log('')
++        job = mirror(drive0, 1, bsync1, msync_mode,
++                     bitmap="bitmap0", bitmap_mode=bsync_mode)
++
++        vm.run_job(job, auto_dismiss=True, auto_finalize=False,
++                   cancel=(failure == 'simulated'))
++        bitmaps = vm.query_bitmaps()
++        log({'bitmaps': bitmaps}, indent=2)
++        log('')
++
++        if bsync_mode == 'always':
++            if failure == 'intermediate':
++                # We manage to copy one sector (one bit) before the error.
++                ebitmap.clear_bit(ebitmap.first_bit)
++            else:
++                # successful mirror / cancelled complete mirror
++                ebitmap.clear()
++
++        if bsync_mode == 'on-success' and not failure:
++            ebitmap.clear()
++
++        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
++
++        # 2 - Reference mirror
++        reference_mirror(drive0, 2, fmirror2)
++
++        # 2 - Bitmap mirror with writes before completion
++        job = mirror(drive0, 2, bsync2, "bitmap",
++                     bitmap="bitmap0", bitmap_mode=bsync_mode)
++
++        bitmaps = perform_writes(drive0, 2)
++        ebitmap.dirty_group(2)
++        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
++
++        # don't use run_job as that logs too much even with use_log=False
++        events = [('JOB_STATUS_CHANGE', {'data': {'id': job}})]
++        while True:
++            ev = iotests.filter_qmp_event(vm.events_wait(events, timeout=10))
++            status = ev['data']['status']
++            if status == 'ready':
++                vm.qmp('job-complete', id=job)
++            elif status == 'standby':
++                vm.qmp('job-resume', id=job)
++            elif status == 'pending':
++                vm.qmp('job-finalize', id=job)
++            elif status == 'null':
++                break
++
++        if bsync_mode != 'never':
++            ebitmap.clear()
++
++        bitmaps = vm.query_bitmaps()
++        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
++
++        # 3 - Writes and Reference mirror
++        bitmaps = perform_writes(drive0, 3)
++        ebitmap.dirty_group(3)
++        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
++        reference_mirror(drive0, 3, fmirror3)
++
++        # 3 - Bitmap mirror (In failure modes, this is a recovery.)
++        job = mirror(drive0, 3, bsync3, "bitmap",
++                     bitmap="bitmap0", bitmap_mode=bsync_mode)
++
++        vm.run_job(job, auto_dismiss=True, auto_finalize=False)
++        bitmaps = vm.query_bitmaps()
++
++        log({'bitmaps': bitmaps}, indent=2)
++        log('')
++        if bsync_mode != 'never':
++            ebitmap.clear()
++        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
++
++        log('--- Cleanup ---\n')
++        vm.qmp_log("block-dirty-bitmap-remove",
++                   node=drive0.node, name="bitmap0")
++        bitmaps = vm.query_bitmaps()
++        log({'bitmaps': bitmaps}, indent=2)
++        vm.shutdown()
++        log('')
++
++        log('--- Verification ---\n')
++        compare_images(bsync1, fmirror1, baseimg=fmirror0,
++                       expected_match=failure != 'intermediate')
++        if not failure or bsync_mode == 'always':
++            # Always keep the last mirror on success or when using 'always'
++            base = bsync1
++        else:
++            base = fmirror1
++
++        compare_images(bsync2, fmirror2, baseimg=base, expected_match=0)
++        compare_images(bsync3, fmirror3, baseimg=bsync2)
++        compare_images(img_path, fmirror3)
++        log('')
++
++def test_mirror_api():
++    """
++    Test malformed and prohibited invocations of the mirror API.
++    """
++    with iotests.FilePaths(['img', 'bsync1']) as \
++         (img_path, mirror_path), \
++         iotests.VM() as vm:
++
++        log("\n=== API failure tests ===\n")
++        log('--- Preparing image & VM ---\n')
++        drive0 = Drive(img_path, vm=vm)
++        drive0.img_create(iotests.imgfmt, SIZE)
++        vm.add_device("{},id=scsi0".format(iotests.get_virtio_scsi_device()))
++        vm.launch()
++
++        file_config = {
++            'driver': 'file',
++            'filename': drive0.path
++        }
++
++        drive0.node = 'drive0'
++        vm.qmp_log('blockdev-add',
++                   filters=[iotests.filter_qmp_testfiles],
++                   node_name=drive0.node,
++                   driver=drive0.fmt,
++                   file=file_config)
++        log('')
++
++        target0 = Drive(mirror_path, vm=vm)
++        target0.create_target("mirror_target", drive0.fmt, drive0.size)
++        log('')
++
++        vm.qmp_log("block-dirty-bitmap-add", node=drive0.node,
++                   name="bitmap0", granularity=GRANULARITY)
++        log('')
++
++        log('-- Testing invalid QMP commands --\n')
++
++        error_cases = {
++            'incremental': {
++                None:        ['on-success', 'always', 'never', None],
++                'bitmap404': ['on-success', 'always', 'never', None],
++                'bitmap0':   ['always', 'never']
++            },
++            'bitmap': {
++                None:        ['on-success', 'always', 'never', None],
++                'bitmap404': ['on-success', 'always', 'never', None],
++                'bitmap0':   [None],
++            },
++            'full': {
++                None:        ['on-success', 'always', 'never'],
++                'bitmap404': ['on-success', 'always', 'never', None],
++                'bitmap0':   ['on-success', 'always', 'never', None],
++            },
++            'top': {
++                None:        ['on-success', 'always', 'never'],
++                'bitmap404': ['on-success', 'always', 'never', None],
++                'bitmap0':   ['on-success', 'always', 'never', None],
++            },
++            'none': {
++                None:        ['on-success', 'always', 'never'],
++                'bitmap404': ['on-success', 'always', 'never', None],
++                'bitmap0':   ['on-success', 'always', 'never', None],
++            }
++        }
++
++        # Dicts, as always, are not stably-ordered prior to 3.7, so use tuples:
++        for sync_mode in ('incremental', 'bitmap', 'full', 'top', 'none'):
++            log("-- Sync mode {:s} tests --\n".format(sync_mode))
++            for bitmap in (None, 'bitmap404', 'bitmap0'):
++                for policy in error_cases[sync_mode][bitmap]:
++                    blockdev_mirror(drive0.vm, drive0.node, "mirror_target",
++                                    sync_mode, job_id='api_job',
++                                    bitmap=bitmap, bitmap_mode=policy)
++                    log('')
++
++
++def main():
++    for bsync_mode in ("never", "on-success", "always"):
++        for failure in ("simulated", "intermediate", None):
++            test_bitmap_sync(bsync_mode, "bitmap", failure)
++
++#    for sync_mode in ('full', 'top'):
++#        for bsync_mode in ('on-success', 'always'):
++#            for failure in ('simulated', 'intermediate', None):
++#                test_bitmap_sync(bsync_mode, sync_mode, failure)
++
++    test_mirror_api()
++
++if __name__ == '__main__':
++    iotests.script_main(main, supported_fmts=['qcow2'],
++                        supported_protocols=['file'])
+diff --git a/tests/qemu-iotests/384.out b/tests/qemu-iotests/384.out
+new file mode 100644
+index 0000000000..9b7408b6d6
+--- /dev/null
++++ b/tests/qemu-iotests/384.out
+@@ -0,0 +1,2846 @@
++
++=== Mode bitmap; Bitmap Sync never with simulated failure ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
++{"return": {}}
++
++--- Write #0 ---
++
++write -P0x49 0x0000000 0x10000
++{"return": ""}
++write -P0x6c 0x0100000 0x10000
++{"return": ""}
++write -P0x6f 0x2000000 0x10000
++{"return": ""}
++write -P0x76 0x3ff0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {}
++}
++
++--- Reference mirror #0 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Add Bitmap ---
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++--- Write #1 ---
++
++write -P0x65 0x0000000 0x10000
++{"return": ""}
++write -P0x77 0x00f8000 0x10000
++{"return": ""}
++write -P0x72 0x2008000 0x10000
++{"return": ""}
++write -P0x69 0x3fe0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-cancel", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_CANCELLED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
++{"return": {}}
++--- Write #2 ---
++
++write -P0x74 0x0010000 0x10000
++{"return": ""}
++write -P0x69 0x00e8000 0x10000
++{"return": ""}
++write -P0x6e 0x2018000 0x10000
++{"return": ""}
++write -P0x67 0x3fe0000 0x20000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 262144,
++        "granularity": 65536,
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      },
++      {
++        "busy": true,
++        "count": 655360,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "locked"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 10 dirty sectors; have 10. OK!
++
++= Checking Bitmap bitmap0 =
++expecting 10 dirty sectors; have 10. OK!
++
++--- Write #3 ---
++
++write -P0xaa 0x0010000 0x30000
++{"return": ""}
++write -P0xbb 0x00d8000 0x10000
++{"return": ""}
++write -P0xcc 0x2028000 0x10000
++{"return": ""}
++write -P0xdd 0x3fc0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 983040,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 15 dirty sectors; have 15. OK!
++
++--- Reference mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 983040,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 15 dirty sectors; have 15. OK!
++
++--- Cleanup ---
++
++{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++{
++  "bitmaps": {}
++}
++
++--- Verification ---
++
++qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++
++
++=== Mode bitmap; Bitmap Sync never with intermediate failure ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "blkdebug", "image": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "inject-error": [{"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 3}, {"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 4}], "set-state": [{"event": "flush_to_disk", "new-state": 2, "state": 1}, {"event": "read_aio", "new-state": 3, "state": 2}, {"event": "read_aio", "new-state": 4, "state": 3}]}, "node-name": "drive0"}}
++{"return": {}}
++
++--- Write #0 ---
++
++write -P0x49 0x0000000 0x10000
++{"return": ""}
++write -P0x6c 0x0100000 0x10000
++{"return": ""}
++write -P0x6f 0x2000000 0x10000
++{"return": ""}
++write -P0x76 0x3ff0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {}
++}
++
++--- Reference mirror #0 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Add Bitmap ---
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++--- Write #1 ---
++
++write -P0x65 0x0000000 0x10000
++{"return": ""}
++write -P0x77 0x00f8000 0x10000
++{"return": ""}
++write -P0x72 0x2008000 0x10000
++{"return": ""}
++write -P0x69 0x3fe0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++{"return": ""}
++
++--- Test mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
++{"return": {}}
++{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_1", "error": "Input/output error", "len": 393216, "offset": 65536, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
++{"return": {}}
++--- Write #2 ---
++
++write -P0x74 0x0010000 0x10000
++{"return": ""}
++write -P0x69 0x00e8000 0x10000
++{"return": ""}
++write -P0x6e 0x2018000 0x10000
++{"return": ""}
++write -P0x67 0x3fe0000 0x20000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 262144,
++        "granularity": 65536,
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      },
++      {
++        "busy": true,
++        "count": 655360,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "locked"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 10 dirty sectors; have 10. OK!
++
++= Checking Bitmap bitmap0 =
++expecting 10 dirty sectors; have 10. OK!
++
++--- Write #3 ---
++
++write -P0xaa 0x0010000 0x30000
++{"return": ""}
++write -P0xbb 0x00d8000 0x10000
++{"return": ""}
++write -P0xcc 0x2028000 0x10000
++{"return": ""}
++write -P0xdd 0x3fc0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 983040,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 15 dirty sectors; have 15. OK!
++
++--- Reference mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 983040,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 15 dirty sectors; have 15. OK!
++
++--- Cleanup ---
++
++{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++{
++  "bitmaps": {}
++}
++
++--- Verification ---
++
++qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++
++
++=== Mode bitmap; Bitmap Sync never without failure ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
++{"return": {}}
++
++--- Write #0 ---
++
++write -P0x49 0x0000000 0x10000
++{"return": ""}
++write -P0x6c 0x0100000 0x10000
++{"return": ""}
++write -P0x6f 0x2000000 0x10000
++{"return": ""}
++write -P0x76 0x3ff0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {}
++}
++
++--- Reference mirror #0 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Add Bitmap ---
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++--- Write #1 ---
++
++write -P0x65 0x0000000 0x10000
++{"return": ""}
++write -P0x77 0x00f8000 0x10000
++{"return": ""}
++write -P0x72 0x2008000 0x10000
++{"return": ""}
++write -P0x69 0x3fe0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
++{"return": {}}
++--- Write #2 ---
++
++write -P0x74 0x0010000 0x10000
++{"return": ""}
++write -P0x69 0x00e8000 0x10000
++{"return": ""}
++write -P0x6e 0x2018000 0x10000
++{"return": ""}
++write -P0x67 0x3fe0000 0x20000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 262144,
++        "granularity": 65536,
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      },
++      {
++        "busy": true,
++        "count": 655360,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "locked"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 10 dirty sectors; have 10. OK!
++
++= Checking Bitmap bitmap0 =
++expecting 10 dirty sectors; have 10. OK!
++
++--- Write #3 ---
++
++write -P0xaa 0x0010000 0x30000
++{"return": ""}
++write -P0xbb 0x00d8000 0x10000
++{"return": ""}
++write -P0xcc 0x2028000 0x10000
++{"return": ""}
++write -P0xdd 0x3fc0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 983040,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 15 dirty sectors; have 15. OK!
++
++--- Reference mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 983040,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 15 dirty sectors; have 15. OK!
++
++--- Cleanup ---
++
++{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++{
++  "bitmaps": {}
++}
++
++--- Verification ---
++
++qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++
++
++=== Mode bitmap; Bitmap Sync on-success with simulated failure ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
++{"return": {}}
++
++--- Write #0 ---
++
++write -P0x49 0x0000000 0x10000
++{"return": ""}
++write -P0x6c 0x0100000 0x10000
++{"return": ""}
++write -P0x6f 0x2000000 0x10000
++{"return": ""}
++write -P0x76 0x3ff0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {}
++}
++
++--- Reference mirror #0 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Add Bitmap ---
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++--- Write #1 ---
++
++write -P0x65 0x0000000 0x10000
++{"return": ""}
++write -P0x77 0x00f8000 0x10000
++{"return": ""}
++write -P0x72 0x2008000 0x10000
++{"return": ""}
++write -P0x69 0x3fe0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-cancel", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_CANCELLED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
++{"return": {}}
++--- Write #2 ---
++
++write -P0x74 0x0010000 0x10000
++{"return": ""}
++write -P0x69 0x00e8000 0x10000
++{"return": ""}
++write -P0x6e 0x2018000 0x10000
++{"return": ""}
++write -P0x67 0x3fe0000 0x20000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 262144,
++        "granularity": 65536,
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      },
++      {
++        "busy": true,
++        "count": 655360,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "locked"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 10 dirty sectors; have 10. OK!
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Write #3 ---
++
++write -P0xaa 0x0010000 0x30000
++{"return": ""}
++write -P0xbb 0x00d8000 0x10000
++{"return": ""}
++write -P0xcc 0x2028000 0x10000
++{"return": ""}
++write -P0xdd 0x3fc0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 524288,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 8 dirty sectors; have 8. OK!
++
++--- Reference mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 0,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Cleanup ---
++
++{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++{
++  "bitmaps": {}
++}
++
++--- Verification ---
++
++qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++
++
++=== Mode bitmap; Bitmap Sync on-success with intermediate failure ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "blkdebug", "image": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "inject-error": [{"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 3}, {"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 4}], "set-state": [{"event": "flush_to_disk", "new-state": 2, "state": 1}, {"event": "read_aio", "new-state": 3, "state": 2}, {"event": "read_aio", "new-state": 4, "state": 3}]}, "node-name": "drive0"}}
++{"return": {}}
++
++--- Write #0 ---
++
++write -P0x49 0x0000000 0x10000
++{"return": ""}
++write -P0x6c 0x0100000 0x10000
++{"return": ""}
++write -P0x6f 0x2000000 0x10000
++{"return": ""}
++write -P0x76 0x3ff0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {}
++}
++
++--- Reference mirror #0 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Add Bitmap ---
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++--- Write #1 ---
++
++write -P0x65 0x0000000 0x10000
++{"return": ""}
++write -P0x77 0x00f8000 0x10000
++{"return": ""}
++write -P0x72 0x2008000 0x10000
++{"return": ""}
++write -P0x69 0x3fe0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++{"return": ""}
++
++--- Test mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
++{"return": {}}
++{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_1", "error": "Input/output error", "len": 393216, "offset": 65536, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
++{"return": {}}
++--- Write #2 ---
++
++write -P0x74 0x0010000 0x10000
++{"return": ""}
++write -P0x69 0x00e8000 0x10000
++{"return": ""}
++write -P0x6e 0x2018000 0x10000
++{"return": ""}
++write -P0x67 0x3fe0000 0x20000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 262144,
++        "granularity": 65536,
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      },
++      {
++        "busy": true,
++        "count": 655360,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "locked"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 10 dirty sectors; have 10. OK!
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Write #3 ---
++
++write -P0xaa 0x0010000 0x30000
++{"return": ""}
++write -P0xbb 0x00d8000 0x10000
++{"return": ""}
++write -P0xcc 0x2028000 0x10000
++{"return": ""}
++write -P0xdd 0x3fc0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 524288,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 8 dirty sectors; have 8. OK!
++
++--- Reference mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 0,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Cleanup ---
++
++{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++{
++  "bitmaps": {}
++}
++
++--- Verification ---
++
++qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++
++
++=== Mode bitmap; Bitmap Sync on-success without failure ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
++{"return": {}}
++
++--- Write #0 ---
++
++write -P0x49 0x0000000 0x10000
++{"return": ""}
++write -P0x6c 0x0100000 0x10000
++{"return": ""}
++write -P0x6f 0x2000000 0x10000
++{"return": ""}
++write -P0x76 0x3ff0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {}
++}
++
++--- Reference mirror #0 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Add Bitmap ---
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++--- Write #1 ---
++
++write -P0x65 0x0000000 0x10000
++{"return": ""}
++write -P0x77 0x00f8000 0x10000
++{"return": ""}
++write -P0x72 0x2008000 0x10000
++{"return": ""}
++write -P0x69 0x3fe0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 0,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Reference mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
++{"return": {}}
++--- Write #2 ---
++
++write -P0x74 0x0010000 0x10000
++{"return": ""}
++write -P0x69 0x00e8000 0x10000
++{"return": ""}
++write -P0x6e 0x2018000 0x10000
++{"return": ""}
++write -P0x67 0x3fe0000 0x20000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 458752,
++        "granularity": 65536,
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      },
++      {
++        "busy": true,
++        "count": 458752,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "locked"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 7 dirty sectors; have 7. OK!
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Write #3 ---
++
++write -P0xaa 0x0010000 0x30000
++{"return": ""}
++write -P0xbb 0x00d8000 0x10000
++{"return": ""}
++write -P0xcc 0x2028000 0x10000
++{"return": ""}
++write -P0xdd 0x3fc0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 524288,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 8 dirty sectors; have 8. OK!
++
++--- Reference mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 0,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Cleanup ---
++
++{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++{
++  "bitmaps": {}
++}
++
++--- Verification ---
++
++qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++
++
++=== Mode bitmap; Bitmap Sync always with simulated failure ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
++{"return": {}}
++
++--- Write #0 ---
++
++write -P0x49 0x0000000 0x10000
++{"return": ""}
++write -P0x6c 0x0100000 0x10000
++{"return": ""}
++write -P0x6f 0x2000000 0x10000
++{"return": ""}
++write -P0x76 0x3ff0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {}
++}
++
++--- Reference mirror #0 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Add Bitmap ---
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++--- Write #1 ---
++
++write -P0x65 0x0000000 0x10000
++{"return": ""}
++write -P0x77 0x00f8000 0x10000
++{"return": ""}
++write -P0x72 0x2008000 0x10000
++{"return": ""}
++write -P0x69 0x3fe0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-cancel", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_CANCELLED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 0,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Reference mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
++{"return": {}}
++--- Write #2 ---
++
++write -P0x74 0x0010000 0x10000
++{"return": ""}
++write -P0x69 0x00e8000 0x10000
++{"return": ""}
++write -P0x6e 0x2018000 0x10000
++{"return": ""}
++write -P0x67 0x3fe0000 0x20000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 458752,
++        "granularity": 65536,
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      },
++      {
++        "busy": true,
++        "count": 458752,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "locked"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 7 dirty sectors; have 7. OK!
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Write #3 ---
++
++write -P0xaa 0x0010000 0x30000
++{"return": ""}
++write -P0xbb 0x00d8000 0x10000
++{"return": ""}
++write -P0xcc 0x2028000 0x10000
++{"return": ""}
++write -P0xdd 0x3fc0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 524288,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 8 dirty sectors; have 8. OK!
++
++--- Reference mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 0,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Cleanup ---
++
++{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++{
++  "bitmaps": {}
++}
++
++--- Verification ---
++
++qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++
++
++=== Mode bitmap; Bitmap Sync always with intermediate failure ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "blkdebug", "image": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "inject-error": [{"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 3}, {"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 4}], "set-state": [{"event": "flush_to_disk", "new-state": 2, "state": 1}, {"event": "read_aio", "new-state": 3, "state": 2}, {"event": "read_aio", "new-state": 4, "state": 3}]}, "node-name": "drive0"}}
++{"return": {}}
++
++--- Write #0 ---
++
++write -P0x49 0x0000000 0x10000
++{"return": ""}
++write -P0x6c 0x0100000 0x10000
++{"return": ""}
++write -P0x6f 0x2000000 0x10000
++{"return": ""}
++write -P0x76 0x3ff0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {}
++}
++
++--- Reference mirror #0 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Add Bitmap ---
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++--- Write #1 ---
++
++write -P0x65 0x0000000 0x10000
++{"return": ""}
++write -P0x77 0x00f8000 0x10000
++{"return": ""}
++write -P0x72 0x2008000 0x10000
++{"return": ""}
++write -P0x69 0x3fe0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++{"return": ""}
++
++--- Test mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
++{"return": {}}
++{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_1", "error": "Input/output error", "len": 393216, "offset": 65536, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 327680,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 5 dirty sectors; have 5. OK!
++
++--- Reference mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
++{"return": {}}
++--- Write #2 ---
++
++write -P0x74 0x0010000 0x10000
++{"return": ""}
++write -P0x69 0x00e8000 0x10000
++{"return": ""}
++write -P0x6e 0x2018000 0x10000
++{"return": ""}
++write -P0x67 0x3fe0000 0x20000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 262144,
++        "granularity": 65536,
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      },
++      {
++        "busy": true,
++        "count": 589824,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "locked"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 9 dirty sectors; have 9. OK!
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Write #3 ---
++
++write -P0xaa 0x0010000 0x30000
++{"return": ""}
++write -P0xbb 0x00d8000 0x10000
++{"return": ""}
++write -P0xcc 0x2028000 0x10000
++{"return": ""}
++write -P0xdd 0x3fc0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 524288,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 8 dirty sectors; have 8. OK!
++
++--- Reference mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 0,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Cleanup ---
++
++{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++{
++  "bitmaps": {}
++}
++
++--- Verification ---
++
++qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++
++
++=== Mode bitmap; Bitmap Sync always without failure ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
++{"return": {}}
++
++--- Write #0 ---
++
++write -P0x49 0x0000000 0x10000
++{"return": ""}
++write -P0x6c 0x0100000 0x10000
++{"return": ""}
++write -P0x6f 0x2000000 0x10000
++{"return": ""}
++write -P0x76 0x3ff0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {}
++}
++
++--- Reference mirror #0 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Add Bitmap ---
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++--- Write #1 ---
++
++write -P0x65 0x0000000 0x10000
++{"return": ""}
++write -P0x77 0x00f8000 0x10000
++{"return": ""}
++write -P0x72 0x2008000 0x10000
++{"return": ""}
++write -P0x69 0x3fe0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 393216,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 6 dirty sectors; have 6. OK!
++
++--- Reference mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #1 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_1"}}
++{"return": {}}
++{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 0,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Reference mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #2 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
++{"return": {}}
++--- Write #2 ---
++
++write -P0x74 0x0010000 0x10000
++{"return": ""}
++write -P0x69 0x00e8000 0x10000
++{"return": ""}
++write -P0x6e 0x2018000 0x10000
++{"return": ""}
++write -P0x67 0x3fe0000 0x20000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 458752,
++        "granularity": 65536,
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      },
++      {
++        "busy": true,
++        "count": 458752,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "locked"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 7 dirty sectors; have 7. OK!
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Write #3 ---
++
++write -P0xaa 0x0010000 0x30000
++{"return": ""}
++write -P0xbb 0x00d8000 0x10000
++{"return": ""}
++write -P0xcc 0x2028000 0x10000
++{"return": ""}
++write -P0xdd 0x3fc0000 0x10000
++{"return": ""}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 524288,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 8 dirty sectors; have 8. OK!
++
++--- Reference mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
++{"return": {}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++
++--- Test mirror #3 ---
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
++{"return": {}}
++{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
++{"return": {}}
++{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
++{
++  "bitmaps": {
++    "drive0": [
++      {
++        "busy": false,
++        "count": 0,
++        "granularity": 65536,
++        "name": "bitmap0",
++        "persistent": false,
++        "recording": true,
++        "status": "active"
++      }
++    ]
++  }
++}
++
++= Checking Bitmap bitmap0 =
++expecting 0 dirty sectors; have 0. OK!
++
++--- Cleanup ---
++
++{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++{
++  "bitmaps": {}
++}
++
++--- Verification ---
++
++qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
++qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
++
++
++=== API failure tests ===
++
++--- Preparing image & VM ---
++
++{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
++{"return": {}}
++
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
++{"return": {}}
++{}
++{}
++{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
++{"return": {}}
++{}
++
++{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
++{"return": {}}
++
++-- Testing invalid QMP commands --
++
++-- Sync mode incremental tests --
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
++
++-- Sync mode bitmap tests --
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++
++-- Sync mode full tests --
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++
++-- Sync mode top tests --
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++
++-- Sync mode none tests --
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
++
++{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
++{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++
+diff --git a/tests/qemu-iotests/group b/tests/qemu-iotests/group
+index 435dccd5af..939efd9c70 100644
+--- a/tests/qemu-iotests/group
++++ b/tests/qemu-iotests/group
+@@ -270,6 +270,7 @@
+ 253 rw quick
+ 254 rw backing quick
+ 255 rw quick
++384 rw
+ 256 rw auto quick
+ 257 rw
+ 258 rw quick
diff --git a/debian/patches/pve/0036-mirror-add-check-for-bitmap-mode-without-bitmap.patch b/debian/patches/pve/0036-mirror-add-check-for-bitmap-mode-without-bitmap.patch
deleted file mode 100644 (file)
index d8682bb..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: =?UTF-8?q?Fabian=20Gr=C3=BCnbichler?= <f.gruenbichler@proxmox.com>
-Date: Mon, 6 Apr 2020 12:17:05 +0200
-Subject: [PATCH] mirror: add check for bitmap-mode without bitmap
-MIME-Version: 1.0
-Content-Type: text/plain; charset=UTF-8
-Content-Transfer-Encoding: 8bit
-
-as one without the other does not make much sense with the current set
-of modes.
-
-Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
----
- blockdev.c | 3 +++
- 1 file changed, 3 insertions(+)
-
-diff --git a/blockdev.c b/blockdev.c
-index bbeff9c439..fa3c2f5548 100644
---- a/blockdev.c
-+++ b/blockdev.c
-@@ -3257,6 +3257,9 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
-         if (bdrv_dirty_bitmap_check(bitmap, BDRV_BITMAP_ALLOW_RO, errp)) {
-             return;
-         }
-+    } else if (has_bitmap_mode) {
-+        error_setg(errp, "Cannot specify bitmap sync mode without a bitmap");
-+        return;
-     }
-     if (has_replaces) {
diff --git a/debian/patches/pve/0037-mirror-move-some-checks-to-qmp.patch b/debian/patches/pve/0037-mirror-move-some-checks-to-qmp.patch
new file mode 100644 (file)
index 0000000..c04c5d6
--- /dev/null
@@ -0,0 +1,272 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Fabian=20Gr=C3=BCnbichler?= <f.gruenbichler@proxmox.com>
+Date: Mon, 6 Apr 2020 12:17:08 +0200
+Subject: [PATCH] mirror: move some checks to qmp
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+and assert the passing conditions in block/mirror.c. while incremental
+mode was never available for drive-mirror, it makes the interface more
+uniform w.r.t. backup block jobs.
+
+Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
+---
+ block/mirror.c             | 28 +++------------
+ blockdev.c                 | 29 +++++++++++++++
+ tests/qemu-iotests/384.out | 72 +++++++++++++++++++-------------------
+ 3 files changed, 70 insertions(+), 59 deletions(-)
+
+diff --git a/block/mirror.c b/block/mirror.c
+index c56b0f87e3..dbba6fc80e 100644
+--- a/block/mirror.c
++++ b/block/mirror.c
+@@ -1584,31 +1584,13 @@ static BlockJob *mirror_start_job(
+     Error *local_err = NULL;
+     int ret;
+-    if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
+-        error_setg(errp, "Sync mode '%s' not supported",
+-                   MirrorSyncMode_str(sync_mode));
+-        return NULL;
+-    } else if (sync_mode == MIRROR_SYNC_MODE_BITMAP) {
+-        if (!bitmap) {
+-            error_setg(errp, "Must provide a valid bitmap name for '%s'"
+-                       " sync mode",
+-                       MirrorSyncMode_str(sync_mode));
+-            return NULL;
+-        }
+-    } else if (bitmap) {
+-        error_setg(errp,
+-                   "sync mode '%s' is not compatible with bitmaps",
+-                   MirrorSyncMode_str(sync_mode));
+-        return NULL;
+-    }
++    /* QMP interface protects us from these cases */
++    assert(sync_mode != MIRROR_SYNC_MODE_INCREMENTAL);
++    assert((bitmap && sync_mode == MIRROR_SYNC_MODE_BITMAP) ||
++           (!bitmap && sync_mode != MIRROR_SYNC_MODE_BITMAP));
++    assert(!(bitmap && granularity));
+     if (bitmap) {
+-        if (granularity) {
+-            error_setg(errp, "granularity (%d)"
+-                       "cannot be specified when a bitmap is provided",
+-                       granularity);
+-            return NULL;
+-        }
+         granularity = bdrv_dirty_bitmap_granularity(bitmap);
+         if (bitmap_mode != BITMAP_SYNC_MODE_NEVER) {
+diff --git a/blockdev.c b/blockdev.c
+index fa3c2f5548..206de2b6c2 100644
+--- a/blockdev.c
++++ b/blockdev.c
+@@ -3236,7 +3236,36 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
+         sync = MIRROR_SYNC_MODE_FULL;
+     }
++    if ((sync == MIRROR_SYNC_MODE_BITMAP) ||
++        (sync == MIRROR_SYNC_MODE_INCREMENTAL)) {
++        /* done before desugaring 'incremental' to print the right message */
++        if (!has_bitmap) {
++            error_setg(errp, "Must provide a valid bitmap name for "
++                       "'%s' sync mode", MirrorSyncMode_str(sync));
++            return;
++        }
++    }
++
++    if (sync == MIRROR_SYNC_MODE_INCREMENTAL) {
++        if (has_bitmap_mode &&
++            bitmap_mode != BITMAP_SYNC_MODE_ON_SUCCESS) {
++            error_setg(errp, "Bitmap sync mode must be '%s' "
++                       "when using sync mode '%s'",
++                       BitmapSyncMode_str(BITMAP_SYNC_MODE_ON_SUCCESS),
++                       MirrorSyncMode_str(sync));
++            return;
++        }
++        has_bitmap_mode = true;
++        sync = MIRROR_SYNC_MODE_BITMAP;
++        bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
++    }
++
+     if (has_bitmap) {
++        if (sync != MIRROR_SYNC_MODE_BITMAP) {
++            error_setg(errp, "Sync mode '%s' not supported with bitmap.",
++                       MirrorSyncMode_str(sync));
++            return;
++        }
+         if (granularity) {
+             error_setg(errp, "Granularity and bitmap cannot both be set");
+             return;
+diff --git a/tests/qemu-iotests/384.out b/tests/qemu-iotests/384.out
+index 9b7408b6d6..06a2e29058 100644
+--- a/tests/qemu-iotests/384.out
++++ b/tests/qemu-iotests/384.out
+@@ -2681,45 +2681,45 @@ qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
+ -- Sync mode incremental tests --
+ {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'incremental' sync mode"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'incremental' sync mode"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'incremental' sync mode"}}
+ {"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
++{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'incremental' sync mode"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+ {"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Bitmap sync mode must be 'on-success' when using sync mode 'incremental'"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Bitmap sync mode must be 'on-success' when using sync mode 'incremental'"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
++{"error": {"class": "GenericError", "desc": "Bitmap sync mode must be 'on-success' when using sync mode 'incremental'"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
++{"error": {"class": "GenericError", "desc": "Bitmap sync mode must be 'on-success' when using sync mode 'incremental'"}}
+ -- Sync mode bitmap tests --
+ {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
++{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
+ {"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
+ {"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
+@@ -2751,28 +2751,28 @@ qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
+ {"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ -- Sync mode top tests --
+@@ -2786,28 +2786,28 @@ qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
+ {"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
+ -- Sync mode none tests --
+@@ -2821,26 +2821,26 @@ qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
+ {"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
+ {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
+-{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
++{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
diff --git a/debian/patches/pve/0037-mirror-switch-to-bdrv_dirty_bitmap_merge_internal.patch b/debian/patches/pve/0037-mirror-switch-to-bdrv_dirty_bitmap_merge_internal.patch
deleted file mode 100644 (file)
index 15bebef..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: =?UTF-8?q?Fabian=20Gr=C3=BCnbichler?= <f.gruenbichler@proxmox.com>
-Date: Mon, 6 Apr 2020 12:17:06 +0200
-Subject: [PATCH] mirror: switch to bdrv_dirty_bitmap_merge_internal
-MIME-Version: 1.0
-Content-Type: text/plain; charset=UTF-8
-Content-Transfer-Encoding: 8bit
-
-since sync_bitmap is busy at the point of merging, and we checked access
-beforehand.
-
-Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
----
- block/mirror.c | 8 ++++----
- 1 file changed, 4 insertions(+), 4 deletions(-)
-
-diff --git a/block/mirror.c b/block/mirror.c
-index 08ac9827f2..c56b0f87e3 100644
---- a/block/mirror.c
-+++ b/block/mirror.c
-@@ -756,8 +756,8 @@ static int mirror_exit_common(Job *job)
-              job->ret == 0 && ret == 0)) {
-             /* Success; synchronize copy back to sync. */
-             bdrv_clear_dirty_bitmap(s->sync_bitmap, NULL);
--            bdrv_merge_dirty_bitmap(s->sync_bitmap, s->dirty_bitmap,
--                                    NULL, &error_abort);
-+            bdrv_dirty_bitmap_merge_internal(s->sync_bitmap, s->dirty_bitmap,
-+                                             NULL, true);
-         }
-     }
-     bdrv_release_dirty_bitmap(s->dirty_bitmap);
-@@ -1749,8 +1749,8 @@ static BlockJob *mirror_start_job(
-     }
-     if (s->sync_mode == MIRROR_SYNC_MODE_BITMAP) {
--        bdrv_merge_dirty_bitmap(s->dirty_bitmap, s->sync_bitmap,
--                                NULL, &local_err);
-+        bdrv_dirty_bitmap_merge_internal(s->dirty_bitmap, s->sync_bitmap,
-+                                         NULL, true);
-         if (local_err) {
-             goto fail;
-         }
diff --git a/debian/patches/pve/0038-PVE-Backup-Add-dirty-bitmap-tracking-for-incremental.patch b/debian/patches/pve/0038-PVE-Backup-Add-dirty-bitmap-tracking-for-incremental.patch
new file mode 100644 (file)
index 0000000..94c13f8
--- /dev/null
@@ -0,0 +1,444 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Stefan Reiter <s.reiter@proxmox.com>
+Date: Mon, 29 Jun 2020 11:06:03 +0200
+Subject: [PATCH] PVE-Backup: Add dirty-bitmap tracking for incremental backups
+
+Uses QEMU's existing MIRROR_SYNC_MODE_BITMAP and a dirty-bitmap on top
+of all backed-up drives. This will only execute the data-write callback
+for any changed chunks, the PBS rust code will reuse chunks from the
+previous index for everything it doesn't receive if reuse_index is true.
+
+On error or cancellation, remove all dirty bitmaps to ensure
+consistency.
+
+Add PBS/incremental specific information to query backup info QMP and
+HMP commands.
+
+Only supported for PBS backups.
+
+Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
+Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
+Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
+---
+ block/monitor/block-hmp-cmds.c |  1 +
+ monitor/hmp-cmds.c             | 45 ++++++++++++----
+ proxmox-backup-client.c        |  3 +-
+ proxmox-backup-client.h        |  1 +
+ pve-backup.c                   | 95 ++++++++++++++++++++++++++++++----
+ qapi/block-core.json           | 12 ++++-
+ 6 files changed, 134 insertions(+), 23 deletions(-)
+
+diff --git a/block/monitor/block-hmp-cmds.c b/block/monitor/block-hmp-cmds.c
+index d485c3ac79..fdc85a5c0e 100644
+--- a/block/monitor/block-hmp-cmds.c
++++ b/block/monitor/block-hmp-cmds.c
+@@ -1038,6 +1038,7 @@ void hmp_backup(Monitor *mon, const QDict *qdict)
+         false, NULL, // PBS fingerprint
+         false, NULL, // PBS backup-id
+         false, 0, // PBS backup-time
++        false, false, // PBS incremental
+         true, dir ? BACKUP_FORMAT_DIR : BACKUP_FORMAT_VMA,
+         false, NULL, false, NULL, !!devlist,
+         devlist, qdict_haskey(qdict, "speed"), speed, &error);
+diff --git a/monitor/hmp-cmds.c b/monitor/hmp-cmds.c
+index 7fd59b1c22..4f692c15a2 100644
+--- a/monitor/hmp-cmds.c
++++ b/monitor/hmp-cmds.c
+@@ -218,19 +218,42 @@ void hmp_info_backup(Monitor *mon, const QDict *qdict)
+             monitor_printf(mon, "End time: %s", ctime(&info->end_time));
+         }
+-        int per = (info->has_total && info->total &&
+-            info->has_transferred && info->transferred) ?
+-            (info->transferred * 100)/info->total : 0;
+-        int zero_per = (info->has_total && info->total &&
+-                        info->has_zero_bytes && info->zero_bytes) ?
+-            (info->zero_bytes * 100)/info->total : 0;
+         monitor_printf(mon, "Backup file: %s\n", info->backup_file);
+         monitor_printf(mon, "Backup uuid: %s\n", info->uuid);
+-        monitor_printf(mon, "Total size: %zd\n", info->total);
+-        monitor_printf(mon, "Transferred bytes: %zd (%d%%)\n",
+-                       info->transferred, per);
+-        monitor_printf(mon, "Zero bytes: %zd (%d%%)\n",
+-                       info->zero_bytes, zero_per);
++
++        if (!(info->has_total && info->total))  {
++            // this should not happen normally
++            monitor_printf(mon, "Total size: %d\n", 0);
++        } else {
++            bool incremental = false;
++            size_t total_or_dirty = info->total;
++            if (info->has_transferred) {
++                if (info->has_dirty && info->dirty) {
++                     if (info->dirty < info->total) {
++                        total_or_dirty = info->dirty;
++                        incremental = true;
++                    }
++                }
++            }
++
++            int per = (info->transferred * 100)/total_or_dirty;
++
++            monitor_printf(mon, "Backup mode: %s\n", incremental ? "incremental" : "full");
++
++            int zero_per = (info->has_zero_bytes && info->zero_bytes) ?
++                (info->zero_bytes * 100)/info->total : 0;
++            monitor_printf(mon, "Total size: %zd\n", info->total);
++            monitor_printf(mon, "Transferred bytes: %zd (%d%%)\n",
++                           info->transferred, per);
++            monitor_printf(mon, "Zero bytes: %zd (%d%%)\n",
++                           info->zero_bytes, zero_per);
++
++            if (info->has_reused) {
++                int reused_per = (info->reused * 100)/total_or_dirty;
++                monitor_printf(mon, "Reused bytes: %zd (%d%%)\n",
++                               info->reused, reused_per);
++            }
++        }
+     }
+     qapi_free_BackupStatus(info);
+diff --git a/proxmox-backup-client.c b/proxmox-backup-client.c
+index b7bc7f2574..0e9c584701 100644
+--- a/proxmox-backup-client.c
++++ b/proxmox-backup-client.c
+@@ -95,6 +95,7 @@ proxmox_backup_co_register_image(
+     ProxmoxBackupHandle *pbs,
+     const char *device_name,
+     uint64_t size,
++    bool incremental,
+     Error **errp)
+ {
+     Coroutine *co = qemu_coroutine_self();
+@@ -104,7 +105,7 @@ proxmox_backup_co_register_image(
+     int pbs_res = -1;
+     proxmox_backup_register_image_async(
+-        pbs, device_name, size ,proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
++        pbs, device_name, size, incremental, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
+     qemu_coroutine_yield();
+     if (pbs_res < 0) {
+         if (errp) error_setg(errp, "backup register image failed: %s", pbs_err ? pbs_err : "unknown error");
+diff --git a/proxmox-backup-client.h b/proxmox-backup-client.h
+index b311bf8de8..20fd6b1719 100644
+--- a/proxmox-backup-client.h
++++ b/proxmox-backup-client.h
+@@ -25,6 +25,7 @@ proxmox_backup_co_register_image(
+     ProxmoxBackupHandle *pbs,
+     const char *device_name,
+     uint64_t size,
++    bool incremental,
+     Error **errp);
+diff --git a/pve-backup.c b/pve-backup.c
+index bb917ee972..3a71270213 100644
+--- a/pve-backup.c
++++ b/pve-backup.c
+@@ -28,6 +28,8 @@
+  *
+  */
++const char *PBS_BITMAP_NAME = "pbs-incremental-dirty-bitmap";
++
+ static struct PVEBackupState {
+     struct {
+         // Everithing accessed from qmp_backup_query command is protected using lock
+@@ -39,7 +41,9 @@ static struct PVEBackupState {
+         uuid_t uuid;
+         char uuid_str[37];
+         size_t total;
++        size_t dirty;
+         size_t transferred;
++        size_t reused;
+         size_t zero_bytes;
+     } stat;
+     int64_t speed;
+@@ -66,6 +70,7 @@ typedef struct PVEBackupDevInfo {
+     uint8_t dev_id;
+     bool completed;
+     char targetfile[PATH_MAX];
++    BdrvDirtyBitmap *bitmap;
+     BlockDriverState *target;
+ } PVEBackupDevInfo;
+@@ -105,11 +110,12 @@ static bool pvebackup_error_or_canceled(void)
+     return error_or_canceled;
+ }
+-static void pvebackup_add_transfered_bytes(size_t transferred, size_t zero_bytes)
++static void pvebackup_add_transfered_bytes(size_t transferred, size_t zero_bytes, size_t reused)
+ {
+     qemu_mutex_lock(&backup_state.stat.lock);
+     backup_state.stat.zero_bytes += zero_bytes;
+     backup_state.stat.transferred += transferred;
++    backup_state.stat.reused += reused;
+     qemu_mutex_unlock(&backup_state.stat.lock);
+ }
+@@ -148,7 +154,8 @@ pvebackup_co_dump_pbs_cb(
+         pvebackup_propagate_error(local_err);
+         return pbs_res;
+     } else {
+-        pvebackup_add_transfered_bytes(size, !buf ? size : 0);
++        size_t reused = (pbs_res == 0) ? size : 0;
++        pvebackup_add_transfered_bytes(size, !buf ? size : 0, reused);
+     }
+     return size;
+@@ -208,11 +215,11 @@ pvebackup_co_dump_vma_cb(
+         } else {
+             if (remaining >= VMA_CLUSTER_SIZE) {
+                 assert(ret == VMA_CLUSTER_SIZE);
+-                pvebackup_add_transfered_bytes(VMA_CLUSTER_SIZE, zero_bytes);
++                pvebackup_add_transfered_bytes(VMA_CLUSTER_SIZE, zero_bytes, 0);
+                 remaining -= VMA_CLUSTER_SIZE;
+             } else {
+                 assert(ret == remaining);
+-                pvebackup_add_transfered_bytes(remaining, zero_bytes);
++                pvebackup_add_transfered_bytes(remaining, zero_bytes, 0);
+                 remaining = 0;
+             }
+         }
+@@ -248,6 +255,18 @@ static void coroutine_fn pvebackup_co_cleanup(void *unused)
+             if (local_err != NULL) {
+                 pvebackup_propagate_error(local_err);
+             }
++        } else {
++            // on error or cancel we cannot ensure synchronization of dirty
++            // bitmaps with backup server, so remove all and do full backup next
++            GList *l = backup_state.di_list;
++            while (l) {
++                PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
++                l = g_list_next(l);
++
++                if (di->bitmap) {
++                    bdrv_release_dirty_bitmap(di->bitmap);
++                }
++            }
+         }
+         proxmox_backup_disconnect(backup_state.pbs);
+@@ -303,6 +322,12 @@ static void pvebackup_complete_cb(void *opaque, int ret)
+     // remove self from job queue
+     backup_state.di_list = g_list_remove(backup_state.di_list, di);
++    if (di->bitmap && ret < 0) {
++        // on error or cancel we cannot ensure synchronization of dirty
++        // bitmaps with backup server, so remove all and do full backup next
++        bdrv_release_dirty_bitmap(di->bitmap);
++    }
++
+     g_free(di);
+     qemu_mutex_unlock(&backup_state.backup_mutex);
+@@ -470,12 +495,18 @@ static bool create_backup_jobs(void) {
+         assert(di->target != NULL);
++        MirrorSyncMode sync_mode = MIRROR_SYNC_MODE_FULL;
++        BitmapSyncMode bitmap_mode = BITMAP_SYNC_MODE_NEVER;
++        if (di->bitmap) {
++            sync_mode = MIRROR_SYNC_MODE_BITMAP;
++            bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
++        }
+         AioContext *aio_context = bdrv_get_aio_context(di->bs);
+         aio_context_acquire(aio_context);
+         BlockJob *job = backup_job_create(
+-            NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
+-            BITMAP_SYNC_MODE_NEVER, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
++            NULL, di->bs, di->target, backup_state.speed, sync_mode, di->bitmap,
++            bitmap_mode, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
+             JOB_DEFAULT, pvebackup_complete_cb, di, 1, NULL, &local_err);
+         aio_context_release(aio_context);
+@@ -526,6 +557,8 @@ typedef struct QmpBackupTask {
+     const char *fingerprint;
+     bool has_fingerprint;
+     int64_t backup_time;
++    bool has_incremental;
++    bool incremental;
+     bool has_format;
+     BackupFormat format;
+     bool has_config_file;
+@@ -621,6 +654,7 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
+     }
+     size_t total = 0;
++    size_t dirty = 0;
+     l = di_list;
+     while (l) {
+@@ -658,6 +692,8 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
+         int dump_cb_block_size = PROXMOX_BACKUP_DEFAULT_CHUNK_SIZE; // Hardcoded (4M)
+         firewall_name = "fw.conf";
++        bool incremental = task->has_incremental && task->incremental;
++
+         char *pbs_err = NULL;
+         pbs = proxmox_backup_new(
+             task->backup_file,
+@@ -677,7 +713,8 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
+             goto err;
+         }
+-        if (proxmox_backup_co_connect(pbs, task->errp) < 0)
++        int connect_result = proxmox_backup_co_connect(pbs, task->errp);
++        if (connect_result < 0)
+             goto err;
+         /* register all devices */
+@@ -688,9 +725,32 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
+             const char *devname = bdrv_get_device_name(di->bs);
+-            int dev_id = proxmox_backup_co_register_image(pbs, devname, di->size, task->errp);
+-            if (dev_id < 0)
++            BdrvDirtyBitmap *bitmap = bdrv_find_dirty_bitmap(di->bs, PBS_BITMAP_NAME);
++
++            bool use_incremental = false;
++            if (incremental) {
++                if (bitmap == NULL) {
++                    bitmap = bdrv_create_dirty_bitmap(di->bs, dump_cb_block_size, PBS_BITMAP_NAME, task->errp);
++                    if (!bitmap) {
++                        goto err;
++                    }
++                    /* mark entire bitmap as dirty to make full backup first */
++                    bdrv_set_dirty_bitmap(bitmap, 0, di->size);
++                    dirty += di->size;
++                } else {
++                    use_incremental = true;
++                    dirty += bdrv_get_dirty_count(bitmap);
++                }
++                di->bitmap = bitmap;
++            } else if (bitmap != NULL) {
++                dirty += di->size;
++                bdrv_release_dirty_bitmap(bitmap);
++            }
++
++            int dev_id = proxmox_backup_co_register_image(pbs, devname, di->size, use_incremental, task->errp);
++            if (dev_id < 0) {
+                 goto err;
++            }
+             if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_pbs_cb, di, task->errp))) {
+                 goto err;
+@@ -699,6 +759,8 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
+             di->dev_id = dev_id;
+         }
+     } else if (format == BACKUP_FORMAT_VMA) {
++        dirty = total;
++
+         vmaw = vma_writer_create(task->backup_file, uuid, &local_err);
+         if (!vmaw) {
+             if (local_err) {
+@@ -726,6 +788,8 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
+             }
+         }
+     } else if (format == BACKUP_FORMAT_DIR) {
++        dirty = total;
++
+         if (mkdir(task->backup_file, 0640) != 0) {
+             error_setg_errno(task->errp, errno, "can't create directory '%s'\n",
+                              task->backup_file);
+@@ -798,8 +862,10 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
+     char *uuid_str = g_strdup(backup_state.stat.uuid_str);
+     backup_state.stat.total = total;
++    backup_state.stat.dirty = dirty;
+     backup_state.stat.transferred = 0;
+     backup_state.stat.zero_bytes = 0;
++    backup_state.stat.reused = 0;
+     qemu_mutex_unlock(&backup_state.stat.lock);
+@@ -823,6 +889,10 @@ err:
+         PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
+         l = g_list_next(l);
++        if (di->bitmap) {
++            bdrv_release_dirty_bitmap(di->bitmap);
++        }
++
+         if (di->target) {
+             bdrv_unref(di->target);
+         }
+@@ -864,6 +934,7 @@ UuidInfo *qmp_backup(
+     bool has_fingerprint, const char *fingerprint,
+     bool has_backup_id, const char *backup_id,
+     bool has_backup_time, int64_t backup_time,
++    bool has_incremental, bool incremental,
+     bool has_format, BackupFormat format,
+     bool has_config_file, const char *config_file,
+     bool has_firewall_file, const char *firewall_file,
+@@ -882,6 +953,8 @@ UuidInfo *qmp_backup(
+         .backup_id = backup_id,
+         .has_backup_time = has_backup_time,
+         .backup_time = backup_time,
++        .has_incremental = has_incremental,
++        .incremental = incremental,
+         .has_format = has_format,
+         .format = format,
+         .has_config_file = has_config_file,
+@@ -950,10 +1023,14 @@ BackupStatus *qmp_query_backup(Error **errp)
+     info->has_total = true;
+     info->total = backup_state.stat.total;
++    info->has_dirty = true;
++    info->dirty = backup_state.stat.dirty;
+     info->has_zero_bytes = true;
+     info->zero_bytes = backup_state.stat.zero_bytes;
+     info->has_transferred = true;
+     info->transferred = backup_state.stat.transferred;
++    info->has_reused = true;
++    info->reused = backup_state.stat.reused;
+     qemu_mutex_unlock(&backup_state.stat.lock);
+diff --git a/qapi/block-core.json b/qapi/block-core.json
+index 8bdbccb397..8ffff7aaab 100644
+--- a/qapi/block-core.json
++++ b/qapi/block-core.json
+@@ -757,8 +757,13 @@
+ #
+ # @total: total amount of bytes involved in the backup process
+ #
++# @dirty: with incremental mode, this is the amount of bytes involved
++#         in the backup process which are marked dirty.
++#
+ # @transferred: amount of bytes already backed up.
+ #
++# @reused: amount of bytes reused due to deduplication.
++#
+ # @zero-bytes: amount of 'zero' bytes detected.
+ #
+ # @start-time: time (epoch) when backup job started.
+@@ -771,8 +776,8 @@
+ #
+ ##
+ { 'struct': 'BackupStatus',
+-  'data': {'*status': 'str', '*errmsg': 'str', '*total': 'int',
+-           '*transferred': 'int', '*zero-bytes': 'int',
++  'data': {'*status': 'str', '*errmsg': 'str', '*total': 'int', '*dirty': 'int',
++           '*transferred': 'int', '*zero-bytes': 'int', '*reused': 'int',
+            '*start-time': 'int', '*end-time': 'int',
+            '*backup-file': 'str', '*uuid': 'str' } }
+@@ -815,6 +820,8 @@
+ #
+ # @backup-time: backup timestamp (Unix epoch, required for format 'pbs')
+ #
++# @incremental: sync incremental changes since last job (optional for format 'pbs')
++#
+ # Returns: the uuid of the backup job
+ #
+ ##
+@@ -825,6 +832,7 @@
+                                     '*fingerprint': 'str',
+                                     '*backup-id': 'str',
+                                     '*backup-time': 'int',
++                                    '*incremental': 'bool',
+                                     '*format': 'BackupFormat',
+                                     '*config-file': 'str',
+                                     '*firewall-file': 'str',
diff --git a/debian/patches/pve/0038-iotests-add-test-for-bitmap-mirror.patch b/debian/patches/pve/0038-iotests-add-test-for-bitmap-mirror.patch
deleted file mode 100644 (file)
index 71ddcd4..0000000
+++ /dev/null
@@ -1,3447 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: =?UTF-8?q?Fabian=20Gr=C3=BCnbichler?= <f.gruenbichler@proxmox.com>
-Date: Mon, 6 Apr 2020 12:17:07 +0200
-Subject: [PATCH] iotests: add test for bitmap mirror
-MIME-Version: 1.0
-Content-Type: text/plain; charset=UTF-8
-Content-Transfer-Encoding: 8bit
-
-heavily based on/practically forked off iotest 257 for bitmap backups,
-but:
-
-- no writes to filter node 'mirror-top' between completion and
-finalization, as those seem to deadlock?
-- no inclusion of not-yet-available full/top sync modes in combination
-with bitmaps
-- extra set of reference/test mirrors to verify that writes in parallel
-with active mirror work
-
-intentionally keeping copyright and ownership of original test case to
-honor provenance.
-
-Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
----
- tests/qemu-iotests/384     |  547 +++++++
- tests/qemu-iotests/384.out | 2846 ++++++++++++++++++++++++++++++++++++
- tests/qemu-iotests/group   |    1 +
- 3 files changed, 3394 insertions(+)
- create mode 100755 tests/qemu-iotests/384
- create mode 100644 tests/qemu-iotests/384.out
-
-diff --git a/tests/qemu-iotests/384 b/tests/qemu-iotests/384
-new file mode 100755
-index 0000000000..b04a8e651a
---- /dev/null
-+++ b/tests/qemu-iotests/384
-@@ -0,0 +1,547 @@
-+#!/usr/bin/env python3
-+#
-+# Test bitmap-sync mirrors (incremental, differential, and partials)
-+#
-+# Copyright (c) 2019 John Snow for Red Hat, Inc.
-+#
-+# This program is free software; you can redistribute it and/or modify
-+# it under the terms of the GNU General Public License as published by
-+# the Free Software Foundation; either version 2 of the License, or
-+# (at your option) any later version.
-+#
-+# This program is distributed in the hope that it will be useful,
-+# but WITHOUT ANY WARRANTY; without even the implied warranty of
-+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-+# GNU General Public License for more details.
-+#
-+# You should have received a copy of the GNU General Public License
-+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
-+#
-+# owner=jsnow@redhat.com
-+
-+import math
-+import os
-+
-+import iotests
-+from iotests import log, qemu_img
-+
-+SIZE = 64 * 1024 * 1024
-+GRANULARITY = 64 * 1024
-+
-+
-+class Pattern:
-+    def __init__(self, byte, offset, size=GRANULARITY):
-+        self.byte = byte
-+        self.offset = offset
-+        self.size = size
-+
-+    def bits(self, granularity):
-+        lower = self.offset // granularity
-+        upper = (self.offset + self.size - 1) // granularity
-+        return set(range(lower, upper + 1))
-+
-+
-+class PatternGroup:
-+    """Grouping of Pattern objects. Initialize with an iterable of Patterns."""
-+    def __init__(self, patterns):
-+        self.patterns = patterns
-+
-+    def bits(self, granularity):
-+        """Calculate the unique bits dirtied by this pattern grouping"""
-+        res = set()
-+        for pattern in self.patterns:
-+            res |= pattern.bits(granularity)
-+        return res
-+
-+
-+GROUPS = [
-+    PatternGroup([
-+        # Batch 0: 4 clusters
-+        Pattern('0x49', 0x0000000),
-+        Pattern('0x6c', 0x0100000),   # 1M
-+        Pattern('0x6f', 0x2000000),   # 32M
-+        Pattern('0x76', 0x3ff0000)]), # 64M - 64K
-+    PatternGroup([
-+        # Batch 1: 6 clusters (3 new)
-+        Pattern('0x65', 0x0000000),   # Full overwrite
-+        Pattern('0x77', 0x00f8000),   # Partial-left (1M-32K)
-+        Pattern('0x72', 0x2008000),   # Partial-right (32M+32K)
-+        Pattern('0x69', 0x3fe0000)]), # Adjacent-left (64M - 128K)
-+    PatternGroup([
-+        # Batch 2: 7 clusters (3 new)
-+        Pattern('0x74', 0x0010000),   # Adjacent-right
-+        Pattern('0x69', 0x00e8000),   # Partial-left  (1M-96K)
-+        Pattern('0x6e', 0x2018000),   # Partial-right (32M+96K)
-+        Pattern('0x67', 0x3fe0000,
-+                2*GRANULARITY)]),     # Overwrite [(64M-128K)-64M)
-+    PatternGroup([
-+        # Batch 3: 8 clusters (5 new)
-+        # Carefully chosen such that nothing re-dirties the one cluster
-+        # that copies out successfully before failure in Group #1.
-+        Pattern('0xaa', 0x0010000,
-+                3*GRANULARITY),       # Overwrite and 2x Adjacent-right
-+        Pattern('0xbb', 0x00d8000),   # Partial-left (1M-160K)
-+        Pattern('0xcc', 0x2028000),   # Partial-right (32M+160K)
-+        Pattern('0xdd', 0x3fc0000)]), # New; leaving a gap to the right
-+]
-+
-+
-+class EmulatedBitmap:
-+    def __init__(self, granularity=GRANULARITY):
-+        self._bits = set()
-+        self.granularity = granularity
-+
-+    def dirty_bits(self, bits):
-+        self._bits |= set(bits)
-+
-+    def dirty_group(self, n):
-+        self.dirty_bits(GROUPS[n].bits(self.granularity))
-+
-+    def clear(self):
-+        self._bits = set()
-+
-+    def clear_bits(self, bits):
-+        self._bits -= set(bits)
-+
-+    def clear_bit(self, bit):
-+        self.clear_bits({bit})
-+
-+    def clear_group(self, n):
-+        self.clear_bits(GROUPS[n].bits(self.granularity))
-+
-+    @property
-+    def first_bit(self):
-+        return sorted(self.bits)[0]
-+
-+    @property
-+    def bits(self):
-+        return self._bits
-+
-+    @property
-+    def count(self):
-+        return len(self.bits)
-+
-+    def compare(self, qmp_bitmap):
-+        """
-+        Print a nice human-readable message checking that a bitmap as reported
-+        by the QMP interface has as many bits set as we expect it to.
-+        """
-+
-+        name = qmp_bitmap.get('name', '(anonymous)')
-+        log("= Checking Bitmap {:s} =".format(name))
-+
-+        want = self.count
-+        have = qmp_bitmap['count'] // qmp_bitmap['granularity']
-+
-+        log("expecting {:d} dirty sectors; have {:d}. {:s}".format(
-+            want, have, "OK!" if want == have else "ERROR!"))
-+        log('')
-+
-+
-+class Drive:
-+    """Represents, vaguely, a drive attached to a VM.
-+    Includes format, graph, and device information."""
-+
-+    def __init__(self, path, vm=None):
-+        self.path = path
-+        self.vm = vm
-+        self.fmt = None
-+        self.size = None
-+        self.node = None
-+
-+    def img_create(self, fmt, size):
-+        self.fmt = fmt
-+        self.size = size
-+        iotests.qemu_img_create('-f', self.fmt, self.path, str(self.size))
-+
-+    def create_target(self, name, fmt, size):
-+        basename = os.path.basename(self.path)
-+        file_node_name = "file_{}".format(basename)
-+        vm = self.vm
-+
-+        log(vm.command('blockdev-create', job_id='bdc-file-job',
-+                       options={
-+                           'driver': 'file',
-+                           'filename': self.path,
-+                           'size': 0,
-+                       }))
-+        vm.run_job('bdc-file-job')
-+        log(vm.command('blockdev-add', driver='file',
-+                       node_name=file_node_name, filename=self.path))
-+
-+        log(vm.command('blockdev-create', job_id='bdc-fmt-job',
-+                       options={
-+                           'driver': fmt,
-+                           'file': file_node_name,
-+                           'size': size,
-+                       }))
-+        vm.run_job('bdc-fmt-job')
-+        log(vm.command('blockdev-add', driver=fmt,
-+                       node_name=name,
-+                       file=file_node_name))
-+        self.fmt = fmt
-+        self.size = size
-+        self.node = name
-+
-+def blockdev_mirror(vm, device, target, sync, **kwargs):
-+    # Strip any arguments explicitly nulled by the caller:
-+    kwargs = {key: val for key, val in kwargs.items() if val is not None}
-+    result = vm.qmp_log('blockdev-mirror',
-+                        device=device,
-+                        target=target,
-+                        sync=sync,
-+                        filter_node_name='mirror-top',
-+                        **kwargs)
-+    return result
-+
-+def blockdev_mirror_mktarget(drive, target_id, filepath, sync, **kwargs):
-+    target_drive = Drive(filepath, vm=drive.vm)
-+    target_drive.create_target(target_id, drive.fmt, drive.size)
-+    blockdev_mirror(drive.vm, drive.node, target_id, sync, **kwargs)
-+
-+def reference_mirror(drive, n, filepath):
-+    log("--- Reference mirror #{:d} ---\n".format(n))
-+    target_id = "ref_target_{:d}".format(n)
-+    job_id = "ref_mirror_{:d}".format(n)
-+    blockdev_mirror_mktarget(drive, target_id, filepath, "full",
-+                             job_id=job_id)
-+    drive.vm.run_job(job_id, auto_dismiss=True)
-+    log('')
-+
-+def mirror(drive, n, filepath, sync, **kwargs):
-+    log("--- Test mirror #{:d} ---\n".format(n))
-+    target_id = "mirror_target_{:d}".format(n)
-+    job_id = "mirror_{:d}".format(n)
-+    kwargs.setdefault('auto-finalize', False)
-+    blockdev_mirror_mktarget(drive, target_id, filepath, sync,
-+                             job_id=job_id, **kwargs)
-+    return job_id
-+
-+def perform_writes(drive, n, filter_node_name=None):
-+    log("--- Write #{:d} ---\n".format(n))
-+    for pattern in GROUPS[n].patterns:
-+        cmd = "write -P{:s} 0x{:07x} 0x{:x}".format(
-+            pattern.byte,
-+            pattern.offset,
-+            pattern.size)
-+        log(cmd)
-+        log(drive.vm.hmp_qemu_io(filter_node_name or drive.node, cmd))
-+    bitmaps = drive.vm.query_bitmaps()
-+    log({'bitmaps': bitmaps}, indent=2)
-+    log('')
-+    return bitmaps
-+
-+
-+def compare_images(image, reference, baseimg=None, expected_match=True):
-+    """
-+    Print a nice human-readable message comparing these images.
-+    """
-+    expected_ret = 0 if expected_match else 1
-+    if baseimg:
-+        assert qemu_img("rebase", "-u", "-b", baseimg, image) == 0
-+    ret = qemu_img("compare", image, reference)
-+    log('qemu_img compare "{:s}" "{:s}" ==> {:s}, {:s}'.format(
-+        image, reference,
-+        "Identical" if ret == 0 else "Mismatch",
-+        "OK!" if ret == expected_ret else "ERROR!"),
-+        filters=[iotests.filter_testfiles])
-+
-+def test_bitmap_sync(bsync_mode, msync_mode='bitmap', failure=None):
-+    """
-+    Test bitmap mirror routines.
-+
-+    :param bsync_mode: Is the Bitmap Sync mode, and can be any of:
-+        - on-success: This is the "incremental" style mode. Bitmaps are
-+                      synchronized to what was copied out only on success.
-+                      (Partial images must be discarded.)
-+        - never:      This is the "differential" style mode.
-+                      Bitmaps are never synchronized.
-+        - always:     This is a "best effort" style mode.
-+                      Bitmaps are always synchronized, regardless of failure.
-+                      (Partial images must be kept.)
-+
-+    :param msync_mode: The mirror sync mode to use for the first mirror.
-+                       Can be any one of:
-+        - bitmap: mirrors based on bitmap manifest.
-+        - full:   Full mirrors.
-+        - top:    Full mirrors of the top layer only.
-+
-+    :param failure: Is the (optional) failure mode, and can be any of:
-+        - None:         No failure. Test the normative path. Default.
-+        - simulated:    Cancel the job right before it completes.
-+                        This also tests writes "during" the job.
-+        - intermediate: This tests a job that fails mid-process and produces
-+                        an incomplete mirror. Testing limitations prevent
-+                        testing competing writes.
-+    """
-+    with iotests.FilePaths(['img', 'bsync1', 'bsync2', 'bsync3',
-+                            'fmirror0', 'fmirror1', 'fmirror2', 'fmirror3']) as \
-+                            (img_path, bsync1, bsync2, bsync3,
-+                             fmirror0, fmirror1, fmirror2, fmirror3), \
-+         iotests.VM() as vm:
-+
-+        mode = "Mode {:s}; Bitmap Sync {:s}".format(msync_mode, bsync_mode)
-+        preposition = "with" if failure else "without"
-+        cond = "{:s} {:s}".format(preposition,
-+                                  "{:s} failure".format(failure) if failure
-+                                  else "failure")
-+        log("\n=== {:s} {:s} ===\n".format(mode, cond))
-+
-+        log('--- Preparing image & VM ---\n')
-+        drive0 = Drive(img_path, vm=vm)
-+        drive0.img_create(iotests.imgfmt, SIZE)
-+        vm.add_device("{},id=scsi0".format(iotests.get_virtio_scsi_device()))
-+        vm.launch()
-+
-+        file_config = {
-+            'driver': 'file',
-+            'filename': drive0.path
-+        }
-+
-+        if failure == 'intermediate':
-+            file_config = {
-+                'driver': 'blkdebug',
-+                'image': file_config,
-+                'set-state': [{
-+                    'event': 'flush_to_disk',
-+                    'state': 1,
-+                    'new_state': 2
-+                }, {
-+                    'event': 'read_aio',
-+                    'state': 2,
-+                    'new_state': 3
-+                }, {
-+                    'event': 'read_aio',
-+                    'state': 3,
-+                    'new_state': 4
-+                }],
-+                'inject-error': [{
-+                    'event': 'read_aio',
-+                    'errno': 5,
-+                    'state': 3,
-+                    'immediately': False,
-+                    'once': True
-+                }, {
-+                    'event': 'read_aio',
-+                    'errno': 5,
-+                    'state': 4,
-+                    'immediately': False,
-+                    'once': True
-+                }]
-+            }
-+
-+        drive0.node = 'drive0'
-+        vm.qmp_log('blockdev-add',
-+                   filters=[iotests.filter_qmp_testfiles],
-+                   node_name=drive0.node,
-+                   driver=drive0.fmt,
-+                   file=file_config)
-+        log('')
-+
-+        # 0 - Writes and Reference mirror
-+        perform_writes(drive0, 0)
-+        reference_mirror(drive0, 0, fmirror0)
-+        log('--- Add Bitmap ---\n')
-+        vm.qmp_log("block-dirty-bitmap-add", node=drive0.node,
-+                   name="bitmap0", granularity=GRANULARITY)
-+        log('')
-+        ebitmap = EmulatedBitmap()
-+
-+        # 1 - Writes and Reference mirror
-+        bitmaps = perform_writes(drive0, 1)
-+        ebitmap.dirty_group(1)
-+        bitmap = vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps)
-+        ebitmap.compare(bitmap)
-+        reference_mirror(drive0, 1, fmirror1)
-+
-+        # 1 - Test mirror (w/ Optional induced failure)
-+        if failure == 'intermediate':
-+            # Activate blkdebug induced failure for second-to-next read
-+            log(vm.hmp_qemu_io(drive0.node, 'flush'))
-+            log('')
-+        job = mirror(drive0, 1, bsync1, msync_mode,
-+                     bitmap="bitmap0", bitmap_mode=bsync_mode)
-+
-+        vm.run_job(job, auto_dismiss=True, auto_finalize=False,
-+                   cancel=(failure == 'simulated'))
-+        bitmaps = vm.query_bitmaps()
-+        log({'bitmaps': bitmaps}, indent=2)
-+        log('')
-+
-+        if bsync_mode == 'always':
-+            if failure == 'intermediate':
-+                # We manage to copy one sector (one bit) before the error.
-+                ebitmap.clear_bit(ebitmap.first_bit)
-+            else:
-+                # successful mirror / cancelled complete mirror
-+                ebitmap.clear()
-+
-+        if bsync_mode == 'on-success' and not failure:
-+            ebitmap.clear()
-+
-+        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
-+
-+        # 2 - Reference mirror
-+        reference_mirror(drive0, 2, fmirror2)
-+
-+        # 2 - Bitmap mirror with writes before completion
-+        job = mirror(drive0, 2, bsync2, "bitmap",
-+                     bitmap="bitmap0", bitmap_mode=bsync_mode)
-+
-+        bitmaps = perform_writes(drive0, 2)
-+        ebitmap.dirty_group(2)
-+        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
-+
-+        # don't use run_job as that logs too much even with use_log=False
-+        events = [('JOB_STATUS_CHANGE', {'data': {'id': job}})]
-+        while True:
-+            ev = iotests.filter_qmp_event(vm.events_wait(events, timeout=10))
-+            status = ev['data']['status']
-+            if status == 'ready':
-+                vm.qmp('job-complete', id=job)
-+            elif status == 'standby':
-+                vm.qmp('job-resume', id=job)
-+            elif status == 'pending':
-+                vm.qmp('job-finalize', id=job)
-+            elif status == 'null':
-+                break
-+
-+        if bsync_mode != 'never':
-+            ebitmap.clear()
-+
-+        bitmaps = vm.query_bitmaps()
-+        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
-+
-+        # 3 - Writes and Reference mirror
-+        bitmaps = perform_writes(drive0, 3)
-+        ebitmap.dirty_group(3)
-+        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
-+        reference_mirror(drive0, 3, fmirror3)
-+
-+        # 3 - Bitmap mirror (In failure modes, this is a recovery.)
-+        job = mirror(drive0, 3, bsync3, "bitmap",
-+                     bitmap="bitmap0", bitmap_mode=bsync_mode)
-+
-+        vm.run_job(job, auto_dismiss=True, auto_finalize=False)
-+        bitmaps = vm.query_bitmaps()
-+
-+        log({'bitmaps': bitmaps}, indent=2)
-+        log('')
-+        if bsync_mode != 'never':
-+            ebitmap.clear()
-+        ebitmap.compare(vm.get_bitmap(drive0.node, 'bitmap0', bitmaps=bitmaps))
-+
-+        log('--- Cleanup ---\n')
-+        vm.qmp_log("block-dirty-bitmap-remove",
-+                   node=drive0.node, name="bitmap0")
-+        bitmaps = vm.query_bitmaps()
-+        log({'bitmaps': bitmaps}, indent=2)
-+        vm.shutdown()
-+        log('')
-+
-+        log('--- Verification ---\n')
-+        compare_images(bsync1, fmirror1, baseimg=fmirror0,
-+                       expected_match=failure != 'intermediate')
-+        if not failure or bsync_mode == 'always':
-+            # Always keep the last mirror on success or when using 'always'
-+            base = bsync1
-+        else:
-+            base = fmirror1
-+
-+        compare_images(bsync2, fmirror2, baseimg=base, expected_match=0)
-+        compare_images(bsync3, fmirror3, baseimg=bsync2)
-+        compare_images(img_path, fmirror3)
-+        log('')
-+
-+def test_mirror_api():
-+    """
-+    Test malformed and prohibited invocations of the mirror API.
-+    """
-+    with iotests.FilePaths(['img', 'bsync1']) as \
-+         (img_path, mirror_path), \
-+         iotests.VM() as vm:
-+
-+        log("\n=== API failure tests ===\n")
-+        log('--- Preparing image & VM ---\n')
-+        drive0 = Drive(img_path, vm=vm)
-+        drive0.img_create(iotests.imgfmt, SIZE)
-+        vm.add_device("{},id=scsi0".format(iotests.get_virtio_scsi_device()))
-+        vm.launch()
-+
-+        file_config = {
-+            'driver': 'file',
-+            'filename': drive0.path
-+        }
-+
-+        drive0.node = 'drive0'
-+        vm.qmp_log('blockdev-add',
-+                   filters=[iotests.filter_qmp_testfiles],
-+                   node_name=drive0.node,
-+                   driver=drive0.fmt,
-+                   file=file_config)
-+        log('')
-+
-+        target0 = Drive(mirror_path, vm=vm)
-+        target0.create_target("mirror_target", drive0.fmt, drive0.size)
-+        log('')
-+
-+        vm.qmp_log("block-dirty-bitmap-add", node=drive0.node,
-+                   name="bitmap0", granularity=GRANULARITY)
-+        log('')
-+
-+        log('-- Testing invalid QMP commands --\n')
-+
-+        error_cases = {
-+            'incremental': {
-+                None:        ['on-success', 'always', 'never', None],
-+                'bitmap404': ['on-success', 'always', 'never', None],
-+                'bitmap0':   ['always', 'never']
-+            },
-+            'bitmap': {
-+                None:        ['on-success', 'always', 'never', None],
-+                'bitmap404': ['on-success', 'always', 'never', None],
-+                'bitmap0':   [None],
-+            },
-+            'full': {
-+                None:        ['on-success', 'always', 'never'],
-+                'bitmap404': ['on-success', 'always', 'never', None],
-+                'bitmap0':   ['on-success', 'always', 'never', None],
-+            },
-+            'top': {
-+                None:        ['on-success', 'always', 'never'],
-+                'bitmap404': ['on-success', 'always', 'never', None],
-+                'bitmap0':   ['on-success', 'always', 'never', None],
-+            },
-+            'none': {
-+                None:        ['on-success', 'always', 'never'],
-+                'bitmap404': ['on-success', 'always', 'never', None],
-+                'bitmap0':   ['on-success', 'always', 'never', None],
-+            }
-+        }
-+
-+        # Dicts, as always, are not stably-ordered prior to 3.7, so use tuples:
-+        for sync_mode in ('incremental', 'bitmap', 'full', 'top', 'none'):
-+            log("-- Sync mode {:s} tests --\n".format(sync_mode))
-+            for bitmap in (None, 'bitmap404', 'bitmap0'):
-+                for policy in error_cases[sync_mode][bitmap]:
-+                    blockdev_mirror(drive0.vm, drive0.node, "mirror_target",
-+                                    sync_mode, job_id='api_job',
-+                                    bitmap=bitmap, bitmap_mode=policy)
-+                    log('')
-+
-+
-+def main():
-+    for bsync_mode in ("never", "on-success", "always"):
-+        for failure in ("simulated", "intermediate", None):
-+            test_bitmap_sync(bsync_mode, "bitmap", failure)
-+
-+#    for sync_mode in ('full', 'top'):
-+#        for bsync_mode in ('on-success', 'always'):
-+#            for failure in ('simulated', 'intermediate', None):
-+#                test_bitmap_sync(bsync_mode, sync_mode, failure)
-+
-+    test_mirror_api()
-+
-+if __name__ == '__main__':
-+    iotests.script_main(main, supported_fmts=['qcow2'],
-+                        supported_protocols=['file'])
-diff --git a/tests/qemu-iotests/384.out b/tests/qemu-iotests/384.out
-new file mode 100644
-index 0000000000..9b7408b6d6
---- /dev/null
-+++ b/tests/qemu-iotests/384.out
-@@ -0,0 +1,2846 @@
-+
-+=== Mode bitmap; Bitmap Sync never with simulated failure ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+--- Write #0 ---
-+
-+write -P0x49 0x0000000 0x10000
-+{"return": ""}
-+write -P0x6c 0x0100000 0x10000
-+{"return": ""}
-+write -P0x6f 0x2000000 0x10000
-+{"return": ""}
-+write -P0x76 0x3ff0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Reference mirror #0 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Add Bitmap ---
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+--- Write #1 ---
-+
-+write -P0x65 0x0000000 0x10000
-+{"return": ""}
-+write -P0x77 0x00f8000 0x10000
-+{"return": ""}
-+write -P0x72 0x2008000 0x10000
-+{"return": ""}
-+write -P0x69 0x3fe0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-cancel", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_CANCELLED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
-+{"return": {}}
-+--- Write #2 ---
-+
-+write -P0x74 0x0010000 0x10000
-+{"return": ""}
-+write -P0x69 0x00e8000 0x10000
-+{"return": ""}
-+write -P0x6e 0x2018000 0x10000
-+{"return": ""}
-+write -P0x67 0x3fe0000 0x20000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 262144,
-+        "granularity": 65536,
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      },
-+      {
-+        "busy": true,
-+        "count": 655360,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "locked"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 10 dirty sectors; have 10. OK!
-+
-+= Checking Bitmap bitmap0 =
-+expecting 10 dirty sectors; have 10. OK!
-+
-+--- Write #3 ---
-+
-+write -P0xaa 0x0010000 0x30000
-+{"return": ""}
-+write -P0xbb 0x00d8000 0x10000
-+{"return": ""}
-+write -P0xcc 0x2028000 0x10000
-+{"return": ""}
-+write -P0xdd 0x3fc0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 983040,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 15 dirty sectors; have 15. OK!
-+
-+--- Reference mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 983040,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 15 dirty sectors; have 15. OK!
-+
-+--- Cleanup ---
-+
-+{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Verification ---
-+
-+qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+
-+
-+=== Mode bitmap; Bitmap Sync never with intermediate failure ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "blkdebug", "image": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "inject-error": [{"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 3}, {"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 4}], "set-state": [{"event": "flush_to_disk", "new-state": 2, "state": 1}, {"event": "read_aio", "new-state": 3, "state": 2}, {"event": "read_aio", "new-state": 4, "state": 3}]}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+--- Write #0 ---
-+
-+write -P0x49 0x0000000 0x10000
-+{"return": ""}
-+write -P0x6c 0x0100000 0x10000
-+{"return": ""}
-+write -P0x6f 0x2000000 0x10000
-+{"return": ""}
-+write -P0x76 0x3ff0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Reference mirror #0 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Add Bitmap ---
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+--- Write #1 ---
-+
-+write -P0x65 0x0000000 0x10000
-+{"return": ""}
-+write -P0x77 0x00f8000 0x10000
-+{"return": ""}
-+write -P0x72 0x2008000 0x10000
-+{"return": ""}
-+write -P0x69 0x3fe0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+{"return": ""}
-+
-+--- Test mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
-+{"return": {}}
-+{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_1", "error": "Input/output error", "len": 393216, "offset": 65536, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
-+{"return": {}}
-+--- Write #2 ---
-+
-+write -P0x74 0x0010000 0x10000
-+{"return": ""}
-+write -P0x69 0x00e8000 0x10000
-+{"return": ""}
-+write -P0x6e 0x2018000 0x10000
-+{"return": ""}
-+write -P0x67 0x3fe0000 0x20000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 262144,
-+        "granularity": 65536,
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      },
-+      {
-+        "busy": true,
-+        "count": 655360,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "locked"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 10 dirty sectors; have 10. OK!
-+
-+= Checking Bitmap bitmap0 =
-+expecting 10 dirty sectors; have 10. OK!
-+
-+--- Write #3 ---
-+
-+write -P0xaa 0x0010000 0x30000
-+{"return": ""}
-+write -P0xbb 0x00d8000 0x10000
-+{"return": ""}
-+write -P0xcc 0x2028000 0x10000
-+{"return": ""}
-+write -P0xdd 0x3fc0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 983040,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 15 dirty sectors; have 15. OK!
-+
-+--- Reference mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 983040,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 15 dirty sectors; have 15. OK!
-+
-+--- Cleanup ---
-+
-+{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Verification ---
-+
-+qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+
-+
-+=== Mode bitmap; Bitmap Sync never without failure ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+--- Write #0 ---
-+
-+write -P0x49 0x0000000 0x10000
-+{"return": ""}
-+write -P0x6c 0x0100000 0x10000
-+{"return": ""}
-+write -P0x6f 0x2000000 0x10000
-+{"return": ""}
-+write -P0x76 0x3ff0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Reference mirror #0 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Add Bitmap ---
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+--- Write #1 ---
-+
-+write -P0x65 0x0000000 0x10000
-+{"return": ""}
-+write -P0x77 0x00f8000 0x10000
-+{"return": ""}
-+write -P0x72 0x2008000 0x10000
-+{"return": ""}
-+write -P0x69 0x3fe0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
-+{"return": {}}
-+--- Write #2 ---
-+
-+write -P0x74 0x0010000 0x10000
-+{"return": ""}
-+write -P0x69 0x00e8000 0x10000
-+{"return": ""}
-+write -P0x6e 0x2018000 0x10000
-+{"return": ""}
-+write -P0x67 0x3fe0000 0x20000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 262144,
-+        "granularity": 65536,
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      },
-+      {
-+        "busy": true,
-+        "count": 655360,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "locked"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 10 dirty sectors; have 10. OK!
-+
-+= Checking Bitmap bitmap0 =
-+expecting 10 dirty sectors; have 10. OK!
-+
-+--- Write #3 ---
-+
-+write -P0xaa 0x0010000 0x30000
-+{"return": ""}
-+write -P0xbb 0x00d8000 0x10000
-+{"return": ""}
-+write -P0xcc 0x2028000 0x10000
-+{"return": ""}
-+write -P0xdd 0x3fc0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 983040,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 15 dirty sectors; have 15. OK!
-+
-+--- Reference mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_3", "len": 983040, "offset": 983040, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 983040,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 15 dirty sectors; have 15. OK!
-+
-+--- Cleanup ---
-+
-+{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Verification ---
-+
-+qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+
-+
-+=== Mode bitmap; Bitmap Sync on-success with simulated failure ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+--- Write #0 ---
-+
-+write -P0x49 0x0000000 0x10000
-+{"return": ""}
-+write -P0x6c 0x0100000 0x10000
-+{"return": ""}
-+write -P0x6f 0x2000000 0x10000
-+{"return": ""}
-+write -P0x76 0x3ff0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Reference mirror #0 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Add Bitmap ---
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+--- Write #1 ---
-+
-+write -P0x65 0x0000000 0x10000
-+{"return": ""}
-+write -P0x77 0x00f8000 0x10000
-+{"return": ""}
-+write -P0x72 0x2008000 0x10000
-+{"return": ""}
-+write -P0x69 0x3fe0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-cancel", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_CANCELLED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
-+{"return": {}}
-+--- Write #2 ---
-+
-+write -P0x74 0x0010000 0x10000
-+{"return": ""}
-+write -P0x69 0x00e8000 0x10000
-+{"return": ""}
-+write -P0x6e 0x2018000 0x10000
-+{"return": ""}
-+write -P0x67 0x3fe0000 0x20000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 262144,
-+        "granularity": 65536,
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      },
-+      {
-+        "busy": true,
-+        "count": 655360,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "locked"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 10 dirty sectors; have 10. OK!
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Write #3 ---
-+
-+write -P0xaa 0x0010000 0x30000
-+{"return": ""}
-+write -P0xbb 0x00d8000 0x10000
-+{"return": ""}
-+write -P0xcc 0x2028000 0x10000
-+{"return": ""}
-+write -P0xdd 0x3fc0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 524288,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 8 dirty sectors; have 8. OK!
-+
-+--- Reference mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 0,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Cleanup ---
-+
-+{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Verification ---
-+
-+qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+
-+
-+=== Mode bitmap; Bitmap Sync on-success with intermediate failure ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "blkdebug", "image": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "inject-error": [{"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 3}, {"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 4}], "set-state": [{"event": "flush_to_disk", "new-state": 2, "state": 1}, {"event": "read_aio", "new-state": 3, "state": 2}, {"event": "read_aio", "new-state": 4, "state": 3}]}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+--- Write #0 ---
-+
-+write -P0x49 0x0000000 0x10000
-+{"return": ""}
-+write -P0x6c 0x0100000 0x10000
-+{"return": ""}
-+write -P0x6f 0x2000000 0x10000
-+{"return": ""}
-+write -P0x76 0x3ff0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Reference mirror #0 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Add Bitmap ---
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+--- Write #1 ---
-+
-+write -P0x65 0x0000000 0x10000
-+{"return": ""}
-+write -P0x77 0x00f8000 0x10000
-+{"return": ""}
-+write -P0x72 0x2008000 0x10000
-+{"return": ""}
-+write -P0x69 0x3fe0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+{"return": ""}
-+
-+--- Test mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
-+{"return": {}}
-+{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_1", "error": "Input/output error", "len": 393216, "offset": 65536, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
-+{"return": {}}
-+--- Write #2 ---
-+
-+write -P0x74 0x0010000 0x10000
-+{"return": ""}
-+write -P0x69 0x00e8000 0x10000
-+{"return": ""}
-+write -P0x6e 0x2018000 0x10000
-+{"return": ""}
-+write -P0x67 0x3fe0000 0x20000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 262144,
-+        "granularity": 65536,
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      },
-+      {
-+        "busy": true,
-+        "count": 655360,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "locked"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 10 dirty sectors; have 10. OK!
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Write #3 ---
-+
-+write -P0xaa 0x0010000 0x30000
-+{"return": ""}
-+write -P0xbb 0x00d8000 0x10000
-+{"return": ""}
-+write -P0xcc 0x2028000 0x10000
-+{"return": ""}
-+write -P0xdd 0x3fc0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 524288,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 8 dirty sectors; have 8. OK!
-+
-+--- Reference mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 0,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Cleanup ---
-+
-+{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Verification ---
-+
-+qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+
-+
-+=== Mode bitmap; Bitmap Sync on-success without failure ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+--- Write #0 ---
-+
-+write -P0x49 0x0000000 0x10000
-+{"return": ""}
-+write -P0x6c 0x0100000 0x10000
-+{"return": ""}
-+write -P0x6f 0x2000000 0x10000
-+{"return": ""}
-+write -P0x76 0x3ff0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Reference mirror #0 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Add Bitmap ---
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+--- Write #1 ---
-+
-+write -P0x65 0x0000000 0x10000
-+{"return": ""}
-+write -P0x77 0x00f8000 0x10000
-+{"return": ""}
-+write -P0x72 0x2008000 0x10000
-+{"return": ""}
-+write -P0x69 0x3fe0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 0,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Reference mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
-+{"return": {}}
-+--- Write #2 ---
-+
-+write -P0x74 0x0010000 0x10000
-+{"return": ""}
-+write -P0x69 0x00e8000 0x10000
-+{"return": ""}
-+write -P0x6e 0x2018000 0x10000
-+{"return": ""}
-+write -P0x67 0x3fe0000 0x20000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 458752,
-+        "granularity": 65536,
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      },
-+      {
-+        "busy": true,
-+        "count": 458752,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "locked"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 7 dirty sectors; have 7. OK!
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Write #3 ---
-+
-+write -P0xaa 0x0010000 0x30000
-+{"return": ""}
-+write -P0xbb 0x00d8000 0x10000
-+{"return": ""}
-+write -P0xcc 0x2028000 0x10000
-+{"return": ""}
-+write -P0xdd 0x3fc0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 524288,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 8 dirty sectors; have 8. OK!
-+
-+--- Reference mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 0,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Cleanup ---
-+
-+{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Verification ---
-+
-+qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+
-+
-+=== Mode bitmap; Bitmap Sync always with simulated failure ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+--- Write #0 ---
-+
-+write -P0x49 0x0000000 0x10000
-+{"return": ""}
-+write -P0x6c 0x0100000 0x10000
-+{"return": ""}
-+write -P0x6f 0x2000000 0x10000
-+{"return": ""}
-+write -P0x76 0x3ff0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Reference mirror #0 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Add Bitmap ---
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+--- Write #1 ---
-+
-+write -P0x65 0x0000000 0x10000
-+{"return": ""}
-+write -P0x77 0x00f8000 0x10000
-+{"return": ""}
-+write -P0x72 0x2008000 0x10000
-+{"return": ""}
-+write -P0x69 0x3fe0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-cancel", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_CANCELLED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 0,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Reference mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
-+{"return": {}}
-+--- Write #2 ---
-+
-+write -P0x74 0x0010000 0x10000
-+{"return": ""}
-+write -P0x69 0x00e8000 0x10000
-+{"return": ""}
-+write -P0x6e 0x2018000 0x10000
-+{"return": ""}
-+write -P0x67 0x3fe0000 0x20000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 458752,
-+        "granularity": 65536,
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      },
-+      {
-+        "busy": true,
-+        "count": 458752,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "locked"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 7 dirty sectors; have 7. OK!
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Write #3 ---
-+
-+write -P0xaa 0x0010000 0x30000
-+{"return": ""}
-+write -P0xbb 0x00d8000 0x10000
-+{"return": ""}
-+write -P0xcc 0x2028000 0x10000
-+{"return": ""}
-+write -P0xdd 0x3fc0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 524288,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 8 dirty sectors; have 8. OK!
-+
-+--- Reference mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 0,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Cleanup ---
-+
-+{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Verification ---
-+
-+qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+
-+
-+=== Mode bitmap; Bitmap Sync always with intermediate failure ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "blkdebug", "image": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "inject-error": [{"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 3}, {"errno": 5, "event": "read_aio", "immediately": false, "once": true, "state": 4}], "set-state": [{"event": "flush_to_disk", "new-state": 2, "state": 1}, {"event": "read_aio", "new-state": 3, "state": 2}, {"event": "read_aio", "new-state": 4, "state": 3}]}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+--- Write #0 ---
-+
-+write -P0x49 0x0000000 0x10000
-+{"return": ""}
-+write -P0x6c 0x0100000 0x10000
-+{"return": ""}
-+write -P0x6f 0x2000000 0x10000
-+{"return": ""}
-+write -P0x76 0x3ff0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Reference mirror #0 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Add Bitmap ---
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+--- Write #1 ---
-+
-+write -P0x65 0x0000000 0x10000
-+{"return": ""}
-+write -P0x77 0x00f8000 0x10000
-+{"return": ""}
-+write -P0x72 0x2008000 0x10000
-+{"return": ""}
-+write -P0x69 0x3fe0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+{"return": ""}
-+
-+--- Test mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
-+{"return": {}}
-+{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"action": "report", "device": "mirror_1", "operation": "read"}, "event": "BLOCK_JOB_ERROR", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_1", "error": "Input/output error", "len": 393216, "offset": 65536, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 327680,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 5 dirty sectors; have 5. OK!
-+
-+--- Reference mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
-+{"return": {}}
-+--- Write #2 ---
-+
-+write -P0x74 0x0010000 0x10000
-+{"return": ""}
-+write -P0x69 0x00e8000 0x10000
-+{"return": ""}
-+write -P0x6e 0x2018000 0x10000
-+{"return": ""}
-+write -P0x67 0x3fe0000 0x20000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 262144,
-+        "granularity": 65536,
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      },
-+      {
-+        "busy": true,
-+        "count": 589824,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "locked"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 9 dirty sectors; have 9. OK!
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Write #3 ---
-+
-+write -P0xaa 0x0010000 0x30000
-+{"return": ""}
-+write -P0xbb 0x00d8000 0x10000
-+{"return": ""}
-+write -P0xcc 0x2028000 0x10000
-+{"return": ""}
-+write -P0xdd 0x3fc0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 524288,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 8 dirty sectors; have 8. OK!
-+
-+--- Reference mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 0,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Cleanup ---
-+
-+{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Verification ---
-+
-+qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+
-+
-+=== Mode bitmap; Bitmap Sync always without failure ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+--- Write #0 ---
-+
-+write -P0x49 0x0000000 0x10000
-+{"return": ""}
-+write -P0x6c 0x0100000 0x10000
-+{"return": ""}
-+write -P0x6f 0x2000000 0x10000
-+{"return": ""}
-+write -P0x76 0x3ff0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Reference mirror #0 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_0", "sync": "full", "target": "ref_target_0"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_0"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_0", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Add Bitmap ---
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+--- Write #1 ---
-+
-+write -P0x65 0x0000000 0x10000
-+{"return": ""}
-+write -P0x77 0x00f8000 0x10000
-+{"return": ""}
-+write -P0x72 0x2008000 0x10000
-+{"return": ""}
-+write -P0x69 0x3fe0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 393216,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 6 dirty sectors; have 6. OK!
-+
-+--- Reference mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_1", "sync": "full", "target": "ref_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_1", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #1 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_1", "sync": "bitmap", "target": "mirror_target_1"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_1"}}
-+{"return": {}}
-+{"data": {"id": "mirror_1", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_1", "len": 393216, "offset": 393216, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 0,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Reference mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_2", "sync": "full", "target": "ref_target_2"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_2"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_2", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #2 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_2", "sync": "bitmap", "target": "mirror_target_2"}}
-+{"return": {}}
-+--- Write #2 ---
-+
-+write -P0x74 0x0010000 0x10000
-+{"return": ""}
-+write -P0x69 0x00e8000 0x10000
-+{"return": ""}
-+write -P0x6e 0x2018000 0x10000
-+{"return": ""}
-+write -P0x67 0x3fe0000 0x20000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 458752,
-+        "granularity": 65536,
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      },
-+      {
-+        "busy": true,
-+        "count": 458752,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "locked"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 7 dirty sectors; have 7. OK!
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Write #3 ---
-+
-+write -P0xaa 0x0010000 0x30000
-+{"return": ""}
-+write -P0xbb 0x00d8000 0x10000
-+{"return": ""}
-+write -P0xcc 0x2028000 0x10000
-+{"return": ""}
-+write -P0xdd 0x3fc0000 0x10000
-+{"return": ""}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 524288,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 8 dirty sectors; have 8. OK!
-+
-+--- Reference mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "ref_mirror_3", "sync": "full", "target": "ref_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "ref_mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "ref_mirror_3", "len": 67108864, "offset": 67108864, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+
-+--- Test mirror #3 ---
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+{"execute": "blockdev-mirror", "arguments": {"auto-finalize": false, "bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "mirror_3", "sync": "bitmap", "target": "mirror_target_3"}}
-+{"return": {}}
-+{"execute": "job-complete", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_READY", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"execute": "job-finalize", "arguments": {"id": "mirror_3"}}
-+{"return": {}}
-+{"data": {"id": "mirror_3", "type": "mirror"}, "event": "BLOCK_JOB_PENDING", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{"data": {"device": "mirror_3", "len": 524288, "offset": 524288, "speed": 0, "type": "mirror"}, "event": "BLOCK_JOB_COMPLETED", "timestamp": {"microseconds": "USECS", "seconds": "SECS"}}
-+{
-+  "bitmaps": {
-+    "drive0": [
-+      {
-+        "busy": false,
-+        "count": 0,
-+        "granularity": 65536,
-+        "name": "bitmap0",
-+        "persistent": false,
-+        "recording": true,
-+        "status": "active"
-+      }
-+    ]
-+  }
-+}
-+
-+= Checking Bitmap bitmap0 =
-+expecting 0 dirty sectors; have 0. OK!
-+
-+--- Cleanup ---
-+
-+{"execute": "block-dirty-bitmap-remove", "arguments": {"name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+{
-+  "bitmaps": {}
-+}
-+
-+--- Verification ---
-+
-+qemu_img compare "TEST_DIR/PID-bsync1" "TEST_DIR/PID-fmirror1" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-bsync2" "TEST_DIR/PID-fmirror2" ==> Mismatch, OK!
-+qemu_img compare "TEST_DIR/PID-bsync3" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
-+
-+
-+=== API failure tests ===
-+
-+--- Preparing image & VM ---
-+
-+{"execute": "blockdev-add", "arguments": {"driver": "qcow2", "file": {"driver": "file", "filename": "TEST_DIR/PID-img"}, "node-name": "drive0"}}
-+{"return": {}}
-+
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-file-job"}}
-+{"return": {}}
-+{}
-+{}
-+{"execute": "job-dismiss", "arguments": {"id": "bdc-fmt-job"}}
-+{"return": {}}
-+{}
-+
-+{"execute": "block-dirty-bitmap-add", "arguments": {"granularity": 65536, "name": "bitmap0", "node": "drive0"}}
-+{"return": {}}
-+
-+-- Testing invalid QMP commands --
-+
-+-- Sync mode incremental tests --
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
-+
-+-- Sync mode bitmap tests --
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+
-+-- Sync mode full tests --
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+
-+-- Sync mode top tests --
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+
-+-- Sync mode none tests --
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
-+
-+{"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
-+{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+
-diff --git a/tests/qemu-iotests/group b/tests/qemu-iotests/group
-index 435dccd5af..939efd9c70 100644
---- a/tests/qemu-iotests/group
-+++ b/tests/qemu-iotests/group
-@@ -270,6 +270,7 @@
- 253 rw quick
- 254 rw backing quick
- 255 rw quick
-+384 rw
- 256 rw auto quick
- 257 rw
- 258 rw quick
diff --git a/debian/patches/pve/0039-mirror-move-some-checks-to-qmp.patch b/debian/patches/pve/0039-mirror-move-some-checks-to-qmp.patch
deleted file mode 100644 (file)
index c04c5d6..0000000
+++ /dev/null
@@ -1,272 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: =?UTF-8?q?Fabian=20Gr=C3=BCnbichler?= <f.gruenbichler@proxmox.com>
-Date: Mon, 6 Apr 2020 12:17:08 +0200
-Subject: [PATCH] mirror: move some checks to qmp
-MIME-Version: 1.0
-Content-Type: text/plain; charset=UTF-8
-Content-Transfer-Encoding: 8bit
-
-and assert the passing conditions in block/mirror.c. while incremental
-mode was never available for drive-mirror, it makes the interface more
-uniform w.r.t. backup block jobs.
-
-Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
----
- block/mirror.c             | 28 +++------------
- blockdev.c                 | 29 +++++++++++++++
- tests/qemu-iotests/384.out | 72 +++++++++++++++++++-------------------
- 3 files changed, 70 insertions(+), 59 deletions(-)
-
-diff --git a/block/mirror.c b/block/mirror.c
-index c56b0f87e3..dbba6fc80e 100644
---- a/block/mirror.c
-+++ b/block/mirror.c
-@@ -1584,31 +1584,13 @@ static BlockJob *mirror_start_job(
-     Error *local_err = NULL;
-     int ret;
--    if (sync_mode == MIRROR_SYNC_MODE_INCREMENTAL) {
--        error_setg(errp, "Sync mode '%s' not supported",
--                   MirrorSyncMode_str(sync_mode));
--        return NULL;
--    } else if (sync_mode == MIRROR_SYNC_MODE_BITMAP) {
--        if (!bitmap) {
--            error_setg(errp, "Must provide a valid bitmap name for '%s'"
--                       " sync mode",
--                       MirrorSyncMode_str(sync_mode));
--            return NULL;
--        }
--    } else if (bitmap) {
--        error_setg(errp,
--                   "sync mode '%s' is not compatible with bitmaps",
--                   MirrorSyncMode_str(sync_mode));
--        return NULL;
--    }
-+    /* QMP interface protects us from these cases */
-+    assert(sync_mode != MIRROR_SYNC_MODE_INCREMENTAL);
-+    assert((bitmap && sync_mode == MIRROR_SYNC_MODE_BITMAP) ||
-+           (!bitmap && sync_mode != MIRROR_SYNC_MODE_BITMAP));
-+    assert(!(bitmap && granularity));
-     if (bitmap) {
--        if (granularity) {
--            error_setg(errp, "granularity (%d)"
--                       "cannot be specified when a bitmap is provided",
--                       granularity);
--            return NULL;
--        }
-         granularity = bdrv_dirty_bitmap_granularity(bitmap);
-         if (bitmap_mode != BITMAP_SYNC_MODE_NEVER) {
-diff --git a/blockdev.c b/blockdev.c
-index fa3c2f5548..206de2b6c2 100644
---- a/blockdev.c
-+++ b/blockdev.c
-@@ -3236,7 +3236,36 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
-         sync = MIRROR_SYNC_MODE_FULL;
-     }
-+    if ((sync == MIRROR_SYNC_MODE_BITMAP) ||
-+        (sync == MIRROR_SYNC_MODE_INCREMENTAL)) {
-+        /* done before desugaring 'incremental' to print the right message */
-+        if (!has_bitmap) {
-+            error_setg(errp, "Must provide a valid bitmap name for "
-+                       "'%s' sync mode", MirrorSyncMode_str(sync));
-+            return;
-+        }
-+    }
-+
-+    if (sync == MIRROR_SYNC_MODE_INCREMENTAL) {
-+        if (has_bitmap_mode &&
-+            bitmap_mode != BITMAP_SYNC_MODE_ON_SUCCESS) {
-+            error_setg(errp, "Bitmap sync mode must be '%s' "
-+                       "when using sync mode '%s'",
-+                       BitmapSyncMode_str(BITMAP_SYNC_MODE_ON_SUCCESS),
-+                       MirrorSyncMode_str(sync));
-+            return;
-+        }
-+        has_bitmap_mode = true;
-+        sync = MIRROR_SYNC_MODE_BITMAP;
-+        bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
-+    }
-+
-     if (has_bitmap) {
-+        if (sync != MIRROR_SYNC_MODE_BITMAP) {
-+            error_setg(errp, "Sync mode '%s' not supported with bitmap.",
-+                       MirrorSyncMode_str(sync));
-+            return;
-+        }
-         if (granularity) {
-             error_setg(errp, "Granularity and bitmap cannot both be set");
-             return;
-diff --git a/tests/qemu-iotests/384.out b/tests/qemu-iotests/384.out
-index 9b7408b6d6..06a2e29058 100644
---- a/tests/qemu-iotests/384.out
-+++ b/tests/qemu-iotests/384.out
-@@ -2681,45 +2681,45 @@ qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
- -- Sync mode incremental tests --
- {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'incremental' sync mode"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'incremental' sync mode"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'incremental' sync mode"}}
- {"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
-+{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'incremental' sync mode"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
- {"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Bitmap sync mode must be 'on-success' when using sync mode 'incremental'"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Bitmap sync mode must be 'on-success' when using sync mode 'incremental'"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
-+{"error": {"class": "GenericError", "desc": "Bitmap sync mode must be 'on-success' when using sync mode 'incremental'"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "incremental", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Sync mode 'incremental' not supported"}}
-+{"error": {"class": "GenericError", "desc": "Bitmap sync mode must be 'on-success' when using sync mode 'incremental'"}}
- -- Sync mode bitmap tests --
- {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
-+{"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
- {"execute": "blockdev-mirror", "arguments": {"device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "bitmap", "target": "mirror_target"}}
- {"error": {"class": "GenericError", "desc": "Must provide a valid bitmap name for 'bitmap' sync mode"}}
-@@ -2751,28 +2751,28 @@ qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
- {"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "full", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- -- Sync mode top tests --
-@@ -2786,28 +2786,28 @@ qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
- {"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "sync mode 'full' is not compatible with bitmaps"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "top", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'full' not supported with bitmap."}}
- -- Sync mode none tests --
-@@ -2821,26 +2821,26 @@ qemu_img compare "TEST_DIR/PID-img" "TEST_DIR/PID-fmirror3" ==> Identical, OK!
- {"error": {"class": "GenericError", "desc": "Cannot specify bitmap sync mode without a bitmap"}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "Dirty bitmap 'bitmap404' not found"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap404", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "on-success", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "always", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "bitmap-mode": "never", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "sync mode 'none' is not compatible with bitmaps"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
- {"execute": "blockdev-mirror", "arguments": {"bitmap": "bitmap0", "device": "drive0", "filter-node-name": "mirror-top", "job-id": "api_job", "sync": "none", "target": "mirror_target"}}
--{"error": {"class": "GenericError", "desc": "bitmap-mode must be specified if a bitmap is provided"}}
-+{"error": {"class": "GenericError", "desc": "Sync mode 'none' not supported with bitmap."}}
diff --git a/debian/patches/pve/0040-PVE-savevm-async-set-up-migration-state.patch b/debian/patches/pve/0040-PVE-savevm-async-set-up-migration-state.patch
deleted file mode 100644 (file)
index 47c05e0..0000000
+++ /dev/null
@@ -1,88 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Stefan Reiter <s.reiter@proxmox.com>
-Date: Wed, 8 Apr 2020 15:29:03 +0200
-Subject: [PATCH] PVE: savevm-async: set up migration state
-
-code mostly adapted from upstream savevm.c
-
-Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
----
- savevm-async.c | 30 ++++++++++++++++++++++++++++--
- 1 file changed, 28 insertions(+), 2 deletions(-)
-
-diff --git a/savevm-async.c b/savevm-async.c
-index 790e27ae37..a38b15d652 100644
---- a/savevm-async.c
-+++ b/savevm-async.c
-@@ -225,6 +225,7 @@ static void *process_savevm_thread(void *opaque)
- {
-     int ret;
-     int64_t maxlen;
-+    MigrationState *ms = migrate_get_current();
-     rcu_register_thread();
-@@ -234,8 +235,7 @@ static void *process_savevm_thread(void *opaque)
-     if (ret < 0) {
-         save_snapshot_error("qemu_savevm_state_setup failed");
--        rcu_unregister_thread();
--        return NULL;
-+        goto out;
-     }
-     while (snap_state.state == SAVE_STATE_ACTIVE) {
-@@ -287,6 +287,12 @@ static void *process_savevm_thread(void *opaque)
-     qemu_bh_schedule(snap_state.cleanup_bh);
-     qemu_mutex_unlock_iothread();
-+out:
-+    /* set migration state accordingly and clear soon-to-be stale file */
-+    migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP,
-+                      ret ? MIGRATION_STATUS_FAILED : MIGRATION_STATUS_COMPLETED);
-+    ms->to_dst_file = NULL;
-+
-     rcu_unregister_thread();
-     return NULL;
- }
-@@ -294,6 +300,7 @@ static void *process_savevm_thread(void *opaque)
- void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
- {
-     Error *local_err = NULL;
-+    MigrationState *ms = migrate_get_current();
-     int bdrv_oflags = BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH;
-@@ -303,6 +310,17 @@ void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
-         return;
-     }
-+    if (migration_is_running(ms->state)) {
-+        error_set(errp, ERROR_CLASS_GENERIC_ERROR, QERR_MIGRATION_ACTIVE);
-+        return;
-+    }
-+
-+    if (migrate_use_block()) {
-+        error_set(errp, ERROR_CLASS_GENERIC_ERROR,
-+                  "Block migration and snapshots are incompatible");
-+        return;
-+    }
-+
-     /* initialize snapshot info */
-     snap_state.saved_vm_running = runstate_is_running();
-     snap_state.bs_pos = 0;
-@@ -341,6 +359,14 @@ void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
-         goto restart;
-     }
-+    /*
-+     * qemu_savevm_* paths use migration code and expect a migration state.
-+     * State is cleared in process_savevm_thread, but has to be initialized
-+     * here (blocking main thread, from QMP) to avoid race conditions.
-+     */
-+    migrate_init(ms);
-+    memset(&ram_counters, 0, sizeof(ram_counters));
-+    ms->to_dst_file = snap_state.file;
-     error_setg(&snap_state.blocker, "block device is in use by savevm");
-     blk_op_block_all(snap_state.target, snap_state.blocker);
diff --git a/debian/patches/pve/0041-PVE-Backup-avoid-use-QemuRecMutex-inside-coroutines.patch b/debian/patches/pve/0041-PVE-Backup-avoid-use-QemuRecMutex-inside-coroutines.patch
deleted file mode 100644 (file)
index 00439d9..0000000
+++ /dev/null
@@ -1,211 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Dietmar Maurer <dietmar@proxmox.com>
-Date: Fri, 17 Apr 2020 08:57:47 +0200
-Subject: [PATCH] PVE Backup: avoid use QemuRecMutex inside coroutines
-
----
- pve-backup.c | 59 +++++++++++++++++++++++++++++++++-------------------
- 1 file changed, 38 insertions(+), 21 deletions(-)
-
-diff --git a/pve-backup.c b/pve-backup.c
-index 169f0c68d0..dddf430399 100644
---- a/pve-backup.c
-+++ b/pve-backup.c
-@@ -11,6 +11,23 @@
- /* PVE backup state and related function */
-+/*
-+ * Note: A resume from a qemu_coroutine_yield can happen in a different thread,
-+ * so you may not use normal mutexes within coroutines:
-+ *
-+ * ---bad-example---
-+ * qemu_rec_mutex_lock(lock)
-+ * ...
-+ * qemu_coroutine_yield() // wait for something
-+ * // we are now inside a different thread
-+ * qemu_rec_mutex_unlock(lock) // Crash - wrong thread!!
-+ * ---end-bad-example--
-+ *
-+ * ==> Always use CoMutext inside coroutines.
-+ * ==> Never acquire/release AioContext withing coroutines (because that use QemuRecMutex)
-+ *
-+ */
-+
- static struct PVEBackupState {
-     struct {
-         // Everithing accessed from qmp_backup_query command is protected using lock
-@@ -30,12 +47,14 @@ static struct PVEBackupState {
-     ProxmoxBackupHandle *pbs;
-     GList *di_list;
-     QemuRecMutex backup_mutex;
-+    CoMutex dump_callback_mutex;
- } backup_state;
- static void pvebackup_init(void)
- {
-     qemu_rec_mutex_init(&backup_state.stat.lock);
-     qemu_rec_mutex_init(&backup_state.backup_mutex);
-+    qemu_co_mutex_init(&backup_state.dump_callback_mutex);
- }
- // initialize PVEBackupState at startup
-@@ -114,16 +133,16 @@ pvebackup_co_dump_pbs_cb(
-     Error *local_err = NULL;
-     int pbs_res = -1;
--    qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+    qemu_co_mutex_lock(&backup_state.dump_callback_mutex);
-     // avoid deadlock if job is cancelled
-     if (pvebackup_error_or_canceled()) {
--        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+        qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
-         return -1;
-     }
-     pbs_res = proxmox_backup_co_write_data(backup_state.pbs, di->dev_id, buf, start, size, &local_err);
--    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+    qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
-     if (pbs_res < 0) {
-         pvebackup_propagate_error(local_err);
-@@ -149,7 +168,6 @@ pvebackup_co_dump_vma_cb(
-     const unsigned char *buf = pbuf;
-     PVEBackupDevInfo *di = opaque;
--
-     int ret = -1;
-     assert(backup_state.vmaw);
-@@ -167,16 +185,16 @@ pvebackup_co_dump_vma_cb(
-     }
-     while (remaining > 0) {
--        qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+        qemu_co_mutex_lock(&backup_state.dump_callback_mutex);
-         // avoid deadlock if job is cancelled
-         if (pvebackup_error_or_canceled()) {
--            qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+            qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
-             return -1;
-         }
-         size_t zero_bytes = 0;
-         ret = vma_writer_write(backup_state.vmaw, di->dev_id, cluster_num, buf, &zero_bytes);
--        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+        qemu_co_mutex_unlock(&backup_state.dump_callback_mutex);
-         ++cluster_num;
-         if (buf) {
-@@ -203,12 +221,11 @@ pvebackup_co_dump_vma_cb(
-     return size;
- }
-+// assumes the caller holds backup_mutex
- static void coroutine_fn pvebackup_co_cleanup(void *unused)
- {
-     assert(qemu_in_coroutine());
--    qemu_rec_mutex_lock(&backup_state.backup_mutex);
--
-     qemu_rec_mutex_lock(&backup_state.stat.lock);
-     backup_state.stat.end_time = time(NULL);
-     qemu_rec_mutex_unlock(&backup_state.stat.lock);
-@@ -239,9 +256,9 @@ static void coroutine_fn pvebackup_co_cleanup(void *unused)
-     g_list_free(backup_state.di_list);
-     backup_state.di_list = NULL;
--    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
- }
-+// assumes the caller holds backup_mutex
- static void coroutine_fn pvebackup_complete_stream(void *opaque)
- {
-     PVEBackupDevInfo *di = opaque;
-@@ -295,6 +312,8 @@ static void pvebackup_complete_cb(void *opaque, int ret)
- static void pvebackup_cancel(void)
- {
-+    assert(!qemu_in_coroutine());
-+
-     Error *cancel_err = NULL;
-     error_setg(&cancel_err, "backup canceled");
-     pvebackup_propagate_error(cancel_err);
-@@ -348,6 +367,7 @@ void qmp_backup_cancel(Error **errp)
-     pvebackup_cancel();
- }
-+// assumes the caller holds backup_mutex
- static int coroutine_fn pvebackup_co_add_config(
-     const char *file,
-     const char *name,
-@@ -431,9 +451,9 @@ static void pvebackup_run_next_job(void)
-         }
-     }
--    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
--
-     block_on_coroutine_fn(pvebackup_co_cleanup, NULL); // no more jobs, run cleanup
-+
-+    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
- }
- static bool create_backup_jobs(void) {
-@@ -520,6 +540,7 @@ typedef struct QmpBackupTask {
-     UuidInfo *result;
- } QmpBackupTask;
-+// assumes the caller holds backup_mutex
- static void coroutine_fn pvebackup_co_prepare(void *opaque)
- {
-     assert(qemu_in_coroutine());
-@@ -543,11 +564,8 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-     const char *config_name = "qemu-server.conf";
-     const char *firewall_name = "qemu-server.fw";
--    qemu_rec_mutex_lock(&backup_state.backup_mutex);
--
-     if (backup_state.di_list) {
--        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
--        error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
-+         error_set(task->errp, ERROR_CLASS_GENERIC_ERROR,
-                   "previous backup not finished");
-         return;
-     }
-@@ -792,8 +810,6 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-     backup_state.di_list = di_list;
--    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
--
-     uuid_info = g_malloc0(sizeof(*uuid_info));
-     uuid_info->UUID = uuid_str;
-@@ -836,8 +852,6 @@ err:
-         rmdir(backup_dir);
-     }
--    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
--
-     task->result = NULL;
-     return;
- }
-@@ -881,13 +895,16 @@ UuidInfo *qmp_backup(
-         .errp = errp,
-     };
-+    qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+
-     block_on_coroutine_fn(pvebackup_co_prepare, &task);
-     if (*errp == NULL) {
--        qemu_rec_mutex_lock(&backup_state.backup_mutex);
-         create_backup_jobs();
-         qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-         pvebackup_run_next_job();
-+    } else {
-+        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-     }
-     return task.result;
diff --git a/debian/patches/pve/0042-PVE-Backup-use-QemuMutex-instead-of-QemuRecMutex.patch b/debian/patches/pve/0042-PVE-Backup-use-QemuMutex-instead-of-QemuRecMutex.patch
deleted file mode 100644 (file)
index b18762d..0000000
+++ /dev/null
@@ -1,227 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Dietmar Maurer <dietmar@proxmox.com>
-Date: Fri, 17 Apr 2020 08:57:48 +0200
-Subject: [PATCH] PVE Backup: use QemuMutex instead of QemuRecMutex
-
-We acquire/release all mutexes outside coroutines now, so we can now
-correctly use a normal mutex.
----
- pve-backup.c | 58 ++++++++++++++++++++++++++--------------------------
- 1 file changed, 29 insertions(+), 29 deletions(-)
-
-diff --git a/pve-backup.c b/pve-backup.c
-index dddf430399..bb917ee972 100644
---- a/pve-backup.c
-+++ b/pve-backup.c
-@@ -31,7 +31,7 @@
- static struct PVEBackupState {
-     struct {
-         // Everithing accessed from qmp_backup_query command is protected using lock
--        QemuRecMutex lock;
-+        QemuMutex lock;
-         Error *error;
-         time_t start_time;
-         time_t end_time;
-@@ -46,14 +46,14 @@ static struct PVEBackupState {
-     VmaWriter *vmaw;
-     ProxmoxBackupHandle *pbs;
-     GList *di_list;
--    QemuRecMutex backup_mutex;
-+    QemuMutex backup_mutex;
-     CoMutex dump_callback_mutex;
- } backup_state;
- static void pvebackup_init(void)
- {
--    qemu_rec_mutex_init(&backup_state.stat.lock);
--    qemu_rec_mutex_init(&backup_state.backup_mutex);
-+    qemu_mutex_init(&backup_state.stat.lock);
-+    qemu_mutex_init(&backup_state.backup_mutex);
-     qemu_co_mutex_init(&backup_state.dump_callback_mutex);
- }
-@@ -91,26 +91,26 @@ lookup_active_block_job(PVEBackupDevInfo *di)
- static void pvebackup_propagate_error(Error *err)
- {
--    qemu_rec_mutex_lock(&backup_state.stat.lock);
-+    qemu_mutex_lock(&backup_state.stat.lock);
-     error_propagate(&backup_state.stat.error, err);
--    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+    qemu_mutex_unlock(&backup_state.stat.lock);
- }
- static bool pvebackup_error_or_canceled(void)
- {
--    qemu_rec_mutex_lock(&backup_state.stat.lock);
-+    qemu_mutex_lock(&backup_state.stat.lock);
-     bool error_or_canceled = !!backup_state.stat.error;
--    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+    qemu_mutex_unlock(&backup_state.stat.lock);
-     return error_or_canceled;
- }
- static void pvebackup_add_transfered_bytes(size_t transferred, size_t zero_bytes)
- {
--    qemu_rec_mutex_lock(&backup_state.stat.lock);
-+    qemu_mutex_lock(&backup_state.stat.lock);
-     backup_state.stat.zero_bytes += zero_bytes;
-     backup_state.stat.transferred += transferred;
--    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+    qemu_mutex_unlock(&backup_state.stat.lock);
- }
- // This may get called from multiple coroutines in multiple io-threads
-@@ -226,9 +226,9 @@ static void coroutine_fn pvebackup_co_cleanup(void *unused)
- {
-     assert(qemu_in_coroutine());
--    qemu_rec_mutex_lock(&backup_state.stat.lock);
-+    qemu_mutex_lock(&backup_state.stat.lock);
-     backup_state.stat.end_time = time(NULL);
--    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+    qemu_mutex_unlock(&backup_state.stat.lock);
-     if (backup_state.vmaw) {
-         Error *local_err = NULL;
-@@ -284,7 +284,7 @@ static void pvebackup_complete_cb(void *opaque, int ret)
-     PVEBackupDevInfo *di = opaque;
--    qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+    qemu_mutex_lock(&backup_state.backup_mutex);
-     di->completed = true;
-@@ -305,7 +305,7 @@ static void pvebackup_complete_cb(void *opaque, int ret)
-     g_free(di);
--    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+    qemu_mutex_unlock(&backup_state.backup_mutex);
-     pvebackup_run_next_job();
- }
-@@ -318,7 +318,7 @@ static void pvebackup_cancel(void)
-     error_setg(&cancel_err, "backup canceled");
-     pvebackup_propagate_error(cancel_err);
--    qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+    qemu_mutex_lock(&backup_state.backup_mutex);
-     if (backup_state.vmaw) {
-         /* make sure vma writer does not block anymore */
-@@ -329,13 +329,13 @@ static void pvebackup_cancel(void)
-         proxmox_backup_abort(backup_state.pbs, "backup canceled");
-     }
--    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+    qemu_mutex_unlock(&backup_state.backup_mutex);
-     for(;;) {
-         BlockJob *next_job = NULL;
--        qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+        qemu_mutex_lock(&backup_state.backup_mutex);
-         GList *l = backup_state.di_list;
-         while (l) {
-@@ -349,7 +349,7 @@ static void pvebackup_cancel(void)
-             }
-         }
--        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+        qemu_mutex_unlock(&backup_state.backup_mutex);
-         if (next_job) {
-             AioContext *aio_context = next_job->job.aio_context;
-@@ -423,7 +423,7 @@ static void pvebackup_run_next_job(void)
- {
-     assert(!qemu_in_coroutine());
--    qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+    qemu_mutex_lock(&backup_state.backup_mutex);
-     GList *l = backup_state.di_list;
-     while (l) {
-@@ -433,7 +433,7 @@ static void pvebackup_run_next_job(void)
-         BlockJob *job = lookup_active_block_job(di);
-         if (job) {
--            qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+            qemu_mutex_unlock(&backup_state.backup_mutex);
-             AioContext *aio_context = job->job.aio_context;
-             aio_context_acquire(aio_context);
-@@ -453,7 +453,7 @@ static void pvebackup_run_next_job(void)
-     block_on_coroutine_fn(pvebackup_co_cleanup, NULL); // no more jobs, run cleanup
--    qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+    qemu_mutex_unlock(&backup_state.backup_mutex);
- }
- static bool create_backup_jobs(void) {
-@@ -778,7 +778,7 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-     }
-     /* initialize global backup_state now */
--    qemu_rec_mutex_lock(&backup_state.stat.lock);
-+    qemu_mutex_lock(&backup_state.stat.lock);
-     if (backup_state.stat.error) {
-         error_free(backup_state.stat.error);
-@@ -801,7 +801,7 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-     backup_state.stat.transferred = 0;
-     backup_state.stat.zero_bytes = 0;
--    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+    qemu_mutex_unlock(&backup_state.stat.lock);
-     backup_state.speed = (task->has_speed && task->speed > 0) ? task->speed : 0;
-@@ -895,16 +895,16 @@ UuidInfo *qmp_backup(
-         .errp = errp,
-     };
--    qemu_rec_mutex_lock(&backup_state.backup_mutex);
-+    qemu_mutex_lock(&backup_state.backup_mutex);
-     block_on_coroutine_fn(pvebackup_co_prepare, &task);
-     if (*errp == NULL) {
-         create_backup_jobs();
--        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+        qemu_mutex_unlock(&backup_state.backup_mutex);
-         pvebackup_run_next_job();
-     } else {
--        qemu_rec_mutex_unlock(&backup_state.backup_mutex);
-+        qemu_mutex_unlock(&backup_state.backup_mutex);
-     }
-     return task.result;
-@@ -914,11 +914,11 @@ BackupStatus *qmp_query_backup(Error **errp)
- {
-     BackupStatus *info = g_malloc0(sizeof(*info));
--    qemu_rec_mutex_lock(&backup_state.stat.lock);
-+    qemu_mutex_lock(&backup_state.stat.lock);
-     if (!backup_state.stat.start_time) {
-         /* not started, return {} */
--        qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+        qemu_mutex_unlock(&backup_state.stat.lock);
-         return info;
-     }
-@@ -955,7 +955,7 @@ BackupStatus *qmp_query_backup(Error **errp)
-     info->has_transferred = true;
-     info->transferred = backup_state.stat.transferred;
--    qemu_rec_mutex_unlock(&backup_state.stat.lock);
-+    qemu_mutex_unlock(&backup_state.stat.lock);
-     return info;
- }
diff --git a/debian/patches/pve/0043-move-savevm-async-back-into-a-coroutine.patch b/debian/patches/pve/0043-move-savevm-async-back-into-a-coroutine.patch
deleted file mode 100644 (file)
index f4945db..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Date: Thu, 30 Apr 2020 15:55:37 +0200
-Subject: [PATCH] move savevm-async back into a coroutine
-
-Move qemu_savevm_state_{header,setup} into the main loop and
-the rest of the iteration into a coroutine. The former need
-to lock the iothread (and we can't unlock it in the
-coroutine), and the latter can't deal with being in a
-separate thread, so a coroutine it must be.
-
-Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
----
- savevm-async.c | 28 +++++++++-------------------
- 1 file changed, 9 insertions(+), 19 deletions(-)
-
-diff --git a/savevm-async.c b/savevm-async.c
-index a38b15d652..af865b9a0a 100644
---- a/savevm-async.c
-+++ b/savevm-async.c
-@@ -51,7 +51,7 @@ static struct SnapshotState {
-     QEMUFile *file;
-     int64_t total_time;
-     QEMUBH *cleanup_bh;
--    QemuThread thread;
-+    Coroutine *co;
- } snap_state;
- SaveVMInfo *qmp_query_savevm(Error **errp)
-@@ -201,11 +201,9 @@ static void process_savevm_cleanup(void *opaque)
-     int ret;
-     qemu_bh_delete(snap_state.cleanup_bh);
-     snap_state.cleanup_bh = NULL;
-+    snap_state.co = NULL;
-     qemu_savevm_state_cleanup();
--    qemu_mutex_unlock_iothread();
--    qemu_thread_join(&snap_state.thread);
--    qemu_mutex_lock_iothread();
-     ret = save_snapshot_cleanup();
-     if (ret < 0) {
-         save_snapshot_error("save_snapshot_cleanup error %d", ret);
-@@ -221,18 +219,13 @@ static void process_savevm_cleanup(void *opaque)
-     }
- }
--static void *process_savevm_thread(void *opaque)
-+static void process_savevm_coro(void *opaque)
- {
-     int ret;
-     int64_t maxlen;
-     MigrationState *ms = migrate_get_current();
--    rcu_register_thread();
--
--    qemu_savevm_state_header(snap_state.file);
--    qemu_savevm_state_setup(snap_state.file);
-     ret = qemu_file_get_error(snap_state.file);
--
-     if (ret < 0) {
-         save_snapshot_error("qemu_savevm_state_setup failed");
-         goto out;
-@@ -247,16 +240,13 @@ static void *process_savevm_thread(void *opaque)
-         maxlen = blk_getlength(snap_state.target) - 30*1024*1024;
-         if (pending_size > 400000 && snap_state.bs_pos + pending_size < maxlen) {
--            qemu_mutex_lock_iothread();
-             ret = qemu_savevm_state_iterate(snap_state.file, false);
-             if (ret < 0) {
-                 save_snapshot_error("qemu_savevm_state_iterate error %d", ret);
-                 break;
-             }
--            qemu_mutex_unlock_iothread();
-             DPRINTF("savevm inerate pending size %lu ret %d\n", pending_size, ret);
-         } else {
--            qemu_mutex_lock_iothread();
-             qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
-             ret = global_state_store();
-             if (ret) {
-@@ -285,16 +275,12 @@ static void *process_savevm_thread(void *opaque)
-     }
-     qemu_bh_schedule(snap_state.cleanup_bh);
--    qemu_mutex_unlock_iothread();
- out:
-     /* set migration state accordingly and clear soon-to-be stale file */
-     migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP,
-                       ret ? MIGRATION_STATUS_FAILED : MIGRATION_STATUS_COMPLETED);
-     ms->to_dst_file = NULL;
--
--    rcu_unregister_thread();
--    return NULL;
- }
- void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
-@@ -373,8 +359,12 @@ void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
-     snap_state.state = SAVE_STATE_ACTIVE;
-     snap_state.cleanup_bh = qemu_bh_new(process_savevm_cleanup, &snap_state);
--    qemu_thread_create(&snap_state.thread, "savevm-async", process_savevm_thread,
--                       NULL, QEMU_THREAD_JOINABLE);
-+    snap_state.co = qemu_coroutine_create(&process_savevm_coro, NULL);
-+    qemu_mutex_unlock_iothread();
-+    qemu_savevm_state_header(snap_state.file);
-+    qemu_savevm_state_setup(snap_state.file);
-+    qemu_mutex_lock_iothread();
-+    aio_co_schedule(iohandler_get_aio_context(), snap_state.co);
-     return;
diff --git a/debian/patches/pve/0044-add-optional-buffer-size-to-QEMUFile.patch b/debian/patches/pve/0044-add-optional-buffer-size-to-QEMUFile.patch
deleted file mode 100644 (file)
index daad1f5..0000000
+++ /dev/null
@@ -1,183 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Wolfgang Bumiller <w.bumiller@proxmox.com>
-Date: Mon, 4 May 2020 11:05:08 +0200
-Subject: [PATCH] add optional buffer size to QEMUFile
-
-So we can use a 4M buffer for savevm-async which should
-increase performance storing the state onto ceph.
-
-Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
----
- migration/qemu-file.c | 36 ++++++++++++++++++++++++------------
- migration/qemu-file.h |  1 +
- savevm-async.c        |  4 ++--
- 3 files changed, 27 insertions(+), 14 deletions(-)
-
-diff --git a/migration/qemu-file.c b/migration/qemu-file.c
-index 1c3a358a14..7362e51c71 100644
---- a/migration/qemu-file.c
-+++ b/migration/qemu-file.c
-@@ -30,7 +30,7 @@
- #include "trace.h"
- #include "qapi/error.h"
--#define IO_BUF_SIZE 32768
-+#define DEFAULT_IO_BUF_SIZE 32768
- #define MAX_IOV_SIZE MIN(IOV_MAX, 64)
- struct QEMUFile {
-@@ -45,7 +45,8 @@ struct QEMUFile {
-                     when reading */
-     int buf_index;
-     int buf_size; /* 0 when writing */
--    uint8_t buf[IO_BUF_SIZE];
-+    size_t buf_allocated_size;
-+    uint8_t *buf;
-     DECLARE_BITMAP(may_free, MAX_IOV_SIZE);
-     struct iovec iov[MAX_IOV_SIZE];
-@@ -101,7 +102,7 @@ bool qemu_file_mode_is_not_valid(const char *mode)
-     return false;
- }
--QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)
-+QEMUFile *qemu_fopen_ops_sized(void *opaque, const QEMUFileOps *ops, size_t buffer_size)
- {
-     QEMUFile *f;
-@@ -109,9 +110,17 @@ QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)
-     f->opaque = opaque;
-     f->ops = ops;
-+    f->buf_allocated_size = buffer_size;
-+    f->buf = malloc(buffer_size);
-+
-     return f;
- }
-+QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)
-+{
-+    return qemu_fopen_ops_sized(opaque, ops, DEFAULT_IO_BUF_SIZE);
-+}
-+
- void qemu_file_set_hooks(QEMUFile *f, const QEMUFileHooks *hooks)
- {
-@@ -346,7 +355,7 @@ static ssize_t qemu_fill_buffer(QEMUFile *f)
-     }
-     len = f->ops->get_buffer(f->opaque, f->buf + pending, f->pos,
--                             IO_BUF_SIZE - pending, &local_error);
-+                             f->buf_allocated_size - pending, &local_error);
-     if (len > 0) {
-         f->buf_size += len;
-         f->pos += len;
-@@ -386,6 +395,9 @@ int qemu_fclose(QEMUFile *f)
-             ret = ret2;
-         }
-     }
-+
-+    free(f->buf);
-+
-     /* If any error was spotted before closing, we should report it
-      * instead of the close() return value.
-      */
-@@ -435,7 +447,7 @@ static void add_buf_to_iovec(QEMUFile *f, size_t len)
- {
-     if (!add_to_iovec(f, f->buf + f->buf_index, len, false)) {
-         f->buf_index += len;
--        if (f->buf_index == IO_BUF_SIZE) {
-+        if (f->buf_index == f->buf_allocated_size) {
-             qemu_fflush(f);
-         }
-     }
-@@ -461,7 +473,7 @@ void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, size_t size)
-     }
-     while (size > 0) {
--        l = IO_BUF_SIZE - f->buf_index;
-+        l = f->buf_allocated_size - f->buf_index;
-         if (l > size) {
-             l = size;
-         }
-@@ -508,8 +520,8 @@ size_t qemu_peek_buffer(QEMUFile *f, uint8_t **buf, size_t size, size_t offset)
-     size_t index;
-     assert(!qemu_file_is_writable(f));
--    assert(offset < IO_BUF_SIZE);
--    assert(size <= IO_BUF_SIZE - offset);
-+    assert(offset < f->buf_allocated_size);
-+    assert(size <= f->buf_allocated_size - offset);
-     /* The 1st byte to read from */
-     index = f->buf_index + offset;
-@@ -559,7 +571,7 @@ size_t qemu_get_buffer(QEMUFile *f, uint8_t *buf, size_t size)
-         size_t res;
-         uint8_t *src;
--        res = qemu_peek_buffer(f, &src, MIN(pending, IO_BUF_SIZE), 0);
-+        res = qemu_peek_buffer(f, &src, MIN(pending, f->buf_allocated_size), 0);
-         if (res == 0) {
-             return done;
-         }
-@@ -593,7 +605,7 @@ size_t qemu_get_buffer(QEMUFile *f, uint8_t *buf, size_t size)
-  */
- size_t qemu_get_buffer_in_place(QEMUFile *f, uint8_t **buf, size_t size)
- {
--    if (size < IO_BUF_SIZE) {
-+    if (size < f->buf_allocated_size) {
-         size_t res;
-         uint8_t *src;
-@@ -618,7 +630,7 @@ int qemu_peek_byte(QEMUFile *f, int offset)
-     int index = f->buf_index + offset;
-     assert(!qemu_file_is_writable(f));
--    assert(offset < IO_BUF_SIZE);
-+    assert(offset < f->buf_allocated_size);
-     if (index >= f->buf_size) {
-         qemu_fill_buffer(f);
-@@ -770,7 +782,7 @@ static int qemu_compress_data(z_stream *stream, uint8_t *dest, size_t dest_len,
- ssize_t qemu_put_compression_data(QEMUFile *f, z_stream *stream,
-                                   const uint8_t *p, size_t size)
- {
--    ssize_t blen = IO_BUF_SIZE - f->buf_index - sizeof(int32_t);
-+    ssize_t blen = f->buf_allocated_size - f->buf_index - sizeof(int32_t);
-     if (blen < compressBound(size)) {
-         return -1;
-diff --git a/migration/qemu-file.h b/migration/qemu-file.h
-index a9b6d6ccb7..8752d27c74 100644
---- a/migration/qemu-file.h
-+++ b/migration/qemu-file.h
-@@ -120,6 +120,7 @@ typedef struct QEMUFileHooks {
- } QEMUFileHooks;
- QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops);
-+QEMUFile *qemu_fopen_ops_sized(void *opaque, const QEMUFileOps *ops, size_t buffer_size);
- void qemu_file_set_hooks(QEMUFile *f, const QEMUFileHooks *hooks);
- int qemu_get_fd(QEMUFile *f);
- int qemu_fclose(QEMUFile *f);
-diff --git a/savevm-async.c b/savevm-async.c
-index af865b9a0a..c3fe741c38 100644
---- a/savevm-async.c
-+++ b/savevm-async.c
-@@ -338,7 +338,7 @@ void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
-         goto restart;
-     }
--    snap_state.file = qemu_fopen_ops(&snap_state, &block_file_ops);
-+    snap_state.file = qemu_fopen_ops_sized(&snap_state, &block_file_ops, 4 * 1024 * 1024);
-     if (!snap_state.file) {
-         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "failed to open '%s'", statefile);
-@@ -454,7 +454,7 @@ int load_snapshot_from_blockdev(const char *filename, Error **errp)
-     blk_op_block_all(be, blocker);
-     /* restore the VM state */
--    f = qemu_fopen_ops(be, &loadstate_file_ops);
-+    f = qemu_fopen_ops_sized(be, &loadstate_file_ops, 4 * 1024 * 1024);
-     if (!f) {
-         error_setg(errp, "Could not open VM state file");
-         goto the_end;
diff --git a/debian/patches/pve/0045-savevm-async-move-more-code-to-cleanup-and-rename-to.patch b/debian/patches/pve/0045-savevm-async-move-more-code-to-cleanup-and-rename-to.patch
deleted file mode 100644 (file)
index 1880717..0000000
+++ /dev/null
@@ -1,188 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Stefan Reiter <s.reiter@proxmox.com>
-Date: Wed, 27 May 2020 11:33:19 +0200
-Subject: [PATCH] savevm-async: move more code to cleanup and rename to
- finalize
-
-process_savevm_cleanup is renamed to process_savevm_finalize to
-accomodate more code that is not all cleanup related.
-
-The benefit of this is that it allows us to call functions which need to
-run in the main AIOContext directly. It doesn't majorly affect snapshot
-performance, since the first instruction that is moved stops the VM,
-so the downtime stays about the same.
-
-The target bdrv is additionally moved to the IOHandler context before
-process_savevm_co to make sure the coroutine can call functions that
-require it to own the bdrv's context. process_savevm_finalize then moves
-it back to the main context to run its part.
-
-Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
----
- savevm-async.c | 87 +++++++++++++++++++++++++++++---------------------
- 1 file changed, 51 insertions(+), 36 deletions(-)
-
-diff --git a/savevm-async.c b/savevm-async.c
-index c3fe741c38..2894c94233 100644
---- a/savevm-async.c
-+++ b/savevm-async.c
-@@ -50,7 +50,7 @@ static struct SnapshotState {
-     int saved_vm_running;
-     QEMUFile *file;
-     int64_t total_time;
--    QEMUBH *cleanup_bh;
-+    QEMUBH *finalize_bh;
-     Coroutine *co;
- } snap_state;
-@@ -196,12 +196,42 @@ static const QEMUFileOps block_file_ops = {
-     .close =          block_state_close,
- };
--static void process_savevm_cleanup(void *opaque)
-+static void process_savevm_finalize(void *opaque)
- {
-     int ret;
--    qemu_bh_delete(snap_state.cleanup_bh);
--    snap_state.cleanup_bh = NULL;
-+    AioContext *iohandler_ctx = iohandler_get_aio_context();
-+    MigrationState *ms = migrate_get_current();
-+
-+    qemu_bh_delete(snap_state.finalize_bh);
-+    snap_state.finalize_bh = NULL;
-     snap_state.co = NULL;
-+
-+    /* We need to own the target bdrv's context for the following functions,
-+     * so move it back. It can stay in the main context and live out its live
-+     * there, since we're done with it after this method ends anyway.
-+     */
-+    aio_context_acquire(iohandler_ctx);
-+    blk_set_aio_context(snap_state.target, qemu_get_aio_context(), NULL);
-+    aio_context_release(iohandler_ctx);
-+
-+    ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
-+    if (ret < 0) {
-+        save_snapshot_error("vm_stop_force_state error %d", ret);
-+    }
-+
-+    (void)qemu_savevm_state_complete_precopy(snap_state.file, false, false);
-+    ret = qemu_file_get_error(snap_state.file);
-+    if (ret < 0) {
-+            save_snapshot_error("qemu_savevm_state_iterate error %d", ret);
-+    }
-+
-+    DPRINTF("state saving complete\n");
-+
-+    /* clear migration state */
-+    migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP,
-+                      ret ? MIGRATION_STATUS_FAILED : MIGRATION_STATUS_COMPLETED);
-+    ms->to_dst_file = NULL;
-+
-     qemu_savevm_state_cleanup();
-     ret = save_snapshot_cleanup();
-@@ -219,16 +249,15 @@ static void process_savevm_cleanup(void *opaque)
-     }
- }
--static void process_savevm_coro(void *opaque)
-+static void coroutine_fn process_savevm_co(void *opaque)
- {
-     int ret;
-     int64_t maxlen;
--    MigrationState *ms = migrate_get_current();
-     ret = qemu_file_get_error(snap_state.file);
-     if (ret < 0) {
-         save_snapshot_error("qemu_savevm_state_setup failed");
--        goto out;
-+        return;
-     }
-     while (snap_state.state == SAVE_STATE_ACTIVE) {
-@@ -245,7 +274,7 @@ static void process_savevm_coro(void *opaque)
-                 save_snapshot_error("qemu_savevm_state_iterate error %d", ret);
-                 break;
-             }
--            DPRINTF("savevm inerate pending size %lu ret %d\n", pending_size, ret);
-+            DPRINTF("savevm iterate pending size %lu ret %d\n", pending_size, ret);
-         } else {
-             qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER, NULL);
-             ret = global_state_store();
-@@ -253,40 +282,20 @@ static void process_savevm_coro(void *opaque)
-                 save_snapshot_error("global_state_store error %d", ret);
-                 break;
-             }
--            ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);
--            if (ret < 0) {
--                save_snapshot_error("vm_stop_force_state error %d", ret);
--                break;
--            }
--            DPRINTF("savevm inerate finished\n");
--            /* upstream made the return value here inconsistent
--             * (-1 instead of 'ret' in one case and 0 after flush which can
--             * still set a file error...)
--             */
--            (void)qemu_savevm_state_complete_precopy(snap_state.file, false, false);
--            ret = qemu_file_get_error(snap_state.file);
--            if (ret < 0) {
--                    save_snapshot_error("qemu_savevm_state_iterate error %d", ret);
--                    break;
--            }
--            DPRINTF("save complete\n");
-+
-+            DPRINTF("savevm iterate complete\n");
-             break;
-         }
-     }
--    qemu_bh_schedule(snap_state.cleanup_bh);
--
--out:
--    /* set migration state accordingly and clear soon-to-be stale file */
--    migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP,
--                      ret ? MIGRATION_STATUS_FAILED : MIGRATION_STATUS_COMPLETED);
--    ms->to_dst_file = NULL;
-+    qemu_bh_schedule(snap_state.finalize_bh);
- }
- void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
- {
-     Error *local_err = NULL;
-     MigrationState *ms = migrate_get_current();
-+    AioContext *iohandler_ctx = iohandler_get_aio_context();
-     int bdrv_oflags = BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH;
-@@ -347,7 +356,7 @@ void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
-     /*
-      * qemu_savevm_* paths use migration code and expect a migration state.
--     * State is cleared in process_savevm_thread, but has to be initialized
-+     * State is cleared in process_savevm_co, but has to be initialized
-      * here (blocking main thread, from QMP) to avoid race conditions.
-      */
-     migrate_init(ms);
-@@ -358,13 +367,19 @@ void qmp_savevm_start(bool has_statefile, const char *statefile, Error **errp)
-     blk_op_block_all(snap_state.target, snap_state.blocker);
-     snap_state.state = SAVE_STATE_ACTIVE;
--    snap_state.cleanup_bh = qemu_bh_new(process_savevm_cleanup, &snap_state);
--    snap_state.co = qemu_coroutine_create(&process_savevm_coro, NULL);
-+    snap_state.finalize_bh = qemu_bh_new(process_savevm_finalize, &snap_state);
-+    snap_state.co = qemu_coroutine_create(&process_savevm_co, NULL);
-     qemu_mutex_unlock_iothread();
-     qemu_savevm_state_header(snap_state.file);
-     qemu_savevm_state_setup(snap_state.file);
-     qemu_mutex_lock_iothread();
--    aio_co_schedule(iohandler_get_aio_context(), snap_state.co);
-+
-+    /* Async processing from here on out happens in iohandler context, so let
-+     * the target bdrv have its home there.
-+     */
-+    blk_set_aio_context(snap_state.target, iohandler_ctx, &local_err);
-+
-+    aio_co_schedule(iohandler_ctx, snap_state.co);
-     return;
diff --git a/debian/patches/pve/0046-util-async-Add-aio_co_reschedule_self.patch b/debian/patches/pve/0046-util-async-Add-aio_co_reschedule_self.patch
deleted file mode 100644 (file)
index 5927453..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Kevin Wolf <kwolf@redhat.com>
-Date: Wed, 27 May 2020 11:33:20 +0200
-Subject: [PATCH] util/async: Add aio_co_reschedule_self()
-
-Add a function that can be used to move the currently running coroutine
-to a different AioContext (and therefore potentially a different
-thread).
-
-Signed-off-by: Kevin Wolf <kwolf@redhat.com>
----
- include/block/aio.h | 10 ++++++++++
- util/async.c        | 30 ++++++++++++++++++++++++++++++
- 2 files changed, 40 insertions(+)
-
-diff --git a/include/block/aio.h b/include/block/aio.h
-index 62ed954344..d5399c67d6 100644
---- a/include/block/aio.h
-+++ b/include/block/aio.h
-@@ -17,6 +17,7 @@
- #ifdef CONFIG_LINUX_IO_URING
- #include <liburing.h>
- #endif
-+#include "qemu/coroutine.h"
- #include "qemu/queue.h"
- #include "qemu/event_notifier.h"
- #include "qemu/thread.h"
-@@ -654,6 +655,15 @@ static inline bool aio_node_check(AioContext *ctx, bool is_external)
-  */
- void aio_co_schedule(AioContext *ctx, struct Coroutine *co);
-+/**
-+ * aio_co_reschedule_self:
-+ * @new_ctx: the new context
-+ *
-+ * Move the currently running coroutine to new_ctx. If the coroutine is already
-+ * running in new_ctx, do nothing.
-+ */
-+void coroutine_fn aio_co_reschedule_self(AioContext *new_ctx);
-+
- /**
-  * aio_co_wake:
-  * @co: the coroutine
-diff --git a/util/async.c b/util/async.c
-index 3165a28f2f..4eba1e6f1b 100644
---- a/util/async.c
-+++ b/util/async.c
-@@ -558,6 +558,36 @@ void aio_co_schedule(AioContext *ctx, Coroutine *co)
-     aio_context_unref(ctx);
- }
-+typedef struct AioCoRescheduleSelf {
-+    Coroutine *co;
-+    AioContext *new_ctx;
-+} AioCoRescheduleSelf;
-+
-+static void aio_co_reschedule_self_bh(void *opaque)
-+{
-+    AioCoRescheduleSelf *data = opaque;
-+    aio_co_schedule(data->new_ctx, data->co);
-+}
-+
-+void coroutine_fn aio_co_reschedule_self(AioContext *new_ctx)
-+{
-+    AioContext *old_ctx = qemu_get_current_aio_context();
-+
-+    if (old_ctx != new_ctx) {
-+        AioCoRescheduleSelf data = {
-+            .co = qemu_coroutine_self(),
-+            .new_ctx = new_ctx,
-+        };
-+        /*
-+         * We can't directly schedule the coroutine in the target context
-+         * because this would be racy: The other thread could try to enter the
-+         * coroutine before it has yielded in this one.
-+         */
-+        aio_bh_schedule_oneshot(old_ctx, aio_co_reschedule_self_bh, &data);
-+        qemu_coroutine_yield();
-+    }
-+}
-+
- void aio_co_wake(struct Coroutine *co)
- {
-     AioContext *ctx;
diff --git a/debian/patches/pve/0047-savevm-async-flush-IOThread-drives-async-before-ente.patch b/debian/patches/pve/0047-savevm-async-flush-IOThread-drives-async-before-ente.patch
deleted file mode 100644 (file)
index b68ec1f..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Stefan Reiter <s.reiter@proxmox.com>
-Date: Wed, 27 May 2020 11:33:21 +0200
-Subject: [PATCH] savevm-async: flush IOThread-drives async before entering
- blocking part
-
-By flushing all drives where its possible to so before entering the
-blocking part (where the VM is stopped), we can reduce the time spent in
-said part for every disk that has an IOThread (other drives cannot be
-flushed async anyway).
-
-Suggested-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
-Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
----
- savevm-async.c | 23 +++++++++++++++++++++++
- 1 file changed, 23 insertions(+)
-
-diff --git a/savevm-async.c b/savevm-async.c
-index 2894c94233..4ce83a0691 100644
---- a/savevm-async.c
-+++ b/savevm-async.c
-@@ -253,6 +253,8 @@ static void coroutine_fn process_savevm_co(void *opaque)
- {
-     int ret;
-     int64_t maxlen;
-+    BdrvNextIterator it;
-+    BlockDriverState *bs = NULL;
-     ret = qemu_file_get_error(snap_state.file);
-     if (ret < 0) {
-@@ -288,6 +290,27 @@ static void coroutine_fn process_savevm_co(void *opaque)
-         }
-     }
-+    /* If a drive runs in an IOThread we can flush it async, and only
-+     * need to sync-flush whatever IO happens between now and
-+     * vm_stop_force_state. bdrv_next can only be called from main AioContext,
-+     * so move there now and after every flush.
-+     */
-+    aio_co_reschedule_self(qemu_get_aio_context());
-+    for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
-+        /* target has BDRV_O_NO_FLUSH, no sense calling bdrv_flush on it */
-+        if (bs == blk_bs(snap_state.target)) {
-+            continue;
-+        }
-+
-+        AioContext *bs_ctx = bdrv_get_aio_context(bs);
-+        if (bs_ctx != qemu_get_aio_context()) {
-+            DPRINTF("savevm: async flushing drive %s\n", bs->filename);
-+            aio_co_reschedule_self(bs_ctx);
-+            bdrv_flush(bs);
-+            aio_co_reschedule_self(qemu_get_aio_context());
-+        }
-+    }
-+
-     qemu_bh_schedule(snap_state.finalize_bh);
- }
diff --git a/debian/patches/pve/0048-savevm-async-add-debug-timing-prints.patch b/debian/patches/pve/0048-savevm-async-add-debug-timing-prints.patch
deleted file mode 100644 (file)
index 68b7635..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Stefan Reiter <s.reiter@proxmox.com>
-Date: Wed, 27 May 2020 11:33:22 +0200
-Subject: [PATCH] savevm-async: add debug timing prints
-
-Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
-[ Thomas: guard variable declaration by DEBUG #ifdef ]
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- savevm-async.c | 22 ++++++++++++++++++++++
- 1 file changed, 22 insertions(+)
-
-diff --git a/savevm-async.c b/savevm-async.c
-index 4ce83a0691..0388cebbe9 100644
---- a/savevm-async.c
-+++ b/savevm-async.c
-@@ -202,6 +202,10 @@ static void process_savevm_finalize(void *opaque)
-     AioContext *iohandler_ctx = iohandler_get_aio_context();
-     MigrationState *ms = migrate_get_current();
-+#ifdef DEBUG_SAVEVM_STATE
-+    int64_t start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
-+#endif
-+
-     qemu_bh_delete(snap_state.finalize_bh);
-     snap_state.finalize_bh = NULL;
-     snap_state.co = NULL;
-@@ -226,6 +230,8 @@ static void process_savevm_finalize(void *opaque)
-     }
-     DPRINTF("state saving complete\n");
-+    DPRINTF("timing: process_savevm_finalize (state saving) took %ld ms\n",
-+        qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - start_time);
-     /* clear migration state */
-     migrate_set_state(&ms->state, MIGRATION_STATUS_SETUP,
-@@ -247,6 +253,9 @@ static void process_savevm_finalize(void *opaque)
-         vm_start();
-         snap_state.saved_vm_running = false;
-     }
-+
-+    DPRINTF("timing: process_savevm_finalize (full) took %ld ms\n",
-+        qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - start_time);
- }
- static void coroutine_fn process_savevm_co(void *opaque)
-@@ -256,6 +265,10 @@ static void coroutine_fn process_savevm_co(void *opaque)
-     BdrvNextIterator it;
-     BlockDriverState *bs = NULL;
-+#ifdef DEBUG_SAVEVM_STATE
-+    int64_t start_time = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
-+#endif
-+
-     ret = qemu_file_get_error(snap_state.file);
-     if (ret < 0) {
-         save_snapshot_error("qemu_savevm_state_setup failed");
-@@ -290,6 +303,12 @@ static void coroutine_fn process_savevm_co(void *opaque)
-         }
-     }
-+    DPRINTF("timing: process_savevm_co took %ld ms\n",
-+        qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - start_time);
-+
-+#ifdef DEBUG_SAVEVM_STATE
-+    int64_t start_time_flush = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
-+#endif
-     /* If a drive runs in an IOThread we can flush it async, and only
-      * need to sync-flush whatever IO happens between now and
-      * vm_stop_force_state. bdrv_next can only be called from main AioContext,
-@@ -311,6 +330,9 @@ static void coroutine_fn process_savevm_co(void *opaque)
-         }
-     }
-+    DPRINTF("timing: async flushing took %ld ms\n",
-+        qemu_clock_get_ms(QEMU_CLOCK_REALTIME) - start_time_flush);
-+
-     qemu_bh_schedule(snap_state.finalize_bh);
- }
diff --git a/debian/patches/pve/0049-Add-some-qemu_vfree-statements-to-prevent-memory-lea.patch b/debian/patches/pve/0049-Add-some-qemu_vfree-statements-to-prevent-memory-lea.patch
deleted file mode 100644 (file)
index fcf46d2..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Stefan Reiter <s.reiter@proxmox.com>
-Date: Mon, 22 Jun 2020 14:54:00 +0200
-Subject: [PATCH] Add some qemu_vfree statements to prevent memory leaks
-
-Suggested-by: Lars Ellenberg <lars.ellenberg@linbit.com>
-Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
----
- vma-writer.c | 2 ++
- vma.c        | 2 ++
- 2 files changed, 4 insertions(+)
-
-diff --git a/vma-writer.c b/vma-writer.c
-index fe86b18a60..06cbc02b1e 100644
---- a/vma-writer.c
-+++ b/vma-writer.c
-@@ -767,5 +767,7 @@ void vma_writer_destroy(VmaWriter *vmaw)
-         g_checksum_free(vmaw->md5csum);
-     }
-+    qemu_vfree(vmaw->headerbuf);
-+    qemu_vfree(vmaw->outbuf);
-     g_free(vmaw);
- }
-diff --git a/vma.c b/vma.c
-index a82752448a..2eea2fc281 100644
---- a/vma.c
-+++ b/vma.c
-@@ -565,6 +565,7 @@ out:
-             g_warning("vma_writer_close failed %s", error_get_pretty(err));
-         }
-     }
-+    qemu_vfree(buf);
- }
- static int create_archive(int argc, char **argv)
-@@ -732,6 +733,7 @@ static int create_archive(int argc, char **argv)
-         g_error("creating vma archive failed");
-     }
-+    vma_writer_destroy(vmaw);
-     return 0;
- }
diff --git a/debian/patches/pve/0050-Fix-backup-for-not-64k-aligned-storages.patch b/debian/patches/pve/0050-Fix-backup-for-not-64k-aligned-storages.patch
deleted file mode 100644 (file)
index c09b709..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Stefan Reiter <s.reiter@proxmox.com>
-Date: Mon, 22 Jun 2020 14:54:02 +0200
-Subject: [PATCH] Fix backup for not 64k-aligned storages
-
-Zero out clusters after the end of the device, this makes restore handle
-it correctly (even if it may try to write those zeros, it won't fail and
-just ignore the out-of-bounds write to disk).
-
-For not even 4k-aligned disks, there is a potential buffer overrun in
-the memcpy (since always 4k are copied), which causes host-memory
-leakage into VMA archives. Fix this by always zeroing the affected area
-in the output-buffer.
-
-Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
-Reported-by: Roland Kammerer <roland.kammerer@linbit.com>
-Suggested-by: Lars Ellenberg <lars.ellenberg@linbit.com>
-Tested-by: Roland Kammerer <roland.kammerer@linbit.com>
----
- vma-writer.c | 23 ++++++++++++++++++++---
- 1 file changed, 20 insertions(+), 3 deletions(-)
-
-diff --git a/vma-writer.c b/vma-writer.c
-index 06cbc02b1e..f5d2c5d23c 100644
---- a/vma-writer.c
-+++ b/vma-writer.c
-@@ -633,17 +633,33 @@ vma_writer_write(VmaWriter *vmaw, uint8_t dev_id, int64_t cluster_num,
-     DPRINTF("VMA WRITE %d %zd\n", dev_id, cluster_num);
-+    uint64_t dev_size = vmaw->stream_info[dev_id].size;
-     uint16_t mask = 0;
-     if (buf) {
-         int i;
-         int bit = 1;
-+        uint64_t byte_offset = cluster_num * VMA_CLUSTER_SIZE;
-         for (i = 0; i < 16; i++) {
-             const unsigned char *vmablock = buf + (i*VMA_BLOCK_SIZE);
--            if (!buffer_is_zero(vmablock, VMA_BLOCK_SIZE)) {
-+
-+            // Note: If the source is not 64k-aligned, we might reach 4k blocks
-+            // after the end of the device. Always mark these as zero in the
-+            // mask, so the restore handles them correctly.
-+            if (byte_offset < dev_size &&
-+                !buffer_is_zero(vmablock, VMA_BLOCK_SIZE))
-+            {
-                 mask |= bit;
-                 memcpy(vmaw->outbuf + vmaw->outbuf_pos, vmablock,
-                        VMA_BLOCK_SIZE);
-+
-+                // prevent memory leakage on unaligned last block
-+                if (byte_offset + VMA_BLOCK_SIZE > dev_size) {
-+                    uint64_t real_data_in_block = dev_size - byte_offset;
-+                    memset(vmaw->outbuf + vmaw->outbuf_pos + real_data_in_block,
-+                           0, VMA_BLOCK_SIZE - real_data_in_block);
-+                }
-+
-                 vmaw->outbuf_pos += VMA_BLOCK_SIZE;
-             } else {
-                 DPRINTF("VMA WRITE %zd ZERO BLOCK %d\n", cluster_num, i);
-@@ -651,6 +667,7 @@ vma_writer_write(VmaWriter *vmaw, uint8_t dev_id, int64_t cluster_num,
-                 *zero_bytes += VMA_BLOCK_SIZE;
-             }
-+            byte_offset += VMA_BLOCK_SIZE;
-             bit = bit << 1;
-         }
-     } else {
-@@ -676,8 +693,8 @@ vma_writer_write(VmaWriter *vmaw, uint8_t dev_id, int64_t cluster_num,
-     if (dev_id != vmaw->vmstate_stream) {
-         uint64_t last = (cluster_num + 1) * VMA_CLUSTER_SIZE;
--        if (last > vmaw->stream_info[dev_id].size) {
--            uint64_t diff = last - vmaw->stream_info[dev_id].size;
-+        if (last > dev_size) {
-+            uint64_t diff = last - dev_size;
-             if (diff >= VMA_CLUSTER_SIZE) {
-                 vma_writer_set_error(vmaw, "vma_writer_write: "
-                                      "read after last cluster");
diff --git a/debian/patches/pve/0051-PVE-Backup-Add-dirty-bitmap-tracking-for-incremental.patch b/debian/patches/pve/0051-PVE-Backup-Add-dirty-bitmap-tracking-for-incremental.patch
deleted file mode 100644 (file)
index 94c13f8..0000000
+++ /dev/null
@@ -1,444 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Stefan Reiter <s.reiter@proxmox.com>
-Date: Mon, 29 Jun 2020 11:06:03 +0200
-Subject: [PATCH] PVE-Backup: Add dirty-bitmap tracking for incremental backups
-
-Uses QEMU's existing MIRROR_SYNC_MODE_BITMAP and a dirty-bitmap on top
-of all backed-up drives. This will only execute the data-write callback
-for any changed chunks, the PBS rust code will reuse chunks from the
-previous index for everything it doesn't receive if reuse_index is true.
-
-On error or cancellation, remove all dirty bitmaps to ensure
-consistency.
-
-Add PBS/incremental specific information to query backup info QMP and
-HMP commands.
-
-Only supported for PBS backups.
-
-Signed-off-by: Stefan Reiter <s.reiter@proxmox.com>
-Signed-off-by: Dietmar Maurer <dietmar@proxmox.com>
-Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
----
- block/monitor/block-hmp-cmds.c |  1 +
- monitor/hmp-cmds.c             | 45 ++++++++++++----
- proxmox-backup-client.c        |  3 +-
- proxmox-backup-client.h        |  1 +
- pve-backup.c                   | 95 ++++++++++++++++++++++++++++++----
- qapi/block-core.json           | 12 ++++-
- 6 files changed, 134 insertions(+), 23 deletions(-)
-
-diff --git a/block/monitor/block-hmp-cmds.c b/block/monitor/block-hmp-cmds.c
-index d485c3ac79..fdc85a5c0e 100644
---- a/block/monitor/block-hmp-cmds.c
-+++ b/block/monitor/block-hmp-cmds.c
-@@ -1038,6 +1038,7 @@ void hmp_backup(Monitor *mon, const QDict *qdict)
-         false, NULL, // PBS fingerprint
-         false, NULL, // PBS backup-id
-         false, 0, // PBS backup-time
-+        false, false, // PBS incremental
-         true, dir ? BACKUP_FORMAT_DIR : BACKUP_FORMAT_VMA,
-         false, NULL, false, NULL, !!devlist,
-         devlist, qdict_haskey(qdict, "speed"), speed, &error);
-diff --git a/monitor/hmp-cmds.c b/monitor/hmp-cmds.c
-index 7fd59b1c22..4f692c15a2 100644
---- a/monitor/hmp-cmds.c
-+++ b/monitor/hmp-cmds.c
-@@ -218,19 +218,42 @@ void hmp_info_backup(Monitor *mon, const QDict *qdict)
-             monitor_printf(mon, "End time: %s", ctime(&info->end_time));
-         }
--        int per = (info->has_total && info->total &&
--            info->has_transferred && info->transferred) ?
--            (info->transferred * 100)/info->total : 0;
--        int zero_per = (info->has_total && info->total &&
--                        info->has_zero_bytes && info->zero_bytes) ?
--            (info->zero_bytes * 100)/info->total : 0;
-         monitor_printf(mon, "Backup file: %s\n", info->backup_file);
-         monitor_printf(mon, "Backup uuid: %s\n", info->uuid);
--        monitor_printf(mon, "Total size: %zd\n", info->total);
--        monitor_printf(mon, "Transferred bytes: %zd (%d%%)\n",
--                       info->transferred, per);
--        monitor_printf(mon, "Zero bytes: %zd (%d%%)\n",
--                       info->zero_bytes, zero_per);
-+
-+        if (!(info->has_total && info->total))  {
-+            // this should not happen normally
-+            monitor_printf(mon, "Total size: %d\n", 0);
-+        } else {
-+            bool incremental = false;
-+            size_t total_or_dirty = info->total;
-+            if (info->has_transferred) {
-+                if (info->has_dirty && info->dirty) {
-+                     if (info->dirty < info->total) {
-+                        total_or_dirty = info->dirty;
-+                        incremental = true;
-+                    }
-+                }
-+            }
-+
-+            int per = (info->transferred * 100)/total_or_dirty;
-+
-+            monitor_printf(mon, "Backup mode: %s\n", incremental ? "incremental" : "full");
-+
-+            int zero_per = (info->has_zero_bytes && info->zero_bytes) ?
-+                (info->zero_bytes * 100)/info->total : 0;
-+            monitor_printf(mon, "Total size: %zd\n", info->total);
-+            monitor_printf(mon, "Transferred bytes: %zd (%d%%)\n",
-+                           info->transferred, per);
-+            monitor_printf(mon, "Zero bytes: %zd (%d%%)\n",
-+                           info->zero_bytes, zero_per);
-+
-+            if (info->has_reused) {
-+                int reused_per = (info->reused * 100)/total_or_dirty;
-+                monitor_printf(mon, "Reused bytes: %zd (%d%%)\n",
-+                               info->reused, reused_per);
-+            }
-+        }
-     }
-     qapi_free_BackupStatus(info);
-diff --git a/proxmox-backup-client.c b/proxmox-backup-client.c
-index b7bc7f2574..0e9c584701 100644
---- a/proxmox-backup-client.c
-+++ b/proxmox-backup-client.c
-@@ -95,6 +95,7 @@ proxmox_backup_co_register_image(
-     ProxmoxBackupHandle *pbs,
-     const char *device_name,
-     uint64_t size,
-+    bool incremental,
-     Error **errp)
- {
-     Coroutine *co = qemu_coroutine_self();
-@@ -104,7 +105,7 @@ proxmox_backup_co_register_image(
-     int pbs_res = -1;
-     proxmox_backup_register_image_async(
--        pbs, device_name, size ,proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
-+        pbs, device_name, size, incremental, proxmox_backup_schedule_wake, &waker, &pbs_res, &pbs_err);
-     qemu_coroutine_yield();
-     if (pbs_res < 0) {
-         if (errp) error_setg(errp, "backup register image failed: %s", pbs_err ? pbs_err : "unknown error");
-diff --git a/proxmox-backup-client.h b/proxmox-backup-client.h
-index b311bf8de8..20fd6b1719 100644
---- a/proxmox-backup-client.h
-+++ b/proxmox-backup-client.h
-@@ -25,6 +25,7 @@ proxmox_backup_co_register_image(
-     ProxmoxBackupHandle *pbs,
-     const char *device_name,
-     uint64_t size,
-+    bool incremental,
-     Error **errp);
-diff --git a/pve-backup.c b/pve-backup.c
-index bb917ee972..3a71270213 100644
---- a/pve-backup.c
-+++ b/pve-backup.c
-@@ -28,6 +28,8 @@
-  *
-  */
-+const char *PBS_BITMAP_NAME = "pbs-incremental-dirty-bitmap";
-+
- static struct PVEBackupState {
-     struct {
-         // Everithing accessed from qmp_backup_query command is protected using lock
-@@ -39,7 +41,9 @@ static struct PVEBackupState {
-         uuid_t uuid;
-         char uuid_str[37];
-         size_t total;
-+        size_t dirty;
-         size_t transferred;
-+        size_t reused;
-         size_t zero_bytes;
-     } stat;
-     int64_t speed;
-@@ -66,6 +70,7 @@ typedef struct PVEBackupDevInfo {
-     uint8_t dev_id;
-     bool completed;
-     char targetfile[PATH_MAX];
-+    BdrvDirtyBitmap *bitmap;
-     BlockDriverState *target;
- } PVEBackupDevInfo;
-@@ -105,11 +110,12 @@ static bool pvebackup_error_or_canceled(void)
-     return error_or_canceled;
- }
--static void pvebackup_add_transfered_bytes(size_t transferred, size_t zero_bytes)
-+static void pvebackup_add_transfered_bytes(size_t transferred, size_t zero_bytes, size_t reused)
- {
-     qemu_mutex_lock(&backup_state.stat.lock);
-     backup_state.stat.zero_bytes += zero_bytes;
-     backup_state.stat.transferred += transferred;
-+    backup_state.stat.reused += reused;
-     qemu_mutex_unlock(&backup_state.stat.lock);
- }
-@@ -148,7 +154,8 @@ pvebackup_co_dump_pbs_cb(
-         pvebackup_propagate_error(local_err);
-         return pbs_res;
-     } else {
--        pvebackup_add_transfered_bytes(size, !buf ? size : 0);
-+        size_t reused = (pbs_res == 0) ? size : 0;
-+        pvebackup_add_transfered_bytes(size, !buf ? size : 0, reused);
-     }
-     return size;
-@@ -208,11 +215,11 @@ pvebackup_co_dump_vma_cb(
-         } else {
-             if (remaining >= VMA_CLUSTER_SIZE) {
-                 assert(ret == VMA_CLUSTER_SIZE);
--                pvebackup_add_transfered_bytes(VMA_CLUSTER_SIZE, zero_bytes);
-+                pvebackup_add_transfered_bytes(VMA_CLUSTER_SIZE, zero_bytes, 0);
-                 remaining -= VMA_CLUSTER_SIZE;
-             } else {
-                 assert(ret == remaining);
--                pvebackup_add_transfered_bytes(remaining, zero_bytes);
-+                pvebackup_add_transfered_bytes(remaining, zero_bytes, 0);
-                 remaining = 0;
-             }
-         }
-@@ -248,6 +255,18 @@ static void coroutine_fn pvebackup_co_cleanup(void *unused)
-             if (local_err != NULL) {
-                 pvebackup_propagate_error(local_err);
-             }
-+        } else {
-+            // on error or cancel we cannot ensure synchronization of dirty
-+            // bitmaps with backup server, so remove all and do full backup next
-+            GList *l = backup_state.di_list;
-+            while (l) {
-+                PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-+                l = g_list_next(l);
-+
-+                if (di->bitmap) {
-+                    bdrv_release_dirty_bitmap(di->bitmap);
-+                }
-+            }
-         }
-         proxmox_backup_disconnect(backup_state.pbs);
-@@ -303,6 +322,12 @@ static void pvebackup_complete_cb(void *opaque, int ret)
-     // remove self from job queue
-     backup_state.di_list = g_list_remove(backup_state.di_list, di);
-+    if (di->bitmap && ret < 0) {
-+        // on error or cancel we cannot ensure synchronization of dirty
-+        // bitmaps with backup server, so remove all and do full backup next
-+        bdrv_release_dirty_bitmap(di->bitmap);
-+    }
-+
-     g_free(di);
-     qemu_mutex_unlock(&backup_state.backup_mutex);
-@@ -470,12 +495,18 @@ static bool create_backup_jobs(void) {
-         assert(di->target != NULL);
-+        MirrorSyncMode sync_mode = MIRROR_SYNC_MODE_FULL;
-+        BitmapSyncMode bitmap_mode = BITMAP_SYNC_MODE_NEVER;
-+        if (di->bitmap) {
-+            sync_mode = MIRROR_SYNC_MODE_BITMAP;
-+            bitmap_mode = BITMAP_SYNC_MODE_ON_SUCCESS;
-+        }
-         AioContext *aio_context = bdrv_get_aio_context(di->bs);
-         aio_context_acquire(aio_context);
-         BlockJob *job = backup_job_create(
--            NULL, di->bs, di->target, backup_state.speed, MIRROR_SYNC_MODE_FULL, NULL,
--            BITMAP_SYNC_MODE_NEVER, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
-+            NULL, di->bs, di->target, backup_state.speed, sync_mode, di->bitmap,
-+            bitmap_mode, false, NULL, BLOCKDEV_ON_ERROR_REPORT, BLOCKDEV_ON_ERROR_REPORT,
-             JOB_DEFAULT, pvebackup_complete_cb, di, 1, NULL, &local_err);
-         aio_context_release(aio_context);
-@@ -526,6 +557,8 @@ typedef struct QmpBackupTask {
-     const char *fingerprint;
-     bool has_fingerprint;
-     int64_t backup_time;
-+    bool has_incremental;
-+    bool incremental;
-     bool has_format;
-     BackupFormat format;
-     bool has_config_file;
-@@ -621,6 +654,7 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-     }
-     size_t total = 0;
-+    size_t dirty = 0;
-     l = di_list;
-     while (l) {
-@@ -658,6 +692,8 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-         int dump_cb_block_size = PROXMOX_BACKUP_DEFAULT_CHUNK_SIZE; // Hardcoded (4M)
-         firewall_name = "fw.conf";
-+        bool incremental = task->has_incremental && task->incremental;
-+
-         char *pbs_err = NULL;
-         pbs = proxmox_backup_new(
-             task->backup_file,
-@@ -677,7 +713,8 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-             goto err;
-         }
--        if (proxmox_backup_co_connect(pbs, task->errp) < 0)
-+        int connect_result = proxmox_backup_co_connect(pbs, task->errp);
-+        if (connect_result < 0)
-             goto err;
-         /* register all devices */
-@@ -688,9 +725,32 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-             const char *devname = bdrv_get_device_name(di->bs);
--            int dev_id = proxmox_backup_co_register_image(pbs, devname, di->size, task->errp);
--            if (dev_id < 0)
-+            BdrvDirtyBitmap *bitmap = bdrv_find_dirty_bitmap(di->bs, PBS_BITMAP_NAME);
-+
-+            bool use_incremental = false;
-+            if (incremental) {
-+                if (bitmap == NULL) {
-+                    bitmap = bdrv_create_dirty_bitmap(di->bs, dump_cb_block_size, PBS_BITMAP_NAME, task->errp);
-+                    if (!bitmap) {
-+                        goto err;
-+                    }
-+                    /* mark entire bitmap as dirty to make full backup first */
-+                    bdrv_set_dirty_bitmap(bitmap, 0, di->size);
-+                    dirty += di->size;
-+                } else {
-+                    use_incremental = true;
-+                    dirty += bdrv_get_dirty_count(bitmap);
-+                }
-+                di->bitmap = bitmap;
-+            } else if (bitmap != NULL) {
-+                dirty += di->size;
-+                bdrv_release_dirty_bitmap(bitmap);
-+            }
-+
-+            int dev_id = proxmox_backup_co_register_image(pbs, devname, di->size, use_incremental, task->errp);
-+            if (dev_id < 0) {
-                 goto err;
-+            }
-             if (!(di->target = bdrv_backup_dump_create(dump_cb_block_size, di->size, pvebackup_co_dump_pbs_cb, di, task->errp))) {
-                 goto err;
-@@ -699,6 +759,8 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-             di->dev_id = dev_id;
-         }
-     } else if (format == BACKUP_FORMAT_VMA) {
-+        dirty = total;
-+
-         vmaw = vma_writer_create(task->backup_file, uuid, &local_err);
-         if (!vmaw) {
-             if (local_err) {
-@@ -726,6 +788,8 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-             }
-         }
-     } else if (format == BACKUP_FORMAT_DIR) {
-+        dirty = total;
-+
-         if (mkdir(task->backup_file, 0640) != 0) {
-             error_setg_errno(task->errp, errno, "can't create directory '%s'\n",
-                              task->backup_file);
-@@ -798,8 +862,10 @@ static void coroutine_fn pvebackup_co_prepare(void *opaque)
-     char *uuid_str = g_strdup(backup_state.stat.uuid_str);
-     backup_state.stat.total = total;
-+    backup_state.stat.dirty = dirty;
-     backup_state.stat.transferred = 0;
-     backup_state.stat.zero_bytes = 0;
-+    backup_state.stat.reused = 0;
-     qemu_mutex_unlock(&backup_state.stat.lock);
-@@ -823,6 +889,10 @@ err:
-         PVEBackupDevInfo *di = (PVEBackupDevInfo *)l->data;
-         l = g_list_next(l);
-+        if (di->bitmap) {
-+            bdrv_release_dirty_bitmap(di->bitmap);
-+        }
-+
-         if (di->target) {
-             bdrv_unref(di->target);
-         }
-@@ -864,6 +934,7 @@ UuidInfo *qmp_backup(
-     bool has_fingerprint, const char *fingerprint,
-     bool has_backup_id, const char *backup_id,
-     bool has_backup_time, int64_t backup_time,
-+    bool has_incremental, bool incremental,
-     bool has_format, BackupFormat format,
-     bool has_config_file, const char *config_file,
-     bool has_firewall_file, const char *firewall_file,
-@@ -882,6 +953,8 @@ UuidInfo *qmp_backup(
-         .backup_id = backup_id,
-         .has_backup_time = has_backup_time,
-         .backup_time = backup_time,
-+        .has_incremental = has_incremental,
-+        .incremental = incremental,
-         .has_format = has_format,
-         .format = format,
-         .has_config_file = has_config_file,
-@@ -950,10 +1023,14 @@ BackupStatus *qmp_query_backup(Error **errp)
-     info->has_total = true;
-     info->total = backup_state.stat.total;
-+    info->has_dirty = true;
-+    info->dirty = backup_state.stat.dirty;
-     info->has_zero_bytes = true;
-     info->zero_bytes = backup_state.stat.zero_bytes;
-     info->has_transferred = true;
-     info->transferred = backup_state.stat.transferred;
-+    info->has_reused = true;
-+    info->reused = backup_state.stat.reused;
-     qemu_mutex_unlock(&backup_state.stat.lock);
-diff --git a/qapi/block-core.json b/qapi/block-core.json
-index 8bdbccb397..8ffff7aaab 100644
---- a/qapi/block-core.json
-+++ b/qapi/block-core.json
-@@ -757,8 +757,13 @@
- #
- # @total: total amount of bytes involved in the backup process
- #
-+# @dirty: with incremental mode, this is the amount of bytes involved
-+#         in the backup process which are marked dirty.
-+#
- # @transferred: amount of bytes already backed up.
- #
-+# @reused: amount of bytes reused due to deduplication.
-+#
- # @zero-bytes: amount of 'zero' bytes detected.
- #
- # @start-time: time (epoch) when backup job started.
-@@ -771,8 +776,8 @@
- #
- ##
- { 'struct': 'BackupStatus',
--  'data': {'*status': 'str', '*errmsg': 'str', '*total': 'int',
--           '*transferred': 'int', '*zero-bytes': 'int',
-+  'data': {'*status': 'str', '*errmsg': 'str', '*total': 'int', '*dirty': 'int',
-+           '*transferred': 'int', '*zero-bytes': 'int', '*reused': 'int',
-            '*start-time': 'int', '*end-time': 'int',
-            '*backup-file': 'str', '*uuid': 'str' } }
-@@ -815,6 +820,8 @@
- #
- # @backup-time: backup timestamp (Unix epoch, required for format 'pbs')
- #
-+# @incremental: sync incremental changes since last job (optional for format 'pbs')
-+#
- # Returns: the uuid of the backup job
- #
- ##
-@@ -825,6 +832,7 @@
-                                     '*fingerprint': 'str',
-                                     '*backup-id': 'str',
-                                     '*backup-time': 'int',
-+                                    '*incremental': 'bool',
-                                     '*format': 'BackupFormat',
-                                     '*config-file': 'str',
-                                     '*firewall-file': 'str',
index 5d6a5d6cf0cb3ad9c038e73522cf25bb6a27e746..d1874a9d94955d513cd1b29f44de65c4f52e6e70 100644 (file)
@@ -16,37 +16,24 @@ pve/0014-PVE-virtio-balloon-improve-query-balloon.patch
 pve/0015-PVE-qapi-modify-query-machines.patch
 pve/0016-PVE-qapi-modify-spice-query.patch
 pve/0017-PVE-internal-snapshot-async.patch
-pve/0018-PVE-block-add-the-zeroinit-block-driver-filter.patch
-pve/0019-PVE-Add-dummy-id-command-line-parameter.patch
-pve/0020-PVE-Config-Revert-target-i386-disable-LINT0-after-re.patch
-pve/0021-PVE-Up-Config-file-posix-make-locking-optiono-on-cre.patch
-pve/0022-PVE-savevm-async-kick-AIO-wait-on-block-state-write.patch
-pve/0023-PVE-move-snapshot-cleanup-into-bottom-half.patch
-pve/0024-PVE-monitor-disable-oob-capability.patch
-pve/0025-PVE-Compat-4.0-used-balloon-qemu-4-0-config-size-fal.patch
-pve/0026-PVE-Allow-version-code-in-machine-type.patch
-pve/0027-PVE-Backup-modify-job-api.patch
-pve/0028-PVE-Backup-add-vma-backup-format-code.patch
-pve/0029-PVE-Backup-add-backup-dump-block-driver.patch
-pve/0030-PVE-Backup-proxmox-backup-patches-for-qemu.patch
-pve/0031-PVE-Backup-aquire-aio_context-before-calling-backup_.patch
-pve/0032-PVE-Backup-pbs-restore-new-command-to-restore-from-p.patch
-pve/0033-PVE-Backup-avoid-coroutines-to-fix-AIO-freeze-cleanu.patch
-pve/0034-drive-mirror-add-support-for-sync-bitmap-mode-never.patch
-pve/0035-drive-mirror-add-support-for-conditional-and-always-.patch
-pve/0036-mirror-add-check-for-bitmap-mode-without-bitmap.patch
-pve/0037-mirror-switch-to-bdrv_dirty_bitmap_merge_internal.patch
-pve/0038-iotests-add-test-for-bitmap-mirror.patch
-pve/0039-mirror-move-some-checks-to-qmp.patch
-pve/0040-PVE-savevm-async-set-up-migration-state.patch
-pve/0041-PVE-Backup-avoid-use-QemuRecMutex-inside-coroutines.patch
-pve/0042-PVE-Backup-use-QemuMutex-instead-of-QemuRecMutex.patch
-pve/0043-move-savevm-async-back-into-a-coroutine.patch
-pve/0044-add-optional-buffer-size-to-QEMUFile.patch
-pve/0045-savevm-async-move-more-code-to-cleanup-and-rename-to.patch
-pve/0046-util-async-Add-aio_co_reschedule_self.patch
-pve/0047-savevm-async-flush-IOThread-drives-async-before-ente.patch
-pve/0048-savevm-async-add-debug-timing-prints.patch
-pve/0049-Add-some-qemu_vfree-statements-to-prevent-memory-lea.patch
-pve/0050-Fix-backup-for-not-64k-aligned-storages.patch
-pve/0051-PVE-Backup-Add-dirty-bitmap-tracking-for-incremental.patch
+pve/0018-add-optional-buffer-size-to-QEMUFile.patch
+pve/0019-PVE-block-add-the-zeroinit-block-driver-filter.patch
+pve/0020-PVE-Add-dummy-id-command-line-parameter.patch
+pve/0021-PVE-Config-Revert-target-i386-disable-LINT0-after-re.patch
+pve/0022-PVE-Up-Config-file-posix-make-locking-optiono-on-cre.patch
+pve/0023-PVE-monitor-disable-oob-capability.patch
+pve/0024-PVE-Compat-4.0-used-balloon-qemu-4-0-config-size-fal.patch
+pve/0025-PVE-Allow-version-code-in-machine-type.patch
+pve/0026-PVE-Backup-modify-job-api.patch
+pve/0027-PVE-Backup-add-vma-backup-format-code.patch
+pve/0028-PVE-Backup-add-backup-dump-block-driver.patch
+pve/0029-PVE-Backup-proxmox-backup-patches-for-qemu.patch
+pve/0030-PVE-Backup-pbs-restore-new-command-to-restore-from-p.patch
+pve/0031-PVE-Backup-avoid-coroutines-to-fix-AIO-freeze-cleanu.patch
+pve/0032-drive-mirror-add-support-for-sync-bitmap-mode-never.patch
+pve/0033-drive-mirror-add-support-for-conditional-and-always-.patch
+pve/0034-mirror-add-check-for-bitmap-mode-without-bitmap.patch
+pve/0035-mirror-switch-to-bdrv_dirty_bitmap_merge_internal.patch
+pve/0036-iotests-add-test-for-bitmap-mirror.patch
+pve/0037-mirror-move-some-checks-to-qmp.patch
+pve/0038-PVE-Backup-Add-dirty-bitmap-tracking-for-incremental.patch