Skip to contentSkip to conversation

block: Deal with filters

PATCH Superseded Max Reitz 4 participants 136 messages Aug 9, 2019 – Dec 11, 2019 Block layer Page 2 of 2

v6 of 8 Superseded Latest is v8 →

lore
Share & tools
lore
author
#119 lore raw

Re: [Qemu-devel] [PATCH v6 35/42] block: Fix check_to_replace_node()

In reply to Vladimir Sementsov-Ogievskiy
Quoted 121 lines · Vladimir Sementsov-Ogievskiy
Quoted 108 lines · Max Reitz
Quoted 107 lines · Vladimir Sementsov-Ogievskiy
Quoted 92 lines · Max Reitz

Currently, check_to_replace_node() only allows mirror to replace a node in the chain of the source node, and only if it is the first non-filter node below the source. Well, technically, the idea is that you can exactly replace a quorum child by mirroring from quorum.

This has (probably) two reasons:
(1) We do not want to create loops.
(2) @replaces and @device should have exactly the same content so replacing them does not cause visible data to change.

This has two issues:
(1) It is overly restrictive. It is completely fine for @replaces to be a filter.
(2) It is not restrictive enough. You can create loops with this as follows:

$ qemu-img create -f qcow2 /tmp/source.qcow2 64M
$ qemu-system-x86_64 -qmp stdio
{"execute": "qmp_capabilities"}
{"execute": "object-add",
   "arguments": {"qom-type": "throttle-group", "id": "tg0"}}
{"execute": "blockdev-add",
   "arguments": {
       "node-name": "source",
       "driver": "throttle",
       "throttle-group": "tg0",
       "file": {
           "node-name": "filtered",
           "driver": "qcow2",
           "file": {
               "driver": "file",
               "filename": "/tmp/source.qcow2"
           } } } }
{"execute": "drive-mirror",
   "arguments": {
       "job-id": "mirror",
       "device": "source",
       "target": "/tmp/target.qcow2",
       "format": "qcow2",
       "node-name": "target",
       "sync" :"none",
       "replaces": "filtered"
   } }
{"execute": "block-job-complete", "arguments": {"device": "mirror"}}

And qemu crashes because of a stack overflow due to the loop being created (target's backing file is source, so when it replaces filtered, it points to itself through source).

(blockdev-mirror can be broken similarly.)

So let us make the checks for the two conditions above explicit, which makes the whole function exactly as restrictive as it needs to be.

---
   include/block/block.h |  1 +
   block.c               | 83 +++++++++++++++++++++++++++++++++++++++----
   blockdev.c            | 34 ++++++++++++++++--
   3 files changed, 110 insertions(+), 8 deletions(-)
include/block/block.h +1 -0
index 6ba853fb90..8da706cd89 100644
@@ -404,6 +404,7 @@ bool bdrv_is_first_non_filter(BlockDriverState *candidate);
 
   /* check if a named node can be replaced when doing drive-mirror */
   BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
+                                        BlockDriverState *backing_bs,
                                           const char *node_name, Error **errp);
 
   /* async block I/O */
block.c +11 -0
index 915b80153c..4858d3e718 100644
@@ -6290,7 +6290,59 @@ bool bdrv_is_first_non_filter(BlockDriverState *candidate)
       return false;
   }
 
+static bool is_child_of(BlockDriverState *child, BlockDriverState *parent)
+{
+    BdrvChild *c;
+
+    if (!parent) {
+        return false;
+    }
+
+    QLIST_FOREACH(c, &parent->children, next) {
+        if (c->bs == child || is_child_of(child, c->bs)) {
+            return true;

block.c bool bdrv_is_first_non_filter(BlockDriverState *candidate) · line 6313

Quoted 10 lines
block.c +10 -0
+        }
+    }
+
+    return false;
+}
+
+/*
+ * Return true if there are only filters in [@top, @base).  Note that
+ * this may include quorum (which bdrv_chain_contains() cannot
+ * handle).

More presizely: return true if exists chain of filters from top to base or if top == base.

Quoted 7 lines
Quoted 4 lines

I keep in mind backup-top filter:

[backup-top]
| \target

backup-top can’t be a filter if it has two children with different contents, though.

Why? target is special child, unrelated to what is read/written over backup-top. It's an own business of backup-top.

Quoted 1 line
Quoted 5 lines
Quoted 1 line

(commit-top and mirror-top aren’t filters either.)

Ahm, I missed something. They have is_filter = true and their children considered to be filtered-rw children in your series? And than, who they are? Format nodes? And how they appears in backing chains than?

Er, right, I remember, I made them filters in patch 1 of this series. m( :-)

But the chain would still be unique, in a sense, because backup-top only has one filtered child, so you could go down the chain with bdrv_filtered_rw_child().

This function doesn’t do that because of Quorum, which is actually a better example. All of its children are filtered, so we must consider all of them.

But backup-top is actually a reason why this function is wrong as it is; the target is not a filtered child, so it shouldn’t return true there.

Hmmmm.

Actually, bdrv_recurse_is_first_non_filter() does nearly what we want. (Which is why it was used here.) The only problem is that it expects @candidate to be a non-filter (as the name implies). But we don’t care about that, actually.

I suppose I can just turn bdrv_recurse_is_first_non_filter() into bdrv_is_child_of(); it has only two callers, one is here, the other is bdrv_is_first_non_filter(). In the latter, we can just check whether @candidate is a filter and return false if it isn’t.

Quoted 76 lines
Quoted 76 lines

That’s why there must be a unique chain [@top, @base).

I should probably not that it will return true if top == base, though, yes.

Quoted 47 lines

|backing -------->[target]
V /
[source] <---------/backing

Quoted 12 lines
block.c +12 -0
+ */
+static bool is_filtered_child(BlockDriverState *top, BlockDriverState *base)
+{
+    BdrvChild *c;
+
+    if (!top) {
+        return false;
+    }
+
+    if (top == base) {
+        return true;
+    }

block.c bool bdrv_is_first_non_filter(BlockDriverState *candidate) · line 6335

Quoted 10 lines
block.c +10 -0
+
+    if (!top->drv->is_filter) {
+        return false;
+    }
+
+    QLIST_FOREACH(c, &top->children, next) {
+        if (is_filtered_child(c->bs, base)) {
+            return true;
+        }
+    }

interesting, how much is it better to somehow reuse DFS search written in should_update_child().. [just note, don't do it in these series please]

Quoted 17 lines
block.c +9 -0
+
+    return false;
+}
+
+/*
+ * @parent_bs is mirror's source BDS, @backing_bs is the BDS which
+ * will be attached to the target when mirror completes.
+ */
   BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
+                                        BlockDriverState *backing_bs,
                                           const char *node_name, Error **errp)
   {
       BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
@@ -6309,13 +6361,32 @@ BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
           goto out;
       }
 
Quoted 13 lines

block.c BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs, · line 6368

Quoted 11 lines
block.c +4 -6
-    /* We don't want arbitrary node of the BDS chain to be replaced only the top
-     * most non filter in order to prevent data corruption.
-     * Another benefit is that this tests exclude backing files which are
-     * blocked by the backing blockers.
+    /*
+     * If to_replace_bs is (recursively) a child of backing_bs,
+     * replacing it may create a loop.  We cannot allow that.
        */
-    if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
-        error_setg(errp, "Only top most non filter can be replaced");
+    if (to_replace_bs == backing_bs || is_child_of(to_replace_bs, backing_bs)) {

first condition is covered by second, so first may be omitted.

It is not. is_child_of() does not return true if child == parent.

Quoted 9 lines
Quoted 8 lines
block.c +8 -0
+        error_setg(errp, "Replacing this node would result in a loop");
+        to_replace_bs = NULL;
+        goto out;
+    }
+
+    /*
+     * Mirror is designed in such a way that when it completes, the
+     * source BDS is seamlessly replaced.
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Not source but to_replace_bs is replaced?

It has originally been designed to replace the source. If it could replace any arbitrary BDS, all of this would be moot.

quorum child, you saying about in commit message?

Which is not any arbitrary BDS, but one that looks exactly like the source.

My point is, mirror has been *designed* to replace the source seamlessly. It can do more things today, but that was its original point.

That means that the target must be exactly the same as the source. And then we come to this:

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

block.c BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs, · line 6383

Quoted 8 lines

It is therefore not allowed

block.c +7 -0
+     * to replace a BDS where this condition would be violated, as that
+     * would defeat the purpose of mirror and could lead to data
+     * corruption.
+     * Therefore, between parent_bs and to_replace_bs there may be
+     * only filters (and the one on top must be a filter, too), so
+     * their data always stays in sync and mirror can complete and
+     * replace to_replace_bs without any possible corruptions.

So replacing a node that’s connected to the source only through filters is fine because that means the replaced node will also have the same content as the source.

How about I replace the first paragraph with:

At the end of the mirror job, the target exhibits exactly the same content as the source, so it can replace the source node seamlessly. It cannot replace a BDS that differs in content, as that could lead to data corruption.

?

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
block.c +6 -0
+     */
+    if (!is_filtered_child(parent_bs, to_replace_bs) &&
+        !is_filtered_child(to_replace_bs, parent_bs))
+    {
+        error_setg(errp, "The node to be replaced must be connected to the "
+                   "source through filter nodes only");
Quoted 8 lines
Quoted 6 lines
Quoted 1 line

"and the one on top must be a filter, too" not mentioned in the error..

Well, unless the source node is the node to be replaced. Hm... This gets very hard to express. I think I’d prefer to keep this as it is, even though it is not quite correct, unless you have a better suggestion of what to report. :-/

I can't imaging something better than just add "(and the one on top must be a filter, too)"

The problem is that “the one on top” wouldn’t sound very clear to me as a user.

Maybe include the explanation à la “The node to be replaced must be connected to the source through filter nodes only, so its data is the exact same at all times”? Maybe then users can guess what this “connected” means exactly.

Quoted 40 lines
Quoted 40 lines
Quoted 39 lines
Quoted 27 lines
           to_replace_bs = NULL;
           goto out;
       }
blockdev.c +7 -2
index 4e72f6f701..758e0b5431 100644
@@ -3887,7 +3887,7 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
       }
 
       if (has_replaces) {
-        BlockDriverState *to_replace_bs;
+        BlockDriverState *to_replace_bs, *backing_bs;
           AioContext *replace_aio_context;
           int64_t bs_size, replace_size;
 
@@ -3897,7 +3897,37 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
               return;
           }
 
