586cba
From b453cf6be8429f4438d51eb24fcf49e7d9f14db6 Mon Sep 17 00:00:00 2001
586cba
From: Hanna Reitz <hreitz@redhat.com>
586cba
Date: Tue, 5 Apr 2022 15:46:50 +0200
586cba
Subject: [PATCH 04/16] qcow2: Improve refcount structure rebuilding
586cba
586cba
RH-Author: Hanna Reitz <hreitz@redhat.com>
586cba
RH-MergeRequest: 96: qcow2: Improve refcount structure rebuilding
586cba
RH-Commit: [1/4] a3606b7abcaebb4930b566e95b1090aead62dfae (hreitz/qemu-kvm-c-9-s)
586cba
RH-Bugzilla: 2072379
586cba
RH-Acked-by: Miroslav Rezanina <mrezanin@redhat.com>
586cba
RH-Acked-by: Eric Blake <eblake@redhat.com>
586cba
RH-Acked-by: Stefan Hajnoczi <stefanha@redhat.com>
586cba
586cba
When rebuilding the refcount structures (when qemu-img check -r found
586cba
errors with refcount = 0, but reference count > 0), the new refcount
586cba
table defaults to being put at the image file end[1].  There is no good
586cba
reason for that except that it means we will not have to rewrite any
586cba
refblocks we already wrote to disk.
586cba
586cba
Changing the code to rewrite those refblocks is not too difficult,
586cba
though, so let us do that.  That is beneficial for images on block
586cba
devices, where we cannot really write beyond the end of the image file.
586cba
586cba
Use this opportunity to add extensive comments to the code, and refactor
586cba
it a bit, getting rid of the backwards-jumping goto.
586cba
586cba
[1] Unless there is something allocated in the area pointed to by the
586cba
    last refblock, so we have to write that refblock.  In that case, we
586cba
    try to put the reftable in there.
586cba
586cba
Buglink: https://bugzilla.redhat.com/show_bug.cgi?id=1519071
586cba
Closes: https://gitlab.com/qemu-project/qemu/-/issues/941
586cba
Reviewed-by: Eric Blake <eblake@redhat.com>
586cba
Signed-off-by: Hanna Reitz <hreitz@redhat.com>
586cba
Message-Id: <20220405134652.19278-2-hreitz@redhat.com>
586cba
(cherry picked from commit a8c07ec287554dcefd33733f0e5888a281ddc95e)
586cba
Signed-off-by: Hanna Reitz <hreitz@redhat.com>
586cba
---
586cba
 block/qcow2-refcount.c | 332 +++++++++++++++++++++++++++++------------
586cba
 1 file changed, 235 insertions(+), 97 deletions(-)
586cba
586cba
diff --git a/block/qcow2-refcount.c b/block/qcow2-refcount.c
586cba
index b91499410c..c5669eaa51 100644
586cba
--- a/block/qcow2-refcount.c
586cba
+++ b/block/qcow2-refcount.c
586cba
@@ -2438,111 +2438,140 @@ static int64_t alloc_clusters_imrt(BlockDriverState *bs,
586cba
 }
586cba
 
586cba
 /*
586cba
- * Creates a new refcount structure based solely on the in-memory information
586cba
- * given through *refcount_table. All necessary allocations will be reflected
586cba
- * in that array.
586cba
+ * Helper function for rebuild_refcount_structure().
586cba
  *
586cba
- * On success, the old refcount structure is leaked (it will be covered by the
586cba
- * new refcount structure).
586cba
+ * Scan the range of clusters [first_cluster, end_cluster) for allocated
586cba
+ * clusters and write all corresponding refblocks to disk.  The refblock
586cba
+ * and allocation data is taken from the in-memory refcount table
586cba
+ * *refcount_table[] (of size *nb_clusters), which is basically one big
586cba
+ * (unlimited size) refblock for the whole image.
586cba
+ *
586cba
+ * For these refblocks, clusters are allocated using said in-memory
586cba
+ * refcount table.  Care is taken that these allocations are reflected
586cba
+ * in the refblocks written to disk.
586cba
+ *
586cba
+ * The refblocks' offsets are written into a reftable, which is
586cba
+ * *on_disk_reftable_ptr[] (of size *on_disk_reftable_entries_ptr).  If
586cba
+ * that reftable is of insufficient size, it will be resized to fit.
586cba
+ * This reftable is not written to disk.
586cba
+ *
586cba
+ * (If *on_disk_reftable_ptr is not NULL, the entries within are assumed
586cba
+ * to point to existing valid refblocks that do not need to be allocated
586cba
+ * again.)
586cba
+ *
586cba
+ * Return whether the on-disk reftable array was resized (true/false),
586cba
+ * or -errno on error.
586cba
  */
