Skip to contentSkip to conversation

qcow2: Add new overlap check functions

PATCH Superseded Max Reitz 2 participants 22 messages May 4, 2015 – May 6, 2015 Block layer

v4 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Max Reitz

author
#0 lore raw

v4 cover qcow2: Add new overlap check functions

This is a continuation of previous versions of this series. v2's cover letter was the most elaborate, which you can find here (includes benchmarks):
http://lists.nongnu.org/archive/html/qemu-devel/2014-11/msg03430.html

See patch 1 for an explanation of why this series exists and what it does. Patch 1 is basically the core of this series, the rest just employs the functions introduced there.

The new thing about v4 is that there now is a way to limit the total combined size of all data structures used for the new overlap prevention algorithm. Bad news: The limit is disabled by default. This is mainly because for image creation, it is pretty hard to find a sane default (it depends on the desired image size; but the image is not created with that size, but rather with size 0 and then truncated; inferring the default from the image size seems to make sense, but we cannot do this for images that are going to be truncated).

RFC: An alternative would be to infer the limit like so:
MAX(1M, guest_image_size / 1M). It seems sane to me and I guess it should work even for images with very, very large guest sizes. But I think it will break if you're trying to preallocate like a 1 PB image (which is not really a concern right now, but let's see about it in ten years)...
On the other hand, the worst that happens is that the event is generated and the overlap checks won't be performed for some parts of the image during its creation. Doesn't sound too bad to me. What do you think, dears reviewers?

In a later patch, we may want to change the meaning of the "constant" overlap checking option to mean the same as "cached", which is everything except for inactive L2 tables. This series does make checking for overlaps with inactive L2 tables at runtime just as cheap as everything else (constant time plus caching), but using these checks means qemu has to read all the snapshot L1 tables when opening a qcow2 file. This does not take long, of course, but it does result in a bit of overhead so I did not want to enable it by default.

v4:
- Patch 1:
- Use the length of bs->file instead of bs itself as a basis on how many windows should be allocated initially
- If the fragment list would take up more memory than the bitmap (which is conceivable, considering that every cluster in the bitmap/bytemap uses exactly one byte, whereas every cluster may use up to one whole entry in the fragment list (which takes up four bytes)), do not drop the bitmap on cache eviction, but rather just abort the generation of the fragment list
- The cache_size parameter should be divided by WINDOW_SIZE only instead of WINDOW_SIZE + sizeof(*s->metadata_list->cached_windows); the user is more likely to specify multiples of WINDOW_SIZE, so we should take that into account (the sizeof(...) part is really negligible, and also, if the user really wants to limit the memory usage, there are now four new patches in this series to do that)
- Just drop the bitmap when the metadata list is destroyed; do not use destroy_window_bitmap() to do so, because this will (unneccessarily) generate a fragment list (which is going to be dropped, too, anyway)
- Patch 13: Added; adds a new QMP event to be used by patch 14
- Patch 14: Added; adds a control mechanism to limit the amount of memory used for the overlap structures (and issues the event from patch 13 if that limit is hit)
- Patch 15: Added; adds runtime options to qcow2 to control the cache size and the total memory limit for the overlap checking
- Patch 16: Added; exposes these options via QMP
- Patch 17: Added; some tests for these new options

git-backport-diff against v3:

Key:
[----] : patches are identical
[####] : number of functional differences between upstream/downstream patch [down] : patch is downstream-only
The flags [FC] indicate (F)unctional and (C)ontextual differences, respectively

001/17:[0071] [FC] 'qcow2: Add new overlap check functions' 002/17:[----] [--] 'qcow2: Pull up overlap check option evaluation' 003/17:[----] [-C] 'qcow2: Create metadata list' 004/17:[----] [-C] 'qcow2/overlaps: Protect image header' 005/17:[----] [--] 'qcow2/overlaps: Protect refcount table' 006/17:[----] [-C] 'qcow2/overlaps: Protect refcount blocks' 007/17:[----] [--] 'qcow2/overlaps: Protect active L1 table' 008/17:[----] [-C] 'qcow2/overlaps: Protect active L2 tables' 009/17:[----] [-C] 'qcow2/overlaps: Protect snapshot table' 010/17:[----] [--] 'qcow2/overlaps: Protect inactive L1 tables' 011/17:[----] [-C] 'qcow2/overlaps: Protect inactive L2 tables' 012/17:[----] [--] 'qcow2: Use new metadata overlap check function' 013/17:[down] 'qcow2/overlaps: Add "memory limit reached" event' 014/17:[down] 'qcow2/overlaps: Add memory usage limit' 015/17:[down] 'qcow2: Add overlap structure memory size options' 016/17:[down] 'qapi: Expose new qcow2 overlap check options' 017/17:[down] 'iotests: Test qcow2's overlap check memory limit'

Max Reitz (17):
qcow2: Add new overlap check functions
qcow2: Pull up overlap check option evaluation
qcow2: Create metadata list qcow2/overlaps: Protect image header qcow2/overlaps: Protect refcount table qcow2/overlaps: Protect refcount blocks qcow2/overlaps: Protect active L1 table qcow2/overlaps: Protect active L2 tables qcow2/overlaps: Protect snapshot table qcow2/overlaps: Protect inactive L1 tables qcow2/overlaps: Protect inactive L2 tables
qcow2: Use new metadata overlap check function qcow2/overlaps: Add "memory limit reached" event qcow2/overlaps: Add memory usage limit
qcow2: Add overlap structure memory size options
qapi: Expose new qcow2 overlap check options
iotests: Test qcow2's overlap check memory limit

 block/Makefile.objs        |   3 +-
 block/qcow2-cluster.c      |  13 ++
 block/qcow2-overlap.c      | 572 +++++++++++++++++++++++++++++++++++++++++++++
 block/qcow2-refcount.c     | 202 +++++++---------
 block/qcow2-snapshot.c     | 105 ++++++++-
 block/qcow2.c              | 162 +++++++++----
 block/qcow2.h              |  15 ++
 docs/qmp/qmp-events.txt    |  28 +++
 qapi/block-core.json       |  37 +++
 qapi/event.json            |  27 +++
 tests/qemu-iotests/060     | 222 ++++++++++++++++++
 tests/qemu-iotests/060.out |  47 ++++
 tests/qemu-iotests/group   |   2 +-
 13 files changed, 1262 insertions(+), 173 deletions(-)
 create mode 100644 block/qcow2-overlap.c
Signature · 1 line
2.3.7
author
#1 lore raw

PATCH v4 1/17 qcow2: Add new overlap check functions

The existing qcow2 metadata overlap detection function used existing structures to determine the location of the image metadata, from plain fields such as l1_table_offset and l1_size in the BDRVQcowState, over image structures in memory such as the L1 table for the L2 tables' positions, or it even read the required data directly from disk for every requested check, such as the snapshot L1 tables for the inactive L2 tables' positions.

These new functions instead keep a dedicated structure for keeping track of the metadata positions in memory. It consists of two parts: First, there is one structure which is basically a list of all metadata structures. Each entry has a bitmask of types (because some metadata structures may actually overlap, such as active and inactive L2 tables), a number of clusters occupied and the offset from the previous entry in clusters. This structure requires relatively little memory, but checking a certain point may take relatively long. Each entry is called a "fragment".

Therefore, there is another representation which is a bitmap, or rather a bytemap, of metadata types. The previously described list is split into multiple windows with each describing a constant number of clusters (WINDOW_SIZE). If the list is to be queried or changed, the respective window is selected in constant time and the bitmap is generated from the fragments belonging to the window. This bitmap can then be queried in constant time and easily be changed.

Because the bitmap representation generally requires more memory, it is only used as a cache. Whenever a window is removed from the cache, the fragment list will be rebuilt from the bitmap if the latter has been modified; except for if the fragment list would actually be bigger than the bitmap, in which case the bitmap is kept but no longer being considered part of the cache. Therefore, the fragment list is only used as the background representation to save memory, whereas the bitmap is used whenever possible.

---
 block/Makefile.objs   |   3 +-
 block/qcow2-overlap.c | 447 ++++++++++++++++++++++++++++++++++++++++++++++++++
 block/qcow2.h         |  13 ++
 3 files changed, 462 insertions(+), 1 deletion(-)
 create mode 100644 block/qcow2-overlap.c
block/Makefile.objs +2 -1
index 0d8c2a4..406bd46 100644
@@ -1,5 +1,6 @@
 block-obj-y += raw_bsd.o qcow.o vdi.o vmdk.o cloop.o bochs.o vpc.o vvfat.o
-block-obj-y += qcow2.o qcow2-refcount.o qcow2-cluster.o qcow2-snapshot.o qcow2-cache.o
+block-obj-y += qcow2.o qcow2-refcount.o qcow2-cluster.o qcow2-snapshot.o
+block-obj-y += qcow2-cache.o qcow2-overlap.o
 block-obj-y += qed.o qed-gencb.o qed-l2-cache.o qed-table.o qed-cluster.o
 block-obj-y += qed-check.o
 block-obj-$(CONFIG_VHDX) += vhdx.o vhdx-endian.o vhdx-log.o
block/qcow2-overlap.c new file +447 -0

447 lines not on this page · raw message

block/qcow2.h +13 -0
index 422b825..4a5530b 100644
@@ -159,6 +159,9 @@ typedef struct QCowSnapshot {
 struct Qcow2Cache;
 typedef struct Qcow2Cache Qcow2Cache;
 
+struct Qcow2MetadataList;
+typedef struct Qcow2MetadataList Qcow2MetadataList;
+
 typedef struct Qcow2UnknownHeaderExtension {
     uint32_t magic;
     uint32_t len;
@@ -271,6 +274,7 @@ typedef struct BDRVQcowState {
 
     bool discard_passthrough[QCOW2_DISCARD_MAX];
 
+    Qcow2MetadataList *metadata_list;
     int overlap_check; /* bitmask of Qcow2MetadataOverlap values */
     bool signaled_corruption;
 
@@ -588,4 +592,13 @@ int qcow2_cache_get_empty(BlockDriverState *bs, Qcow2Cache *c, uint64_t offset,
     void **table);
 int qcow2_cache_put(BlockDriverState *bs, Qcow2Cache *c, void **table);
 
+/* qcow2-overlap.c functions */
+int qcow2_create_empty_metadata_list(BlockDriverState *bs, size_t cache_size,
+                                     Error **errp);
+void qcow2_metadata_list_destroy(BlockDriverState *bs);
+void qcow2_metadata_list_enter(BlockDriverState *bs, uint64_t offset,
+                               int nb_clusters, QCow2MetadataOverlap type);
+void qcow2_metadata_list_remove(BlockDriverState *bs, uint64_t offset,
+                                int nb_clusters, QCow2MetadataOverlap type);
+
 #endif
Signature · 1 line
2.3.7
author
#2 lore raw

PATCH v4 2/17 qcow2: Pull up overlap check option evaluation

In reply to Max Reitz

Pull up the absorption of the qcow2-relevant command line options and the evaluation of the overlap check options in qcow2_open().

---
 block/qcow2.c | 96 +++++++++++++++++++++++++++++------------------------------
 1 file changed, 48 insertions(+), 48 deletions(-)
block/qcow2.c +48 -48
index b9a72e3..c46dc4c 100644
@@ -700,6 +700,54 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
         bs->encrypted = 1;
     }
 
+    opts = qemu_opts_create(&qcow2_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;
+    }
+
+    opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
+    opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
+    if (opt_overlap_check_template && opt_overlap_check &&
+        strcmp(opt_overlap_check_template, opt_overlap_check))
+    {
+        error_setg(errp, "Conflicting values for qcow2 options '"
+                   QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
+                   "' ('%s')", opt_overlap_check, opt_overlap_check_template);
+        ret = -EINVAL;
+        goto fail;
+    }
+    if (!opt_overlap_check) {
+        opt_overlap_check = opt_overlap_check_template ?: "cached";
+    }
+
+    if (!strcmp(opt_overlap_check, "none")) {
+        overlap_check_template = 0;
+    } else if (!strcmp(opt_overlap_check, "constant")) {
+        overlap_check_template = QCOW2_OL_CONSTANT;
+    } else if (!strcmp(opt_overlap_check, "cached")) {
+        overlap_check_template = QCOW2_OL_CACHED;
+    } else if (!strcmp(opt_overlap_check, "all")) {
+        overlap_check_template = QCOW2_OL_ALL;
+    } else {
+        error_setg(errp, "Unsupported value '%s' for qcow2 option "
+                   "'overlap-check'. Allowed are either of the following: "
+                   "none, constant, cached, all", opt_overlap_check);
+        ret = -EINVAL;
+        goto fail;
+    }
+
+    s->overlap_check = 0;
+    for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
+        /* overlap-check defines a template bitmask, but every flag may be
+         * overwritten through the associated boolean option */
+        s->overlap_check |=
+            qemu_opt_get_bool(opts, overlap_bool_option_names[i],
+                              overlap_check_template & (1 << i)) << i;
+    }
+
     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
     s->l2_size = 1 << s->l2_bits;
     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
@@ -795,14 +843,6 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
     }
 
     /* get L2 table/refcount block cache size from command line options */
-    opts = qemu_opts_create(&qcow2_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;
-    }
-
     read_cache_sizes(opts, &l2_cache_size, &refcount_cache_size, &local_err);
     if (local_err) {
         error_propagate(errp, local_err);
@@ -937,46 +977,6 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
     s->discard_passthrough[QCOW2_DISCARD_OTHER] =
         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
 
-    opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
-    opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
-    if (opt_overlap_check_template && opt_overlap_check &&
-        strcmp(opt_overlap_check_template, opt_overlap_check))
-    {
-        error_setg(errp, "Conflicting values for qcow2 options '"
-                   QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
-                   "' ('%s')", opt_overlap_check, opt_overlap_check_template);
-        ret = -EINVAL;
-        goto fail;
-    }
-    if (!opt_overlap_check) {
-        opt_overlap_check = opt_overlap_check_template ?: "cached";
-    }
-
-    if (!strcmp(opt_overlap_check, "none")) {
-        overlap_check_template = 0;
-    } else if (!strcmp(opt_overlap_check, "constant")) {
-        overlap_check_template = QCOW2_OL_CONSTANT;
-    } else if (!strcmp(opt_overlap_check, "cached")) {
-        overlap_check_template = QCOW2_OL_CACHED;
-    } else if (!strcmp(opt_overlap_check, "all")) {
-        overlap_check_template = QCOW2_OL_ALL;
-    } else {
-        error_setg(errp, "Unsupported value '%s' for qcow2 option "
-                   "'overlap-check'. Allowed are either of the following: "
-                   "none, constant, cached, all", opt_overlap_check);
-        ret = -EINVAL;
-        goto fail;
-    }
-
-    s->overlap_check = 0;
-    for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
-        /* overlap-check defines a template bitmask, but every flag may be
-         * overwritten through the associated boolean option */
-        s->overlap_check |=
-            qemu_opt_get_bool(opts, overlap_bool_option_names[i],
-                              overlap_check_template & (1 << i)) << i;
-    }
-
     qemu_opts_del(opts);
     opts = NULL;
 
Signature · 1 line
2.3.7
author
#3 lore raw

PATCH v4 3/17 qcow2: Create metadata list

In reply to Max Reitz

Create and destroy the metadata list on creation and destruction of a qcow2 BDS, respectively. Skip creation if no overlap checks should be performed.

---
 block/qcow2.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
block/qcow2.c +11 -0
index c46dc4c..b15a612 100644
@@ -758,6 +758,14 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
 
+    if (s->overlap_check) {
+        /* TODO: Let the user override this default */
+        ret = qcow2_create_empty_metadata_list(bs, 65536, errp);
+        if (ret < 0) {
+            goto fail;
+        }
+    }
+
     s->refcount_table_offset = header.refcount_table_offset;
     s->refcount_table_size =
         header.refcount_table_clusters << (s->cluster_bits - 3);
@@ -1012,6 +1020,7 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
     }
     g_free(s->cluster_cache);
     qemu_vfree(s->cluster_data);