-        to_replace_bs = check_to_replace_node(bs, replaces, errp);
+        if (backing_mode == MIRROR_SOURCE_BACKING_CHAIN ||
+            backing_mode == MIRROR_OPEN_BACKING_CHAIN)
+        {
+            /*
+             * While we do not quite know what OPEN_BACKING_CHAIN
+             * (used for mode=existing) will yield, it is probably

blockdev.c static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs, · line 3915

Quoted 10 lines
blockdev.c +10 -0
+             * best to restrict it exactly like SOURCE_BACKING_CHAIN,
+             * because that is our best guess.
+             */
+            switch (sync) {
+            case MIRROR_SYNC_MODE_FULL:
+                backing_bs = NULL;
+                break;
+
+            case MIRROR_SYNC_MODE_TOP:
+                backing_bs = bdrv_filtered_cow_bs(bdrv_skip_rw_filters(bs));

why not bdrv_backing_chain_next(bs) like in mirror_start?

Quoted 4 lines
Quoted 2 lines

Good question. I suppose it should be bdrv_filtered_cow_bs(bdrv_backing_chain_next(bs)) in mirror_start()?

You mean bdrv_filtered_cow_bs(bdrv_skip_rw_filters(bs)), I hope)

Er, yes, sure.

Quoted 5 lines
Quoted 3 lines

Because with sync=top, we just want to remove the topmost COW node (and filters on top), but keep filters behind it.

Agreed.

OK.

Max

#120 lore raw

Re: [Qemu-devel] [PATCH v6 35/42] block: Fix check_to_replace_node()

Quoted 148 lines · Max Reitz
Quoted 121 lines · Vladimir Sementsov-Ogievskiy
Quoted 108 lines · Max Reitz
Quoted 107 lines · Vladimir Sementsov-Ogievskiy
Quoted 92 lines · Max Reitz

Currently, check_to_replace_node() only allows mirror to replace a node in the chain of the source node, and only if it is the first non-filter node below the source. Well, technically, the idea is that you can exactly replace a quorum child by mirroring from quorum.

This has (probably) two reasons:
(1) We do not want to create loops.
(2) @replaces and @device should have exactly the same content so replacing them does not cause visible data to change.

This has two issues:
(1) It is overly restrictive. It is completely fine for @replaces to be a filter.
(2) It is not restrictive enough. You can create loops with this as follows:

$ qemu-img create -f qcow2 /tmp/source.qcow2 64M
$ qemu-system-x86_64 -qmp stdio
{"execute": "qmp_capabilities"}
{"execute": "object-add",
    "arguments": {"qom-type": "throttle-group", "id": "tg0"}}
{"execute": "blockdev-add",
    "arguments": {
        "node-name": "source",
        "driver": "throttle",
        "throttle-group": "tg0",
        "file": {
            "node-name": "filtered",
            "driver": "qcow2",
            "file": {
                "driver": "file",
                "filename": "/tmp/source.qcow2"
            } } } }
{"execute": "drive-mirror",
    "arguments": {
        "job-id": "mirror",
        "device": "source",
        "target": "/tmp/target.qcow2",
        "format": "qcow2",
        "node-name": "target",
        "sync" :"none",
        "replaces": "filtered"
    } }
{"execute": "block-job-complete", "arguments": {"device": "mirror"}}

And qemu crashes because of a stack overflow due to the loop being created (target's backing file is source, so when it replaces filtered, it points to itself through source).

(blockdev-mirror can be broken similarly.)

So let us make the checks for the two conditions above explicit, which makes the whole function exactly as restrictive as it needs to be.

---
    include/block/block.h |  1 +
    block.c               | 83 +++++++++++++++++++++++++++++++++++++++----
    blockdev.c            | 34 ++++++++++++++++--
    3 files changed, 110 insertions(+), 8 deletions(-)
include/block/block.h +1 -0
index 6ba853fb90..8da706cd89 100644
@@ -404,6 +404,7 @@ bool bdrv_is_first_non_filter(BlockDriverState *candidate);
 
    /* check if a named node can be replaced when doing drive-mirror */
    BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
+                                        BlockDriverState *backing_bs,
                                            const char *node_name, Error **errp);
 
    /* async block I/O */
block.c +11 -0
index 915b80153c..4858d3e718 100644
@@ -6290,7 +6290,59 @@ bool bdrv_is_first_non_filter(BlockDriverState *candidate)
        return false;
    }
 
+static bool is_child_of(BlockDriverState *child, BlockDriverState *parent)
+{
+    BdrvChild *c;
+
+    if (!parent) {
+        return false;
+    }
+
+    QLIST_FOREACH(c, &parent->children, next) {
+        if (c->bs == child || is_child_of(child, c->bs)) {
+            return true;

block.c bool bdrv_is_first_non_filter(BlockDriverState *candidate) · line 6313

Quoted 10 lines
block.c +10 -0
+        }
+    }
+
+    return false;
+}
+
+/*
+ * Return true if there are only filters in [@top, @base).  Note that
+ * this may include quorum (which bdrv_chain_contains() cannot
+ * handle).

More presizely: return true if exists chain of filters from top to base or if top == base.

Quoted 7 lines
Quoted 4 lines

I keep in mind backup-top filter:

[backup-top]
| \target

backup-top can’t be a filter if it has two children with different contents, though.

Why? target is special child, unrelated to what is read/written over backup-top. It's an own business of backup-top.

Quoted 1 line
Quoted 5 lines
Quoted 1 line

(commit-top and mirror-top aren’t filters either.)

Ahm, I missed something. They have is_filter = true and their children considered to be filtered-rw children in your series? And than, who they are? Format nodes? And how they appears in backing chains than?

Er, right, I remember, I made them filters in patch 1 of this series. m( :-)

But the chain would still be unique, in a sense, because backup-top only has one filtered child, so you could go down the chain with bdrv_filtered_rw_child().

This function doesn’t do that because of Quorum, which is actually a better example. All of its children are filtered, so we must consider all of them.

But backup-top is actually a reason why this function is wrong as it is; the target is not a filtered child, so it shouldn’t return true there.

Hmmmm.

Actually, bdrv_recurse_is_first_non_filter() does nearly what we want. (Which is why it was used here.) The only problem is that it expects @candidate to be a non-filter (as the name implies). But we don’t care about that, actually.

Quoted 4 lines

I suppose I can just turn bdrv_recurse_is_first_non_filter() into bdrv_is_child_of(); it has only two callers, one is here, the other is bdrv_is_first_non_filter(). In the latter, we can just check whether @candidate is a filter and return false if it isn’t.

Wow, me go and see that bdrv_recurse_is_first_non_filter is something complicated backed by driver callback, different for different filters 0_O.. It seems to be a generator of some chain, which is not backing chain. Ohh

Hmm, but what you are proposing will break "_first_" part of interface: it maybe child of, an we may check is it filter or not, but how to check that it is exactly "first"? Ok, anyway if you are going to rewrite it somehow I can wait and than look at new patch to understand.

Quoted 106 lines
Quoted 77 lines
Quoted 77 lines

That’s why there must be a unique chain [@top, @base).

I should probably not that it will return true if top == base, though, yes.

Quoted 47 lines

|backing -------->[target]
V /
[source] <---------/backing

Quoted 12 lines
block.c +12 -0
+ */
+static bool is_filtered_child(BlockDriverState *top, BlockDriverState *base)
+{
+    BdrvChild *c;
+
+    if (!top) {
+        return false;
+    }
+
+    if (top == base) {
+        return true;
+    }

block.c bool bdrv_is_first_non_filter(BlockDriverState *candidate) · line 6335

Quoted 10 lines
block.c +10 -0
+
+    if (!top->drv->is_filter) {
+        return false;
+    }
+
+    QLIST_FOREACH(c, &top->children, next) {
+        if (is_filtered_child(c->bs, base)) {
+            return true;
+        }
+    }

interesting, how much is it better to somehow reuse DFS search written in should_update_child().. [just note, don't do it in these series please]

Quoted 17 lines
block.c +9 -0
+
+    return false;
+}
+
+/*
+ * @parent_bs is mirror's source BDS, @backing_bs is the BDS which
+ * will be attached to the target when mirror completes.
+ */
    BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
+                                        BlockDriverState *backing_bs,
                                            const char *node_name, Error **errp)
    {
        BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
@@ -6309,13 +6361,32 @@ BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
            goto out;
        }
 
Quoted 13 lines

block.c BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs, · line 6368

Quoted 11 lines
block.c +4 -6
-    /* We don't want arbitrary node of the BDS chain to be replaced only the top
-     * most non filter in order to prevent data corruption.
-     * Another benefit is that this tests exclude backing files which are
-     * blocked by the backing blockers.
+    /*
+     * If to_replace_bs is (recursively) a child of backing_bs,
+     * replacing it may create a loop.  We cannot allow that.
         */
-    if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
-        error_setg(errp, "Only top most non filter can be replaced");
+    if (to_replace_bs == backing_bs || is_child_of(to_replace_bs, backing_bs)) {

first condition is covered by second, so first may be omitted.

It is not. is_child_of() does not return true if child == parent.

Quoted 9 lines
Quoted 8 lines
block.c +8 -0
+        error_setg(errp, "Replacing this node would result in a loop");
+        to_replace_bs = NULL;
+        goto out;
+    }
+
+    /*
+     * Mirror is designed in such a way that when it completes, the
+     * source BDS is seamlessly replaced.
Quoted 6 lines
Quoted 4 lines
Quoted 1 line

Not source but to_replace_bs is replaced?

It has originally been designed to replace the source. If it could replace any arbitrary BDS, all of this would be moot.

quorum child, you saying about in commit message?

Which is not any arbitrary BDS, but one that looks exactly like the source.

My point is, mirror has been *designed* to replace the source seamlessly. It can do more things today, but that was its original point.

That means that the target must be exactly the same as the source. And then we come to this:

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines

block.c BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs, · line 6383

Quoted 8 lines

It is therefore not allowed

block.c +7 -0
+     * to replace a BDS where this condition would be violated, as that
+     * would defeat the purpose of mirror and could lead to data
+     * corruption.
+     * Therefore, between parent_bs and to_replace_bs there may be
+     * only filters (and the one on top must be a filter, too), so
+     * their data always stays in sync and mirror can complete and
+     * replace to_replace_bs without any possible corruptions.

So replacing a node that’s connected to the source only through filters is fine because that means the replaced node will also have the same content as the source.

Quoted 7 lines

How about I replace the first paragraph with:

At the end of the mirror job, the target exhibits exactly the same content as the source, so it can replace the source node seamlessly. It cannot replace a BDS that differs in content, as that could lead to data corruption.

OK for me, thanks

Quoted 17 lines
Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
block.c +6 -0
+     */
+    if (!is_filtered_child(parent_bs, to_replace_bs) &&
+        !is_filtered_child(to_replace_bs, parent_bs))
+    {
+        error_setg(errp, "The node to be replaced must be connected to the "
+                   "source through filter nodes only");
Quoted 8 lines
Quoted 6 lines
Quoted 1 line

"and the one on top must be a filter, too" not mentioned in the error..

Well, unless the source node is the node to be replaced. Hm... This gets very hard to express. I think I’d prefer to keep this as it is, even though it is not quite correct, unless you have a better suggestion of what to report. :-/

I can't imaging something better than just add "(and the one on top must be a filter, too)"

Quoted 7 lines

The problem is that “the one on top” wouldn’t sound very clear to me as a user.

Maybe include the explanation à la “The node to be replaced must be connected to the source through filter nodes only, so its data is the exact same at all times”? Maybe then users can guess what this “connected” means exactly.

Hmm, what about: "There may be not more than one data node in the whole chain from node to be replaced to the source node and others must filters, to be sure that data of source node and the node to be replaced are the same at all times"?

For sure, Eric is the best at such exercises.

But, anyway, I'm OK with your variant, it's all a kind of nit-picking.

Quoted 58 lines
Quoted 41 lines
Quoted 41 lines
Quoted 40 lines
Quoted 28 lines
            to_replace_bs = NULL;
            goto out;
        }
blockdev.c +7 -2
index 4e72f6f701..758e0b5431 100644
@@ -3887,7 +3887,7 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
        }
 
        if (has_replaces) {
-        BlockDriverState *to_replace_bs;
+        BlockDriverState *to_replace_bs, *backing_bs;
            AioContext *replace_aio_context;
            int64_t bs_size, replace_size;
 
@@ -3897,7 +3897,37 @@ static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs,
                return;
            }
 