586cba
-static int rebuild_refcount_structure(BlockDriverState *bs,
586cba
-                                      BdrvCheckResult *res,
586cba
-                                      void **refcount_table,
586cba
-                                      int64_t *nb_clusters)
586cba
+static int rebuild_refcounts_write_refblocks(
586cba
+        BlockDriverState *bs, void **refcount_table, int64_t *nb_clusters,
586cba
+        int64_t first_cluster, int64_t end_cluster,
586cba
+        uint64_t **on_disk_reftable_ptr, uint32_t *on_disk_reftable_entries_ptr
586cba
+    )
586cba
 {
586cba
     BDRVQcow2State *s = bs->opaque;
586cba
-    int64_t first_free_cluster = 0, reftable_offset = -1, cluster = 0;
586cba
+    int64_t cluster;
586cba
     int64_t refblock_offset, refblock_start, refblock_index;
586cba
-    uint32_t reftable_size = 0;
586cba
-    uint64_t *on_disk_reftable = NULL;
586cba
+    int64_t first_free_cluster = 0;
586cba
+    uint64_t *on_disk_reftable = *on_disk_reftable_ptr;
586cba
+    uint32_t on_disk_reftable_entries = *on_disk_reftable_entries_ptr;
586cba
     void *on_disk_refblock;
586cba
-    int ret = 0;
586cba
-    struct {
586cba
-        uint64_t reftable_offset;
586cba
-        uint32_t reftable_clusters;
586cba
-    } QEMU_PACKED reftable_offset_and_clusters;
586cba
-
586cba
-    qcow2_cache_empty(bs, s->refcount_block_cache);
586cba
+    bool reftable_grown = false;
586cba
+    int ret;
586cba
 
586cba
-write_refblocks:
586cba
-    for (; cluster < *nb_clusters; cluster++) {
586cba
+    for (cluster = first_cluster; cluster < end_cluster; cluster++) {
586cba
+        /* Check all clusters to find refblocks that contain non-zero entries */
586cba
         if (!s->get_refcount(*refcount_table, cluster)) {
586cba
             continue;
586cba
         }
586cba
 
586cba
+        /*
586cba
+         * This cluster is allocated, so we need to create a refblock
586cba
+         * for it.  The data we will write to disk is just the
586cba
+         * respective slice from *refcount_table, so it will contain
586cba
+         * accurate refcounts for all clusters belonging to this
586cba
+         * refblock.  After we have written it, we will therefore skip
586cba
+         * all remaining clusters in this refblock.
586cba
+         */
586cba
+
586cba
         refblock_index = cluster >> s->refcount_block_bits;
586cba
         refblock_start = refblock_index << s->refcount_block_bits;
586cba
 
586cba
-        /* Don't allocate a cluster in a refblock already written to disk */
586cba
-        if (first_free_cluster < refblock_start) {
586cba
-            first_free_cluster = refblock_start;
586cba
-        }
586cba
-        refblock_offset = alloc_clusters_imrt(bs, 1, refcount_table,
586cba
-                                              nb_clusters, &first_free_cluster);
586cba
-        if (refblock_offset < 0) {
586cba
-            fprintf(stderr, "ERROR allocating refblock: %s\n",
586cba
-                    strerror(-refblock_offset));
586cba
-            res->check_errors++;
586cba
-            ret = refblock_offset;
586cba
-            goto fail;
586cba
-        }
586cba
+        if (on_disk_reftable_entries > refblock_index &&
586cba
+            on_disk_reftable[refblock_index])
586cba
+        {
586cba
+            /*
586cba
+             * We can get here after a `goto write_refblocks`: We have a
586cba
+             * reftable from a previous run, and the refblock is already
586cba
+             * allocated.  No need to allocate it again.
586cba
+             */
586cba
+            refblock_offset = on_disk_reftable[refblock_index];
586cba
+        } else {
586cba
+            int64_t refblock_cluster_index;
586cba
 
586cba
-        if (reftable_size <= refblock_index) {
586cba
-            uint32_t old_reftable_size = reftable_size;
586cba
-            uint64_t *new_on_disk_reftable;
586cba
+            /* Don't allocate a cluster in a refblock already written to disk */
586cba
+            if (first_free_cluster < refblock_start) {
586cba
+                first_free_cluster = refblock_start;
586cba
+            }
586cba
+            refblock_offset = alloc_clusters_imrt(bs, 1, refcount_table,
586cba
+                                                  nb_clusters,
586cba
+                                                  &first_free_cluster);
586cba
+            if (refblock_offset < 0) {
586cba
+                fprintf(stderr, "ERROR allocating refblock: %s\n",
586cba
+                        strerror(-refblock_offset));
586cba
+                return refblock_offset;
586cba
+            }
586cba
 
586cba
-            reftable_size = ROUND_UP((refblock_index + 1) * REFTABLE_ENTRY_SIZE,
586cba
-                                     s->cluster_size) / REFTABLE_ENTRY_SIZE;
586cba
-            new_on_disk_reftable = g_try_realloc(on_disk_reftable,
586cba
-                                                 reftable_size *
586cba
-                                                 REFTABLE_ENTRY_SIZE);
586cba
-            if (!new_on_disk_reftable) {
586cba
-                res->check_errors++;
586cba
-                ret = -ENOMEM;
586cba
-                goto fail;
586cba
+            refblock_cluster_index = refblock_offset / s->cluster_size;
586cba
+            if (refblock_cluster_index >= end_cluster) {
586cba
+                /*
586cba
+                 * We must write the refblock that holds this refblock's
586cba
+                 * refcount
586cba
+                 */
586cba
+                end_cluster = refblock_cluster_index + 1;
586cba
             }
586cba
-            on_disk_reftable = new_on_disk_reftable;
586cba
 
586cba
-            memset(on_disk_reftable + old_reftable_size, 0,
586cba
-                   (reftable_size - old_reftable_size) * REFTABLE_ENTRY_SIZE);
586cba
+            if (on_disk_reftable_entries <= refblock_index) {
586cba
+                on_disk_reftable_entries =
586cba
+                    ROUND_UP((refblock_index + 1) * REFTABLE_ENTRY_SIZE,
586cba
+                             s->cluster_size) / REFTABLE_ENTRY_SIZE;
586cba
+                on_disk_reftable =
586cba
+                    g_try_realloc(on_disk_reftable,
586cba
+                                  on_disk_reftable_entries *
586cba
+                                  REFTABLE_ENTRY_SIZE);
586cba
+                if (!on_disk_reftable) {
586cba
+                    return -ENOMEM;
586cba
+                }
586cba
 
586cba
-            /* The offset we have for the reftable is now no longer valid;
586cba
-             * this will leak that range, but we can easily fix that by running
586cba
-             * a leak-fixing check after this rebuild operation */
586cba
-            reftable_offset = -1;
586cba
-        } else {
586cba
-            assert(on_disk_reftable);
586cba
-        }
586cba
-        on_disk_reftable[refblock_index] = refblock_offset;
586cba
+                memset(on_disk_reftable + *on_disk_reftable_entries_ptr, 0,
586cba
+                       (on_disk_reftable_entries -
586cba
+                        *on_disk_reftable_entries_ptr) *
586cba
+                       REFTABLE_ENTRY_SIZE);
586cba
 
586cba
-        /* If this is apparently the last refblock (for now), try to squeeze the
586cba
-         * reftable in */
586cba
-        if (refblock_index == (*nb_clusters - 1) >> s->refcount_block_bits &&
586cba
-            reftable_offset < 0)
586cba
-        {
586cba
-            uint64_t reftable_clusters = size_to_clusters(s, reftable_size *
586cba
-                                                          REFTABLE_ENTRY_SIZE);
586cba
-            reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,
586cba
-                                                  refcount_table, nb_clusters,
586cba
-                                                  &first_free_cluster);
586cba
-            if (reftable_offset < 0) {
586cba
-                fprintf(stderr, "ERROR allocating reftable: %s\n",
586cba
-                        strerror(-reftable_offset));
586cba
-                res->check_errors++;
586cba
-                ret = reftable_offset;
586cba
-                goto fail;
586cba
+                *on_disk_reftable_ptr = on_disk_reftable;
586cba
+                *on_disk_reftable_entries_ptr = on_disk_reftable_entries;
586cba
+
586cba
+                reftable_grown = true;
586cba
+            } else {
586cba
+                assert(on_disk_reftable);
586cba
             }
586cba
+            on_disk_reftable[refblock_index] = refblock_offset;
586cba
         }
586cba
 
586cba
+        /* Refblock is allocated, write it to disk */
586cba
+
586cba
         ret = qcow2_pre_write_overlap_check(bs, 0, refblock_offset,
586cba
                                             s->cluster_size, false);
586cba
         if (ret < 0) {
586cba
             fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));
586cba
-            goto fail;
586cba
+            return ret;
586cba
         }
586cba
 
586cba
-        /* The size of *refcount_table is always cluster-aligned, therefore the
586cba
-         * write operation will not overflow */
586cba
+        /*
586cba
+         * The refblock is simply a slice of *refcount_table.
586cba
+         * Note that the size of *refcount_table is always aligned to
586cba
+         * whole clusters, so the write operation will not result in
586cba
+         * out-of-bounds accesses.
586cba
+         */
586cba
         on_disk_refblock = (void *)((char *) *refcount_table +
586cba
                                     refblock_index * s->cluster_size);
586cba
 
586cba
@@ -2550,23 +2579,99 @@ write_refblocks:
586cba
                           s->cluster_size);
586cba
         if (ret < 0) {
586cba
             fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));
586cba
-            goto fail;
586cba
+            return ret;
586cba
         }