+    qcow2_metadata_list_destroy(bs);
     return ret;
 }
 
@@ -1466,6 +1475,8 @@ static void qcow2_close(BlockDriverState *bs)
     qemu_vfree(s->cluster_data);
     qcow2_refcount_close(bs);
     qcow2_free_snapshots(bs);
+
+    qcow2_metadata_list_destroy(bs);
 }
 
 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
Signature · 1 line
2.3.7
author
#4 lore raw

PATCH v4 4/17 qcow2/overlaps: Protect image header

In reply to Max Reitz

Enter the image header into the metadata list to protect it against accidental modifications.

---
 block/qcow2.c | 2 ++
 1 file changed, 2 insertions(+)
block/qcow2.c +2 -0
index b15a612..fc53b34 100644
@@ -766,6 +766,8 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
         }
     }
 
+    qcow2_metadata_list_enter(bs, 0, 1, QCOW2_OL_MAIN_HEADER);
+
     s->refcount_table_offset = header.refcount_table_offset;
     s->refcount_table_size =
         header.refcount_table_clusters << (s->cluster_bits - 3);
Signature · 1 line
2.3.7
author
#5 lore raw

PATCH v4 5/17 qcow2/overlaps: Protect refcount table

In reply to Max Reitz

Keep track of the refcount table in the metadata list to protect it against accidental modifications.

---
 block/qcow2-refcount.c | 18 ++++++++++++++++++
 block/qcow2.c          |  4 ++++
 2 files changed, 22 insertions(+)
block/qcow2-refcount.c +18 -0
index f47260b..439835d 100644
@@ -585,6 +585,14 @@ static int alloc_refcount_block(BlockDriverState *bs,
     s->refcount_table_size = table_size;
     s->refcount_table_offset = table_offset;
 
+    qcow2_metadata_list_remove(bs, old_table_offset,
+                               size_to_clusters(s, old_table_size *
+                                                   sizeof(uint64_t)),
+                               QCOW2_OL_REFCOUNT_TABLE);
+
+    qcow2_metadata_list_enter(bs, table_offset, table_clusters,
+                              QCOW2_OL_REFCOUNT_TABLE);
+
     /* Free old table. */
     qcow2_free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t),
                         QCOW2_DISCARD_OTHER);
@@ -2161,6 +2169,16 @@ write_refblocks:
         goto fail;
     }
 
+    qcow2_metadata_list_remove(bs, s->refcount_table_offset,
+                               size_to_clusters(s, s->refcount_table_size
+                                                   * sizeof(uint64_t)),
+                               QCOW2_OL_REFCOUNT_TABLE);
+
+    qcow2_metadata_list_enter(bs, reftable_offset,
+                              size_to_clusters(s, reftable_size *
+                                                  sizeof(uint64_t)),
+                              QCOW2_OL_REFCOUNT_TABLE);
+
     for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {
         be64_to_cpus(&on_disk_reftable[refblock_index]);
     }
block/qcow2.c +4 -0
index fc53b34..e9dbd72 100644
@@ -784,6 +784,10 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
         error_setg(errp, "Invalid reference count table offset");
         goto fail;
     }
+    qcow2_metadata_list_enter(bs, s->refcount_table_offset,
+                              size_to_clusters(s, s->refcount_table_size *
+                                                  sizeof(uint64_t)),
+                              QCOW2_OL_REFCOUNT_TABLE);
 
     /* Snapshot table offset/length */
     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
Signature · 1 line
2.3.7
author
#6 lore raw

PATCH v4 6/17 qcow2/overlaps: Protect refcount blocks

In reply to Max Reitz

Keep track of the refcount blocks in the metadata list to protect them against accidental modifications.

---
 block/qcow2-refcount.c | 38 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 37 insertions(+), 1 deletion(-)
block/qcow2-refcount.c +37 -1
index 439835d..306ff4b 100644
@@ -106,8 +106,16 @@ int qcow2_refcount_init(BlockDriverState *bs)
         if (ret < 0) {
             goto fail;
         }
-        for(i = 0; i < s->refcount_table_size; i++)
+        for (i = 0; i < s->refcount_table_size; i++) {
+            uint64_t refblock_offset;
+
             be64_to_cpus(&s->refcount_table[i]);
+            refblock_offset = s->refcount_table[i] & REFT_OFFSET_MASK;
+            if (refblock_offset) {
+                qcow2_metadata_list_enter(bs, refblock_offset, 1,
+                                          QCOW2_OL_REFCOUNT_BLOCK);
+            }
+        }
     }
     return 0;
  fail:
@@ -442,6 +450,7 @@ static int alloc_refcount_block(BlockDriverState *bs,
         }
 
         s->refcount_table[refcount_table_index] = new_block;
+        qcow2_metadata_list_enter(bs, new_block, 1, QCOW2_OL_REFCOUNT_BLOCK);
 
         /* The new refcount block may be where the caller intended to put its
          * data, so let it restart the search. */