-        to_replace_bs = check_to_replace_node(bs, replaces, errp);
+        if (backing_mode == MIRROR_SOURCE_BACKING_CHAIN ||
+            backing_mode == MIRROR_OPEN_BACKING_CHAIN)
+        {
+            /*
+             * While we do not quite know what OPEN_BACKING_CHAIN
+             * (used for mode=existing) will yield, it is probably

blockdev.c static void blockdev_mirror_common(const char *job_id, BlockDriverState *bs, · line 3915

Quoted 10 lines
blockdev.c +10 -0
+             * best to restrict it exactly like SOURCE_BACKING_CHAIN,
+             * because that is our best guess.
+             */
+            switch (sync) {
+            case MIRROR_SYNC_MODE_FULL:
+                backing_bs = NULL;
+                break;
+
+            case MIRROR_SYNC_MODE_TOP:
+                backing_bs = bdrv_filtered_cow_bs(bdrv_skip_rw_filters(bs));

why not bdrv_backing_chain_next(bs) like in mirror_start?

Quoted 4 lines
Quoted 2 lines

Good question. I suppose it should be bdrv_filtered_cow_bs(bdrv_backing_chain_next(bs)) in mirror_start()?

You mean bdrv_filtered_cow_bs(bdrv_skip_rw_filters(bs)), I hope)

Er, yes, sure.

Quoted 5 lines
Quoted 3 lines

Because with sync=top, we just want to remove the topmost COW node (and filters on top), but keep filters behind it.

Agreed.

OK.

Max

Signature · 2 lines
Best regards,
Vladimir
author
#121 lore raw

PATCH v6 36/42 iotests: Add tests for mirror @replaces loops

In reply to Max Reitz

This adds two tests for cases where our old check_to_replace_node() function failed to detect that executing this job with these parameters would result in a cyclic graph.

---
 tests/qemu-iotests/041     | 124 +++++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/041.out |   4 +-
 2 files changed, 126 insertions(+), 2 deletions(-)
tests/qemu-iotests/041 +124 -0
index 26bf1701eb..0c1432f189 100755
@@ -1067,5 +1067,129 @@ class TestOrphanedSource(iotests.QMPTestCase):
                              target='dest-ro')
         self.assert_qmp(result, 'error/class', 'GenericError')
 
+# Various tests for the @replaces option (independent of quorum)
+class TestReplaces(iotests.QMPTestCase):
+    def setUp(self):
+        self.vm = iotests.VM()
+        self.vm.launch()
+
+    def tearDown(self):
+        self.vm.shutdown()
+
+    def test_drive_mirror_loop(self):
+        qemu_img('create', '-f', iotests.imgfmt, test_img, '1M')
+
+        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
+        self.assert_qmp(result, 'return', {})
+
+        result = self.vm.qmp('blockdev-add', **{
+                    'node-name': 'source',
+                    'driver': 'throttle',
+                    'throttle-group': 'tg',
+                    'file': {
+                        'node-name': 'filtered',
+                        'driver': iotests.imgfmt,
+                        'file': {
+                            'driver': 'file',
+                            'filename': test_img
+                        }
+                    }
+                })
+        self.assert_qmp(result, 'return', {})
+
+        # Mirror from @source to @target in sync=none, so that @source
+        # will be @target's backing file; but replace @filtered.
+        # Then, @target's backing file will be @source, whose backing
+        # file is now @target instead of @filtered.  That is a loop.
+        # (But apart from the loop, replacing @filtered instead of
+        # @source is fine, because both are just filtered versions of
+        # each other.)
+        result = self.vm.qmp('drive-mirror',
+                             job_id='mirror',
+                             device='source',
+                             target=target_img,
+                             format=iotests.imgfmt,
+                             node_name='target',
+                             sync='none',
+                             replaces='filtered')
+        if 'error' in result:
+            # This is the correct result
+            self.assert_qmp(result, 'error/class', 'GenericError')
+        else:
+            # This is wrong, but let's run it to the bitter conclusion
+            self.complete_and_wait(drive='mirror')
+            # Fail for good measure, although qemu should have crashed
+            # anyway
+            self.fail('Loop creation was successful')
+
+        os.remove(test_img)
+        try:
+            os.remove(target_img)
+        except OSError:
+            pass
+
+    def test_blockdev_mirror_loop(self):
+        qemu_img('create', '-f', iotests.imgfmt, test_img, '1M')
+        qemu_img('create', '-f', iotests.imgfmt, target_img, '1M')
+
+        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
+        self.assert_qmp(result, 'return', {})
+
+        result = self.vm.qmp('blockdev-add', **{
+                    'node-name': 'source',
+                    'driver': 'throttle',
+                    'throttle-group': 'tg',
+                    'file': {
+                        'node-name': 'middle',
+                        'driver': 'throttle',
+                        'throttle-group': 'tg',
+                        'file': {
+                            'node-name': 'bottom',
+                            'driver': iotests.imgfmt,
+                            'file': {
+                                'driver': 'file',
+                                'filename': test_img
+                            }
+                        }
+                    }
+                })
+        self.assert_qmp(result, 'return', {})
+
+        result = self.vm.qmp('blockdev-add', **{
+                    'node-name': 'target',
+                    'driver': iotests.imgfmt,
+                    'file': {
+                        'driver': 'file',
+                        'filename': target_img
+                    },
+                    'backing': 'middle'
+                })
+
+        # Mirror from @source to @target.  With blockdev-mirror, the
+        # current (old) backing file is retained (which is @middle).
+        # By replacing @bottom, @middle's file will be @target, whose
+        # backing file is @middle again.  That is a loop.
+        # (But apart from the loop, replacing @bottom instead of
+        # @source is fine, because both are just filtered versions of
+        # each other.)
+        result = self.vm.qmp('blockdev-mirror',
+                             job_id='mirror',
+                             device='source',
+                             target='target',
+                             sync='full',
+                             replaces='bottom')
+        if 'error' in result:
+            # This is the correct result
+            self.assert_qmp(result, 'error/class', 'GenericError')
+        else:
+            # This is wrong, but let's run it to the bitter conclusion
+            self.complete_and_wait(drive='mirror')
+            # Fail for good measure, although qemu should have crashed
+            # anyway
+            self.fail('Loop creation was successful')
+
+        os.remove(test_img)
+        os.remove(target_img)
+
 if __name__ == '__main__':
     iotests.main(supported_fmts=['qcow2', 'qed'])
tests/qemu-iotests/041.out +2 -2
index e071d0b261..2c448b4239 100644
@@ -1,5 +1,5 @@
-........................................................................................
+..........................................................................................
 ----------------------------------------------------------------------
-Ran 88 tests
+Ran 90 tests
 
 OK
Signature · 1 line
2.21.0
author
#122 lore raw

PATCH v6 37/42 block: Leave BDS.backing_file constant

In reply to Max Reitz

Parts of the block layer treat BDS.backing_file as if it were whatever the image header says (i.e., if it is a relative path, it is relative to the overlay), other parts treat it like a cache for bs->backing->bs->filename (relative paths are relative to the CWD). Considering bs->backing->bs->filename exists, let us make it mean the former.

Among other things, this now allows the user to specify a base when using qemu-img to commit an image file in a directory that is not the CWD (assuming, everything uses relative filenames).

Before this patch:

$ ./qemu-img create -f qcow2 foo/bot.qcow2 1M
$ ./qemu-img create -f qcow2 -b bot.qcow2 foo/mid.qcow2
$ ./qemu-img create -f qcow2 -b mid.qcow2 foo/top.qcow2
$ ./qemu-img commit -b mid.qcow2 foo/top.qcow2
qemu-img: Did not find 'mid.qcow2' in the backing chain of 'foo/top.qcow2'
$ ./qemu-img commit -b foo/mid.qcow2 foo/top.qcow2
qemu-img: Did not find 'foo/mid.qcow2' in the backing chain of 'foo/top.qcow2'
$ ./qemu-img commit -b $PWD/foo/mid.qcow2 foo/top.qcow2
qemu-img: Did not find '[...]/foo/mid.qcow2' in the backing chain of 'foo/top.qcow2'

After this patch:

$ ./qemu-img commit -b mid.qcow2 foo/top.qcow2
Image committed.
$ ./qemu-img commit -b foo/mid.qcow2 foo/top.qcow2
qemu-img: Did not find 'foo/mid.qcow2' in the backing chain of 'foo/top.qcow2'
$ ./qemu-img commit -b $PWD/foo/mid.qcow2 foo/top.qcow2
Image committed.

With this change, bdrv_find_backing_image() must look at whether the user has overridden a BDS's backing file. If so, it can no longer use bs->backing_file, but must instead compare the given filename against the backing node's filename directly.

Note that this changes the QAPI output for a node's backing_file. We had very inconsistent output there (sometimes what the image header said, sometimes the actual filename of the backing image). This inconsistent output was effectively useless, so we have to decide one way or the other. Considering that bs->backing_file usually at runtime contained the path to the image relative to qemu's CWD (or absolute), this patch changes QAPI's backing_file to always report the bs->backing->bs->filename from now on. If you want to receive the image header information, you have to refer to full-backing-filename.

This necessitates a change to iotest 228. The interesting information it really wanted is the image header, and it can get that now, but it has to use full-backing-filename instead of backing_file. Because of this patch's changes to bs->backing_file's behavior, we also need some reference output changes.

Along with the changes to bs->backing_file, stop updating BDS.backing_format in bdrv_backing_attach() as well. This necessitates a change to the reference output of iotest 191.

iotest 245 changes in behavior: With the backing node no longer overriding the parent node's backing_file string, you can now omit the @backing option when reopening a node with neither a default nor a current backing file even if it used to have a backing node at some point.

---
 include/block/block_int.h  | 19 ++++++++++++++-----
 block.c                    | 35 ++++++++++++++++++++++++++++-------
 block/qapi.c               |  7 ++++---
 tests/qemu-iotests/191.out |  1 -
 tests/qemu-iotests/228     |  6 +++---
 tests/qemu-iotests/228.out |  6 +++---
 tests/qemu-iotests/245     |  4 +++-
 7 files changed, 55 insertions(+), 23 deletions(-)