586cba
 
586cba
-        /* Go to the end of this refblock */
586cba
+        /* This refblock is done, skip to its end */
586cba
         cluster = refblock_start + s->refcount_block_size - 1;
586cba
     }
586cba
 
586cba
-    if (reftable_offset < 0) {
586cba
-        uint64_t post_refblock_start, reftable_clusters;
586cba
+    return reftable_grown;
586cba
+}
586cba
+
586cba
+/*
586cba
+ * Creates a new refcount structure based solely on the in-memory information
586cba
+ * given through *refcount_table (this in-memory information is basically just
586cba
+ * the concatenation of all refblocks).  All necessary allocations will be
586cba
+ * reflected in that array.
586cba
+ *
586cba
+ * On success, the old refcount structure is leaked (it will be covered by the
586cba
+ * new refcount structure).
586cba
+ */
586cba
+static int rebuild_refcount_structure(BlockDriverState *bs,
586cba
+                                      BdrvCheckResult *res,
586cba
+                                      void **refcount_table,
586cba
+                                      int64_t *nb_clusters)
586cba
+{
586cba
+    BDRVQcow2State *s = bs->opaque;
586cba
+    int64_t reftable_offset = -1;
586cba
+    int64_t reftable_length = 0;
586cba
+    int64_t reftable_clusters;
586cba
+    int64_t refblock_index;
586cba
+    uint32_t on_disk_reftable_entries = 0;
586cba
+    uint64_t *on_disk_reftable = NULL;
586cba
+    int ret = 0;
586cba
+    int reftable_size_changed = 0;
586cba
+    struct {
586cba
+        uint64_t reftable_offset;
586cba
+        uint32_t reftable_clusters;
586cba
+    } QEMU_PACKED reftable_offset_and_clusters;
586cba
+
586cba
+    qcow2_cache_empty(bs, s->refcount_block_cache);
586cba
+
586cba
+    /*
586cba
+     * For each refblock containing entries, we try to allocate a
586cba
+     * cluster (in the in-memory refcount table) and write its offset
586cba
+     * into on_disk_reftable[].  We then write the whole refblock to
586cba
+     * disk (as a slice of the in-memory refcount table).
586cba
+     * This is done by rebuild_refcounts_write_refblocks().
586cba
+     *
586cba
+     * Once we have scanned all clusters, we try to find space for the
586cba
+     * reftable.  This will dirty the in-memory refcount table (i.e.
586cba
+     * make it differ from the refblocks we have already written), so we
586cba
+     * need to run rebuild_refcounts_write_refblocks() again for the
586cba
+     * range of clusters where the reftable has been allocated.
586cba
+     *
586cba
+     * This second run might make the reftable grow again, in which case
586cba
+     * we will need to allocate another space for it, which is why we
586cba
+     * repeat all this until the reftable stops growing.
586cba
+     *
586cba
+     * (This loop will terminate, because with every cluster the
586cba
+     * reftable grows, it can accomodate a multitude of more refcounts,
586cba
+     * so that at some point this must be able to cover the reftable
586cba
+     * and all refblocks describing it.)
586cba
+     *
586cba
+     * We then convert the reftable to big-endian and write it to disk.
586cba
+     *
586cba
+     * Note that we never free any reftable allocations.  Doing so would
586cba
+     * needlessly complicate the algorithm: The eventual second check
586cba
+     * run we do will clean up all leaks we have caused.
586cba
+     */
586cba
+
586cba
+    reftable_size_changed =
586cba
+        rebuild_refcounts_write_refblocks(bs, refcount_table, nb_clusters,
586cba
+                                          0, *nb_clusters,
586cba
+                                          &on_disk_reftable,
586cba
+                                          &on_disk_reftable_entries);
586cba
+    if (reftable_size_changed < 0) {
586cba
+        res->check_errors++;
586cba
+        ret = reftable_size_changed;
586cba
+        goto fail;
586cba
+    }
586cba
+
586cba
+    /*
586cba
+     * There was no reftable before, so rebuild_refcounts_write_refblocks()
586cba
+     * must have increased its size (from 0 to something).
586cba
+     */
586cba
+    assert(reftable_size_changed);
586cba
+
586cba
+    do {
586cba
+        int64_t reftable_start_cluster, reftable_end_cluster;
586cba
+        int64_t first_free_cluster = 0;
586cba
+
586cba
+        reftable_length = on_disk_reftable_entries * REFTABLE_ENTRY_SIZE;
586cba
+        reftable_clusters = size_to_clusters(s, reftable_length);
586cba
 
586cba
-        post_refblock_start = ROUND_UP(*nb_clusters, s->refcount_block_size);
586cba
-        reftable_clusters =
586cba
-            size_to_clusters(s, reftable_size * REFTABLE_ENTRY_SIZE);
586cba
-        /* Not pretty but simple */
586cba
-        if (first_free_cluster < post_refblock_start) {
586cba
-            first_free_cluster = post_refblock_start;
586cba
-        }
586cba
         reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,
586cba
                                               refcount_table, nb_clusters,
586cba
                                               &first_free_cluster);
586cba
@@ -2578,24 +2683,55 @@ write_refblocks:
586cba
             goto fail;
586cba
         }
