From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Fabian Ebner <f.ebner@proxmox.com>
Date: Wed, 22 Jun 2022 10:45:11 +0200
Subject: [PATCH] vma: create: support 64KiB-unaligned input images

which fixes backing up templates with such disks in PVE, for example
efitype=4m EFI disks on a file-based storage (size = 540672).

If there is not enough left to read, blk_co_preadv will return -EIO,
so limit the size in the last iteration.

For writing, an unaligned end is already handled correctly.

The call to memset is not strictly necessary, because writing also
checks that it doesn't write data beyond the end of the image. But
there are two reasons to do it:
1. It's cleaner that way.
2. It allows detecting when the final piece is all zeroes, which might
   not happen if the buffer still contains data from the previous
   iteration.

Signed-off-by: Fabian Ebner <f.ebner@proxmox.com>
---
 vma.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/vma.c b/vma.c
index e6e9ffc7fe..304f02bc84 100644
--- a/vma.c
+++ b/vma.c
@@ -548,7 +548,7 @@ static void coroutine_fn backup_run(void *opaque)
     struct iovec iov;
     QEMUIOVector qiov;
 
-    int64_t start, end;
+    int64_t start, end, readlen;
     int ret = 0;
 
     unsigned char *buf = blk_blockalign(job->target, VMA_CLUSTER_SIZE);
@@ -562,8 +562,16 @@ static void coroutine_fn backup_run(void *opaque)
         iov.iov_len = VMA_CLUSTER_SIZE;
         qemu_iovec_init_external(&qiov, &iov, 1);
 
+        if (start + 1 == end) {
+            memset(buf, 0, VMA_CLUSTER_SIZE);
+            readlen = job->len - start * VMA_CLUSTER_SIZE;
+            assert(readlen > 0 && readlen <= VMA_CLUSTER_SIZE);
+        } else {
+            readlen = VMA_CLUSTER_SIZE;
+        }
+
         ret = blk_co_preadv(job->target, start * VMA_CLUSTER_SIZE,
-                            VMA_CLUSTER_SIZE, &qiov, 0);
+                            readlen, &qiov, 0);
         if (ret < 0) {
             vma_writer_set_error(job->vmaw, "read error", -1);
             goto out;