include/block/block_int.h +14 -5
index 42ee2fcf7f..993bafc090 100644
@@ -784,11 +784,20 @@ struct BlockDriverState {
     bool walking_aio_notifiers; /* to make removal during iteration safe */
 
     char filename[PATH_MAX];
-    char backing_file[PATH_MAX]; /* if non zero, the image is a diff of
-                                    this file image */
-    /* The backing filename indicated by the image header; if we ever
-     * open this file, then this is replaced by the resulting BDS's
-     * filename (i.e. after a bdrv_refresh_filename() run). */
+    /*
+     * If not empty, this image is a diff in relation to backing_file.
+     * Note that this is the name given in the image header and
+     * therefore may or may not be equal to .backing->bs->filename.
+     * If this field contains a relative path, it is to be resolved
+     * relatively to the overlay's location.
+     */
+    char backing_file[PATH_MAX];
+    /*
+     * The backing filename indicated by the image header.  Contrary
+     * to backing_file, if we ever open this file, auto_backing_file
+     * is replaced by the resulting BDS's filename (i.e. after a
+     * bdrv_refresh_filename() run).
+     */
     char auto_backing_file[PATH_MAX];
     char backing_format[16]; /* if non-zero and backing_file exists */
 
block.c +28 -7
index 4858d3e718..88533fa0d3 100644
@@ -78,6 +78,8 @@ static BlockDriverState *bdrv_open_inherit(const char *filename,
                                            const BdrvChildRole *child_role,
                                            Error **errp);
 
+static bool bdrv_backing_overridden(BlockDriverState *bs);
+
 /* If non-zero, use only whitelisted block drivers */
 static int use_bdrv_whitelist;
 
@@ -1065,10 +1067,6 @@ static void bdrv_backing_attach(BdrvChild *c)
     bdrv_refresh_filename(backing_hd);
 
     parent->open_flags &= ~BDRV_O_NO_BACKING;
-    pstrcpy(parent->backing_file, sizeof(parent->backing_file),
-            backing_hd->filename);
-    pstrcpy(parent->backing_format, sizeof(parent->backing_format),
-            backing_hd->drv ? backing_hd->drv->format_name : "");
 
     bdrv_op_block_all(backing_hd, parent->backing_blocker);
     /* Otherwise we won't be able to commit or stream */
@@ -5294,6 +5292,7 @@ BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
     char *backing_file_full = NULL;
     char *filename_tmp = NULL;
     int is_protocol = 0;
+    bool filenames_refreshed = false;
     BlockDriverState *curr_bs = NULL;
     BlockDriverState *retval = NULL;
 
@@ -5318,9 +5317,31 @@ BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
     {
         BlockDriverState *bs_below = bdrv_backing_chain_next(curr_bs);
 
-        /* If either of the filename paths is actually a protocol, then
-         * compare unmodified paths; otherwise make paths relative */
-        if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
+        if (bdrv_backing_overridden(curr_bs)) {
+            /*
+             * If the backing file was overridden, we can only compare
+             * directly against the backing node's filename.
+             */
+
+            if (!filenames_refreshed) {
+                /*
+                 * This will automatically refresh all of the
+                 * filenames in the rest of the backing chain, so we
+                 * only need to do this once.
+                 */
+                bdrv_refresh_filename(bs_below);
+                filenames_refreshed = true;
+            }
+
+            if (strcmp(backing_file, bs_below->filename) == 0) {
+                retval = bs_below;
+                break;
+            }
+        } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
+            /*
+             * If either of the filename paths is actually a protocol, then
+             * compare unmodified paths; otherwise make paths relative.
+             */
             char *backing_file_full_ret;
 
             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
block/qapi.c +4 -3
index 4f59ac1c0f..751c3e695a 100644
@@ -45,7 +45,7 @@ BlockDeviceInfo *bdrv_block_device_info(BlockBackend *blk,
                                         BlockDriverState *bs, Error **errp)
 {
     ImageInfo **p_image_info;
-    BlockDriverState *bs0;
+    BlockDriverState *bs0, *backing;
     BlockDeviceInfo *info;
 
     if (!bs->drv) {
@@ -74,9 +74,10 @@ BlockDeviceInfo *bdrv_block_device_info(BlockBackend *blk,
         info->node_name = g_strdup(bs->node_name);
     }
 
-    if (bs->backing_file[0]) {
+    backing = bdrv_filtered_cow_bs(bs);
+    if (backing) {
         info->has_backing_file = true;
-        info->backing_file = g_strdup(bs->backing_file);
+        info->backing_file = g_strdup(backing->filename);
     }
 
     if (!QLIST_EMPTY(&bs->dirty_bitmaps)) {
tests/qemu-iotests/191.out +0 -1
index 3fc92bb56e..0b3c216b0c 100644
@@ -605,7 +605,6 @@ wrote 65536/65536 bytes at offset 1048576
                     "backing-filename": "TEST_DIR/t.IMGFMT.base",
                     "dirty-flag": false
                 },
-                "backing-filename-format": "IMGFMT",
                 "virtual-size": 67108864,
                 "filename": "TEST_DIR/t.IMGFMT.ovl3",
                 "cluster-size": 65536,
tests/qemu-iotests/228 +3 -3
index 9a50afd205..a1f3187212 100755
@@ -34,7 +34,7 @@ def log_node_info(node):
 
     log('bs->filename: ' + node['image']['filename'],
         filters=[filter_testfiles, filter_imgfmt])
-    log('bs->backing_file: ' + node['backing_file'],
+    log('bs->backing_file: ' + node['image']['full-backing-filename'],
         filters=[filter_testfiles, filter_imgfmt])
 
     if 'backing-image' in node['image']:
@@ -70,8 +70,8 @@ with iotests.FilePath('base.img') as base_img_path, \
                 },
                 filters=[filter_qmp_testfiles, filter_qmp_imgfmt])
 
-    # Filename should be plain, and the backing filename should not
-    # contain the "file:" prefix
+    # Filename should be plain, and the backing node filename should
+    # not contain the "file:" prefix
     log_node_info(vm.node_info('node0'))
 
     vm.qmp_log('blockdev-del', node_name='node0')
tests/qemu-iotests/228.out +3 -3
index 4217df24fe..8c82009abe 100644
@@ -4,7 +4,7 @@
 {"return": {}}
 
 bs->filename: TEST_DIR/PID-top.img
-bs->backing_file: TEST_DIR/PID-base.img
+bs->backing_file: file:TEST_DIR/PID-base.img
 bs->backing->bs->filename: TEST_DIR/PID-base.img
 
 {"execute": "blockdev-del", "arguments": {"node-name": "node0"}}
@@ -41,7 +41,7 @@ bs->backing->bs->filename: TEST_DIR/PID-base.img
 {"return": {}}
 
 bs->filename: TEST_DIR/PID-top.img
-bs->backing_file: TEST_DIR/PID-base.img
+bs->backing_file: file:TEST_DIR/PID-base.img
 bs->backing->bs->filename: TEST_DIR/PID-base.img
 
 {"execute": "blockdev-del", "arguments": {"node-name": "node0"}}
@@ -55,7 +55,7 @@ bs->backing->bs->filename: TEST_DIR/PID-base.img
 {"return": {}}
 
 bs->filename: json:{"backing": {"driver": "null-co"}, "driver": "IMGFMT", "file": {"driver": "file", "filename": "TEST_DIR/PID-top.img"}}
-bs->backing_file: null-co://
+bs->backing_file: TEST_DIR/PID-base.img
 bs->backing->bs->filename: null-co://
 
 {"execute": "blockdev-del", "arguments": {"node-name": "node0"}}
tests/qemu-iotests/245 +3 -1
index bc1ceb9792..049ef6a71f 100644
@@ -722,7 +722,9 @@ class TestBlockdevReopen(iotests.QMPTestCase):
 
         # Detach hd2 from hd0.
         self.reopen(opts, {'backing': None})
-        self.reopen(opts, {}, "backing is missing for 'hd0'")
+
+        # Without a backing file, we can omit 'backing' again
+        self.reopen(opts)
 
         # Remove both hd0 and hd2
         result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
Signature · 1 line
2.21.0
#123 lore raw

Re: [Qemu-devel] [PATCH v6 37/42] block: Leave BDS.backing_file constant

Quoted 13 lines · Max Reitz

Parts of the block layer treat BDS.backing_file as if it were whatever the image header says (i.e., if it is a relative path, it is relative to the overlay), other parts treat it like a cache for bs->backing->bs->filename (relative paths are relative to the CWD). Considering bs->backing->bs->filename exists, let us make it mean the former.

Among other things, this now allows the user to specify a base when using qemu-img to commit an image file in a directory that is not the CWD (assuming, everything uses relative filenames).

Before this patch:

Quoted 9 lines
$ ./qemu-img create -f qcow2 foo/bot.qcow2 1M
$ ./qemu-img create -f qcow2 -b bot.qcow2 foo/mid.qcow2
$ ./qemu-img create -f qcow2 -b mid.qcow2 foo/top.qcow2
$ ./qemu-img commit -b mid.qcow2 foo/top.qcow2
qemu-img: Did not find 'mid.qcow2' in the backing chain of 'foo/top.qcow2'
$ ./qemu-img commit -b foo/mid.qcow2 foo/top.qcow2
qemu-img: Did not find 'foo/mid.qcow2' in the backing chain of 'foo/top.qcow2'
$ ./qemu-img commit -b $PWD/foo/mid.qcow2 foo/top.qcow2
qemu-img: Did not find '[...]/foo/mid.qcow2' in the backing chain of 'foo/top.qcow2'

nothing works

Quoted 9 lines

After this patch:

$ ./qemu-img commit -b mid.qcow2 foo/top.qcow2
Image committed.
$ ./qemu-img commit -b foo/mid.qcow2 foo/top.qcow2
qemu-img: Did not find 'foo/mid.qcow2' in the backing chain of 'foo/top.qcow2'
$ ./qemu-img commit -b $PWD/foo/mid.qcow2 foo/top.qcow2
Image committed.

something works.. However it seems that not working one is actually most probable to be called by user. Anyway something is better than nothing.

Quoted 49 lines

With this change, bdrv_find_backing_image() must look at whether the user has overridden a BDS's backing file. If so, it can no longer use bs->backing_file, but must instead compare the given filename against the backing node's filename directly.

Note that this changes the QAPI output for a node's backing_file. We had very inconsistent output there (sometimes what the image header said, sometimes the actual filename of the backing image). This inconsistent output was effectively useless, so we have to decide one way or the other. Considering that bs->backing_file usually at runtime contained the path to the image relative to qemu's CWD (or absolute), this patch changes QAPI's backing_file to always report the bs->backing->bs->filename from now on. If you want to receive the image header information, you have to refer to full-backing-filename.

This necessitates a change to iotest 228. The interesting information it really wanted is the image header, and it can get that now, but it has to use full-backing-filename instead of backing_file. Because of this patch's changes to bs->backing_file's behavior, we also need some reference output changes.

Along with the changes to bs->backing_file, stop updating BDS.backing_format in bdrv_backing_attach() as well. This necessitates a change to the reference output of iotest 191.

iotest 245 changes in behavior: With the backing node no longer overriding the parent node's backing_file string, you can now omit the @backing option when reopening a node with neither a default nor a current backing file even if it used to have a backing node at some point.

---
  include/block/block_int.h  | 19 ++++++++++++++-----
  block.c                    | 35 ++++++++++++++++++++++++++++-------
  block/qapi.c               |  7 ++++---
  tests/qemu-iotests/191.out |  1 -
  tests/qemu-iotests/228     |  6 +++---
  tests/qemu-iotests/228.out |  6 +++---
  tests/qemu-iotests/245     |  4 +++-
  7 files changed, 55 insertions(+), 23 deletions(-)
include/block/block_int.h +0 -0
index 42ee2fcf7f..993bafc090 100644
@@ -784,11 +784,20 @@ struct BlockDriverState {
      bool walking_aio_notifiers; /* to make removal during iteration safe */

include/block/block_int.h struct BlockDriverState { · line 789

Quoted 10 lines
include/block/block_int.h +3 -5
 
      char filename[PATH_MAX];
-    char backing_file[PATH_MAX]; /* if non zero, the image is a diff of
-                                    this file image */
-    /* The backing filename indicated by the image header; if we ever
-     * open this file, then this is replaced by the resulting BDS's
-     * filename (i.e. after a bdrv_refresh_filename() run). */
+    /*
+     * If not empty, this image is a diff in relation to backing_file.
+     * Note that this is the name given in the image header

Is it synced when image header is updated? If yes, it's not constant, if not it's just wrong.

include/block/block_int.h struct BlockDriverState { · line 797

Quoted 9 lines

and

include/block/block_int.h +8 -0
+     * therefore may or may not be equal to .backing->bs->filename.
+     * If this field contains a relative path, it is to be resolved
+     * relatively to the overlay's location.
+     */
+    char backing_file[PATH_MAX];
+    /*
+     * The backing filename indicated by the image header.  Contrary
+     * to backing_file, if we ever open this file, auto_backing_file

Preexisting, but for a fresh look (I don't know backing_file and auto_backing_file related logic and assume that these are strange fields which would better not exist) this is hard to understand.

open this file - which one? this bds? or it's backing?

Quoted 52 lines
include/block/block_int.h +3 -0
+     * is replaced by the resulting BDS's filename (i.e. after a
+     * bdrv_refresh_filename() run).
+     */
      char auto_backing_file[PATH_MAX];
      char backing_format[16]; /* if non-zero and backing_file exists */
block.c +10 -7
index 4858d3e718..88533fa0d3 100644
@@ -78,6 +78,8 @@ static BlockDriverState *bdrv_open_inherit(const char *filename,
                                             const BdrvChildRole *child_role,
                                             Error **errp);
 
+static bool bdrv_backing_overridden(BlockDriverState *bs);
+
  /* If non-zero, use only whitelisted block drivers */
  static int use_bdrv_whitelist;
 
@@ -1065,10 +1067,6 @@ static void bdrv_backing_attach(BdrvChild *c)
      bdrv_refresh_filename(backing_hd);
 
      parent->open_flags &= ~BDRV_O_NO_BACKING;
-    pstrcpy(parent->backing_file, sizeof(parent->backing_file),
-            backing_hd->filename);
-    pstrcpy(parent->backing_format, sizeof(parent->backing_format),
-            backing_hd->drv ? backing_hd->drv->format_name : "");
 
      bdrv_op_block_all(backing_hd, parent->backing_blocker);
      /* Otherwise we won't be able to commit or stream */
@@ -5294,6 +5292,7 @@ BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
      char *backing_file_full = NULL;
      char *filename_tmp = NULL;
      int is_protocol = 0;
+    bool filenames_refreshed = false;
      BlockDriverState *curr_bs = NULL;
      BlockDriverState *retval = NULL;
 
@@ -5318,9 +5317,31 @@ BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
      {
          BlockDriverState *bs_below = bdrv_backing_chain_next(curr_bs);
 
-        /* If either of the filename paths is actually a protocol, then
-         * compare unmodified paths; otherwise make paths relative */
-        if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
+        if (bdrv_backing_overridden(curr_bs)) {
+            /*
+             * If the backing file was overridden, we can only compare
+             * directly against the backing node's filename.
+             */
+
+            if (!filenames_refreshed) {

block.c BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs, · line 5336

Quoted 10 lines
block.c +10 -0
+                /*
+                 * This will automatically refresh all of the
+                 * filenames in the rest of the backing chain, so we
+                 * only need to do this once.
+                 */
+                bdrv_refresh_filename(bs_below);
+                filenames_refreshed = true;
+            }
+
+            if (strcmp(backing_file, bs_below->filename) == 0) {

Don't you want try realpath() here too?

And I doubt, why we can't always assume bdrv_backing_overridden() = true? (keeping in mind that it may give false positives, as comment says)?

Just go through backing chain and check

searched_file == bs->filename || realpath(searched_file) == realpath(bs->filename) ?

Do we need to cover case when something is relative to parent really? I'm not sure but it seems like in libvirt absolute paths are used always.. And if we need just add to this condition:

|| realpath(joinpath(prev_bs->filename, searched_file)) == realpath(bs->filename))

Quoted 120 lines
block.c +8 -0
+                retval = bs_below;
+                break;
+            }
+        } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
+            /*
+             * If either of the filename paths is actually a protocol, then
+             * compare unmodified paths; otherwise make paths relative.
+             */
              char *backing_file_full_ret;
 
              if (strcmp(backing_file, curr_bs->backing_file) == 0) {
block/qapi.c +4 -3
index 4f59ac1c0f..751c3e695a 100644
@@ -45,7 +45,7 @@ BlockDeviceInfo *bdrv_block_device_info(BlockBackend *blk,
                                          BlockDriverState *bs, Error **errp)
  {
      ImageInfo **p_image_info;
-    BlockDriverState *bs0;
+    BlockDriverState *bs0, *backing;
      BlockDeviceInfo *info;
 
      if (!bs->drv) {
@@ -74,9 +74,10 @@ BlockDeviceInfo *bdrv_block_device_info(BlockBackend *blk,
          info->node_name = g_strdup(bs->node_name);
      }
 
-    if (bs->backing_file[0]) {
+    backing = bdrv_filtered_cow_bs(bs);
+    if (backing) {
          info->has_backing_file = true;
-        info->backing_file = g_strdup(bs->backing_file);
+        info->backing_file = g_strdup(backing->filename);
      }
 
      if (!QLIST_EMPTY(&bs->dirty_bitmaps)) {
tests/qemu-iotests/191.out +0 -1
index 3fc92bb56e..0b3c216b0c 100644
@@ -605,7 +605,6 @@ wrote 65536/65536 bytes at offset 1048576
                      "backing-filename": "TEST_DIR/t.IMGFMT.base",
                      "dirty-flag": false
                  },
-                "backing-filename-format": "IMGFMT",
                  "virtual-size": 67108864,
                  "filename": "TEST_DIR/t.IMGFMT.ovl3",
                  "cluster-size": 65536,
tests/qemu-iotests/228 +3 -3
index 9a50afd205..a1f3187212 100755
@@ -34,7 +34,7 @@ def log_node_info(node):
 
      log('bs->filename: ' + node['image']['filename'],
          filters=[filter_testfiles, filter_imgfmt])
-    log('bs->backing_file: ' + node['backing_file'],
+    log('bs->backing_file: ' + node['image']['full-backing-filename'],
          filters=[filter_testfiles, filter_imgfmt])
 
      if 'backing-image' in node['image']:
@@ -70,8 +70,8 @@ with iotests.FilePath('base.img') as base_img_path, \
                  },
                  filters=[filter_qmp_testfiles, filter_qmp_imgfmt])
 
-    # Filename should be plain, and the backing filename should not
-    # contain the "file:" prefix
+    # Filename should be plain, and the backing node filename should
+    # not contain the "file:" prefix
      log_node_info(vm.node_info('node0'))
 
      vm.qmp_log('blockdev-del', node_name='node0')
tests/qemu-iotests/228.out +3 -3
index 4217df24fe..8c82009abe 100644
@@ -4,7 +4,7 @@
  {"return": {}}
 
  bs->filename: TEST_DIR/PID-top.img
-bs->backing_file: TEST_DIR/PID-base.img
+bs->backing_file: file:TEST_DIR/PID-base.img
  bs->backing->bs->filename: TEST_DIR/PID-base.img
 
  {"execute": "blockdev-del", "arguments": {"node-name": "node0"}}
@@ -41,7 +41,7 @@ bs->backing->bs->filename: TEST_DIR/PID-base.img
  {"return": {}}
 
  bs->filename: TEST_DIR/PID-top.img
-bs->backing_file: TEST_DIR/PID-base.img
+bs->backing_file: file:TEST_DIR/PID-base.img
  bs->backing->bs->filename: TEST_DIR/PID-base.img
 
  {"execute": "blockdev-del", "arguments": {"node-name": "node0"}}
@@ -55,7 +55,7 @@ bs->backing->bs->filename: TEST_DIR/PID-base.img
  {"return": {}}
 
  bs->filename: json:{"backing": {"driver": "null-co"}, "driver": "IMGFMT", "file": {"driver": "file", "filename": "TEST_DIR/PID-top.img"}}
-bs->backing_file: null-co://
+bs->backing_file: TEST_DIR/PID-base.img
  bs->backing->bs->filename: null-co://
 
  {"execute": "blockdev-del", "arguments": {"node-name": "node0"}}
tests/qemu-iotests/245 +3 -1
index bc1ceb9792..049ef6a71f 100644
@@ -722,7 +722,9 @@ class TestBlockdevReopen(iotests.QMPTestCase):
 
          # Detach hd2 from hd0.
          self.reopen(opts, {'backing': None})
-        self.reopen(opts, {}, "backing is missing for 'hd0'")
+
+        # Without a backing file, we can omit 'backing' again
+        self.reopen(opts)
 
          # Remove both hd0 and hd2
          result = self.vm.qmp('blockdev-del', conv_keys = True, node_name = 'hd0')
Signature · 2 lines
Best regards,
Vladimir
author
#124 lore raw

PATCH v6 38/42 iotests: Let complete_and_wait() work with commit

In reply to Max Reitz

complete_and_wait() and wait_ready() currently only work for mirror jobs. Let them work for active commit jobs, too.

---
 tests/qemu-iotests/iotests.py | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
tests/qemu-iotests/iotests.py +7 -3
index 84438e837c..3ef846d1dc 100644
@@ -761,8 +761,12 @@ class QMPTestCase(unittest.TestCase):
 
     def wait_ready(self, drive='drive0'):
         '''Wait until a block job BLOCK_JOB_READY event'''
-        f = {'data': {'type': 'mirror', 'device': drive } }
-        event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
+        event = self.vm.events_wait([
+                ('BLOCK_JOB_READY',
+                 {'data': {'type': 'mirror', 'device': drive } }),
+                ('BLOCK_JOB_READY',
+                 {'data': {'type': 'commit', 'device': drive } })
+            ])
 
     def wait_ready_and_cancel(self, drive='drive0'):
         self.wait_ready(drive=drive)
@@ -780,7 +784,7 @@ class QMPTestCase(unittest.TestCase):
         self.assert_qmp(result, 'return', {})
 
         event = self.wait_until_completed(drive=drive)
-        self.assert_qmp(event, 'data/type', 'mirror')
+        self.assertTrue(event['data']['type'] in ['mirror', 'commit'])
 
     def pause_wait(self, job_id='job0'):
         with Timeout(1, "Timeout waiting for job to pause"):
Signature · 1 line
2.21.0
Reviewed-by on v6 38/42
#125 lore raw

Re: [Qemu-devel] [PATCH v6 38/42] iotests: Let complete_and_wait() work with commit

Quoted 29 lines · Max Reitz

complete_and_wait() and wait_ready() currently only work for mirror jobs. Let them work for active commit jobs, too.

---
  tests/qemu-iotests/iotests.py | 10 +++++++---
  1 file changed, 7 insertions(+), 3 deletions(-)
tests/qemu-iotests/iotests.py +6 -2
index 84438e837c..3ef846d1dc 100644
@@ -761,8 +761,12 @@ class QMPTestCase(unittest.TestCase):
 
      def wait_ready(self, drive='drive0'):
          '''Wait until a block job BLOCK_JOB_READY event'''
-        f = {'data': {'type': 'mirror', 'device': drive } }
-        event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
+        event = self.vm.events_wait([
+                ('BLOCK_JOB_READY',
+                 {'data': {'type': 'mirror', 'device': drive } }),
+                ('BLOCK_JOB_READY',
+                 {'data': {'type': 'commit', 'device': drive } })
+            ])
 
      def wait_ready_and_cancel(self, drive='drive0'):
          self.wait_ready(drive=drive)

tests/qemu-iotests/iotests.py class QMPTestCase(unittest.TestCase): · line 790

Quoted 8 lines
tests/qemu-iotests/iotests.py +1 -1
@@ -780,7 +784,7 @@ class QMPTestCase(unittest.TestCase):
          self.assert_qmp(result, 'return', {})
 
          event = self.wait_until_completed(drive=drive)
-        self.assert_qmp(event, 'data/type', 'mirror')
+        self.assertTrue(event['data']['type'] in ['mirror', 'commit'])
 
      def pause_wait(self, job_id='job0'):
          with Timeout(1, "Timeout waiting for job to pause"):
Signature · 2 lines
Best regards,
Vladimir
author
#126 lore raw

PATCH v6 39/42 iotests: Add filter commit test cases

In reply to Max Reitz

This patch adds some tests on how commit copes with filter nodes.

---
 tests/qemu-iotests/040     | 177 +++++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/040.out |   4 +-
 2 files changed, 179 insertions(+), 2 deletions(-)
tests/qemu-iotests/040 +177 -0
index 6db9abf8e6..a0a0db8889 100755
@@ -428,5 +428,182 @@ class TestReopenOverlay(ImageCommitTestCase):
     def test_reopen_overlay(self):
         self.run_commit_test(self.img1, self.img0)
 
+class TestCommitWithFilters(iotests.QMPTestCase):
+    img0 = os.path.join(iotests.test_dir, '0.img')
+    img1 = os.path.join(iotests.test_dir, '1.img')
+    img2 = os.path.join(iotests.test_dir, '2.img')
+    img3 = os.path.join(iotests.test_dir, '3.img')
+
+    def setUp(self):
+        qemu_img('create', '-f', iotests.imgfmt, self.img0, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img1, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img2, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img3, '64M')
+
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 1 0M 1M', self.img0)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 2 1M 1M', self.img1)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 3 2M 1M', self.img2)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 4 3M 1M', self.img3)
+
+        # Distributions of the patterns in the files; this is checked
+        # by tearDown() and should be changed by the test cases as is
+        # necessary
+        self.pattern_files = [self.img0, self.img1, self.img2, self.img3]
+
+        self.vm = iotests.VM()
+        self.vm.launch()
+        self.has_quit = False
+
+        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
+        self.assert_qmp(result, 'return', {})
+
+        result = self.vm.qmp('blockdev-add', **{
+                'node-name': 'top-filter',
+                'driver': 'throttle',
+                'throttle-group': 'tg',
+                'file': {
+                    'node-name': 'cow-3',
+                    'driver': iotests.imgfmt,
+                    'file': {
+                        'driver': 'file',
+                        'filename': self.img3
+                    },
+                    'backing': {
+                        'node-name': 'cow-2',
+                        'driver': iotests.imgfmt,
+                        'file': {
+                            'driver': 'file',
+                            'filename': self.img2
+                        },
+                        'backing': {
+                            'node-name': 'cow-1',
+                            'driver': iotests.imgfmt,
+                            'file': {
+                                'driver': 'file',
+                                'filename': self.img1
+                            },
+                            'backing': {
+                                'node-name': 'bottom-filter',
+                                'driver': 'throttle',
+                                'throttle-group': 'tg',
+                                'file': {
+                                    'node-name': 'cow-0',
+                                    'driver': iotests.imgfmt,
+                                    'file': {
+                                        'driver': 'file',
+                                        'filename': self.img0
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+            })
+        self.assert_qmp(result, 'return', {})
+
+    def tearDown(self):
+        self.vm.shutdown(has_quit=self.has_quit)
+
+        for index in range(len(self.pattern_files)):
+            result = qemu_io('-f', iotests.imgfmt,
+                             '-c', 'read -P %i %iM 1M' % (index + 1, index),
+                             self.pattern_files[index])
+            self.assertFalse('Pattern verification failed' in result)
+
+        os.remove(self.img3)
+        os.remove(self.img2)
+        os.remove(self.img1)
+        os.remove(self.img0)
+
+    # Filters make for funny filenames, so we cannot just use
+    # self.imgX to get them
+    def get_filename(self, node):
+        return self.vm.node_info(node)['image']['filename']
+
+    def test_filterless_commit(self):
+        self.assert_no_active_block_jobs()
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top-filter',
+                             top_node='cow-2',
+                             base_node='cow-1')
+        self.assert_qmp(result, 'return', {})
+        self.wait_until_completed(drive='commit')
+
+        self.assertIsNotNone(self.vm.node_info('cow-3'))
+        self.assertIsNone(self.vm.node_info('cow-2'))
+        self.assertIsNotNone(self.vm.node_info('cow-1'))
+
+        # 2 has been comitted into 1
+        self.pattern_files[2] = self.img1
+
+    def test_commit_through_filter(self):
+        self.assert_no_active_block_jobs()
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top-filter',
+                             top_node='cow-1',
+                             base_node='cow-0')
+        self.assert_qmp(result, 'return', {})
+        self.wait_until_completed(drive='commit')
+
+        self.assertIsNotNone(self.vm.node_info('cow-2'))
+        self.assertIsNone(self.vm.node_info('cow-1'))
+        self.assertIsNone(self.vm.node_info('bottom-filter'))
+        self.assertIsNotNone(self.vm.node_info('cow-0'))
+
+        # 1 has been comitted into 0
+        self.pattern_files[1] = self.img0
+
+    def test_filtered_active_commit_with_filter(self):
+        # Add a device, so the commit job finds a parent it can change
+        # to point to the base node (so we can test that top-filter is
+        # dropped from the graph)
+        result = self.vm.qmp('device_add', id='drv0', driver='virtio-blk',
+                             drive='top-filter')
+        self.assert_qmp(result, 'return', {})
+
+        # Try to release our reference to top-filter; that should not
+        # work because drv0 uses it
+        result = self.vm.qmp('blockdev-del', node_name='top-filter')
+        self.assert_qmp(result, 'error/class', 'GenericError')
+        self.assert_qmp(result, 'error/desc', 'Node top-filter is in use')
+
+        self.assert_no_active_block_jobs()
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top-filter',
+                             base_node='cow-2')
+        self.assert_qmp(result, 'return', {})
+        self.complete_and_wait(drive='commit')
+
+        # Try to release our reference to top-filter again
+        result = self.vm.qmp('blockdev-del', node_name='top-filter')
+        self.assert_qmp(result, 'return', {})
+
+        self.assertIsNone(self.vm.node_info('top-filter'))
+        self.assertIsNone(self.vm.node_info('cow-3'))
+        self.assertIsNotNone(self.vm.node_info('cow-2'))
+
+        # 3 has been comitted into 2
+        self.pattern_files[3] = self.img2
+
+    def test_filtered_active_commit_without_filter(self):
+        self.assert_no_active_block_jobs()
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top-filter',
+                             top_node='cow-3',
+                             base_node='cow-2')
+        self.assert_qmp(result, 'return', {})
+        self.complete_and_wait(drive='commit')
+
+        self.assertIsNotNone(self.vm.node_info('top-filter'))
+        self.assertIsNone(self.vm.node_info('cow-3'))
+        self.assertIsNotNone(self.vm.node_info('cow-2'))
+
+        # 3 has been comitted into 2
+        self.pattern_files[3] = self.img2
+
 if __name__ == '__main__':
     iotests.main(supported_fmts=['qcow2', 'qed'])
tests/qemu-iotests/040.out +2 -2
index 220a5fa82c..fe58934d7a 100644
@@ -1,5 +1,5 @@
-...............................................
+...................................................
 ----------------------------------------------------------------------
-Ran 47 tests
+Ran 51 tests
 
 OK
Signature · 1 line
2.21.0
Reviewed-by on v6 39/42
#127 lore raw

Re: [Qemu-devel] [PATCH v6 39/42] iotests: Add filter commit test cases

Quoted 83 lines · Max Reitz

This patch adds some tests on how commit copes with filter nodes.

---
  tests/qemu-iotests/040     | 177 +++++++++++++++++++++++++++++++++++++
  tests/qemu-iotests/040.out |   4 +-
  2 files changed, 179 insertions(+), 2 deletions(-)
tests/qemu-iotests/040 +67 -0
index 6db9abf8e6..a0a0db8889 100755
@@ -428,5 +428,182 @@ class TestReopenOverlay(ImageCommitTestCase):
      def test_reopen_overlay(self):
          self.run_commit_test(self.img1, self.img0)
 
+class TestCommitWithFilters(iotests.QMPTestCase):
+    img0 = os.path.join(iotests.test_dir, '0.img')
+    img1 = os.path.join(iotests.test_dir, '1.img')
+    img2 = os.path.join(iotests.test_dir, '2.img')
+    img3 = os.path.join(iotests.test_dir, '3.img')
+
+    def setUp(self):
+        qemu_img('create', '-f', iotests.imgfmt, self.img0, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img1, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img2, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img3, '64M')
+
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 1 0M 1M', self.img0)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 2 1M 1M', self.img1)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 3 2M 1M', self.img2)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 4 3M 1M', self.img3)
+
+        # Distributions of the patterns in the files; this is checked
+        # by tearDown() and should be changed by the test cases as is
+        # necessary
+        self.pattern_files = [self.img0, self.img1, self.img2, self.img3]
+
+        self.vm = iotests.VM()
+        self.vm.launch()
+        self.has_quit = False
+
+        result = self.vm.qmp('object-add', qom_type='throttle-group', id='tg')
+        self.assert_qmp(result, 'return', {})
+
+        result = self.vm.qmp('blockdev-add', **{
+                'node-name': 'top-filter',
+                'driver': 'throttle',
+                'throttle-group': 'tg',
+                'file': {
+                    'node-name': 'cow-3',
+                    'driver': iotests.imgfmt,
+                    'file': {
+                        'driver': 'file',
+                        'filename': self.img3
+                    },
+                    'backing': {
+                        'node-name': 'cow-2',
+                        'driver': iotests.imgfmt,
+                        'file': {
+                            'driver': 'file',
+                            'filename': self.img2
+                        },
+                        'backing': {
+                            'node-name': 'cow-1',
+                            'driver': iotests.imgfmt,
+                            'file': {
+                                'driver': 'file',
+                                'filename': self.img1
+                            },
+                            'backing': {
+                                'node-name': 'bottom-filter',
+                                'driver': 'throttle',
+                                'throttle-group': 'tg',
+                                'file': {
+                                    'node-name': 'cow-0',
+                                    'driver': iotests.imgfmt,
+                                    'file': {
+                                        'driver': 'file',
+                                        'filename': self.img0
+                                    }
+                                }
+                            }

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 507

Quoted 10 lines
tests/qemu-iotests/040 +10 -0
+                        }
+                    }
+                }
+            })
+        self.assert_qmp(result, 'return', {})
+
+    def tearDown(self):
+        self.vm.shutdown(has_quit=self.has_quit)
+
+        for index in range(len(self.pattern_files)):

you may use enumerate for such cases:
for ind, file in enumerate(self.pattern_files):

    ...

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 511

Quoted 4 lines
tests/qemu-iotests/040 +4 -0
+            result = qemu_io('-f', iotests.imgfmt,
+                             '-c', 'read -P %i %iM 1M' % (index + 1, index),
+                             self.pattern_files[index])
+            self.assertFalse('Pattern verification failed' in result)

A bit better would be to keep this loop in a function and do "writes" through it too, to make it more obvious that they are the same.. But I'm OK with it as is.

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 522

Quoted 11 lines
tests/qemu-iotests/040 +11 -0
+
+        os.remove(self.img3)
+        os.remove(self.img2)
+        os.remove(self.img1)
+        os.remove(self.img0)
+
+    # Filters make for funny filenames, so we cannot just use
+    # self.imgX to get them
+    def get_filename(self, node):
+        return self.vm.node_info(node)['image']['filename']
+

maybe:
def assertHasNode(self, node_name):
self.assertIsNotNone(self.vm.node_info(node_name))

and similar for assertNoNode...

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 524

Quoted 2 lines
tests/qemu-iotests/040 +2 -0
+    def test_filterless_commit(self):
+        self.assert_no_active_block_jobs()

why not just to include this call into setUp() ? Or even, just drop it? We create and start new vm in setUp, it don't have any block jobs for sure.

Quoted 52 lines
tests/qemu-iotests/040 +52 -0
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top-filter',
+                             top_node='cow-2',
+                             base_node='cow-1')
+        self.assert_qmp(result, 'return', {})
+        self.wait_until_completed(drive='commit')
+
+        self.assertIsNotNone(self.vm.node_info('cow-3'))
+        self.assertIsNone(self.vm.node_info('cow-2'))
+        self.assertIsNotNone(self.vm.node_info('cow-1'))
+
+        # 2 has been comitted into 1
+        self.pattern_files[2] = self.img1
+
+    def test_commit_through_filter(self):
+        self.assert_no_active_block_jobs()
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top-filter',
+                             top_node='cow-1',
+                             base_node='cow-0')
+        self.assert_qmp(result, 'return', {})
+        self.wait_until_completed(drive='commit')
+
+        self.assertIsNotNone(self.vm.node_info('cow-2'))
+        self.assertIsNone(self.vm.node_info('cow-1'))
+        self.assertIsNone(self.vm.node_info('bottom-filter'))
+        self.assertIsNotNone(self.vm.node_info('cow-0'))
+
+        # 1 has been comitted into 0
+        self.pattern_files[1] = self.img0
+
+    def test_filtered_active_commit_with_filter(self):
+        # Add a device, so the commit job finds a parent it can change
+        # to point to the base node (so we can test that top-filter is
+        # dropped from the graph)
+        result = self.vm.qmp('device_add', id='drv0', driver='virtio-blk',
+                             drive='top-filter')
+        self.assert_qmp(result, 'return', {})
+
+        # Try to release our reference to top-filter; that should not
+        # work because drv0 uses it
+        result = self.vm.qmp('blockdev-del', node_name='top-filter')
+        self.assert_qmp(result, 'error/class', 'GenericError')
+        self.assert_qmp(result, 'error/desc', 'Node top-filter is in use')
+
+        self.assert_no_active_block_jobs()
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top-filter',
+                             base_node='cow-2')

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 586

Quoted 10 lines
tests/qemu-iotests/040 +10 -0
+        self.assert_qmp(result, 'return', {})
+        self.complete_and_wait(drive='commit')
+
+        # Try to release our reference to top-filter again
+        result = self.vm.qmp('blockdev-del', node_name='top-filter')
+        self.assert_qmp(result, 'return', {})
+
+        self.assertIsNone(self.vm.node_info('top-filter'))
+        self.assertIsNone(self.vm.node_info('cow-3'))
+        self.assertIsNotNone(self.vm.node_info('cow-2'))

It would be good to assert here the cow-2 became drv0 child. However, otherwise it should be automatically dropped, so it's not necessary.

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 598

Quoted 12 lines
tests/qemu-iotests/040 +12 -0
+
+        # 3 has been comitted into 2
+        self.pattern_files[3] = self.img2
+
+    def test_filtered_active_commit_without_filter(self):
+        self.assert_no_active_block_jobs()
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top-filter',
+                             top_node='cow-3',
+                             base_node='cow-2')
+        self.assert_qmp(result, 'return', {})

can we check that really "active" commit is started, i.e. mirror block job?

Quoted 17 lines
tests/qemu-iotests/040 +9 -0
+        self.complete_and_wait(drive='commit')
+
+        self.assertIsNotNone(self.vm.node_info('top-filter'))
+        self.assertIsNone(self.vm.node_info('cow-3'))
+        self.assertIsNotNone(self.vm.node_info('cow-2'))
+
+        # 3 has been comitted into 2
+        self.pattern_files[3] = self.img2
+
  if __name__ == '__main__':
      iotests.main(supported_fmts=['qcow2', 'qed'])
tests/qemu-iotests/040.out +0 -0
index 220a5fa82c..fe58934d7a 100644

tests/qemu-iotests/040.out line 5

Quoted 7 lines
tests/qemu-iotests/040.out +2 -2
@@ -1,5 +1,5 @@
-...............................................
+...................................................
  ----------------------------------------------------------------------
-Ran 47 tests
+Ran 51 tests
 
  OK

With or without any of my suggestions:

Signature · 2 lines
Best regards,
Vladimir
author
#128 lore raw

Re: [Qemu-devel] [PATCH v6 39/42] iotests: Add filter commit test cases

Quoted 13 lines · Vladimir Sementsov-Ogievskiy
Quoted 12 lines · Max Reitz

This patch adds some tests on how commit copes with filter nodes.

---
  tests/qemu-iotests/040     | 177 +++++++++++++++++++++++++++++++++++++
  tests/qemu-iotests/040.out |   4 +-
  2 files changed, 179 insertions(+), 2 deletions(-)
tests/qemu-iotests/040 +0 -0
index 6db9abf8e6..a0a0db8889 100755

[...]

Quoted 8 lines

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 507

Quoted 4 lines
tests/qemu-iotests/040 +4 -0
+    def tearDown(self):
+        self.vm.shutdown(has_quit=self.has_quit)
+
+        for index in range(len(self.pattern_files)):

you may use enumerate for such cases:
for ind, file in enumerate(self.pattern_files):

    ...

Ah, nice.

Quoted 7 lines

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 511

Quoted 4 lines
tests/qemu-iotests/040 +4 -0
+            result = qemu_io('-f', iotests.imgfmt,
+                             '-c', 'read -P %i %iM 1M' % (index + 1, index),
+                             self.pattern_files[index])
+            self.assertFalse('Pattern verification failed' in result)

A bit better would be to keep this loop in a function and do "writes" through it too, to make it more obvious that they are the same.. But I'm OK with it as is.

Hm, yes. I’ll have a look.

Quoted 16 lines

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 522

Quoted 11 lines
tests/qemu-iotests/040 +11 -0
+
+        os.remove(self.img3)
+        os.remove(self.img2)
+        os.remove(self.img1)
+        os.remove(self.img0)
+
+    # Filters make for funny filenames, so we cannot just use
+    # self.imgX to get them
+    def get_filename(self, node):
+        return self.vm.node_info(node)['image']['filename']
+

maybe:
def assertHasNode(self, node_name):
self.assertIsNotNone(self.vm.node_info(node_name))

Quoted 1 line

and similar for assertNoNode...

Hm, I don’t know. It fits on one line either way.

Quoted 5 lines

tests/qemu-iotests/040

Quoted 2 lines
tests/qemu-iotests/040 +2 -0
+    def test_filterless_commit(self):
+        self.assert_no_active_block_jobs()

why not just to include this call into setUp() ? Or even, just drop it? We create and start new vm in setUp, it don't have any block jobs for sure.

Other tests do it the same way, e.g. 030, 040, and 041.

[...]

Quoted 6 lines

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 586

Quoted 3 lines
tests/qemu-iotests/040 +3 -0
+        self.assertIsNone(self.vm.node_info('top-filter'))
+        self.assertIsNone(self.vm.node_info('cow-3'))
+        self.assertIsNotNone(self.vm.node_info('cow-2'))

It would be good to assert here the cow-2 became drv0 child. However, otherwise it should be automatically dropped, so it's not necessary.

Yep, like cow-3. I’ll look into it anyway.

Quoted 6 lines
Quoted 6 lines
tests/qemu-iotests/040 +6 -0
+
+        # 3 has been comitted into 2
+        self.pattern_files[3] = self.img2
+
+    def test_filtered_active_commit_without_filter(self):
+        self.assert_no_active_block_jobs()
Quoted 8 lines

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 598

Quoted 6 lines
tests/qemu-iotests/040 +6 -0
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top-filter',
+                             top_node='cow-3',
+                             base_node='cow-2')
+        self.assert_qmp(result, 'return', {})

can we check that really "active" commit is started, i.e. mirror block job?

We do:

Quoted 1 line
Quoted 1 line

+ self.complete_and_wait(drive='commit')

wait_ready is True by default, so this will first wait for a READY event. That only happens for active commit.

Max

#129 lore raw

Re: [Qemu-devel] [PATCH v6 39/42] iotests: Add filter commit test cases

In reply to Max Reitz
Quoted 31 lines · Max Reitz

This patch adds some tests on how commit copes with filter nodes.

---
  tests/qemu-iotests/040     | 177 +++++++++++++++++++++++++++++++++++++
  tests/qemu-iotests/040.out |   4 +-
  2 files changed, 179 insertions(+), 2 deletions(-)
tests/qemu-iotests/040 +15 -0
index 6db9abf8e6..a0a0db8889 100755
@@ -428,5 +428,182 @@ class TestReopenOverlay(ImageCommitTestCase):
      def test_reopen_overlay(self):
          self.run_commit_test(self.img1, self.img0)
 
+class TestCommitWithFilters(iotests.QMPTestCase):
+    img0 = os.path.join(iotests.test_dir, '0.img')
+    img1 = os.path.join(iotests.test_dir, '1.img')
+    img2 = os.path.join(iotests.test_dir, '2.img')
+    img3 = os.path.join(iotests.test_dir, '3.img')
+
+    def setUp(self):
+        qemu_img('create', '-f', iotests.imgfmt, self.img0, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img1, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img2, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img3, '64M')
+
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 1 0M 1M', self.img0)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 2 1M 1M', self.img1)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 3 2M 1M', self.img2)

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 455

Quoted 10 lines
tests/qemu-iotests/040 +10 -0
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 4 3M 1M', self.img3)
+
+        # Distributions of the patterns in the files; this is checked
+        # by tearDown() and should be changed by the test cases as is
+        # necessary
+        self.pattern_files = [self.img0, self.img1, self.img2, self.img3]
+
+        self.vm = iotests.VM()
+        self.vm.launch()
+        self.has_quit = False

has_quit is unused actually. It's always False.

Signature · 2 lines
Best regards,
Vladimir
author
#130 lore raw

Re: [Qemu-devel] [PATCH v6 39/42] iotests: Add filter commit test cases

Quoted 36 lines · Vladimir Sementsov-Ogievskiy
Quoted 35 lines · Max Reitz

This patch adds some tests on how commit copes with filter nodes.

---
  tests/qemu-iotests/040     | 177 +++++++++++++++++++++++++++++++++++++
  tests/qemu-iotests/040.out |   4 +-
  2 files changed, 179 insertions(+), 2 deletions(-)
tests/qemu-iotests/040 +19 -0
index 6db9abf8e6..a0a0db8889 100755
@@ -428,5 +428,182 @@ class TestReopenOverlay(ImageCommitTestCase):
      def test_reopen_overlay(self):
          self.run_commit_test(self.img1, self.img0)
 
+class TestCommitWithFilters(iotests.QMPTestCase):
+    img0 = os.path.join(iotests.test_dir, '0.img')
+    img1 = os.path.join(iotests.test_dir, '1.img')
+    img2 = os.path.join(iotests.test_dir, '2.img')
+    img3 = os.path.join(iotests.test_dir, '3.img')
+
+    def setUp(self):
+        qemu_img('create', '-f', iotests.imgfmt, self.img0, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img1, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img2, '64M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img3, '64M')
+
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 1 0M 1M', self.img0)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 2 1M 1M', self.img1)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 3 2M 1M', self.img2)
+        qemu_io('-f', iotests.imgfmt, '-c', 'write -P 4 3M 1M', self.img3)
+
+        # Distributions of the patterns in the files; this is checked
+        # by tearDown() and should be changed by the test cases as is
Quoted 8 lines

tests/qemu-iotests/040 class TestReopenOverlay(ImageCommitTestCase): · line 455

Quoted 6 lines
tests/qemu-iotests/040 +6 -0
+        # necessary
+        self.pattern_files = [self.img0, self.img1, self.img2, self.img3]
+
+        self.vm = iotests.VM()
+        self.vm.launch()
+        self.has_quit = False

has_quit is unused actually. It's always False.

True. (:-)) I wonder why I added it.