586cba
 
586cba
-        goto write_refblocks;
586cba
-    }
586cba
+        /*
586cba
+         * We need to update the affected refblocks, so re-run the
586cba
+         * write_refblocks loop for the reftable's range of clusters.
586cba
+         */
586cba
+        assert(offset_into_cluster(s, reftable_offset) == 0);
586cba
+        reftable_start_cluster = reftable_offset / s->cluster_size;
586cba
+        reftable_end_cluster = reftable_start_cluster + reftable_clusters;
586cba
+        reftable_size_changed =
586cba
+            rebuild_refcounts_write_refblocks(bs, refcount_table, nb_clusters,
586cba
+                                              reftable_start_cluster,
586cba
+                                              reftable_end_cluster,
586cba
+                                              &on_disk_reftable,
586cba
+                                              &on_disk_reftable_entries);
586cba
+        if (reftable_size_changed < 0) {
586cba
+            res->check_errors++;
586cba
+            ret = reftable_size_changed;
586cba
+            goto fail;
586cba
+        }
586cba
+
586cba
+        /*
586cba
+         * If the reftable size has changed, we will need to find a new
586cba
+         * allocation, repeating the loop.
586cba
+         */
586cba
+    } while (reftable_size_changed);
586cba
 
586cba
-    for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {
586cba
+    /* The above loop must have run at least once */
586cba
+    assert(reftable_offset >= 0);
586cba
+
586cba
+    /*
586cba
+     * All allocations are done, all refblocks are written, convert the
586cba
+     * reftable to big-endian and write it to disk.
586cba
+     */
586cba
+
586cba
+    for (refblock_index = 0; refblock_index < on_disk_reftable_entries;
586cba
+         refblock_index++)
586cba
+    {
586cba
         cpu_to_be64s(&on_disk_reftable[refblock_index]);
586cba
     }
586cba
 
586cba
-    ret = qcow2_pre_write_overlap_check(bs, 0, reftable_offset,
586cba
-                                        reftable_size * REFTABLE_ENTRY_SIZE,
586cba
+    ret = qcow2_pre_write_overlap_check(bs, 0, reftable_offset, reftable_length,
586cba
                                         false);
586cba
     if (ret < 0) {
586cba
         fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));
586cba
         goto fail;
586cba
     }