@@ -515,6 +524,7 @@ static int alloc_refcount_block(BlockDriverState *bs,
     uint64_t table_offset = meta_offset + blocks_clusters * s->cluster_size;
     uint64_t *new_table = g_try_new0(uint64_t, table_size);
     void *new_blocks = g_try_malloc0(blocks_clusters * s->cluster_size);
+    uint64_t block_index;
 
     assert(table_size > 0 && blocks_clusters > 0);
     if (new_table == NULL || new_blocks == NULL) {
@@ -593,6 +603,12 @@ static int alloc_refcount_block(BlockDriverState *bs,
     qcow2_metadata_list_enter(bs, table_offset, table_clusters,
                               QCOW2_OL_REFCOUNT_TABLE);
 
+    for (block_index = 0; block_index < blocks_clusters; block_index++) {
+        qcow2_metadata_list_enter(bs, meta_offset +
+                                  (block_index << s->cluster_bits), 1,
+                                  QCOW2_OL_REFCOUNT_BLOCK);
+    }
+
     /* Free old table. */
     qcow2_free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t),
                         QCOW2_DISCARD_OTHER);
@@ -2174,14 +2190,34 @@ write_refblocks:
                                                    * sizeof(uint64_t)),
                                QCOW2_OL_REFCOUNT_TABLE);
 
+    for (refblock_index = 0; refblock_index < s->refcount_table_size;
+         refblock_index++)
+    {
+        uint64_t refblock_offset = s->refcount_table[refblock_index] &
+                                   REFT_OFFSET_MASK;
+        if (refblock_offset) {
+            qcow2_metadata_list_remove(bs, refblock_offset, 1,
+                                       QCOW2_OL_REFCOUNT_BLOCK);
+        }
+    }
+
     qcow2_metadata_list_enter(bs, reftable_offset,
                               size_to_clusters(s, reftable_size *
                                                   sizeof(uint64_t)),
                               QCOW2_OL_REFCOUNT_TABLE);
 
     for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {
+        uint64_t refblock_offset;
+
         be64_to_cpus(&on_disk_reftable[refblock_index]);
+
+        refblock_offset = on_disk_reftable[refblock_index] & REFT_OFFSET_MASK;
+        if (refblock_offset) {
+            qcow2_metadata_list_enter(bs, refblock_offset, 1,
+                                      QCOW2_OL_REFCOUNT_BLOCK);
+        }
     }
+
     s->refcount_table = on_disk_reftable;
     s->refcount_table_offset = reftable_offset;
     s->refcount_table_size = reftable_size;
Signature · 1 line
2.3.7
author
#7 lore raw

PATCH v4 7/17 qcow2/overlaps: Protect active L1 table

In reply to Max Reitz

Keep track of the active L1 table in the metadata list to protect it against accidental modifications.

---
 block/qcow2-cluster.c  | 11 +++++++++++
 block/qcow2-snapshot.c | 10 ++++++++++
 block/qcow2.c          |  4 ++++
 3 files changed, 25 insertions(+)
block/qcow2-cluster.c +11 -0
index ed2b44d..da965d6 100644
@@ -125,6 +125,17 @@ int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
     s->l1_table = new_l1_table;
     old_l1_size = s->l1_size;
     s->l1_size = new_l1_size;
+
+    qcow2_metadata_list_remove(bs, old_l1_table_offset,
+                               size_to_clusters(s, old_l1_size *
+                                                   sizeof(uint64_t)),
+                               QCOW2_OL_ACTIVE_L1);
+
+    qcow2_metadata_list_enter(bs, s->l1_table_offset,
+                              size_to_clusters(s, s->l1_size *
+                                                  sizeof(uint64_t)),
+                              QCOW2_OL_ACTIVE_L1);
+
     qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),
                         QCOW2_DISCARD_OTHER);
     return 0;
block/qcow2-snapshot.c +10 -0
index 17bb211..a5d7940 100644
@@ -718,6 +718,11 @@ int qcow2_snapshot_load_tmp(BlockDriverState *bs,
         return ret;
     }
 
+    qcow2_metadata_list_remove(bs, s->l1_table_offset,
+                               size_to_clusters(s, s->l1_size *
+                                                   sizeof(uint64_t)),
+                               QCOW2_OL_ACTIVE_L1);
+
     /* Switch the L1 table */
     qemu_vfree(s->l1_table);
 
@@ -729,5 +734,10 @@ int qcow2_snapshot_load_tmp(BlockDriverState *bs,
         be64_to_cpus(&s->l1_table[i]);
     }
 
+    qcow2_metadata_list_enter(bs, s->l1_table_offset,
+                              size_to_clusters(s, s->l1_size *
+                                                  sizeof(uint64_t)),
+                              QCOW2_OL_ACTIVE_L1);
+
     return 0;
 }
block/qcow2.c +4 -0
index e9dbd72..46a8a39 100644
@@ -836,6 +836,10 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
     }
     s->l1_table_offset = header.l1_table_offset;
 
+    qcow2_metadata_list_enter(bs, s->l1_table_offset,
+                              size_to_clusters(s, s->l1_size *
+                                                  sizeof(uint64_t)),
+                              QCOW2_OL_ACTIVE_L1);
 
     if (s->l1_size > 0) {
         s->l1_table = qemu_try_blockalign(bs->file,
Signature · 1 line
2.3.7
author
#8 lore raw

PATCH v4 8/17 qcow2/overlaps: Protect active L2 tables

In reply to Max Reitz

Keep track of the active L2 tables in the metadata list to protect them against accidental modifications.

---
 block/qcow2-cluster.c  |  2 ++
 block/qcow2-refcount.c |  6 ++++++
 block/qcow2-snapshot.c | 21 +++++++++++++++++++++
 block/qcow2.c          |  8 +++++++-
 4 files changed, 36 insertions(+), 1 deletion(-)
block/qcow2-cluster.c +2 -0
index da965d6..7bdfdbe 100644
@@ -288,6 +288,8 @@ static int l2_allocate(BlockDriverState *bs, int l1_index, uint64_t **table)
         goto fail;
     }
 
+    qcow2_metadata_list_enter(bs, l2_offset, 1, QCOW2_OL_ACTIVE_L2);
+
     *table = l2_table;
     trace_qcow2_l2_allocate_done(bs, l1_index, 0);
     return 0;
block/qcow2-refcount.c +6 -0
index 306ff4b..b583beb 100644
@@ -1219,6 +1219,12 @@ int qcow2_update_snapshot_refcount(BlockDriverState *bs,
                 if (ret < 0) {
                     goto fail;
                 }
+                if (addend < 0) {
+                    if (!l1_allocated) {
+                        qcow2_metadata_list_remove(bs, l2_offset, 1,
+                                                   QCOW2_OL_ACTIVE_L2);
+                    }
+                }
             }
             ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
                                      &refcount);
block/qcow2-snapshot.c +21 -0
index a5d7940..aa211e3 100644
@@ -559,6 +559,13 @@ int qcow2_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)
     g_free(sn_l1_table);
     sn_l1_table = NULL;
 
+    for (i = 0; i < s->l1_size; i++) {
+        uint64_t l2_offset = s->l1_table[i] & L1E_OFFSET_MASK;
+        if (l2_offset) {
+            qcow2_metadata_list_enter(bs, l2_offset, 1, QCOW2_OL_ACTIVE_L2);
+        }
+    }
+
     /*
      * Update QCOW_OFLAG_COPIED in the active L1 table (it may have changed
      * when we decreased the refcount of the old snapshot.
@@ -723,6 +730,13 @@ int qcow2_snapshot_load_tmp(BlockDriverState *bs,
                                                    sizeof(uint64_t)),
                                QCOW2_OL_ACTIVE_L1);
 
+    for (i = 0; i < s->l1_size; i++) {
+        uint64_t l2_offset = s->l1_table[i] & L1E_OFFSET_MASK;
+        if (l2_offset) {
+            qcow2_metadata_list_remove(bs, l2_offset, 1, QCOW2_OL_ACTIVE_L2);
+        }
+    }
+
     /* Switch the L1 table */
     qemu_vfree(s->l1_table);
 
@@ -739,5 +753,12 @@ int qcow2_snapshot_load_tmp(BlockDriverState *bs,
                                                   sizeof(uint64_t)),
                               QCOW2_OL_ACTIVE_L1);
 
+    for (i = 0; i < s->l1_size; i++) {
+        uint64_t l2_offset = s->l1_table[i] & L1E_OFFSET_MASK;
+        if (l2_offset) {
+            qcow2_metadata_list_enter(bs, l2_offset, 1, QCOW2_OL_ACTIVE_L2);
+        }
+    }
+
     return 0;
 }
block/qcow2.c +7 -1
index 46a8a39..1e173a3 100644
@@ -855,8 +855,14 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
             error_setg_errno(errp, -ret, "Could not read L1 table");
             goto fail;
         }
-        for(i = 0;i < s->l1_size; i++) {
+        for (i = 0; i < s->l1_size; i++) {
+            uint64_t l2_offset;
+
             be64_to_cpus(&s->l1_table[i]);
+            l2_offset = s->l1_table[i] & L1E_OFFSET_MASK;
+            if (l2_offset) {
+                qcow2_metadata_list_enter(bs, l2_offset, 1, QCOW2_OL_ACTIVE_L2);
+            }
         }
     }
 
Signature · 1 line
2.3.7
author
#9 lore raw

PATCH v4 9/17 qcow2/overlaps: Protect snapshot table

In reply to Max Reitz

Keep track of the snapshot table in the metadata list to protect it against accidental modifications.

---
 block/qcow2-snapshot.c | 10 ++++++++++
 block/qcow2.c          |  6 ++++++
 2 files changed, 16 insertions(+)
block/qcow2-snapshot.c +10 -0
index aa211e3..966982f 100644
@@ -262,8 +262,18 @@ static int qcow2_write_snapshots(BlockDriverState *bs)
     /* free the old snapshot table */
     qcow2_free_clusters(bs, s->snapshots_offset, s->snapshots_size,
                         QCOW2_DISCARD_SNAPSHOT);
+
+    qcow2_metadata_list_remove(bs, s->snapshots_offset,
+                               size_to_clusters(s, s->snapshots_size),
+                               QCOW2_OL_SNAPSHOT_TABLE);
+
     s->snapshots_offset = snapshots_offset;
     s->snapshots_size = snapshots_size;
+
+    qcow2_metadata_list_enter(bs, s->snapshots_offset,
+                              size_to_clusters(s, s->snapshots_size),
+                              QCOW2_OL_SNAPSHOT_TABLE);
+
     return 0;
 
 fail:
block/qcow2.c +6 -0
index 1e173a3..4e7005e 100644
@@ -803,6 +803,12 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
         error_setg(errp, "Invalid snapshot table offset");
         goto fail;
     }
+    if (header.nb_snapshots) {
+        qcow2_metadata_list_enter(bs, header.snapshots_offset,
+                                  size_to_clusters(s, header.nb_snapshots *
+                                                   sizeof(QCowSnapshotHeader)),
+                                  QCOW2_OL_SNAPSHOT_TABLE);
+    }
 
     /* read the level 1 table */
     if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
Signature · 1 line
2.3.7
author
#10 lore raw

PATCH v4 10/17 qcow2/overlaps: Protect inactive L1 tables

In reply to Max Reitz

Keep track of the inactive L1 tables in the metadata list to protect them against accidental modifications.

---
 block/qcow2-snapshot.c | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
block/qcow2-snapshot.c +25 -0
index 966982f..ccde56d 100644
@@ -121,6 +121,21 @@ int qcow2_read_snapshots(BlockDriverState *bs)
             ret = -EFBIG;
             goto fail;
         }
+
+        if (!(s->overlap_check & QCOW2_OL_INACTIVE_L1)) {
+            continue;
+        }
+
+        if (sn->l1_size > INT_MAX / sizeof(uint64_t)) {
+            /* Do not fail opening the image because a snapshot is broken which
+             * might not be used anyway */
+            continue;
+        }
+
+        qcow2_metadata_list_enter(bs, sn->l1_table_offset,
+                                  size_to_clusters(s, sn->l1_size *
+                                                      sizeof(uint64_t)),
+                                  QCOW2_OL_INACTIVE_L1);
     }
 
     assert(offset - s->snapshots_offset <= INT_MAX);
@@ -414,6 +429,11 @@ int qcow2_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info)
     g_free(l1_table);
     l1_table = NULL;
 
+    qcow2_metadata_list_enter(bs, sn->l1_table_offset,
+                              size_to_clusters(s, sn->l1_size *
+                                                  sizeof(uint64_t)),
+                              QCOW2_OL_INACTIVE_L1);
+
     /*
      * Increase the refcounts of all clusters and make sure everything is
      * stable on disk before updating the snapshot table to contain a pointer
@@ -634,6 +654,11 @@ int qcow2_snapshot_delete(BlockDriverState *bs,
     g_free(sn.id_str);
     g_free(sn.name);
 
+    qcow2_metadata_list_remove(bs, sn.l1_table_offset,
+                               size_to_clusters(s, sn.l1_size *
+                                                   sizeof(uint64_t)),
+                               QCOW2_OL_INACTIVE_L1);
+
     /*
      * Now decrease the refcounts of clusters referenced by the snapshot and
      * free the L1 table.
Signature · 1 line
2.3.7
author
#11 lore raw

PATCH v4 11/17 qcow2/overlaps: Protect inactive L2 tables

In reply to Max Reitz

Keep track of the inactive L2 tables in the metadata list to protect them against accidental modifications.

---
 block/qcow2-refcount.c | 20 ++++++++++++++++++++
 block/qcow2-snapshot.c | 43 ++++++++++++++++++++++++++++++++++++++++---
 2 files changed, 60 insertions(+), 3 deletions(-)
block/qcow2-refcount.c +20 -0
index b583beb..00b7258 100644
@@ -1221,8 +1221,28 @@ int qcow2_update_snapshot_refcount(BlockDriverState *bs,
                 }
                 if (addend < 0) {
                     if (!l1_allocated) {
+                        /* This is easy */
                         qcow2_metadata_list_remove(bs, l2_offset, 1,
                                                    QCOW2_OL_ACTIVE_L2);
+                    } else {
+                        /* If refcount == 0, this is, too. If refcount > 1, we
+                         * know that there must be some other inactive L2
+                         * reference; and for refcount == 1, if this is an
+                         * active L2 table, this was the last inactive L2
+                         * reference. */
+                        bool remove;
+                        if (refcount == 0) {
+                            remove = true;
+                        } else if (refcount == 1) {
+                            remove = qcow2_check_metadata_overlap(bs,
+                                ~QCOW2_OL_ACTIVE_L2, l2_offset,s->cluster_size);
+                        } else {
+                            remove = false;
+                        }
+                        if (remove) {
+                            qcow2_metadata_list_remove(bs, l2_offset, 1,
+                                                       QCOW2_OL_INACTIVE_L2);
+                        }
                     }
                 }
             }
block/qcow2-snapshot.c +40 -3

72 lines not on this page · raw message

Signature · 1 line
2.3.7
author
#12 lore raw

PATCH v4 12/17 qcow2: Use new metadata overlap check function

In reply to Max Reitz

Make the static new overlap check function global and drop the old function.

---
 block/qcow2-overlap.c  |   8 +---
 block/qcow2-refcount.c | 120 -------------------------------------------------
 2 files changed, 2 insertions(+), 126 deletions(-)
block/qcow2-overlap.c +2 -6
index 35390a5..92097dd 100644
@@ -356,12 +356,8 @@ static int single_check_metadata_overlap(Qcow2MetadataList *mdl, int ign,
     return window->bitmap[bitmap_i] & ~ign;
 }
 