Max

author
#131 lore raw

PATCH v6 40/42 iotests: Add filter mirror test cases

In reply to Max Reitz

This patch adds some test cases how mirroring relates to filters. One of them tests what happens when you mirror off a filtered COW node, two others use the mirror filter node as basically our only example of an implicitly created filter node so far (besides the commit filter).

---
 tests/qemu-iotests/041     | 146 ++++++++++++++++++++++++++++++++++++-
 tests/qemu-iotests/041.out |   4 +-
 2 files changed, 147 insertions(+), 3 deletions(-)
tests/qemu-iotests/041 +145 -1
index 0c1432f189..c2b5299f62 100755
@@ -20,8 +20,9 @@
 
 import time
 import os
+import json
 import iotests
-from iotests import qemu_img, qemu_io
+from iotests import qemu_img, qemu_img_pipe, qemu_io
 
 backing_img = os.path.join(iotests.test_dir, 'backing.img')
 target_backing_img = os.path.join(iotests.test_dir, 'target-backing.img')
@@ -1191,5 +1192,148 @@ class TestReplaces(iotests.QMPTestCase):
         os.remove(test_img)
         os.remove(target_img)
 
+# Tests for mirror with filters (and how the mirror filter behaves, as
+# an example for an implicit filter)
+class TestFilters(iotests.QMPTestCase):
+    def setUp(self):
+        qemu_img('create', '-f', iotests.imgfmt, backing_img, '1M')
+        qemu_img('create', '-f', iotests.imgfmt, '-b', backing_img, test_img)
+        qemu_img('create', '-f', iotests.imgfmt, '-b', backing_img, target_img)
+
+        qemu_io('-c', 'write -P 1 0 512k', backing_img)
+        qemu_io('-c', 'write -P 2 512k 512k', test_img)
+
+        self.vm = iotests.VM()
+        self.vm.launch()
+
+        result = self.vm.qmp('blockdev-add', **{
+                                'node-name': 'target',
+                                'driver': iotests.imgfmt,
+                                'file': {
+                                    'driver': 'file',
+                                    'filename': target_img
+                                },
+                                'backing': None
+                            })
+        self.assert_qmp(result, 'return', {})
+
+        self.filterless_chain = {
+                'node-name': 'source',
+                'driver': iotests.imgfmt,
+                'file': {
+                    'driver': 'file',
+                    'filename': test_img
+                },
+                'backing': {
+                    'node-name': 'backing',
+                    'driver': iotests.imgfmt,
+                    'file': {
+                        'driver': 'file',
+                        'filename': backing_img
+                    }
+                }
+            }
+
+    def tearDown(self):
+        self.vm.shutdown()
+
+        os.remove(test_img)
+        os.remove(target_img)
+        os.remove(backing_img)
+
+    def test_cor(self):
+        result = self.vm.qmp('blockdev-add', **{
+                                'node-name': 'filter',
+                                'driver': 'copy-on-read',
+                                'file': self.filterless_chain
+                            })
+        self.assert_qmp(result, 'return', {})
+
+        result = self.vm.qmp('blockdev-mirror',
+                             job_id='mirror',
+                             device='filter',
+                             target='target',
+                             sync='top')
+        self.assert_qmp(result, 'return', {})
+
+        self.complete_and_wait('mirror')
+
+        self.vm.qmp('blockdev-del', node_name='target')
+
+        target_map = qemu_img_pipe('map', '--output=json', target_img)
+        target_map = json.loads(target_map)
+
+        assert target_map[0]['start'] == 0
+        assert target_map[0]['length'] == 512 * 1024
+        assert target_map[0]['depth'] == 1
+
+        assert target_map[1]['start'] == 512 * 1024
+        assert target_map[1]['length'] == 512 * 1024
+        assert target_map[1]['depth'] == 0
+
+    def test_implicit_mirror_filter(self):
+        result = self.vm.qmp('blockdev-add', **self.filterless_chain)
+        self.assert_qmp(result, 'return', {})
+
+        # We need this so we can query from above the mirror node
+        result = self.vm.qmp('device_add',
+                             driver='virtio-blk',
+                             id='virtio',
+                             bus='pci.0',
+                             drive='source')
+        self.assert_qmp(result, 'return', {})
+
+        result = self.vm.qmp('blockdev-mirror',
+                             job_id='mirror',
+                             device='source',
+                             target='target',
+                             sync='top')
+        self.assert_qmp(result, 'return', {})
+
+        # The mirror filter is now an implicit node, so it should be
+        # invisible when querying the backing chain
+        device_info = self.vm.qmp('query-block')['return'][0]
+        assert device_info['qdev'] == '/machine/peripheral/virtio/virtio-backend'
+
+        assert device_info['inserted']['node-name'] == 'source'
+
+        image_info = device_info['inserted']['image']
+        assert image_info['filename'] == test_img
+        assert image_info['backing-image']['filename'] == backing_img
+
+        self.complete_and_wait('mirror')
+
+    def test_explicit_mirror_filter(self):
+        # Same test as above, but this time we give the mirror filter
+        # a node-name so it will not be invisible
+        result = self.vm.qmp('blockdev-add', **self.filterless_chain)
+        self.assert_qmp(result, 'return', {})
+
+        # We need this so we can query from above the mirror node
+        result = self.vm.qmp('device_add',
+                             driver='virtio-blk',
+                             id='virtio',
+                             bus='pci.0',
+                             drive='source')
+        self.assert_qmp(result, 'return', {})
+
+        result = self.vm.qmp('blockdev-mirror',
+                             job_id='mirror',
+                             device='source',
+                             target='target',
+                             sync='top',
+                             filter_node_name='mirror-filter')
+        self.assert_qmp(result, 'return', {})
+
+        # With a node-name given to it, the mirror filter should now
+        # be visible
+        device_info = self.vm.qmp('query-block')['return'][0]
+        assert device_info['qdev'] == '/machine/peripheral/virtio/virtio-backend'
+
+        assert device_info['inserted']['node-name'] == 'mirror-filter'
+
+        self.complete_and_wait('mirror')
+
+
 if __name__ == '__main__':
     iotests.main(supported_fmts=['qcow2', 'qed'])