586cba
 
586cba
-    assert(reftable_size < INT_MAX / REFTABLE_ENTRY_SIZE);
586cba
+    assert(reftable_length < INT_MAX);
586cba
     ret = bdrv_pwrite(bs->file, reftable_offset, on_disk_reftable,
586cba
-                      reftable_size * REFTABLE_ENTRY_SIZE);
586cba
+                      reftable_length);
586cba
     if (ret < 0) {
586cba
         fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));
586cba
         goto fail;
586cba
@@ -2604,7 +2740,7 @@ write_refblocks:
586cba
     /* Enter new reftable into the image header */
586cba
     reftable_offset_and_clusters.reftable_offset = cpu_to_be64(reftable_offset);
586cba
     reftable_offset_and_clusters.reftable_clusters =
586cba
-        cpu_to_be32(size_to_clusters(s, reftable_size * REFTABLE_ENTRY_SIZE));
586cba
+        cpu_to_be32(reftable_clusters);
586cba
     ret = bdrv_pwrite_sync(bs->file,
586cba
                            offsetof(QCowHeader, refcount_table_offset),
586cba
                            &reftable_offset_and_clusters,
586cba
@@ -2614,12 +2750,14 @@ write_refblocks:
586cba
         goto fail;
586cba
     }
586cba
 
586cba
-    for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {
586cba
+    for (refblock_index = 0; refblock_index < on_disk_reftable_entries;
586cba
+         refblock_index++)
586cba
+    {
586cba
         be64_to_cpus(&on_disk_reftable[refblock_index]);
586cba
     }
586cba
     s->refcount_table = on_disk_reftable;
586cba
     s->refcount_table_offset = reftable_offset;
586cba
-    s->refcount_table_size = reftable_size;
586cba
+    s->refcount_table_size = on_disk_reftable_entries;
586cba
     update_max_refcount_table_index(s);
586cba
 
586cba
     return 0;
586cba
-- 
586cba
2.31.1
586cba