-/* This will replace qcow2_check_metadata_overlap() */
-static int check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
-                                  int64_t size) __attribute__((used));
-
-static int check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
-                                  int64_t size)
+int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
+                                 int64_t size)
 {
     BDRVQcowState *s = bs->opaque;
     uint64_t start_cluster = offset >> s->cluster_bits;
block/qcow2-refcount.c +0 -120

126 lines not on this page · raw message

Signature · 1 line
2.3.7
author
#13 lore raw

PATCH v4 13/17 qcow2/overlaps: Add "memory limit reached" event

In reply to Max Reitz

Later, a mechanism to set a limit on how much memory may be used for the overlap prevention structures will be introduced. If that limit is about to be exceeded, a QMP event should be emitted. This very event is specified by this patch.

---
 docs/qmp/qmp-events.txt | 28 ++++++++++++++++++++++++++++
 qapi/event.json         | 27 +++++++++++++++++++++++++++
 2 files changed, 55 insertions(+)
docs/qmp/qmp-events.txt +28 -0
index b19e490..4ec257e 100644
@@ -261,6 +261,34 @@ Example:
 { "event": "POWERDOWN",
     "timestamp": { "seconds": 1267040730, "microseconds": 682951 } }
 
+QCOW2_OVERLAP_CHECK_MEMORY_LIMIT_REACHED
+----------------------------------------
+
+Emitted by the qcow2 block driver if the preset size limit for the in-memory
+structures for metadata overlap prevention has been reached and an allocation
+of further resources has been denied. This means that it cannot be guaranteed
+that overlap checks will be performed for the specified range; if no range is
+given, no checks can be expected to be performed whatsoever.
+
+Note that this event does not guarantee that no check will be performed in the
+given range (or on the whole image, if no range is given), but only signals the
+possibility that this might be the case. The ability to check the full range or
+a part of it may be restored at any point in time.
+
+Data:
+- "reference": Device name if set; node name otherwise. (json-string)
+- "start":     Offset of the range of clusters (possibly) no longer being
+               checked for writes overlapping with existing metadata.
+               (json-int, optional)
+- "length":    Length of that range in bytes. (json-int, optional)
+
+Example:
+
+{ "event": "QCOW2_OVERLAP_CHECK_MEMORY_LIMIT_REACHED",
+    "data": { "reference": "virtio0", "start": "805306368",
+              "length": "268435456" },
+    "timestamp": { "seconds": 1429331400, "microseconds": 519454 } }
+
 QUORUM_FAILURE
 --------------
 
qapi/event.json +27 -0
index c51dc49..a6cd053 100644
@@ -330,3 +330,30 @@
 ##
 { 'event': 'VSERPORT_CHANGE',
   'data': { 'id': 'str', 'open': 'bool' } }
+
+##
+# @QCOW2_OVERLAP_CHECK_MEMORY_LIMIT_REACHED
+#
+# Emitted by the qcow2 block driver if the preset size limit for the in-memory
+# structures for metadata overlap prevention has been reached and an allocation
+# of further resources has been denied. This means that no overlap checks will
+# be performed for the specified range.
+#
+# Note that this event does not guarantee that no check will be performed in the
+# given range (or on the whole image, if no range is given), but only signals
+# the possibility that this might be the case. The ability to check the full
+# range or a part of it may be restored at any point in time.
+#
+# @reference: device name if set; node name otherwise
+#
+# @start:     #optional offset of the range of clusters (possibly) no longer
+#             being checked for writes overlapping with existing metadata
+#
+# @length:    #optional length of that range in bytes
+#
+# Since: 2.4
+##
+{ 'event': 'QCOW2_OVERLAP_CHECK_MEMORY_LIMIT_REACHED',
+  'data': { 'reference': 'str',
+            '*start':    'int',
+            '*length':   'int' } }
Signature · 1 line
2.3.7
author
#17 lore raw

PATCH v4 15/17 qcow2: Add overlap structure memory size options

In reply to Max Reitz

Add runtime options to qcow2 to control the size of the structures used for metadata overlap prevention (one option to control the size of the bitmap cache, another one to control the total memory size limit).

---
 block/qcow2.c | 35 +++++++++++++++++++++++++++++++++--
 block/qcow2.h |  2 ++
 2 files changed, 35 insertions(+), 2 deletions(-)
block/qcow2.c +33 -2
index fbf4d6f..1d0900d 100644
@@ -453,6 +453,18 @@ static QemuOptsList qcow2_runtime_opts = {
             .help = "Check for unintended writes into an inactive L2 table",
         },
         {
+            .name = QCOW2_OPT_OVERLAP_BITMAP_SIZE,
+            .type = QEMU_OPT_SIZE,
+            .help = "Size for the bitmap cache used by the metadata overlap "
+                    "check",
+        },
+        {
+            .name = QCOW2_OPT_OVERLAP_TOTAL_SIZE_LIMIT,
+            .type = QEMU_OPT_SIZE,
+            .help = "Maximum total memory size to be used for the metadata "
+                    "overlap check structures",
+        },
+        {
             .name = QCOW2_OPT_CACHE_SIZE,
             .type = QEMU_OPT_SIZE,
             .help = "Maximum combined metadata (L2 tables and refcount blocks) "
@@ -759,8 +771,27 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
 
     if (s->overlap_check) {
-        /* TODO: Let the user override this default */
-        ret = qcow2_create_empty_metadata_list(bs, 65536, SIZE_MAX, errp);
+        uint64_t cache_size, total_size;
+
+        cache_size = qemu_opt_get_size(opts, QCOW2_OPT_OVERLAP_BITMAP_SIZE,
+                                       65536);
+        if (cache_size > SIZE_MAX) {
+            error_setg(errp, "qcow2 option '" QCOW2_OPT_OVERLAP_BITMAP_SIZE
+                       "' expects an argument less or equal to %zu", SIZE_MAX);
+            ret = -EINVAL;
+            goto fail;
+        }
+
+        total_size = qemu_opt_get_size(opts, QCOW2_OPT_OVERLAP_TOTAL_SIZE_LIMIT,
+                                       SIZE_MAX);
+        if (total_size > SIZE_MAX) {
+            error_setg(errp, "qcow2 option '" QCOW2_OPT_OVERLAP_TOTAL_SIZE_LIMIT
+                       "' expects an argument less or equal to %zu", SIZE_MAX);
+            ret = -EINVAL;
+            goto fail;
+        }
+
+        ret = qcow2_create_empty_metadata_list(bs, cache_size, total_size, errp);
         if (ret < 0) {
             goto fail;
         }
block/qcow2.h +2 -0
index cbb932a..6cb024c 100644
@@ -90,6 +90,8 @@
 #define QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE "overlap-check.snapshot-table"
 #define QCOW2_OPT_OVERLAP_INACTIVE_L1 "overlap-check.inactive-l1"
 #define QCOW2_OPT_OVERLAP_INACTIVE_L2 "overlap-check.inactive-l2"
+#define QCOW2_OPT_OVERLAP_BITMAP_SIZE "overlap-structures.bitmap-size"
+#define QCOW2_OPT_OVERLAP_TOTAL_SIZE_LIMIT "overlap-structures.total-size-limit"
 #define QCOW2_OPT_CACHE_SIZE "cache-size"
 #define QCOW2_OPT_L2_CACHE_SIZE "l2-cache-size"
 #define QCOW2_OPT_REFCOUNT_CACHE_SIZE "refcount-cache-size"
Signature · 1 line
2.3.7
author
#16 lore raw

PATCH v4 14/17 qcow2/overlaps: Add memory usage limit

In reply to Max Reitz

This adds an adjustable limit for the total memory usage of the overlap prevention structures.

---
 block/qcow2-overlap.c | 145 +++++++++++++++++++++++++++++++++++++++++++++++---
 block/qcow2.c         |   2 +-
 block/qcow2.h         |   2 +-
 3 files changed, 139 insertions(+), 10 deletions(-)
block/qcow2-overlap.c +137 -8
index 92097dd..654d5c3 100644
@@ -23,9 +23,11 @@
  */
 
 #include "block/block_int.h"
+#include "sysemu/block-backend.h"
 #include "qemu-common.h"
 #include "qemu/range.h"
 #include "qcow2.h"
+#include "qapi-event.h"
 
 /* Number of clusters which are covered by each metadata window;
  * note that this may not exceed 2^16 as long as
@@ -68,12 +70,50 @@ struct Qcow2MetadataList {
 
     unsigned current_age;
 
+    size_t mem_usage, max_mem_usage;
+
     /* Index into the windows array */
     int *cached_windows;
     size_t nb_cached_windows;
 };
 
 /**
+ * Logs newly allocated memory in the @mdl->mem_usage field. Returns true iff
+ * @mdl->mem_usage + @size * @nmemb <= @mdl->max_mem_usage, that is, if
+ * allocating that memory is still within limits. In that case, @mdl->mem_usage
+ * is increased by @size * @nmemb; otherwise, it is left unchanged.
+ */
+static bool increase_mdl_mem_usage(Qcow2MetadataList *mdl, size_t size,
+                                   size_t nmemb)
+{
+    if (nmemb && SIZE_MAX / nmemb < size) {
+        /* Overflow */
+        return false;
+    }
+
+    size *= nmemb;
+    if (mdl->mem_usage + size < mdl->mem_usage ||
+        mdl->mem_usage + size > mdl->max_mem_usage)
+    {
+        return false;
+    }
+
+    mdl->mem_usage += size;
+    return true;
+}
+
+static void signal_memory_excess(BlockDriverState *bs, uint64_t start_cluster,
+                                 uint64_t nb_clusters)
+{
+    BDRVQcowState *s = bs->opaque;
+    const char *ref = bs->blk ? blk_name(bs->blk) : bs->node_name;
+
+    qapi_event_send_qcow2_overlap_check_memory_limit_reached(ref, true,
+        start_cluster * s->cluster_size, true, nb_clusters * s->cluster_size,
+        &error_abort);
+}
+
+/**
  * Destroys the cached window bitmap. If it has been modified, the fragment list
  * will be rebuilt accordingly.
  */
@@ -81,11 +121,16 @@ static void destroy_window_bitmap(Qcow2MetadataList *mdl,
                                   Qcow2MetadataWindow *window)
 {
     Qcow2MetadataFragment *new_fragments;
+    bool increase_ret;
 
     if (!window->bitmap) {
         return;
     }
 
+    /* Treat the bitmap as freed already; while not really correct, this gives
+     * us space for the fragment list */
+    mdl->mem_usage -= WINDOW_SIZE;
+
     if (window->bitmap_modified) {
         int bitmap_i, fragment_i = 0;
         QCow2MetadataOverlap current_types = 0;
@@ -105,6 +150,9 @@ static void destroy_window_bitmap(Qcow2MetadataList *mdl,
             } else {
                 if (current_types && current_nb_clusters) {
                     if (fragment_i >= window->fragments_array_size) {
+                        mdl->mem_usage -= sizeof(Qcow2MetadataFragment)
+                                          * window->fragments_array_size;
+
                         window->fragments_array_size =
                             3 * window->fragments_array_size / 2 + 1;
                         if (sizeof(Qcow2MetadataFragment)
@@ -115,6 +163,16 @@ static void destroy_window_bitmap(Qcow2MetadataList *mdl,
                             goto fail;
                         }
 
+                        increase_ret = increase_mdl_mem_usage(mdl,
+                            sizeof(Qcow2MetadataFragment),
+                            window->fragments_array_size);
+                        /* This can never be false: Because mem_usage was
+                         * reduced by WINDOW_SIZE at the beginning of this
+                         * function and the size of the fragment list is certain
+                         * to be less than WINDOW_SIZE, there must be enough
+                         * memory available. */
+                        assert(increase_ret);
+
                         new_fragments =
                             g_try_renew(Qcow2MetadataFragment,
                                         window->fragments,
@@ -148,6 +206,7 @@ static void destroy_window_bitmap(Qcow2MetadataList *mdl,
         new_fragments = g_try_renew(Qcow2MetadataFragment, window->fragments,
                                     window->nb_fragments);
         if (new_fragments) {
+            mdl->mem_usage -= window->fragments_array_size - window->nb_fragments;
             window->fragments = new_fragments;
             window->fragments_array_size = window->nb_fragments;
         }
@@ -163,12 +222,20 @@ fail:
     window->fragments = NULL;
     window->nb_fragments = 0;
     window->fragments_array_size = 0;
+
+    /* window->bitmap is not destroyed, so we need to account for it (because
+     * we "borrowed" the space before) */
+    increase_ret = increase_mdl_mem_usage(mdl, sizeof(uint8_t), WINDOW_SIZE);
+    /* If we land here, no additional memory was allocated (only
+     * window->fragments may grow in this function, but at this point it has
+     * been freed), so we must be able to reclaim the space */
+    assert(increase_ret);
 }
 
 /**
  * Creates a bitmap from the fragment list.
  */
-static void build_window_bitmap(Qcow2MetadataList *mdl,
+static bool build_window_bitmap(Qcow2MetadataList *mdl,
                                 Qcow2MetadataWindow *window)
 {
     int cache_i, oldest_cache_i = -1, i;
@@ -202,9 +269,13 @@ static void build_window_bitmap(Qcow2MetadataList *mdl,
     /* Maybe there already is a bitmap because it was more space-efficient than
      * the range list representation */
     if (window->bitmap) {
-        return;
+        return true;
     }
 
+    if (!increase_mdl_mem_usage(mdl, sizeof(uint8_t), WINDOW_SIZE)) {
+        window->bitmap = NULL;
+        return false;
+    }
     window->bitmap = g_new0(uint8_t, WINDOW_SIZE);
 
     for (i = 0; i < window->nb_fragments; i++) {
@@ -215,6 +286,8 @@ static void build_window_bitmap(Qcow2MetadataList *mdl,
     }
 
     window->bitmap_modified = false;
+
+    return true;
 }
 
 /**
@@ -251,10 +324,24 @@ void qcow2_metadata_list_enter(BlockDriverState *bs, uint64_t offset,
              * the array to exactly the required size */
             Qcow2MetadataWindow *new_windows;
 
+            if (!increase_mdl_mem_usage(s->metadata_list,
+                                        sizeof(Qcow2MetadataWindow),
+                                        window_i + 1
+                                        - s->metadata_list->nb_windows))
+            {
+                /* This will happen for any cluster from here until end_cluster,
+                 * so we can just abort immediately */
+                signal_memory_excess(bs, window_i * WINDOW_SIZE,
+                                     end_cluster - current_cluster);
+                return;
+            }
+
             new_windows = g_try_renew(Qcow2MetadataWindow,
                                       s->metadata_list->windows,
                                       window_i + 1);
             if (!new_windows) {
+                signal_memory_excess(bs, window_i * WINDOW_SIZE,
+                                     end_cluster - current_cluster);
                 return;
             }
 
@@ -268,7 +355,10 @@ void qcow2_metadata_list_enter(BlockDriverState *bs, uint64_t offset,
 
         window = &s->metadata_list->windows[window_i];
         if (!window->bitmap) {
-            build_window_bitmap(s->metadata_list, window);
+            if (!build_window_bitmap(s->metadata_list, window)) {
+                signal_memory_excess(bs, window_i * WINDOW_SIZE, WINDOW_SIZE);
+                goto next_window;
+            }
         }
 
         for (bitmap_i = bitmap_i_start; bitmap_i < bitmap_i_end; bitmap_i++) {
@@ -278,6 +368,7 @@ void qcow2_metadata_list_enter(BlockDriverState *bs, uint64_t offset,
         window->age = s->metadata_list->current_age++;
         window->bitmap_modified = true;
 
+next_window:
         /* Go to the next window */
         current_cluster += WINDOW_SIZE - bitmap_i_start;
     }
@@ -320,7 +411,17 @@ void qcow2_metadata_list_remove(BlockDriverState *bs, uint64_t offset,
 
         window = &s->metadata_list->windows[window_i];
         if (!window->bitmap) {
-            build_window_bitmap(s->metadata_list, window);
+            if (!build_window_bitmap(s->metadata_list, window)) {
+                signal_memory_excess(bs, window_i * WINDOW_SIZE, WINDOW_SIZE);
+                /* We *must* drop the given metadata types from the list, no
+                 * matter what; therefore, the best thing we can do is empty
+                 * the fragment list */
+                g_free(window->fragments);
+                window->fragments = NULL;
+                window->nb_fragments = 0;
+                window->fragments_array_size = 0;
+                goto next_window;
+            }
         }
 
         for (bitmap_i = bitmap_i_start; bitmap_i < bitmap_i_end; bitmap_i++) {
@@ -330,12 +431,14 @@ void qcow2_metadata_list_remove(BlockDriverState *bs, uint64_t offset,
         window->age = s->metadata_list->current_age++;
         window->bitmap_modified = true;
 
+next_window:
         /* Go to the next window */
         current_cluster += WINDOW_SIZE - bitmap_i_start;
     }
 }
 
-static int single_check_metadata_overlap(Qcow2MetadataList *mdl, int ign,
+static int single_check_metadata_overlap(BlockDriverState *bs,
+                                         Qcow2MetadataList *mdl, int ign,
                                          uint64_t cluster)
 {
     uint64_t window_i = cluster / WINDOW_SIZE;
@@ -348,7 +451,10 @@ static int single_check_metadata_overlap(Qcow2MetadataList *mdl, int ign,
     window = &mdl->windows[window_i];
 
     if (!window->bitmap) {
-        build_window_bitmap(mdl, window);
+        if (!build_window_bitmap(mdl, window)) {
+            signal_memory_excess(bs, window_i * WINDOW_SIZE, WINDOW_SIZE);
+            return 0;
+        }
     }
 
     window->age = mdl->current_age++;
@@ -368,7 +474,7 @@ int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
     for (current_cluster = start_cluster; current_cluster < end_cluster;
          current_cluster++)
     {
-        ret |= single_check_metadata_overlap(s->metadata_list, ign,
+        ret |= single_check_metadata_overlap(bs, s->metadata_list, ign,
                                              current_cluster);
     }
 
@@ -376,16 +482,33 @@ int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
 }
 
 int qcow2_create_empty_metadata_list(BlockDriverState *bs, size_t cache_size,
-                                     Error **errp)
+                                     size_t max_total_mem_size, Error **errp)
 {
     BDRVQcowState *s = bs->opaque;
     int ret;
     size_t cache_entries, i;
 
+    if (max_total_mem_size < sizeof(Qcow2MetadataList)) {
+        error_setg(errp, "Cannot allocate metadata list");
+        ret = -ENOMEM;
+        goto fail;
+    }
+
     s->metadata_list = g_new0(Qcow2MetadataList, 1);
+    s->metadata_list->max_mem_usage = max_total_mem_size;
+    s->metadata_list->mem_usage = sizeof(Qcow2MetadataList);
+
     s->metadata_list->nb_windows =
         DIV_ROUND_UP(bdrv_nb_sectors(bs->file),
                      (uint64_t)s->cluster_sectors * WINDOW_SIZE);
+    if (!increase_mdl_mem_usage(s->metadata_list, sizeof(Qcow2MetadataWindow),
+                                s->metadata_list->nb_windows))
+    {
+        error_setg(errp, "Cannot allocate metadata overlap check windows");
+        ret = -ENOMEM;
+        goto fail;
+    }
+
     s->metadata_list->windows = g_try_new0(Qcow2MetadataWindow,
                                            s->metadata_list->nb_windows);
     if (s->metadata_list->nb_windows && !s->metadata_list->windows) {
@@ -404,6 +527,12 @@ int qcow2_create_empty_metadata_list(BlockDriverState *bs, size_t cache_size,
     }
 
     s->metadata_list->nb_cached_windows = cache_entries;
+    if (!increase_mdl_mem_usage(s->metadata_list, sizeof(int), cache_entries)) {
+        error_setg(errp, "Cannot allocate metadata overlap cache pointers");
+        ret = -ENOMEM;
+        goto fail;
+    }
+
     s->metadata_list->cached_windows = g_try_new(int, cache_entries);
     if (!s->metadata_list->cached_windows) {
         error_setg(errp, "Could not allocate metadata overlap cache pointers");
block/qcow2.c +1 -1
index 4e7005e..fbf4d6f 100644
@@ -760,7 +760,7 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
 
     if (s->overlap_check) {
         /* TODO: Let the user override this default */
-        ret = qcow2_create_empty_metadata_list(bs, 65536, errp);
+        ret = qcow2_create_empty_metadata_list(bs, 65536, SIZE_MAX, errp);
         if (ret < 0) {
             goto fail;
         }
block/qcow2.h +1 -1
index 4a5530b..cbb932a 100644
@@ -594,7 +594,7 @@ int qcow2_cache_put(BlockDriverState *bs, Qcow2Cache *c, void **table);
 
 /* qcow2-overlap.c functions */
 int qcow2_create_empty_metadata_list(BlockDriverState *bs, size_t cache_size,
-                                     Error **errp);
+                                     size_t max_total_mem_size, Error **errp);
 void qcow2_metadata_list_destroy(BlockDriverState *bs);
 void qcow2_metadata_list_enter(BlockDriverState *bs, uint64_t offset,
                                int nb_clusters, QCow2MetadataOverlap type);
Signature · 1 line
2.3.7
author
#18 lore raw

PATCH v4 16/17 qapi: Expose new qcow2 overlap check options

In reply to Max Reitz

Expose the two new options for controlling the memory usage of the overlap check implementation via QAPI.

---
 qapi/block-core.json | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
qapi/block-core.json +37 -0
index 1c17224..99456e6 100644
@@ -1509,6 +1509,39 @@
             'mode':  'Qcow2OverlapCheckMode' } }
 
 ##
+# @Qcow2OverlapStructures
+#
+# Contains options for controlling the behavior of the metadata overlap
+# prevention structures.
+#
+# The primary structure used for overlap check and prevention is a bitmap
+# (actually a bytemap) which has one entry per cluster designating the type(s)
+# of metadata it contains. In order to save memory, there is an RLE-like
+# representation of this bitmap, too.
+#
+# The whole array of clusters is chunked. The RLE representation of one chunk
+# is converted to the equivalent bitmap whenever a cluster in the chunk is
+# accessed. The bitmaps are kept for a limited number of chunks (as a cache). On
+# cache eviction, the bitmap is converted back to RLE again.
+#
+# @bitmap-size:      #optional size (in bytes) of the bitmap cache, defaults to
+#                    64 kB
+#
+# @total-size-limit: #optional maximum total size (in bytes) of all the metadata
+#                    overlap prevention data structures combined; if this limit
+#                    is exceeded, a QCOW2_OVERLAP_CHECK_MEMORY_LIMIT_REACHED
+#                    event will be emitted and some parts of the image may no
+#                    longer be protected against erroneous overwriting of
+#                    metadata by (meta)data of a different kind. Defaults to
+#                    SIZE_MAX.
+#
+# Since: 2.4
+##
+{ 'type': 'Qcow2OverlapStructures',
+  'data': { '*bitmap-size':      'int',
+            '*total-size-limit': 'int' } }
+
+##
 # @BlockdevOptionsQcow2
 #
 # Driver specific block device options for qcow2.
@@ -1530,6 +1563,9 @@
 # @overlap-check:         #optional which overlap checks to perform for writes
 #                         to the image, defaults to 'cached' (since 2.2)
 #
+# @overlap-structures:    #optional options for controlling the behavior of the
+#                         metadata overlap prevention structures (since 2.4)
+#
 # @cache-size:            #optional the maximum total size of the L2 table and
 #                         refcount block caches in bytes (since 2.2)
 #
@@ -1548,6 +1584,7 @@
             '*pass-discard-snapshot': 'bool',
             '*pass-discard-other': 'bool',
             '*overlap-check': 'Qcow2OverlapChecks',
+            '*overlap-structures': 'Qcow2OverlapStructures',
             '*cache-size': 'int',
             '*l2-cache-size': 'int',
             '*refcount-cache-size': 'int' } }
Signature · 1 line
2.3.7
author
#21 lore raw

PATCH v4 17/17 iotests: Test qcow2's overlap check memory limit

In reply to Max Reitz

This patch adds some test cases for the memory limit concerning the in-memory structures used to detect and prevent accidental metadata overlaps.

---
 tests/qemu-iotests/060     | 222 +++++++++++++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/060.out |  47 ++++++++++
 tests/qemu-iotests/group   |   2 +-
 3 files changed, 270 insertions(+), 1 deletion(-)
tests/qemu-iotests/060 +222 -0
index c81319c..b0bc86a 100755
@@ -37,6 +37,7 @@ trap "_cleanup; exit \$status" 0 1 2 3 15
 # get standard environment, filters and checks
 . ./common.rc
 . ./common.filter
+. ./common.qemu
 
 # This tests qocw2-specific low-level functionality
 _supported_fmt qcow2
@@ -243,6 +244,227 @@ poke_file "$TEST_IMG" "$(($l2_offset+8))" "\x80\x00\x00\x00\x00\x06\x2a\x00"
 # Should emit two error messages
 $QEMU_IO -c "discard 0 64k" -c "read 64k 64k" "$TEST_IMG" | _filter_qemu_io
 
+echo
+echo "=== Testing memory limit ==="
+echo
+
+_make_test_img 64M
+# Use blockdev-add instead of adding the drive at startup, so that events which
+# are generated when the image is opened will be sent over QMP
+_launch_qemu
+_send_qemu_cmd $QEMU_HANDLE "{ 'execute': 'qmp_capabilities' }" 'return'
+
+echo
+echo '--- Zero limit ---'
+echo
+
+# This should fail (because allocating the metadata structure list itself fails)
+_send_qemu_cmd $QEMU_HANDLE \
+    "{ 'execute': 'blockdev-add'," \
+    "  'arguments': {" \
+    "      'options': {" \
+    "          'id': 'drv0'," \
+    "          'driver': 'qcow2'," \
+    "          'overlap-structures': {" \
+    "              'total-size-limit': 0" \
+    "          }," \
+    "          'file': {" \
+    "             'driver': 'file'," \
+    "             'filename': '$TEST_IMG'" \
+    "          } } } }" \
+    'error'
+
+echo
+echo '--- Zero limit with overlap checks disabled ---'
+echo
+
+# This should work (because overlap checks are disabled)
+_send_qemu_cmd $QEMU_HANDLE \
+    "{ 'execute': 'blockdev-add'," \
+    "  'arguments': {" \
+    "      'options': {" \
+    "          'id': 'drv1'," \
+    "          'driver': 'qcow2'," \
+    "          'overlap-check': 'none'," \
+    "          'overlap-structures': {" \
+    "              'total-size-limit': 0" \
+    "          }," \
+    "          'file': {" \
+    "             'driver': 'file'," \
+    "             'filename': '$TEST_IMG'" \
+    "          } } } }" \
+    'return'
+
+echo
+echo '--- Limit too small for entering metadata ---'
+echo
+
+# For the initial metadata structures, the following data is required:
+#  - Qcow2MetadataList (32 B on x86, 56 B on x64)
+#  - nb_windows * Qcow2MetadataWindow (nb_windows is
+#    ceil(x / (64k * WINDOW_SIZE)) = 1 (WINDOW_SIZE = 4096; x is the size of the
+#    underlying file, which is probably below 1 MB)); therefore, this is 24 B on
+#    x86, and 32 B on x64)
+#  - cache_entries * int (cache_entries is cache_size / WINDOW_SIZE =
+#    65536 / 4096 = 16, therefore this is 64 B on both x86 and x64)
+# In total, we need 120 B on x86 and 152 B on x64 (Linux/gcc).
+#
+# Creating a single bytemap takes WINDOW_SIZE (4096) B. Therefore, setting the
+# limit to 256 B will definitely suffice for the structures required to create
+# the metadata structures, but trying to enter even a single metadata structure
+# will fail.
+# The "start" field of the event(s) generated will be 0; the "length" field will
+# be WINDOW_SIZE * cluster_size = 4096 * 64k = 256M.
+_send_qemu_cmd $QEMU_HANDLE \
+    "{ 'execute': 'blockdev-add'," \
+    "  'arguments': {" \
+    "      'options': {" \
+    "          'id': 'drv2'," \
+    "          'driver': 'qcow2'," \
+    "          'overlap-structures': {" \
+    "              'bitmap-size': 65536," \
+    "              'total-size-limit': 256" \
+    "          }," \
+    "          'file': {" \
+    "             'driver': 'file'," \
+    "             'filename': '$TEST_IMG'" \
+    "          } } } }" \
+    'return'
+
+_cleanup_qemu
+
+echo
+echo '--- Limit too small for both bitmap and fragment list ---'
+echo
+
+# Now test the case of trying to convert the bitmap back to the fragment list,
+# but where memory does not suffice to hold both. Because the bitmap is released
+# after the fragment list has been created, it should work anyway, because the
+# implementation can consider the bitmap freed before it is actually freed.
+# In order for this to work on both x86 and x64, the fragment list needs to take
+# up more than 32 B (152 - 120) of memory. Every entry has 4 B, so we need 9
+# entries. One is the image header, then there is the L1 table, the refcount
+# table, a refcount block, and then there are more than 1000 free clusters; a
+# maximum of 256 clusters can be represented by a single fragment, so these are
+# another 4 entries. In total, there are thus 8 entries so far, so we need
+# another one, which we can do by writing data and thus creating an L2 table.
+$QEMU_IO -c 'write 0 64k' "$TEST_IMG" | _filter_qemu_io
+
+# Also, we need to point to an offset beyond WINDOW_SIZE * cluster_size (256M),
+# so that we can make qcow2 evict the first window.
+poke_file "$TEST_IMG" "$(($l2_offset+8))" "\x80\x00\x00\x00\x10\x00\x00\x00"
+
+_launch_qemu
+_send_qemu_cmd $QEMU_HANDLE "{ 'execute': 'qmp_capabilities' }" 'return'
+
+# For the planned cache eviction to work, bitmap-size must be WINDOW_SIZE;
+# therefore, the initial metadata structure size shrinks by 15 * sizeof(int),
+# that is, 60 B on both x86 and x64.
+# The total-size-limit should thus be 92 + 4096 = 4188
+_send_qemu_cmd $QEMU_HANDLE \
+    "{ 'execute': 'blockdev-add'," \
+    "  'arguments': {" \
+    "      'options': {" \
+    "          'id': 'drv0'," \
+    "          'driver': 'qcow2'," \
+    "          'overlap-structures': {" \
+    "              'bitmap-size': 4096," \
+    "              'total-size-limit': 4188" \
+    "          }," \
+    "          'file': {" \
+    "             'driver': 'file'," \
+    "             'filename': '$TEST_IMG'" \
+    "          } } } }" \
+    'return'
+
+# Writing something to the second data cluster, thus making qemu load the second
+# metadata window, evicting the first one
+_send_qemu_cmd $QEMU_HANDLE \
+    "{ 'execute': 'human-monitor-command'," \
+    "  'arguments': { 'command-line': 'qemu-io drv0 \"write 64k 64k\"' } }" \
+    'return'
+
+_cleanup_qemu
+
+echo
+echo '--- Fragment list is larger than bitmap ---'
+echo
+
+# Finally, test that bitmaps are not converted to fragment lists if the fragment
+# list actually is longer than the bitmap.
+CLUSTER_SIZE=512 _make_test_img 64M
+
+# Every L2 table describes 512 / 8 = 64 clusters, that is, a range of 32k.
+# Therefore, writing clusters 32k apart results in a alternating pattern of
+# L2 table and data cluster. If we write 1024 clusters in this way, the fragment
+# list for the first window would therefore have to contain at least 2048
+# fragments, which is longer (8 kB) than the bitmap is (4 kB fixed). Therefore,
+# the fragment list should not be generated on cache eviction.
+(for i in $(seq 0 1023); do
+    echo "write $(($i*32))k 512"
+done) | $QEMU_IO -t unsafe "$TEST_IMG" &> /dev/null
+
+l2_offset_512=$((0x4600))
+
+# Now point the first data cluster to WINDOW_SIZE * 512 = 2M
+# (the image length is about 2048 * 512 = 1M at this point)
+poke_file "$TEST_IMG" "$(($l2_offset_512))" "\x80\x00\x00\x00\x00\x20\x00\x00"
+# (the first cluster is now leaked, but who cares)
+
+# "Allocate" that cluster
+$QEMU_IO -c 'write 0 512' "$TEST_IMG" | _filter_qemu_io
+
+# And point the second data cluster to the first L2 table so we can test whether
+# the overlap check still works
+poke_file "$TEST_IMG" "$(($l2_offset_512+8))" "\x80\x00\x00\x00\x00\x00\x46\x00"
+
+cp "$TEST_IMG" /tmp
+
+_launch_qemu
+_send_qemu_cmd $QEMU_HANDLE "{ 'execute': 'qmp_capabilities' }" 'return'
+
+# Memory which we will allow to be allocated:
+#  - Qcow2MetadataList (32 B on x86, 56 B on x64)
+#  - nb_windows * Qcow2MetadataWindow (nb_windows is 2, because we made sure
+#    that we would have an image with two windows; therefore, this is 48 B on
+#    x86, and 64 B on x64)
+#  - cache_entries * int (cache_entries is cache_size / WINDOW_SIZE =
+#    4096 / 4096 = 1, therefore this is 4 B on both x86 and x64)
+#  - One bitmap (WINDOW_SIZE = 4096 B)
+# In total, that is 4220 B at most. If the bytemap would be converted to the
+# according fragment list, it would require 8 kB, which is definitely more.
+_send_qemu_cmd $QEMU_HANDLE \
+    "{ 'execute': 'blockdev-add'," \
+    "  'arguments': {" \
+    "      'options': {" \
+    "          'id': 'drv0'," \
+    "          'driver': 'qcow2'," \
+    "          'overlap-structures': {" \
+    "              'bitmap-size': 4096," \
+    "              'total-size-limit': 4220" \
+    "          }," \
+    "          'file': {" \
+    "             'driver': 'file'," \
+    "             'filename': '$TEST_IMG'" \
+    "          } } } }" \
+    'return'
+
+# Force cache eviction by accessing a cluster in the second window
+# (This will result in a "memory limit reached" event because there is no space
+# for the second bitmap)
+_send_qemu_cmd $QEMU_HANDLE \
+    "{ 'execute': 'human-monitor-command'," \
+    "  'arguments': { 'command-line': 'qemu-io drv0 \"write 0 512\"' } }" \
+    'return'
+
+# Trigger the overlap prevention
+_send_qemu_cmd $QEMU_HANDLE \
+    "{ 'execute': 'human-monitor-command'," \
+    "  'arguments': { 'command-line': 'qemu-io drv0 \"write 512 512\"' } }" \
+    'return'
+
+_cleanup_qemu
+
 # success, all done
 echo "*** done"
 rm -f $seq.full
tests/qemu-iotests/060.out +47 -0

51 lines not on this page · raw message

tests/qemu-iotests/group +1 -1
index 6ca3466..5f35d1e 100644
@@ -66,7 +66,7 @@
 057 rw auto
 058 rw auto quick
 059 rw auto quick
-060 rw auto quick
+060 rw auto
 061 rw auto
 062 rw auto quick
 063 rw auto quick
Signature · 1 line
2.3.7
#14 lore raw

Re: [Qemu-devel] [PATCH v4 13/17] qcow2/overlaps: Add "memory limit reached" event

In reply to Max Reitz
Quoted 14 lines · Max Reitz

Later, a mechanism to set a limit on how much memory may be used for the overlap prevention structures will be introduced. If that limit is about to be exceeded, a QMP event should be emitted. This very event is specified by this patch.

---
 docs/qmp/qmp-events.txt | 28 ++++++++++++++++++++++++++++
 qapi/event.json         | 27 +++++++++++++++++++++++++++
 2 files changed, 55 insertions(+)
docs/qmp/qmp-events.txt +3 -0
+
+Data:
+- "reference": Device name if set; node name otherwise. (json-string)

docs/qmp/qmp-events.txt Example: · line 289

Quoted 10 lines
docs/qmp/qmp-events.txt +10 -0
+- "start":     Offset of the range of clusters (possibly) no longer being
+               checked for writes overlapping with existing metadata.
+               (json-int, optional)
+- "length":    Length of that range in bytes. (json-int, optional)
+
+Example:
+
+{ "event": "QCOW2_OVERLAP_CHECK_MEMORY_LIMIT_REACHED",
+    "data": { "reference": "virtio0", "start": "805306368",
+              "length": "268435456" },

s/"805306368"/805306368/ and likewise for length (a json-int does not use quotes).

Otherwise seems okay.

Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
#19 lore raw

Re: [Qemu-devel] [PATCH v4 16/17] qapi: Expose new qcow2 overlap check options

In reply to Max Reitz
Quoted 20 lines · Max Reitz

Expose the two new options for controlling the memory usage of the overlap check implementation via QAPI.

---
 qapi/block-core.json | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
qapi/block-core.json +4 -0
index 1c17224..99456e6 100644
@@ -1509,6 +1509,39 @@
             'mode':  'Qcow2OverlapCheckMode' } }
 
 ##
+# @Qcow2OverlapStructures
+#
+# Contains options for controlling the behavior of the metadata overlap
+# prevention structures.

qapi/block-core.json line 1525

Quoted 10 lines
qapi/block-core.json +10 -0
+#
+# The primary structure used for overlap check and prevention is a bitmap
+# (actually a bytemap) which has one entry per cluster designating the type(s)
+# of metadata it contains. In order to save memory, there is an RLE-like
+# representation of this bitmap, too.
+#
+# The whole array of clusters is chunked. The RLE representation of one chunk
+# is converted to the equivalent bitmap whenever a cluster in the chunk is
+# accessed. The bitmaps are kept for a limited number of chunks (as a cache). On
+# cache eviction, the bitmap is converted back to RLE again.

Feels a bit verbose at describing the internal representation, especially if we change the internals at some point in the future. I'm more interested that there are two limits at play, and that tuning them larger may consume more memory but offer better protection on large images.

qapi/block-core.json line 1529

Quoted 4 lines
qapi/block-core.json +4 -0
+#
+# @bitmap-size:      #optional size (in bytes) of the bitmap cache, defaults to
+#                    64 kB
+#

Any requirement on it being a power of 2, or even a recommendation on how large or small to make it in relation to an image size?

qapi/block-core.json line 1530

Quoted 1 line
qapi/block-core.json +1 -0
+# @total-size-limit: #optional maximum total size (in bytes) of all the metadata

What happens if bitmap-size is larger than total-size-limit?

qapi/block-core.json line 1540

Quoted 10 lines
qapi/block-core.json +10 -0
+#                    overlap prevention data structures combined; if this limit
+#                    is exceeded, a QCOW2_OVERLAP_CHECK_MEMORY_LIMIT_REACHED
+#                    event will be emitted and some parts of the image may no
+#                    longer be protected against erroneous overwriting of
+#                    metadata by (meta)data of a different kind. Defaults to
+#                    SIZE_MAX.
+#
+# Since: 2.4
+##
+{ 'type': 'Qcow2OverlapStructures',

Rebase conflict with my series that does s/type/struct/

Quoted 26 lines
qapi/block-core.json +8 -0
+  'data': { '*bitmap-size':      'int',
+            '*total-size-limit': 'int' } }
+
+##
 # @BlockdevOptionsQcow2
 #
 # Driver specific block device options for qcow2.
@@ -1530,6 +1563,9 @@
 # @overlap-check:         #optional which overlap checks to perform for writes
 #                         to the image, defaults to 'cached' (since 2.2)
 #
+# @overlap-structures:    #optional options for controlling the behavior of the
+#                         metadata overlap prevention structures (since 2.4)
+#
 # @cache-size:            #optional the maximum total size of the L2 table and
 #                         refcount block caches in bytes (since 2.2)
 #
@@ -1548,6 +1584,7 @@
             '*pass-discard-snapshot': 'bool',
             '*pass-discard-other': 'bool',
             '*overlap-check': 'Qcow2OverlapChecks',
+            '*overlap-structures': 'Qcow2OverlapStructures',
             '*cache-size': 'int',
             '*l2-cache-size': 'int',
             '*refcount-cache-size': 'int' } }
Signature · 2 lines
Eric Blake   eblake redhat com    +1-919-301-3266
Libvirt virtualization library http://libvirt.org
author
#15 lore raw

Re: [Qemu-devel] [PATCH v4 13/17] qcow2/overlaps: Add "memory limit reached" event

In reply to Eric Blake
Quoted 18 lines · Eric Blake
Quoted 17 lines · Max Reitz

Later, a mechanism to set a limit on how much memory may be used for the overlap prevention structures will be introduced. If that limit is about to be exceeded, a QMP event should be emitted. This very event is specified by this patch.

---
  docs/qmp/qmp-events.txt | 28 ++++++++++++++++++++++++++++
  qapi/event.json         | 27 +++++++++++++++++++++++++++
  2 files changed, 55 insertions(+)
docs/qmp/qmp-events.txt +7 -0
+
+Data:
+- "reference": Device name if set; node name otherwise. (json-string)
+- "start":     Offset of the range of clusters (possibly) no longer being
+               checked for writes overlapping with existing metadata.
+               (json-int, optional)
+- "length":    Length of that range in bytes. (json-int, optional)
Quoted 8 lines

docs/qmp/qmp-events.txt Example: · line 289

Quoted 6 lines
docs/qmp/qmp-events.txt +6 -0
+
+Example:
+
+{ "event": "QCOW2_OVERLAP_CHECK_MEMORY_LIMIT_REACHED",
+    "data": { "reference": "virtio0", "start": "805306368",
+              "length": "268435456" },

s/"805306368"/805306368/ and likewise for length (a json-int does not use quotes).

Oops, right. Will fix.

Quoted 1 line

Otherwise seems okay.

Good, thanks :-)

Max

author
#20 lore raw

Re: [Qemu-devel] [PATCH v4 16/17] qapi: Expose new qcow2 overlap check options

In reply to Eric Blake
Quoted 27 lines · Eric Blake
Quoted 26 lines · Max Reitz

Expose the two new options for controlling the memory usage of the overlap check implementation via QAPI.

---
  qapi/block-core.json | 37 +++++++++++++++++++++++++++++++++++++
  1 file changed, 37 insertions(+)
qapi/block-core.json +10 -0
index 1c17224..99456e6 100644
@@ -1509,6 +1509,39 @@
              'mode':  'Qcow2OverlapCheckMode' } }
 
  ##
+# @Qcow2OverlapStructures
+#
+# Contains options for controlling the behavior of the metadata overlap
+# prevention structures.
+#
+# The primary structure used for overlap check and prevention is a bitmap
+# (actually a bytemap) which has one entry per cluster designating the type(s)
+# of metadata it contains. In order to save memory, there is an RLE-like
+# representation of this bitmap, too.
+#
Quoted 8 lines

qapi/block-core.json line 1525

Quoted 4 lines
qapi/block-core.json +4 -0
+# The whole array of clusters is chunked. The RLE representation of one chunk
+# is converted to the equivalent bitmap whenever a cluster in the chunk is
+# accessed. The bitmaps are kept for a limited number of chunks (as a cache). On
+# cache eviction, the bitmap is converted back to RLE again.

Feels a bit verbose at describing the internal representation, especially if we change the internals at some point in the future. I'm more interested that there are two limits at play, and that tuning them larger may consume more memory but offer better protection on large images.

Well, that works for total-size-limit, but it won't work as an explanation for bitmap-size. I could rename it to cache-size and just say that it's the size of some (opaque) internal cache, though.

Quoted 6 lines

qapi/block-core.json line 1529

Quoted 4 lines
qapi/block-core.json +4 -0
+#
+# @bitmap-size:      #optional size (in bytes) of the bitmap cache, defaults to
+#                    64 kB
+#

Any requirement on it being a power of 2, or even a recommendation on how large or small to make it in relation to an image size?

No requirements and I can't give recommendations. We do have a fixed default for the metadata caches (refcount blocks and L2 tables), too, and this is basically the same thing when it comes to choosing the right size. For a large image, you have multiple e.g. L2 tables and also multiple windows concerning the overlap checks; therefore, if you have a lot of totally random accesses, both caches will fail. Considering that we seem to have accepted this for the metadata caches, I think it should be fine here, too.

Quoted 2 lines

qapi/block-core.json line 1530

Quoted 1 line
qapi/block-core.json +1 -0
+# @total-size-limit: #optional maximum total size (in bytes) of all the metadata

What happens if bitmap-size is larger than total-size-limit?

Interesting question. Well, what does happen is that at some point it tries to create a bitmap for the cache, and that will fail due to the size limit, so the event will get thrown. The problem is that accessing any area of the qcow2 file which does not yet have an entry in the bitmap cache will result in hitting the limit, so there is no protection for these areas.

The problem is that it's difficult to give a limit for the ratio of bitmap-size to total-size-limit which always works. A fragments list (the RLE representation) will never exceed the bitmap in size, so using 0.5 as the maximum ratio seems to make sense. However, there are other structures as well, such as the array of windows which depends on the size of the qcow2 file, so depending on the file, the maximum ratio may get infinitely small.

So I guess the best thing to do would be to detect the limit excess condition when creating a new bitmap, and then instead of trying to occupy a previously empty cache entry, evict a non-empty one (repeat until there is enough memory available, or the cache is empty, in which case it is justified to complain about hitting the memory limit).

Quoted 12 lines

qapi/block-core.json line 1540

Quoted 11 lines
qapi/block-core.json +10 -0
+#                    overlap prevention data structures combined; if this limit
+#                    is exceeded, a QCOW2_OVERLAP_CHECK_MEMORY_LIMIT_REACHED
+#                    event will be emitted and some parts of the image may no
+#                    longer be protected against erroneous overwriting of
+#                    metadata by (meta)data of a different kind. Defaults to
+#                    SIZE_MAX.
+#
+# Since: 2.4
+##
+{ 'type': 'Qcow2OverlapStructures',

Rebase conflict with my series that does s/type/struct/

Will fix.

Thanks for reviewing,

Max

Quoted 26 lines
Quoted 26 lines
qapi/block-core.json +8 -0
+  'data': { '*bitmap-size':      'int',
+            '*total-size-limit': 'int' } }
+
+##
  # @BlockdevOptionsQcow2
  #
  # Driver specific block device options for qcow2.
@@ -1530,6 +1563,9 @@
  # @overlap-check:         #optional which overlap checks to perform for writes
  #                         to the image, defaults to 'cached' (since 2.2)
  #
+# @overlap-structures:    #optional options for controlling the behavior of the
+#                         metadata overlap prevention structures (since 2.4)
+#
  # @cache-size:            #optional the maximum total size of the L2 table and
  #                         refcount block caches in bytes (since 2.2)
  #
@@ -1548,6 +1584,7 @@
              '*pass-discard-snapshot': 'bool',
              '*pass-discard-other': 'bool',
              '*overlap-check': 'Qcow2OverlapChecks',
+            '*overlap-structures': 'Qcow2OverlapStructures',
              '*cache-size': 'int',
              '*l2-cache-size': 'int',
              '*refcount-cache-size': 'int' } }