tests/qemu-iotests/041.out +2 -2
index 2c448b4239..ffc779b4d1 100644
@@ -1,5 +1,5 @@
-..........................................................................................
+.............................................................................................
 ----------------------------------------------------------------------
-Ran 90 tests
+Ran 93 tests
 
 OK
Signature · 1 line
2.21.0
Reviewed-by on v6 40/42
#132 lore raw

Re: [Qemu-devel] [PATCH v6 40/42] iotests: Add filter mirror test cases

Quoted 6 lines · Max Reitz

This patch adds some test cases how mirroring relates to filters. One of them tests what happens when you mirror off a filtered COW node, two others use the mirror filter node as basically our only example of an implicitly created filter node so far (besides the commit filter).

Signature · 2 lines
Best regards,
Vladimir
author
#133 lore raw

PATCH v6 41/42 iotests: Add test for commit in sub directory

In reply to Max Reitz

Add a test for committing an overlay in a sub directory to one of the images in its backing chain, using both relative and absolute filenames.

---
 tests/qemu-iotests/020     | 36 ++++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/020.out | 10 ++++++++++
 2 files changed, 46 insertions(+)
tests/qemu-iotests/020 +36 -0
index 6b0ebb37d2..94633c3a32 100755
@@ -31,6 +31,11 @@ _cleanup()
 	_cleanup_test_img
     rm -f "$TEST_IMG.base"
     rm -f "$TEST_IMG.orig"
+
+    rm -f "$TEST_DIR/subdir/t.$IMGFMT.base"
+    rm -f "$TEST_DIR/subdir/t.$IMGFMT.mid"
+    rm -f "$TEST_DIR/subdir/t.$IMGFMT"
+    rmdir "$TEST_DIR/subdir" &> /dev/null
 }
 trap "_cleanup; exit \$status" 0 1 2 3 15
 
@@ -133,6 +138,37 @@ $QEMU_IO -c 'writev 0 64k' "$TEST_IMG" | _filter_qemu_io
 $QEMU_IMG commit "$TEST_IMG"
 _cleanup
 
+
+echo
+echo 'Testing commit in sub-directory with relative filenames'
+echo
+
+pushd "$TEST_DIR" > /dev/null
+
+mkdir subdir
+
+TEST_IMG="subdir/t.$IMGFMT.base" _make_test_img 1M
+TEST_IMG="subdir/t.$IMGFMT.mid" _make_test_img -b "t.$IMGFMT.base"
+TEST_IMG="subdir/t.$IMGFMT" _make_test_img -b "t.$IMGFMT.mid"
+
+# Should work
+$QEMU_IMG commit -b "t.$IMGFMT.mid" "subdir/t.$IMGFMT"
+
+# Might theoretically work, but does not in practice (we have to
+# decide between this and the above; and since we always represent
+# backing file names as relative to the overlay, we go for the above)
+$QEMU_IMG commit -b "subdir/t.$IMGFMT.mid" "subdir/t.$IMGFMT" 2>&1 | \
+    _filter_imgfmt
+
+# This should work as well
+$QEMU_IMG commit -b "$TEST_DIR/subdir/t.$IMGFMT.mid" "subdir/t.$IMGFMT"
+
+popd > /dev/null
+
+# Now let's try with just absolute filenames
+$QEMU_IMG commit -b "$TEST_DIR/subdir/t.$IMGFMT.mid" \
+    "$TEST_DIR/subdir/t.$IMGFMT"
+
 # success, all done
 echo "*** done"
 rm -f $seq.full
tests/qemu-iotests/020.out +10 -0
index 4b722b2dd0..228c37dded 100644
@@ -1094,4 +1094,14 @@ Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=1048576 backing_file=json:{'driv
 wrote 65536/65536 bytes at offset 0
 64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
 qemu-img: Block job failed: No space left on device
+
+Testing commit in sub-directory with relative filenames
+
+Formatting 'subdir/t.IMGFMT.base', fmt=IMGFMT size=1048576
+Formatting 'subdir/t.IMGFMT.mid', fmt=IMGFMT size=1048576 backing_file=t.IMGFMT.base
+Formatting 'subdir/t.IMGFMT', fmt=IMGFMT size=1048576 backing_file=t.IMGFMT.mid
+Image committed.
+qemu-img: Did not find 'subdir/t.IMGFMT.mid' in the backing chain of 'subdir/t.IMGFMT'
+Image committed.
+Image committed.
 *** done
Signature · 1 line
2.21.0
author
#134 lore raw

PATCH v6 42/42 iotests: Test committing to overridden backing

In reply to Max Reitz
---
 tests/qemu-iotests/040     | 61 ++++++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/040.out |  4 +--
 2 files changed, 63 insertions(+), 2 deletions(-)
tests/qemu-iotests/040 +61 -0
index a0a0db8889..558fdb9a09 100755
@@ -605,5 +605,66 @@ class TestCommitWithFilters(iotests.QMPTestCase):
         # 3 has been comitted into 2
         self.pattern_files[3] = self.img2
 
+class TestCommitWithOverriddenBacking(iotests.QMPTestCase):
+    img_base_a = os.path.join(iotests.test_dir, 'base_a.img')
+    img_base_b = os.path.join(iotests.test_dir, 'base_b.img')
+    img_top = os.path.join(iotests.test_dir, 'top.img')
+
+    def setUp(self):
+        qemu_img('create', '-f', iotests.imgfmt, self.img_base_a, '1M')
+        qemu_img('create', '-f', iotests.imgfmt, self.img_base_b, '1M')
+        qemu_img('create', '-f', iotests.imgfmt, '-b', self.img_base_a, \
+                 self.img_top)
+
+        self.vm = iotests.VM()
+        self.vm.launch()
+
+        # Use base_b instead of base_a as the backing of top
+        result = self.vm.qmp('blockdev-add', **{
+                                'node-name': 'top',
+                                'driver': iotests.imgfmt,
+                                'file': {
+                                    'driver': 'file',
+                                    'filename': self.img_top
+                                },
+                                'backing': {
+                                    'node-name': 'base',
+                                    'driver': iotests.imgfmt,
+                                    'file': {
+                                        'driver': 'file',
+                                        'filename': self.img_base_b
+                                    }
+                                }
+                            })
+        self.assert_qmp(result, 'return', {})
+
+    def tearDown(self):
+        self.vm.shutdown()
+        os.remove(self.img_top)
+        os.remove(self.img_base_a)
+        os.remove(self.img_base_b)
+
+    def test_commit_to_a(self):
+        # Try committing to base_a (which should fail, as top's
+        # backing image is base_b instead)
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top',
+                             base=self.img_base_a)
+        self.assert_qmp(result, 'error/class', 'GenericError')
+
+    def test_commit_to_b(self):
+        # Try committing to base_b (which should work, since that is
+        # actually top's backing image)
+        result = self.vm.qmp('block-commit',
+                             job_id='commit',
+                             device='top',
+                             base=self.img_base_b)
+        self.assert_qmp(result, 'return', {})
+
+        self.vm.event_wait('BLOCK_JOB_READY')
+        self.vm.qmp('block-job-complete', device='commit')
+        self.vm.event_wait('BLOCK_JOB_COMPLETED')
+
 if __name__ == '__main__':
     iotests.main(supported_fmts=['qcow2', 'qed'])
tests/qemu-iotests/040.out +2 -2
index fe58934d7a..499af0e2ff 100644
@@ -1,5 +1,5 @@
-...................................................
+.....................................................
 ----------------------------------------------------------------------
-Ran 51 tests
+Ran 53 tests
 
 OK
Signature · 1 line
2.21.0