Skip to contentSkip to conversation

block: cheaper zero handling in backup and commit

PATCH Superseded Denis V. Lunev 3 participants 19 messages Aug 28 – Sep 14 Block layer

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

cover block: cheaper zero handling in backup and commit

Backup and commit re-query the source block status for every task and size a task by the copy buffer, so a long run of zeroes turns into a crowd of small write-zeroes requests. This series reuses what the up-front scan already learned and lets one write-zeroes task cover a whole run.

Backup of a 16G qcow2 image holding 1G of data, the rest never allocated, sync=full to a raw target on ext4:

               tasks    time
    before     16384    1.6s
    after       1088    1.0s

Such an image is the normal case rather than a corner one: a guest with discard enabled on a disk which is mostly free leaves exactly this shape behind.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>

Denis V. Lunev (9):
block/commit: pass BDRV_WANT_PRECISE to block-status iotests/040: cover large and fragmented commit runs block/commit: batch block-status queries iotests/124: cover backup of zero clusters and holes block/block-copy: don't reserve memory for zero tasks block/block-copy: extract block_copy_set_task_method() block/block-copy: track known-zero source clusters block/backup: pre-fill zero_bitmap for full/bitmap block/block-copy: coalesce write-zeroes tasks

 block/backup.c             |  93 ++++++---
 block/block-copy.c         | 239 +++++++++++++++++++---
 block/commit.c             |  50 ++++-
 include/block/block-copy.h |   5 +
 tests/qemu-iotests/040     |  95 ++++++++-
 tests/qemu-iotests/040.out |   4 +-
 tests/qemu-iotests/124     | 402 ++++++++++++++++++++++++++++++++++++-
 tests/qemu-iotests/124.out |   4 +-
 8 files changed, 811 insertions(+), 81 deletions(-)

base-commit: 0a1ebd448b38afaa118597cbb633dbec24ef74d3

Signature · 1 line
2.53.0
#1 lore raw

PATCH 1/9 block/commit: pass BDRV_WANT_PRECISE to block-status

From: Denis V. Lunev <[email protected]>

c33159dec790 replaced the want_zero bool with a bitmask of BDRV_WANT_* flags. block/commit.c was missed and still passes "true", which is BDRV_BLOCK_DATA, not BDRV_WANT_PRECISE. Convert it like the other callers.

Fixes c33159dec790 ("block: Expand block status mode from bool to flags")
CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
CC Eric Blake <[email protected]>
---
 block/commit.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
block/commit.c +2 -2
index 2d52c39594..4e0b0f9029 100644
@@ -140,8 +140,8 @@ commit_iteration(CommitBlockJob *s, int64_t offset,
     /* Copy if allocated above the base */
     WITH_GRAPH_RDLOCK_GUARD() {
         ret = bdrv_co_common_block_status_above(blk_bs(s->top),
-            s->base_overlay, true, true, offset, COMMIT_BUFFER_SIZE,
-            &bytes, NULL, NULL, NULL);
+            s->base_overlay, true, BDRV_WANT_PRECISE, offset,
+            COMMIT_BUFFER_SIZE, &bytes, NULL, NULL, NULL);
     }
 
     trace_commit_one_iteration(s, offset, bytes, ret);
Signature · 1 line
2.53.0
Reviewed-by on v1 1/9
#2 lore raw

Re: [PATCH 1/9] block/commit: pass BDRV_WANT_PRECISE to block-status

Quoted 4 lines · Denis V. Lunev

c33159dec790 replaced the want_zero bool with a bitmask of BDRV_WANT_* flags. block/commit.c was missed and still passes "true", which is BDRV_BLOCK_DATA, not BDRV_WANT_PRECISE. Convert it like the other callers.

Signature · 1 line
Andrey Drobyshev <[email protected]>
#3 lore raw

PATCH 2/9 iotests/040: cover large and fragmented commit runs

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

040 never commits runs long enough to span more than one block-status query, so the answer that commit_iteration() is about to start caching goes untested.

Add two cases on a base <- mid <- active chain, committing mid so the job takes the regular commit path rather than active commit, and compare base against a snapshot of mid taken before the commit. One case mixes multi-megabyte data and hole runs, the other fragments them down to single clusters with every transition off the 512K boundary.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
---
 tests/qemu-iotests/040     | 95 +++++++++++++++++++++++++++++++++++++-
 tests/qemu-iotests/040.out |  4 +-
 2 files changed, 96 insertions(+), 3 deletions(-)
tests/qemu-iotests/040 +94 -1
index 5c18e413ec..57e32b99c1 100755
@@ -25,13 +25,14 @@
 import time
 import os
 import iotests
-from iotests import qemu_img, qemu_io
+from iotests import qemu_img, qemu_img_create, qemu_io, compare_images
 import struct
 import errno
 
 backing_img = os.path.join(iotests.test_dir, 'backing.img')
 mid_img = os.path.join(iotests.test_dir, 'mid.img')
 test_img = os.path.join(iotests.test_dir, 'test.img')
+reference_img = os.path.join(iotests.test_dir, 'reference.img')
 
 class ImageCommitTestCase(iotests.QMPTestCase):
     '''Abstract base class for image commit test cases'''
@@ -951,6 +952,98 @@ class TestCommitWithOverriddenBacking(iotests.QMPTestCase):
         self.vm.qmp('block-job-complete', device='commit')
         self.vm.event_wait('BLOCK_JOB_COMPLETED')
 
+class TestCommitLargeRuns(iotests.QMPTestCase):
+    """Commit runs long enough to cross commit_iteration()'s cached span."""
+
+    MB = 1024 * 1024
+    CLUSTER = 64 * 1024
+
+    # Runs several COMMIT_BUFFER_SIZE (512K) chunks long, both kinds.
+    SIZE = 32 * MB
+    LAYOUT = [
+        (0, 4 * MB, 'data'),
+        (4 * MB, 6 * MB, 'hole'),
+        (10 * MB, 4 * MB, 'data'),
+        (14 * MB, 6 * MB, 'hole'),
+        (20 * MB, 4 * MB, 'data'),
+    ]
+
+    # The same, with every transition off the 512K boundary.
+    SIZE_FRAGMENTED = 384 * CLUSTER  # 24M
+    LAYOUT_FRAGMENTED = [
+        (0, 45 * CLUSTER, 'data'),
+        (100 * CLUSTER, CLUSTER, 'data'),   # data island in a hole
+        (150 * CLUSTER, 80 * CLUSTER, 'data'),
+        # [230C, 231C) is a hole island in a data run
+        (231 * CLUSTER, 69 * CLUSTER, 'data'),
+    ]
+
+    def setUp(self):
+        self.vm = iotests.VM()
+        self.vm.launch()
+
+    def tearDown(self):
+        self.vm.shutdown()
+        for img in (backing_img, mid_img, test_img, reference_img):
+            if os.path.exists(img):
+                os.remove(img)
+
+    def build_images(self, layout, size):
+        # A pattern of its own in base, so a misplaced cluster shows up.
+        qemu_img_create('-f', iotests.imgfmt, backing_img, str(size))
+        qemu_io('-c', f'write -P 0x11 0 {size}', backing_img)
+
+        qemu_img_create('-f', iotests.imgfmt, '-b', backing_img, '-F',
+                        iotests.imgfmt, mid_img, str(size))
+        for offset, length, kind in layout:
+            if kind == 'data':
+                qemu_io('-c', f'write -P 0x22 {offset} {length}', mid_img)
+
+        # What base must equal once mid is committed into it.
+        qemu_img('convert', '-f', iotests.imgfmt, '-O', iotests.imgfmt,
+                 mid_img, reference_img)
+
+        # An empty layer above mid, so top_node=mid is not the active one.
+        qemu_img_create('-f', iotests.imgfmt, '-b', mid_img, '-F',
+                        iotests.imgfmt, test_img, str(size))
+
+        self.vm.cmd('blockdev-add', {
+            'node-name': 'base',
+            'driver': iotests.imgfmt,
+            'file': {'driver': 'file', 'filename': backing_img},
+        })
+        self.vm.cmd('blockdev-add', {
+            'node-name': 'mid',
+            'driver': iotests.imgfmt,
+            'file': {'driver': 'file', 'filename': mid_img},
+            'backing': 'base',
+        })
+        self.vm.cmd('blockdev-add', {
+            'node-name': 'active',
+            'driver': iotests.imgfmt,
+            'file': {'driver': 'file', 'filename': test_img},
+            'backing': 'mid',
+        })
+
+    def commit_and_verify(self):
+        self.vm.cmd('block-commit', job_id='commit0', device='active',
+                    top_node='mid', base_node='base')
+        self.wait_until_completed(drive='commit0')
+
+        self.vm.cmd('blockdev-del', node_name='active')
+        self.vm.cmd('blockdev-del', node_name='mid')
+        self.vm.cmd('blockdev-del', node_name='base')
+        self.assertTrue(compare_images(reference_img, backing_img))
+
+    def test_commit_large_runs(self):
+        self.build_images(self.LAYOUT, self.SIZE)
+        self.commit_and_verify()
+
+    def test_commit_fragmented_runs(self):
+        self.build_images(self.LAYOUT_FRAGMENTED, self.SIZE_FRAGMENTED)
+        self.commit_and_verify()
+
+
 if __name__ == '__main__':
     iotests.main(supported_fmts=['qcow2', 'qed'],
                  supported_protocols=['file'])
tests/qemu-iotests/040.out +2 -2
index 1bb1dc5f0e..d2e2a2d98f 100644
@@ -1,5 +1,5 @@
-.................................................................
+...................................................................
 ----------------------------------------------------------------------
-Ran 65 tests
+Ran 67 tests
 
 OK
Signature · 1 line
2.53.0
#4 lore raw

Re: [PATCH 2/9] iotests/040: cover large and fragmented commit runs

Quoted 54 lines

040 never commits runs long enough to span more than one block-status query, so the answer that commit_iteration() is about to start caching goes untested.

Add two cases on a base <- mid <- active chain, committing mid so the job takes the regular commit path rather than active commit, and compare base against a snapshot of mid taken before the commit. One case mixes multi-megabyte data and hole runs, the other fragments them down to single clusters with every transition off the 512K boundary.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
tests/qemu-iotests/040 +17 -1
index 5c18e413ec9..57e32b99c10 100755
@@ -25,13 +25,14 @@
 import time
 import os
 import iotests
-from iotests import qemu_img, qemu_io
+from iotests import qemu_img, qemu_img_create, qemu_io, compare_images
 import struct
 import errno
 
 backing_img = os.path.join(iotests.test_dir, 'backing.img')
 mid_img = os.path.join(iotests.test_dir, 'mid.img')
 test_img = os.path.join(iotests.test_dir, 'test.img')
+reference_img = os.path.join(iotests.test_dir, 'reference.img')
 
 class ImageCommitTestCase(iotests.QMPTestCase):
     '''Abstract base class for image commit test cases'''
@@ -951,6 +952,98 @@ class TestCommitWithOverriddenBacking(iotests.QMPTestCase):
         self.vm.qmp('block-job-complete', device='commit')
         self.vm.event_wait('BLOCK_JOB_COMPLETED')
 
+class TestCommitLargeRuns(iotests.QMPTestCase):
+    """Commit runs long enough to cross commit_iteration()'s cached span."""
+
+    MB = 1024 * 1024
+    CLUSTER = 64 * 1024
+
+    # Runs several COMMIT_BUFFER_SIZE (512K) chunks long, both kinds.
+    SIZE = 32 * MB
+    LAYOUT = [
+        (0, 4 * MB, 'data'),
+        (4 * MB, 6 * MB, 'hole'),
+        (10 * MB, 4 * MB, 'data'),
+        (14 * MB, 6 * MB, 'hole'),
+        (20 * MB, 4 * MB, 'data'),
+    ]

tests/qemu-iotests/040 class TestCommitWithOverriddenBacking(iotests.QMPTestCase): · line 979

Quoted 10 lines
tests/qemu-iotests/040 +10 -0
+
+    # The same, with every transition off the 512K boundary.
+    SIZE_FRAGMENTED = 384 * CLUSTER  # 24M
+    LAYOUT_FRAGMENTED = [
+        (0, 45 * CLUSTER, 'data'),
+        (100 * CLUSTER, CLUSTER, 'data'),   # data island in a hole
+        (150 * CLUSTER, 80 * CLUSTER, 'data'),
+        # [230C, 231C) is a hole island in a data run
+        (231 * CLUSTER, 69 * CLUSTER, 'data'),
+    ]

We explicitly mark 'hole' in LAYOUT, but not in LAYOUT_FRAGMENTED. Maybe make it consistent?

Also, the next commit changes how block-commit doing write_zeroes() - shouldn't we add 'zero' regions as well to test that?

Andrey

Signature · 1 line
Andrey Drobyshev <[email protected]>
#5 lore raw

PATCH 3/9 block/commit: batch block-status queries

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

commit_iteration() asks for block status COMMIT_BUFFER_SIZE (512K) at a time, so a long run above base pays one query per 512K for an answer the whole run shares.

Query the remainder of the image instead and keep the answer in a CommitStatus owned by commit_run(). Nothing can write top above base_overlay while the job runs: BLK_PERM_CONSISTENT_READ is shared only from filtered_base downwards, and the job writes below base_overlay.

Copying is still bounded by the read buffer. Zeroes need no buffer, so COMMIT_ZERO_CHUNK bounds them, keeping a cancel from waiting on a huge write-zeroes, and an unallocated span is crossed in one step.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
---
 block/commit.c | 50 +++++++++++++++++++++++++++++++++++++++-----------
 1 file changed, 39 insertions(+), 11 deletions(-)
block/commit.c +39 -11
index 4e0b0f9029..5aa3df31e1 100644
@@ -31,8 +31,17 @@ enum {
      * contiguous regions of the image is efficient.
      */
     COMMIT_BUFFER_SIZE = 512 * 1024, /* in bytes */
+    COMMIT_ZERO_CHUNK = 256 * 1024 * 1024, /* in bytes */
 };
 
+/* Last block-status answer, covering [offset, end). Empty when equal. */
+typedef struct CommitStatus {
+    int64_t len;
+    int64_t offset;
+    int64_t end;
+    int ret;
+} CommitStatus;
+
 typedef struct CommitBlockJob {
     BlockJob common;
     BlockDriverState *commit_top_bs;
@@ -130,26 +139,43 @@ static void commit_clean(Job *job)
 
 static int coroutine_fn
 commit_iteration(CommitBlockJob *s, int64_t offset,
-                 int64_t *requested_bytes, void *buf)
+                 int64_t *requested_bytes, void *buf, CommitStatus *st)
 {
     BlockErrorAction action;
-    int64_t bytes = *requested_bytes;
+    int64_t bytes;
     int ret = 0;
     bool error_in_source = true;
 
-    /* Copy if allocated above the base */
-    WITH_GRAPH_RDLOCK_GUARD() {
-        ret = bdrv_co_common_block_status_above(blk_bs(s->top),
-            s->base_overlay, true, BDRV_WANT_PRECISE, offset,
-            COMMIT_BUFFER_SIZE, &bytes, NULL, NULL, NULL);
+    if (offset < st->offset || offset >= st->end) {
+        /* Copy if allocated above the base */
+        WITH_GRAPH_RDLOCK_GUARD() {
+            ret = bdrv_co_common_block_status_above(blk_bs(s->top),
+                s->base_overlay, true, BDRV_WANT_PRECISE, offset,
+                st->len - offset, &bytes, NULL, NULL, NULL);
+        }
+
+        if (ret < 0) {
+            trace_commit_one_iteration(s, offset, 0, ret);
+            goto fail;
+        }
+
+        st->offset = offset;
+        st->end = offset + bytes;
+        st->ret = ret;
     }
 
-    trace_commit_one_iteration(s, offset, bytes, ret);
+    ret = st->ret;
+    bytes = st->end - offset;
 
-    if (ret < 0) {
-        goto fail;
+    /* An unallocated span costs no I/O, so it is crossed in one step. */
+    if (ret & BDRV_BLOCK_ZERO) {
+        bytes = MIN(bytes, COMMIT_ZERO_CHUNK);
+    } else if (ret & BDRV_BLOCK_ALLOCATED) {
+        bytes = MIN(bytes, COMMIT_BUFFER_SIZE);
     }
 
+    trace_commit_one_iteration(s, offset, bytes, ret);
+
     if (ret & BDRV_BLOCK_ALLOCATED) {
         if (ret & BDRV_BLOCK_ZERO) {
             /*
@@ -215,6 +241,7 @@ static int coroutine_fn commit_run(Job *job, Error **errp)
     int64_t n = 0; /* bytes */
     QEMU_AUTO_VFREE void *buf = NULL;
     int64_t len, base_len;
+    CommitStatus st = { 0 };
 
     len = blk_co_getlength(s->top);
     if (len < 0) {
@@ -235,6 +262,7 @@ static int coroutine_fn commit_run(Job *job, Error **errp)
     }
 
     buf = blk_blockalign(s->top, COMMIT_BUFFER_SIZE);
+    st.len = len;
 
     for (offset = 0; offset < len; offset += n) {
         /* Note that even when no rate limit is applied we need to yield
@@ -245,7 +273,7 @@ static int coroutine_fn commit_run(Job *job, Error **errp)
             break;
         }
 
-        ret = commit_iteration(s, offset, &n, buf);
+        ret = commit_iteration(s, offset, &n, buf, &st);
 
         if (ret < 0) {
             return ret;
Signature · 1 line
2.53.0
#6 lore raw

Re: [PATCH 3/9] block/commit: batch block-status queries

Quoted 24 lines

commit_iteration() asks for block status COMMIT_BUFFER_SIZE (512K) at a time, so a long run above base pays one query per 512K for an answer the whole run shares.

Query the remainder of the image instead and keep the answer in a CommitStatus owned by commit_run(). Nothing can write top above base_overlay while the job runs: BLK_PERM_CONSISTENT_READ is shared only from filtered_base downwards, and the job writes below base_overlay.

Copying is still bounded by the read buffer. Zeroes need no buffer, so COMMIT_ZERO_CHUNK bounds them, keeping a cancel from waiting on a huge write-zeroes, and an unallocated span is crossed in one step.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
block/commit.c +0 -0
index 4e0b0f9029b..5aa3df31e1c 100644

block/commit.c enum { · line 34

Quoted 4 lines
block/commit.c +1 -0
@@ -31,8 +31,17 @@ enum {
      * contiguous regions of the image is efficient.
      */
     COMMIT_BUFFER_SIZE = 512 * 1024, /* in bytes */
+    COMMIT_ZERO_CHUNK = 256 * 1024 * 1024, /* in bytes */

Comment above was targeting the COMMIT_BUFFER_SIZE only, now it seems to be applied to both constants, which is misleading. Also why exactly 256M? It isn't explained neither in here nor in the commit message.

Quoted 22 lines
block/commit.c +9 -2
 };
 
+/* Last block-status answer, covering [offset, end). Empty when equal. */
+typedef struct CommitStatus {
+    int64_t len;
+    int64_t offset;
+    int64_t end;
+    int ret;
+} CommitStatus;
+
 typedef struct CommitBlockJob {
     BlockJob common;
     BlockDriverState *commit_top_bs;
@@ -130,26 +139,43 @@ static void commit_clean(Job *job)
 
 static int coroutine_fn
 commit_iteration(CommitBlockJob *s, int64_t offset,
-                 int64_t *requested_bytes, void *buf)
+                 int64_t *requested_bytes, void *buf, CommitStatus *st)
 {
     BlockErrorAction action;
-    int64_t bytes = *requested_bytes;

block/commit.c static void commit_clean(Job *job) · line 149

Quoted 10 lines
block/commit.c +2 -5
+    int64_t bytes;
     int ret = 0;
     bool error_in_source = true;
 
-    /* Copy if allocated above the base */
-    WITH_GRAPH_RDLOCK_GUARD() {
-        ret = bdrv_co_common_block_status_above(blk_bs(s->top),
-            s->base_overlay, true, BDRV_WANT_PRECISE, offset,
-            COMMIT_BUFFER_SIZE, &bytes, NULL, NULL, NULL);
+    if (offset < st->offset || offset >= st->end) {

If I understand the code correctly the (offset < st->offset) part of this condition is never true. commit_run() is the only caller, and offset monotonically non-decreases in the for loop. Then st->offset is only ever set to values which 'offset' did hold at some point. So we should strip this condition from if statement, and I'd even add assert(offset >= st->offset) check at the function preamble.

Andrey

Signature · 1 line
Andrey Drobyshev <[email protected]>
#7 lore raw

PATCH 4/9 iotests/124: cover backup of zero clusters and holes

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

The backup tests compare content only, and their sources hold data alone, so nothing pins how backup treats zero clusters and holes. Back up a source mixing data, write-zero and holes with sync=full, sync=top and sync=bitmap, and check the target with qemu-img map, which tells a copied cluster apart from a write-zero and from an untouched one.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
---
 tests/qemu-iotests/124     | 402 ++++++++++++++++++++++++++++++++++++-
 tests/qemu-iotests/124.out |   4 +-
 2 files changed, 403 insertions(+), 3 deletions(-)
tests/qemu-iotests/124 +401 -1
index b2f4328e34..eb5ab02904 100755
@@ -22,8 +22,11 @@
 #
 
 import os
+from collections import namedtuple
+
 import iotests
-from iotests import try_remove
+from iotests import (compare_images, qemu_img_create, qemu_img_map, qemu_io,
+                     try_remove)
 from qemu.qmp.qmp_client import ExecuteError
 
 
@@ -748,6 +751,403 @@ class TestIncrementalBackupBlkdebug(TestIncrementalBackupBase):
         self.check_backups()
 
 
+# Backup of sources mixing data, zero clusters and holes.
+
+Extent = namedtuple('Extent', ['start', 'length', 'kind'])
+
+source_img = os.path.join(iotests.test_dir, 'source')
+base_img = os.path.join(iotests.test_dir, 'base')
+target_img = os.path.join(iotests.test_dir, 'target')
+
+SIZE = 64 * 1024 * 1024
+MB = 1024 * 1024
+CLUSTER = 64 * 1024
+
+# Data, write-zero and holes, every combination at a cluster boundary.
+LAYOUT = [
+    (0, MB, 'data'),
+    (2 * MB, MB, 'zero'),
+    (5 * MB, 2 * MB, 'data'),
+    (8 * MB, MB, 'zero'),
+    (10 * MB, MB // 2, 'data'),
+    (20 * MB, 4 * MB, 'zero'),
+    (30 * MB, MB, 'data'),
+]
+
+# Single-cluster runs, and a zero run ending exactly at EOF.
+BOUNDARY_SIZE = 16 * MB
+LAYOUT_BOUNDARY = [
+    (0, CLUSTER, 'zero'),
+    (CLUSTER, CLUSTER, 'data'),
+    (2 * CLUSTER, CLUSTER, 'zero'),
+    (3 * CLUSTER, CLUSTER, 'data'),
+    (4 * CLUSTER, 8 * MB, 'zero'),
+    (4 * CLUSTER + 8 * MB, CLUSTER, 'data'),
+    (BOUNDARY_SIZE - CLUSTER, CLUSTER, 'zero'),
+]
+
+# A zero run past the old block_copy_chunk_size() 16M cap.
+LARGE_ZERO_SIZE = 48 * MB
+LAYOUT_LARGE_ZERO = [
+    (0, MB, 'data'),
+    (4 * MB, 32 * MB, 'zero'),
+    (40 * MB, MB, 'data'),
+]
+
+# Image size not a multiple of the cluster size: a partial tail cluster.
+TAIL_SIZE = 4 * MB + 4096
+LAYOUT_TAIL_ZERO = [
+    (0, MB, 'data'),
+    (2 * MB, TAIL_SIZE - 2 * MB, 'zero'),
+]
+LAYOUT_TAIL_DATA = [
+    (0, MB, 'data'),
+    (2 * MB, MB, 'zero'),
+    (4 * MB, TAIL_SIZE - 4 * MB, 'data'),
+]
+
+
+def coalesce(extents):
+    out = []
+    for e in extents:
+        prev = out[-1] if out else None
+        adjacent = prev is not None and prev.start + prev.length == e.start
+        if adjacent and prev.kind == e.kind:
+            out[-1] = prev._replace(length=prev.length + e.length)
+        else:
+            out.append(e)
+    return out
+
+
+def layout_to_extents(layout, size, gap='hole'):
+    extents = []
+    pos = 0
+    for offset, length, kind in layout:
+        if offset > pos:
+            extents.append(Extent(pos, offset - pos, gap))
+        extents.append(Extent(offset, length, kind))
+        pos = offset + length
+    if pos < size:
+        extents.append(Extent(pos, size - pos, gap))
+    return coalesce(extents)
+
+
+class TestBackupZeroClusters(iotests.QMPTestCase):
+    def setUp(self):
+        self.vm = iotests.VM()
+        self.vm.launch()
+
+    def tearDown(self):
+        self.vm.shutdown()
+        for img in (source_img, base_img, target_img):
+            if os.path.exists(img):
+                os.remove(img)
+
+    def hmp_write(self, drive, cmd):
+        res = self.vm.hmp_qemu_io(drive, cmd)
+        assert 'error' not in res['return'].lower(), res
+
+    def assert_map(self, img, layout, size, backing=False, gap='hole'):
+        # Content is not enough, pin the data/zero/hole split as well.
+        def classify(e):
+            is_hole = e['depth'] > 0 if backing else not e['present']
+            return 'hole' if is_hole else ('zero' if e['zero'] else 'data')
+
+        actual = coalesce([Extent(e['start'], e['length'], classify(e))
+                           for e in qemu_img_map(img)])
+
+        self.assertEqual(actual, layout_to_extents(layout, size, gap))
+
+    def add_source(self, layout=None, size=SIZE, backing=None):
+        if layout is None:
+            layout = LAYOUT
+
+        create_args = ['-f', iotests.imgfmt]
+        if backing:
+            create_args += ['-b', backing, '-F', iotests.imgfmt]
+        create_args += [source_img, str(size)]
+        qemu_img_create(*create_args)
+
+        self.vm.cmd('blockdev-add', {
+            'node-name': 'src',
+            'driver': iotests.imgfmt,
+            'file': {'driver': 'file', 'filename': source_img},
+        })
+
+        # Write through the node, so an attached bitmap sees it.
+        for offset, length, kind in layout:
+            opt = '-z' if kind == 'zero' else '-P 0x5a'
+            self.hmp_write('src', f'write {opt} {offset} {length}')
+
+    def do_backup(self, sync, target_backing=None, size=SIZE, prefill=None,
+                 **kwargs):
+        create_args = ['-f', iotests.imgfmt]
+        if target_backing:
+            create_args += ['-b', target_backing, '-F', iotests.imgfmt]
+        create_args += [target_img, str(size)]
+        qemu_img_create(*create_args)
+
+        if prefill is not None:
+            # Not zero, so a skipped cluster is provably untouched.
+            qemu_io('-c', f'write -P {prefill} 0 {size}', target_img)
+
+        self.vm.cmd('blockdev-add', {
+            'node-name': 'target',
+            'driver': iotests.imgfmt,
+            'file': {'driver': 'file', 'filename': target_img},
+        })
+
+        self.vm.cmd('blockdev-backup', device='src', target='target',
+                    job_id='bk0', sync=sync, **kwargs)
+        self.wait_until_completed(drive='bk0')
+
+        self.vm.cmd('blockdev-del', node_name='target')
+        self.vm.cmd('blockdev-del', node_name='src')
+
+    def test_full(self):
+        self.add_source()
+        self.do_backup('full')
+        self.assertTrue(compare_images(source_img, target_img))
+        self.assert_map(target_img, LAYOUT, SIZE, gap='zero')
+
+    def test_full_zero_overwrite(self):
+        # full skips holes, so only check that zero overwrites prefill.
+        self.add_source(layout=[(2 * MB, MB, 'zero')])
+        self.do_backup('full', prefill=0xcc)
+        qemu_io('-c', f'read -P 0 {2 * MB} {MB}', target_img)
+
+    def test_bitmap(self):
+        self.add_source()
+
+        # A new bitmap tracks nothing yet: dirty all, then re-apply.
+        self.vm.cmd('block-dirty-bitmap-add', node='src', name='bm0')
+        self.hmp_write('src', f'write -z 0 {SIZE}')
+        for offset, length, kind in LAYOUT:
+            opt = '-z' if kind == 'zero' else '-P 0x5a'
+            self.hmp_write('src', f'write {opt} {offset} {length}')
+
+        self.do_backup('bitmap', bitmap='bm0', bitmap_mode='never')
+        self.assertTrue(compare_images(source_img, target_img))
+
+        # The blanket write-zero above turned LAYOUT's gaps into zero.
+        self.assert_map(target_img, LAYOUT, SIZE, gap='zero')
+
+    def test_top(self):
+        # Non-zero backing data, so a hole and an explicit zero differ.
+        qemu_img_create('-f', iotests.imgfmt, base_img, str(SIZE))
+        qemu_io('-c', f'write -P 0x33 0 {SIZE}', base_img)
+
+        self.add_source(backing=base_img)
+
+        self.do_backup('top', target_backing=base_img)
+        self.assertTrue(compare_images(source_img, target_img))
+        self.assert_map(target_img, LAYOUT, SIZE, backing=True)
+
+    def test_boundary_full(self):
+        self.add_source(layout=LAYOUT_BOUNDARY, size=BOUNDARY_SIZE)
+        self.do_backup('full', size=BOUNDARY_SIZE)
+        self.assertTrue(compare_images(source_img, target_img))
+        self.assert_map(target_img, LAYOUT_BOUNDARY, BOUNDARY_SIZE,
+                        gap='zero')
+
+    def test_boundary_bitmap(self):
+        self.add_source(layout=LAYOUT_BOUNDARY, size=BOUNDARY_SIZE)
+
+        self.vm.cmd('block-dirty-bitmap-add', node='src', name='bm0')
+        self.hmp_write('src', f'write -z 0 {BOUNDARY_SIZE}')
+        for offset, length, kind in LAYOUT_BOUNDARY:
+            opt = '-z' if kind == 'zero' else '-P 0x5a'
+            self.hmp_write('src', f'write {opt} {offset} {length}')
+
+        self.do_backup('bitmap', bitmap='bm0', size=BOUNDARY_SIZE,
+                       bitmap_mode='never')
+        self.assertTrue(compare_images(source_img, target_img))
+        self.assert_map(target_img, LAYOUT_BOUNDARY, BOUNDARY_SIZE, gap='zero')
+
+    def test_large_zero_full(self):
+        self.add_source(layout=LAYOUT_LARGE_ZERO, size=LARGE_ZERO_SIZE)
+        self.do_backup('full', size=LARGE_ZERO_SIZE)
+        self.assertTrue(compare_images(source_img, target_img))
+        self.assert_map(target_img, LAYOUT_LARGE_ZERO, LARGE_ZERO_SIZE,
+                        gap='zero')
+
+    def test_large_zero_bitmap(self):
+        self.add_source(layout=LAYOUT_LARGE_ZERO, size=LARGE_ZERO_SIZE)
+
+        self.vm.cmd('block-dirty-bitmap-add', node='src', name='bm0')
+        self.hmp_write('src', f'write -z 0 {LARGE_ZERO_SIZE}')
+        for offset, length, kind in LAYOUT_LARGE_ZERO:
+            opt = '-z' if kind == 'zero' else '-P 0x5a'
+            self.hmp_write('src', f'write {opt} {offset} {length}')
+
+        self.do_backup('bitmap', bitmap='bm0', size=LARGE_ZERO_SIZE,
+                       bitmap_mode='never')
+        self.assertTrue(compare_images(source_img, target_img))
+        self.assert_map(target_img, LAYOUT_LARGE_ZERO, LARGE_ZERO_SIZE,
+                        gap='zero')
+
+    def test_huge_zero(self):
+        # One run past BLOCK_COPY_MAX_ZERO_CHUNK (256M), so it splits.
+        size = 768 * MB
+        self.add_source(layout=[(0, size, 'zero')], size=size)
+        self.do_backup('full', size=size)
+        self.assertTrue(compare_images(source_img, target_img))
+        self.assert_map(target_img, [(0, size, 'zero')], size)
+
+    def test_tail_data(self):
+        self.add_source(layout=LAYOUT_TAIL_DATA, size=TAIL_SIZE)
+        self.do_backup('full', size=TAIL_SIZE)
+        self.assertTrue(compare_images(source_img, target_img))
+        self.assert_map(target_img, LAYOUT_TAIL_DATA, TAIL_SIZE, gap='zero')
+
+    def test_tail_zero(self):
+        # The partial tail cluster falls out of zero_bitmap, so it copies.
+        self.add_source(layout=LAYOUT_TAIL_ZERO, size=TAIL_SIZE)
+        self.do_backup('full', size=TAIL_SIZE)
+        self.assertTrue(compare_images(source_img, target_img))
+
+        tail_cluster = (TAIL_SIZE // CLUSTER) * CLUSTER
+        expected = [
+            (0, MB, 'data'),
+            (2 * MB, tail_cluster - 2 * MB, 'zero'),
+            (tail_cluster, TAIL_SIZE - tail_cluster, 'data'),
+        ]
+        self.assert_map(target_img, expected, TAIL_SIZE, gap='zero')
+
+    def test_tail_zero_bitmap(self):
+        # Same tail rounding as test_tail_zero, via the bitmap scan.
+        self.add_source(layout=LAYOUT_TAIL_ZERO, size=TAIL_SIZE)
+
+        self.vm.cmd('block-dirty-bitmap-add', node='src', name='bm0')
+        self.hmp_write('src', f'write -z 0 {TAIL_SIZE}')
+        for offset, length, kind in LAYOUT_TAIL_ZERO:
+            opt = '-z' if kind == 'zero' else '-P 0x5a'
+            self.hmp_write('src', f'write {opt} {offset} {length}')
+
+        self.do_backup('bitmap', bitmap='bm0', size=TAIL_SIZE,
+                       bitmap_mode='never')
+        self.assertTrue(compare_images(source_img, target_img))
+
+        tail_cluster = (TAIL_SIZE // CLUSTER) * CLUSTER
+        expected = [
+            (0, MB, 'data'),
+            (2 * MB, tail_cluster - 2 * MB, 'zero'),
+            (tail_cluster, TAIL_SIZE - tail_cluster, 'data'),
+        ]
+        self.assert_map(target_img, expected, TAIL_SIZE, gap='zero')
+
+    def test_mixed_cluster(self):
+        # 4K source clusters, so content varies inside one 64K cluster.
+        size = 2 * CLUSTER
+        qemu_img_create('-f', iotests.imgfmt, '-o', 'cluster_size=4k',
+                        source_img, str(size))
+        self.vm.cmd('blockdev-add', {
+            'node-name': 'src',
+            'driver': iotests.imgfmt,
+            'file': {'driver': 'file', 'filename': source_img},
+        })
+
+        # Zero, data and a hole inside the first cluster.
+        self.hmp_write('src', 'write -z 0 8k')
+        self.hmp_write('src', 'write -P 0x5a 8k 8k')
+
+        # The second cluster is uniformly zero.
+        self.hmp_write('src', f'write -z {CLUSTER} {CLUSTER}')
+
+        self.do_backup('full', size=size)
+        self.assertTrue(compare_images(source_img, target_img))
+
+        # A mixed cluster must be data, or the data at [8k, 16k) is lost.
+        self.assert_map(target_img, [(0, CLUSTER, 'data'),
+                                     (CLUSTER, CLUSTER, 'zero')], size)
+
+    def test_top_zero_broken(self):
+        # An overlay hole before an explicit-zero run: the zero prefix
+        # must stop at the hole, or the backing data under it is lost.
+        size = 2 * CLUSTER
+        qemu_img_create('-f', iotests.imgfmt, '-o', 'cluster_size=4k',
+                        base_img, str(size))
+        qemu_io('-c', f'write -P 0x33 0 {size}', base_img)
+
+        qemu_img_create('-f', iotests.imgfmt, '-o', 'cluster_size=4k',
+                        '-b', base_img, '-F', iotests.imgfmt,
+                        source_img, str(size))
+        self.vm.cmd('blockdev-add', {
+            'node-name': 'src',
+            'driver': iotests.imgfmt,
+            'file': {'driver': 'file', 'filename': source_img},
+        })
+        # [0, 4k) stays a hole, the zero run spills into cluster 1.
+        self.hmp_write('src', f'write -z 4096 {CLUSTER}')
+
+        self.do_backup('top', target_backing=base_img, size=size)
+        self.assertTrue(compare_images(source_img, target_img))
+
+    def test_bitmap_straddle(self):
+        # One dirty run straddling a zero/data transition, both ways.
+        self.add_source(layout=[])
+        self.vm.cmd('block-dirty-bitmap-add', node='src', name='bm0')
+
+        # zero -> data straddle: one contiguous dirty run [7M, 9M)
+        self.hmp_write('src', f'write -z {7 * MB} {MB}')
+        self.hmp_write('src', f'write -P 0x5a {8 * MB} {MB}')
+
+        # data -> zero straddle: one contiguous dirty run [15M, 17M)
+        self.hmp_write('src', f'write -P 0x5a {15 * MB} {MB}')
+        self.hmp_write('src', f'write -z {16 * MB} {MB}')
+
+        self.do_backup('bitmap', bitmap='bm0', bitmap_mode='never')
+        self.assertTrue(compare_images(source_img, target_img))
+
+    def test_bitmap_fragmented(self):
+        # Isolated single-cluster dirty spots: nothing outside them
+        # may reach the target.
+        self.add_source(layout=[])
+
+        # Written before the bitmap exists, so untracked.
+        self.hmp_write('src', f'write -P 0x5a 0 {16 * MB}')
+
+        self.vm.cmd('block-dirty-bitmap-add', node='src', name='bm0')
+
+        # The only dirty bit in the data region.
+        data_island = 4 * MB
+        self.hmp_write('src', f'write -P 0x7b {data_island} {CLUSTER}')
+
+        # The only dirty bit in the hole region.
+        zero_island = 24 * MB
+        self.hmp_write('src', f'write -z {zero_island} {CLUSTER}')
+
+        self.do_backup('bitmap', bitmap='bm0', bitmap_mode='never',
+                      prefill=0xcc)
+
+        # Only the two isolated spots should have reached target ...
+        qemu_io('-c', f'read -P 0x7b {data_island} {CLUSTER}', target_img)
+        qemu_io('-c', f'read -P 0 {zero_island} {CLUSTER}', target_img)
+
+        # ... everything else must still hold the prefill pattern.
+        qemu_io('-c', f'read -P 0xcc 0 {CLUSTER}', target_img)
+        qemu_io('-c', f'read -P 0xcc {8 * MB} {CLUSTER}', target_img)
+
+    def test_bitmap_clean_zero_gap(self):
+        # A clean zero run between two dirty ones must stay prefilled.
+        self.add_source(layout=[], size=16 * MB)
+        self.hmp_write('src', f'write -z 0 {16 * MB}')
+
+        self.vm.cmd('block-dirty-bitmap-add', node='src', name='bm0')
+        self.hmp_write('src', f'write -z {2 * MB} {MB}')
+        self.hmp_write('src', f'write -z {6 * MB} {MB}')
+
+        self.do_backup('bitmap', bitmap='bm0', bitmap_mode='never',
+                      size=16 * MB, prefill=0xcc)
+
+        qemu_io('-c', f'read -P 0 {2 * MB} {MB}', target_img)
+        qemu_io('-c', f'read -P 0 {6 * MB} {MB}', target_img)
+
+        qemu_io('-c', f'read -P 0xcc 0 {2 * MB}', target_img)
+        qemu_io('-c', f'read -P 0xcc {3 * MB} {3 * MB}', target_img)
+        qemu_io('-c', f'read -P 0xcc {7 * MB} {9 * MB}', target_img)
+
+
 if __name__ == '__main__':
     iotests.main(supported_fmts=['qcow2'],
                  supported_protocols=['file'])
tests/qemu-iotests/124.out +2 -2
index fa16b5ccef..5ce2f9a2ed 100644
@@ -1,5 +1,5 @@
-.............
+..............................
 ----------------------------------------------------------------------
-Ran 13 tests
+Ran 30 tests
 
 OK
Signature · 1 line
2.53.0
#8 lore raw

Re: [PATCH 4/9] iotests/124: cover backup of zero clusters and holes

Quoted 76 lines

The backup tests compare content only, and their sources hold data alone, so nothing pins how backup treats zero clusters and holes. Back up a source mixing data, write-zero and holes with sync=full, sync=top and sync=bitmap, and check the target with qemu-img map, which tells a copied cluster apart from a write-zero and from an untouched one.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
tests/qemu-iotests/124 +48 -1
index b2f4328e345..eb5ab02904f 100755
@@ -22,8 +22,11 @@
 #
 
 import os
+from collections import namedtuple
+
 import iotests
-from iotests import try_remove
+from iotests import (compare_images, qemu_img_create, qemu_img_map, qemu_io,
+                     try_remove)
 from qemu.qmp.qmp_client import ExecuteError
 
 
@@ -748,6 +751,403 @@ class TestIncrementalBackupBlkdebug(TestIncrementalBackupBase):
         self.check_backups()
 
 
+# Backup of sources mixing data, zero clusters and holes.
+
+Extent = namedtuple('Extent', ['start', 'length', 'kind'])
+
+source_img = os.path.join(iotests.test_dir, 'source')
+base_img = os.path.join(iotests.test_dir, 'base')
+target_img = os.path.join(iotests.test_dir, 'target')
+
+SIZE = 64 * 1024 * 1024
+MB = 1024 * 1024
+CLUSTER = 64 * 1024
+
+# Data, write-zero and holes, every combination at a cluster boundary.
+LAYOUT = [
+    (0, MB, 'data'),
+    (2 * MB, MB, 'zero'),
+    (5 * MB, 2 * MB, 'data'),
+    (8 * MB, MB, 'zero'),
+    (10 * MB, MB // 2, 'data'),
+    (20 * MB, 4 * MB, 'zero'),
+    (30 * MB, MB, 'data'),
+]
+
+# Single-cluster runs, and a zero run ending exactly at EOF.
+BOUNDARY_SIZE = 16 * MB
+LAYOUT_BOUNDARY = [
+    (0, CLUSTER, 'zero'),
+    (CLUSTER, CLUSTER, 'data'),
+    (2 * CLUSTER, CLUSTER, 'zero'),
+    (3 * CLUSTER, CLUSTER, 'data'),
+    (4 * CLUSTER, 8 * MB, 'zero'),
+    (4 * CLUSTER + 8 * MB, CLUSTER, 'data'),
+    (BOUNDARY_SIZE - CLUSTER, CLUSTER, 'zero'),
+]
+
+# A zero run past the old block_copy_chunk_size() 16M cap.
+LARGE_ZERO_SIZE = 48 * MB
+LAYOUT_LARGE_ZERO = [
+    (0, MB, 'data'),
+    (4 * MB, 32 * MB, 'zero'),
+    (40 * MB, MB, 'data'),
+]
+
+# Image size not a multiple of the cluster size: a partial tail cluster.

tests/qemu-iotests/124 class TestIncrementalBackupBlkdebug(TestIncrementalBackupBase): · line 807

Quoted 10 lines
tests/qemu-iotests/124 +10 -0
+TAIL_SIZE = 4 * MB + 4096
+LAYOUT_TAIL_ZERO = [
+    (0, MB, 'data'),
+    (2 * MB, TAIL_SIZE - 2 * MB, 'zero'),
+]
+LAYOUT_TAIL_DATA = [
+    (0, MB, 'data'),
+    (2 * MB, MB, 'zero'),
+    (4 * MB, TAIL_SIZE - 4 * MB, 'data'),
+]

These globals with layout + size must be paired by hand, along with expected layouts. What if mimic what we do in iotests/040 in such a way:

Case = namedtuple('Case', ['size', 'layout', 'expected'], defaults=[None])

class TestBackupZeroClusters(iotests.QMPTestCase):

      BOUNDARY = Case(16 * MB, [
          (0, CLUSTER, 'zero'),
          ...
      ])
      ...
      def test_boundary_full(self):
          self.add_source(self.BOUNDARY)
          self.backup_and_check('full', self.BOUNDARY)
Quoted 52 lines
tests/qemu-iotests/124 +52 -0
+
+
+def coalesce(extents):
+    out = []
+    for e in extents:
+        prev = out[-1] if out else None
+        adjacent = prev is not None and prev.start + prev.length == e.start
+        if adjacent and prev.kind == e.kind:
+            out[-1] = prev._replace(length=prev.length + e.length)
+        else:
+            out.append(e)
+    return out
+
+
+def layout_to_extents(layout, size, gap='hole'):
+    extents = []
+    pos = 0
+    for offset, length, kind in layout:
+        if offset > pos:
+            extents.append(Extent(pos, offset - pos, gap))
+        extents.append(Extent(offset, length, kind))
+        pos = offset + length
+    if pos < size:
+        extents.append(Extent(pos, size - pos, gap))
+    return coalesce(extents)
+
+
+class TestBackupZeroClusters(iotests.QMPTestCase):
+    def setUp(self):
+        self.vm = iotests.VM()
+        self.vm.launch()
+
+    def tearDown(self):
+        self.vm.shutdown()
+        for img in (source_img, base_img, target_img):
+            if os.path.exists(img):
+                os.remove(img)
+
+    def hmp_write(self, drive, cmd):
+        res = self.vm.hmp_qemu_io(drive, cmd)
+        assert 'error' not in res['return'].lower(), res
+
+    def assert_map(self, img, layout, size, backing=False, gap='hole'):
+        # Content is not enough, pin the data/zero/hole split as well.
+        def classify(e):
+            is_hole = e['depth'] > 0 if backing else not e['present']
+            return 'hole' if is_hole else ('zero' if e['zero'] else 'data')
+
+        actual = coalesce([Extent(e['start'], e['length'], classify(e))
+                           for e in qemu_img_map(img)])
+
+        self.assertEqual(actual, layout_to_extents(layout, size, gap))

tests/qemu-iotests/124 class TestIncrementalBackupBlkdebug(TestIncrementalBackupBase): · line 869

Quoted 10 lines
tests/qemu-iotests/124 +10 -0
+
+    def add_source(self, layout=None, size=SIZE, backing=None):
+        if layout is None:
+            layout = LAYOUT
+
+        create_args = ['-f', iotests.imgfmt]
+        if backing:
+            create_args += ['-b', backing, '-F', iotests.imgfmt]
+        create_args += [source_img, str(size)]
+        qemu_img_create(*create_args)

This patch just has lots of duplicated code. E.g. this image creation code might be replaced with:

def create_image(path, size, backing=None, opts=None):

      args = ['-f', iotests.imgfmt]
      if opts:
          args += ['-o', opts]
      if backing:
          args += ['-b', backing, '-F', iotests.imgfmt]
      qemu_img_create(*args, path, str(size))

+ provide opts=None arg to add_source().

That'll work at least for add_source(), do_backup(), test_top(), test_mixed_cluster(), test_top_zero_broken().

tests/qemu-iotests/124 class TestIncrementalBackupBlkdebug(TestIncrementalBackupBase): · line 880

Quoted 11 lines
tests/qemu-iotests/124 +11 -0
+
+        self.vm.cmd('blockdev-add', {
+            'node-name': 'src',
+            'driver': iotests.imgfmt,
+            'file': {'driver': 'file', 'filename': source_img},
+        })
+
+        # Write through the node, so an attached bitmap sees it.
+        for offset, length, kind in layout:
+            opt = '-z' if kind == 'zero' else '-P 0x5a'
+            self.hmp_write('src', f'write {opt} {offset} {length}')

This for loop is repeated multiple times. How about smth like:

def write_layout(self, layout):

    for offset, length, kind in layout:
        opt = '-z' if kind == 'zero' else '-P 0x5a'
        self.hmp_write('src', f'write {opt} {offset} {length}')
Quoted 21 lines
tests/qemu-iotests/124 +21 -0
+
+    def do_backup(self, sync, target_backing=None, size=SIZE, prefill=None,
+                 **kwargs):
+        create_args = ['-f', iotests.imgfmt]
+        if target_backing:
+            create_args += ['-b', target_backing, '-F', iotests.imgfmt]
+        create_args += [target_img, str(size)]
+        qemu_img_create(*create_args)
+
+        if prefill is not None:
+            # Not zero, so a skipped cluster is provably untouched.
+            qemu_io('-c', f'write -P {prefill} 0 {size}', target_img)
+
+        self.vm.cmd('blockdev-add', {
+            'node-name': 'target',
+            'driver': iotests.imgfmt,
+            'file': {'driver': 'file', 'filename': target_img},
+        })
+
+        self.vm.cmd('blockdev-backup', device='src', target='target',
+                    job_id='bk0', sync=sync, **kwargs)

tests/qemu-iotests/124 class TestIncrementalBackupBlkdebug(TestIncrementalBackupBase): · line 911

Quoted 10 lines
tests/qemu-iotests/124 +10 -0
+        self.wait_until_completed(drive='bk0')
+
+        self.vm.cmd('blockdev-del', node_name='target')
+        self.vm.cmd('blockdev-del', node_name='src')
+
+    def test_full(self):
+        self.add_source()
+        self.do_backup('full')
+        self.assertTrue(compare_images(source_img, target_img))
+        self.assert_map(target_img, LAYOUT, SIZE, gap='zero')

do_backup() + assertions is a repeating pattern as well. How about:

def backup_and_check(self, sync, layout, size=SIZE, *, gap='zero',
backing=False, **kwargs):
self.do_backup(sync, size=size, **kwargs) self.assertTrue(compare_images(source_img, target_img)) self.assert_map(target_img, layout, size, gap=gap, backing=backing)

Quoted 6 lines
tests/qemu-iotests/124 +6 -0
+
+    def test_full_zero_overwrite(self):
+        # full skips holes, so only check that zero overwrites prefill.
+        self.add_source(layout=[(2 * MB, MB, 'zero')])
+        self.do_backup('full', prefill=0xcc)
+        qemu_io('-c', f'read -P 0 {2 * MB} {MB}', target_img)

tests/qemu-iotests/124 class TestIncrementalBackupBlkdebug(TestIncrementalBackupBase): · line 927

Quoted 10 lines
tests/qemu-iotests/124 +10 -0
+
+    def test_bitmap(self):
+        self.add_source()
+
+        # A new bitmap tracks nothing yet: dirty all, then re-apply.
+        self.vm.cmd('block-dirty-bitmap-add', node='src', name='bm0')
+        self.hmp_write('src', f'write -z 0 {SIZE}')
+        for offset, length, kind in LAYOUT:
+            opt = '-z' if kind == 'zero' else '-P 0x5a'
+            self.hmp_write('src', f'write {opt} {offset} {length}')

Same code repeats in all bitmap-related tests. How about smth like:

      def dirty_layout(self, layout, size):
          self.vm.cmd('block-dirty-bitmap-add', node='src', name='bm0')
          self.hmp_write('src', f'write -z 0 {size}')
          self.write_layout(layout)

Andrey

Signature · 1 line
Andrey Drobyshev <[email protected]>
#9 lore raw

PATCH 5/9 block/block-copy: don't reserve memory for zero tasks

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

block_copy_dirty_clusters() charges task->req.bytes to the shared memory pool for every task, but a COPY_WRITE_ZEROES task allocates no bounce buffer, so there is nothing to account for. Add block_copy_task_shres_bytes() and use it at all three call sites.

Zero tasks lose the throttling the pool gave them incidentally and are bounded only by BLOCK_COPY_MAX_WORKERS (64).

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
---
 block/block-copy.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
block/block-copy.c +8 -3
index 1826c2e1c7..21ebe8aec2 100644
@@ -453,6 +453,11 @@ void block_copy_set_progress_meter(BlockCopyState *s, ProgressMeter *pm)
     s->progress = pm;
 }
 
+static uint64_t block_copy_task_shres_bytes(BlockCopyTask *task)
+{
+    return task->method == COPY_WRITE_ZEROES ? 0 : task->req.bytes;
+}
+
 /*
  * Takes ownership of @task
  *
@@ -474,7 +479,7 @@ static coroutine_fn int block_copy_task_run(AioTaskPool *pool,
 
     aio_task_pool_wait_slot(pool);
     if (aio_task_pool_status(pool) < 0) {
-        co_put_to_shres(task->s->mem, task->req.bytes);
+        co_put_to_shres(task->s->mem, block_copy_task_shres_bytes(task));
         block_copy_task_end(task, -ECANCELED);
         g_free(task);
         return -ECANCELED;
@@ -605,7 +610,7 @@ static coroutine_fn int block_copy_task_entry(AioTask *task)
             progress_work_done(s->progress, t->req.bytes);
         }
     }
-    co_put_to_shres(s->mem, t->req.bytes);
+    co_put_to_shres(s->mem, block_copy_task_shres_bytes(t));
     block_copy_task_end(t, ret);
 
     if (s->discard_source && ret == 0) {
@@ -816,7 +821,7 @@ block_copy_dirty_clusters(BlockCopyCallState *call_state)
 
         trace_block_copy_process(s, task->req.offset);
 
-        co_get_from_shres(s->mem, task->req.bytes);
+        co_get_from_shres(s->mem, block_copy_task_shres_bytes(task));
 
         offset = task_end(task);
         bytes = end - offset;
Signature · 1 line
2.53.0
#10 lore raw

PATCH 6/9 block/block-copy: extract block_copy_set_task_method()

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

Move the per-task block-status query and its skip_unallocated and BDRV_BLOCK_ZERO handling out of block_copy_dirty_clusters() into block_copy_set_task_method(). No behavior change. The next patch changes that decision, and having it in one place keeps that change to just the new logic.

The block-status result no longer lands in the caller's @ret, so drop the note saying @ret may be positive at the out: label.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
---
 block/block-copy.c | 46 ++++++++++++++++++++++++++++++----------------
 1 file changed, 30 insertions(+), 16 deletions(-)
block/block-copy.c +30 -16
index 21ebe8aec2..d71d070dbd 100644
@@ -741,6 +741,35 @@ int64_t coroutine_fn block_copy_reset_unallocated(BlockCopyState *s,
     return ret;
 }
 
+/*
+ * Decide how @task is copied: COPY_WRITE_ZEROES if it reads as zero. May
+ * shrink @task. Returns false if @task is to be skipped (already ended,
+ * not freed).
+ */
+static bool coroutine_fn GRAPH_RDLOCK
+block_copy_set_task_method(BlockCopyState *s, BlockCopyTask *task)
+{
+    int ret;
+    int64_t status_bytes;
+
+    ret = block_copy_block_status(s, task->req.offset, task->req.bytes,
+                                  &status_bytes);
+    assert(ret >= 0); /* never fail */
+    if (status_bytes < task->req.bytes) {
+        block_copy_task_shrink(task, status_bytes);
+    }
+    if (qatomic_read(&s->skip_unallocated) && !(ret & BDRV_BLOCK_ALLOCATED)) {
+        block_copy_task_end(task, 0);
+        trace_block_copy_skip_range(s, task->req.offset, task->req.bytes);
+        return false;
+    }
+    if (ret & BDRV_BLOCK_ZERO) {
+        task->method = COPY_WRITE_ZEROES;
+    }
+
+    return true;
+}
+
 /*
  * block_copy_dirty_clusters
  *
@@ -773,7 +802,6 @@ block_copy_dirty_clusters(BlockCopyCallState *call_state)
     while (bytes && aio_task_pool_status(aio) == 0 &&
            !qatomic_read(&call_state->cancelled)) {
         BlockCopyTask *task;
-        int64_t status_bytes;
 
         task = block_copy_task_create(s, call_state, offset, bytes);
         if (!task) {
@@ -787,24 +815,12 @@ block_copy_dirty_clusters(BlockCopyCallState *call_state)
 
         found_dirty = true;
 
-        ret = block_copy_block_status(s, task->req.offset, task->req.bytes,
-                                      &status_bytes);
-        assert(ret >= 0); /* never fail */
-        if (status_bytes < task->req.bytes) {
-            block_copy_task_shrink(task, status_bytes);
-        }
-        if (qatomic_read(&s->skip_unallocated) &&
-            !(ret & BDRV_BLOCK_ALLOCATED)) {
-            block_copy_task_end(task, 0);
-            trace_block_copy_skip_range(s, task->req.offset, task->req.bytes);
+        if (!block_copy_set_task_method(s, task)) {
             offset = task_end(task);
             bytes = end - offset;
             g_free(task);
             continue;
         }
-        if (ret & BDRV_BLOCK_ZERO) {
-            task->method = COPY_WRITE_ZEROES;
-        }
 
         if (!call_state->ignore_ratelimit) {
             uint64_t ns = ratelimit_calculate_delay(&s->rate_limit, 0);
@@ -845,8 +861,6 @@ out:
          * block_copy_task_run. If it fails, it means some task already failed
          * for real reason, let's return first failure.
          * Still, assert that we don't rewrite failure by success.
-         *
-         * Note: ret may be positive here because of block-status result.
          */
         assert(ret >= 0 || aio_task_pool_status(aio) < 0);
         ret = aio_task_pool_status(aio);
Signature · 1 line
2.53.0
#11 lore raw

PATCH 7/9 block/block-copy: track known-zero source clusters

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

block_copy_reset_unallocated()'s up-front scan already queries the source, and the same query reports zero-ness. The copy loop re-queries per task and, having no answer up front, can only size a task by the copy buffer, so a mostly-zero image is cut into thousands of pieces that each turn out to read as zero.

Cache the answer in zero_bitmap, published by zero_bitmap_valid once the scan is done. block_copy_task_create() then picks the method from the bitmap and ends the task where the answer changes, so a zero task never reaches into data and a copy task never swallows a zero run. The per-task query stays as the fallback until the flag is set, since CBW intercepts guest writes while the scan is still running.

The scan and the query it replaces must resolve BDRV_BLOCK_ZERO against the same part of the chain, so the scan moves from bdrv_co_is_allocated() to bdrv_co_block_status_above() and the base selection is factored out into block_copy_status_base().

zero_bitmap is a plain HBitmap, not a BdrvDirtyBitmap: an internal cache has no business in query-named-block-nodes. One writer and readers gated by the flag need no mutex, but the publish needs ordering, hence store-release and load-acquire. It is allocated on demand, so sync=none and a standalone copy-before-write filter do not pay for it.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
---
 block/backup.c             |   1 +
 block/block-copy.c         | 108 ++++++++++++++++++++++++++++++++-----
 include/block/block-copy.h |   1 +
 3 files changed, 98 insertions(+), 12 deletions(-)
block/backup.c +1 -0
index d4713fa1cd..11d70243e2 100644
@@ -280,6 +280,7 @@ static int coroutine_fn backup_run(Job *job, Error **errp)
             offset += count;
         }
         block_copy_set_skip_unallocated(s->bcs, false);
+        block_copy_set_zero_bitmap_valid(s->bcs);
     }
 
     if (s->sync_mode == MIRROR_SYNC_MODE_NONE) {
block/block-copy.c +96 -12

206 lines not on this page · raw message

include/block/block-copy.h +1 -0
index 0df2771181..e4e5b56753 100644
@@ -101,5 +101,6 @@ void block_copy_call_cancel(BlockCopyCallState *call_state);
 BdrvDirtyBitmap *block_copy_dirty_bitmap(BlockCopyState *s);
 int64_t block_copy_cluster_size(BlockCopyState *s);
 void block_copy_set_skip_unallocated(BlockCopyState *s, bool skip);
+void block_copy_set_zero_bitmap_valid(BlockCopyState *s);
 
 #endif /* BLOCK_COPY_H */
Signature · 1 line
2.53.0
#12 lore raw

Re: [PATCH 7/9] block/block-copy: track known-zero source clusters

Quoted 153 lines

block_copy_reset_unallocated()'s up-front scan already queries the source, and the same query reports zero-ness. The copy loop re-queries per task and, having no answer up front, can only size a task by the copy buffer, so a mostly-zero image is cut into thousands of pieces that each turn out to read as zero.

Cache the answer in zero_bitmap, published by zero_bitmap_valid once the scan is done. block_copy_task_create() then picks the method from the bitmap and ends the task where the answer changes, so a zero task never reaches into data and a copy task never swallows a zero run. The per-task query stays as the fallback until the flag is set, since CBW intercepts guest writes while the scan is still running.

The scan and the query it replaces must resolve BDRV_BLOCK_ZERO against the same part of the chain, so the scan moves from bdrv_co_is_allocated() to bdrv_co_block_status_above() and the base selection is factored out into block_copy_status_base().

zero_bitmap is a plain HBitmap, not a BdrvDirtyBitmap: an internal cache has no business in query-named-block-nodes. One writer and readers gated by the flag need no mutex, but the publish needs ordering, hence store-release and load-acquire. It is allocated on demand, so sync=none and a standalone copy-before-write filter do not pay for it.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
block/backup.c +1 -0
index d4713fa1cd4..11d70243e24 100644
@@ -280,6 +280,7 @@ static int coroutine_fn backup_run(Job *job, Error **errp)
             offset += count;
         }
         block_copy_set_skip_unallocated(s->bcs, false);
+        block_copy_set_zero_bitmap_valid(s->bcs);
     }
 
     if (s->sync_mode == MIRROR_SYNC_MODE_NONE) {
block/block-copy.c +43 -8
index d71d070dbd0..94d4f3dd69a 100644
@@ -20,6 +20,8 @@
 #include "block/block_int-io.h"
 #include "block/dirty-bitmap.h"
 #include "block/reqlist.h"
+#include "qemu/hbitmap.h"
+#include "qemu/host-utils.h"
 #include "system/block-backend.h"
 #include "qemu/units.h"
 #include "qemu/co-shared-resource.h"
@@ -157,6 +159,10 @@ typedef struct BlockCopyState {
     bool skip_unallocated; /* atomic */
     /* State fields that use a thread-safe API */
     BdrvDirtyBitmap *copy_bitmap;
+    /* Clusters reading as zero; allocated on demand, frozen once valid. */
+    HBitmap *zero_bitmap;
+    /* Published only after the scan, with skip_unallocated already false. */
+    bool zero_bitmap_valid; /* atomic, store-release/load-acquire */
     ProgressMeter *progress;
     SharedResource *mem;
     RateLimit rate_limit;
@@ -190,6 +196,7 @@ block_copy_task_create(BlockCopyState *s, BlockCopyCallState *call_state,
                        int64_t offset, int64_t bytes)
 {
     BlockCopyTask *task;
+    BlockCopyMethod method;
     int64_t max_chunk;
 
     QEMU_LOCK_GUARD(&s->lock);
@@ -201,6 +208,27 @@ block_copy_task_create(BlockCopyState *s, BlockCopyCallState *call_state,
         return NULL;
     }
 
+    method = s->method;
+
+    /*
+     * The scan already knows how this range reads: pick the method here and
+     * stop the task where the answer changes.
+     */
+    if (qatomic_load_acquire(&s->zero_bitmap_valid)) {
+        int64_t boundary;
+
+        if (hbitmap_get(s->zero_bitmap, offset)) {
+            method = COPY_WRITE_ZEROES;
+            boundary = hbitmap_next_zero(s->zero_bitmap, offset, bytes);
+        } else {
+            boundary = hbitmap_next_dirty(s->zero_bitmap, offset, bytes);
+        }
+
+        if (boundary >= 0) {
+            bytes = boundary - offset;
+        }
+    }
+
     assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
     bytes = QEMU_ALIGN_UP(bytes, s->cluster_size);
 
@@ -215,7 +243,7 @@ block_copy_task_create(BlockCopyState *s, BlockCopyCallState *call_state,
         .task.func = block_copy_task_entry,
         .s = s,
         .call_state = call_state,
-        .method = s->method,
+        .method = method,
     };
     reqlist_init_req(&s->reqs, &task->req, offset, bytes);
 
@@ -271,6 +299,9 @@ void block_copy_state_free(BlockCopyState *s)
 
     ratelimit_destroy(&s->rate_limit);
     bdrv_release_dirty_bitmap(s->copy_bitmap);
+    if (s->zero_bitmap) {
+        hbitmap_free(s->zero_bitmap);
+    }
     shres_destroy(s->mem);
     g_free(s);
 }
@@ -624,20 +655,24 @@ static coroutine_fn int block_copy_task_entry(AioTask *task)
     return ret;
 }
 
+/* The scan and the per-task query must resolve BDRV_BLOCK_ZERO alike. */
+static GRAPH_RDLOCK BlockDriverState *block_copy_status_base(BlockCopyState *s)
+{
+    if (qatomic_read(&s->skip_unallocated)) {
+        return bdrv_backing_chain_next(s->source->bs);
+    }
+
+    return NULL;
+}
+
 static coroutine_fn GRAPH_RDLOCK
 int block_copy_block_status(BlockCopyState *s, int64_t offset, int64_t bytes,
                             int64_t *pnum)
 {
     int64_t num;
-    BlockDriverState *base;
+    BlockDriverState *base = block_copy_status_base(s);
     int ret;
 
-    if (qatomic_read(&s->skip_unallocated)) {
-        base = bdrv_backing_chain_next(s->source->bs);
-    } else {
-        base = NULL;
-    }
-
     ret = bdrv_co_block_status_above(s->source->bs, base, offset, bytes, &num,
                                      NULL, NULL);
     if (ret < 0 || num < s->cluster_size) {

block/block-copy.c int block_copy_block_status(BlockCopyState *s, int64_t offset, int64_t bytes, · line 699

Quoted 8 lines
block/block-copy.c +5 -0
@@ -657,16 +692,41 @@ int block_copy_block_status(BlockCopyState *s, int64_t offset, int64_t bytes,
     return ret;
 }
 
+/* Only the scan allocates, and it runs before zero_bitmap_valid. */
+static HBitmap *block_copy_zero_bitmap(BlockCopyState *s)
+{
+    if (!s->zero_bitmap) {
+        s->zero_bitmap = hbitmap_alloc(s->len, ctz32(s->cluster_size));

Hmm why it's ctz32() when cluster_size is int64_t ? Is this intentional or an oversight?

Andrey

Signature · 1 line
Andrey Drobyshev <[email protected]>
#13 lore raw

Re: [PATCH 7/9] block/block-copy: track known-zero source clusters

Quoted 156 lines · Andrey Drobyshev
Quoted 156 lines

block_copy_reset_unallocated()'s up-front scan already queries the source, and the same query reports zero-ness. The copy loop re-queries per task and, having no answer up front, can only size a task by the copy buffer, so a mostly-zero image is cut into thousands of pieces that each turn out to read as zero.

Cache the answer in zero_bitmap, published by zero_bitmap_valid once the scan is done. block_copy_task_create() then picks the method from the bitmap and ends the task where the answer changes, so a zero task never reaches into data and a copy task never swallows a zero run. The per-task query stays as the fallback until the flag is set, since CBW intercepts guest writes while the scan is still running.

The scan and the query it replaces must resolve BDRV_BLOCK_ZERO against the same part of the chain, so the scan moves from bdrv_co_is_allocated() to bdrv_co_block_status_above() and the base selection is factored out into block_copy_status_base().

zero_bitmap is a plain HBitmap, not a BdrvDirtyBitmap: an internal cache has no business in query-named-block-nodes. One writer and readers gated by the flag need no mutex, but the publish needs ordering, hence store-release and load-acquire. It is allocated on demand, so sync=none and a standalone copy-before-write filter do not pay for it.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
block/backup.c +1 -0
index d4713fa1cd4..11d70243e24 100644
@@ -280,6 +280,7 @@ static int coroutine_fn backup_run(Job *job, Error **errp)
             offset += count;
         }
         block_copy_set_skip_unallocated(s->bcs, false);
+        block_copy_set_zero_bitmap_valid(s->bcs);
     }
 
     if (s->sync_mode == MIRROR_SYNC_MODE_NONE) {
block/block-copy.c +43 -8
index d71d070dbd0..94d4f3dd69a 100644
@@ -20,6 +20,8 @@
 #include "block/block_int-io.h"
 #include "block/dirty-bitmap.h"
 #include "block/reqlist.h"
+#include "qemu/hbitmap.h"
+#include "qemu/host-utils.h"
 #include "system/block-backend.h"
 #include "qemu/units.h"
 #include "qemu/co-shared-resource.h"
@@ -157,6 +159,10 @@ typedef struct BlockCopyState {
     bool skip_unallocated; /* atomic */
     /* State fields that use a thread-safe API */
     BdrvDirtyBitmap *copy_bitmap;
+    /* Clusters reading as zero; allocated on demand, frozen once valid. */
+    HBitmap *zero_bitmap;
+    /* Published only after the scan, with skip_unallocated already false. */
+    bool zero_bitmap_valid; /* atomic, store-release/load-acquire */
     ProgressMeter *progress;
     SharedResource *mem;
     RateLimit rate_limit;
@@ -190,6 +196,7 @@ block_copy_task_create(BlockCopyState *s, BlockCopyCallState *call_state,
                        int64_t offset, int64_t bytes)
 {
     BlockCopyTask *task;
+    BlockCopyMethod method;
     int64_t max_chunk;
 
     QEMU_LOCK_GUARD(&s->lock);
@@ -201,6 +208,27 @@ block_copy_task_create(BlockCopyState *s, BlockCopyCallState *call_state,
         return NULL;
     }
 
+    method = s->method;
+
+    /*
+     * The scan already knows how this range reads: pick the method here and
+     * stop the task where the answer changes.
+     */
+    if (qatomic_load_acquire(&s->zero_bitmap_valid)) {
+        int64_t boundary;
+
+        if (hbitmap_get(s->zero_bitmap, offset)) {
+            method = COPY_WRITE_ZEROES;
+            boundary = hbitmap_next_zero(s->zero_bitmap, offset, bytes);
+        } else {
+            boundary = hbitmap_next_dirty(s->zero_bitmap, offset, bytes);
+        }
+
+        if (boundary >= 0) {
+            bytes = boundary - offset;
+        }
+    }
+
     assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
     bytes = QEMU_ALIGN_UP(bytes, s->cluster_size);
 
@@ -215,7 +243,7 @@ block_copy_task_create(BlockCopyState *s, BlockCopyCallState *call_state,
         .task.func = block_copy_task_entry,
         .s = s,
         .call_state = call_state,
-        .method = s->method,
+        .method = method,
     };
     reqlist_init_req(&s->reqs, &task->req, offset, bytes);
 
@@ -271,6 +299,9 @@ void block_copy_state_free(BlockCopyState *s)
 
     ratelimit_destroy(&s->rate_limit);
     bdrv_release_dirty_bitmap(s->copy_bitmap);
+    if (s->zero_bitmap) {
+        hbitmap_free(s->zero_bitmap);
+    }
     shres_destroy(s->mem);
     g_free(s);
 }
@@ -624,20 +655,24 @@ static coroutine_fn int block_copy_task_entry(AioTask *task)
     return ret;
 }
 
+/* The scan and the per-task query must resolve BDRV_BLOCK_ZERO alike. */
+static GRAPH_RDLOCK BlockDriverState *block_copy_status_base(BlockCopyState *s)
+{
+    if (qatomic_read(&s->skip_unallocated)) {
+        return bdrv_backing_chain_next(s->source->bs);
+    }
+
+    return NULL;
+}
+
 static coroutine_fn GRAPH_RDLOCK
 int block_copy_block_status(BlockCopyState *s, int64_t offset, int64_t bytes,
                             int64_t *pnum)
 {
     int64_t num;
-    BlockDriverState *base;
+    BlockDriverState *base = block_copy_status_base(s);
     int ret;
 
-    if (qatomic_read(&s->skip_unallocated)) {
-        base = bdrv_backing_chain_next(s->source->bs);
-    } else {
-        base = NULL;
-    }
-
     ret = bdrv_co_block_status_above(s->source->bs, base, offset, bytes, &num,
                                      NULL, NULL);
     if (ret < 0 || num < s->cluster_size) {
@@ -657,16 +692,41 @@ int block_copy_block_status(BlockCopyState *s, int64_t offset, int64_t bytes,
     return ret;
 }
 
Quoted 7 lines

block/block-copy.c int block_copy_block_status(BlockCopyState *s, int64_t offset, int64_t bytes, · line 699

Quoted 5 lines
block/block-copy.c +5 -0
+/* Only the scan allocates, and it runs before zero_bitmap_valid. */
+static HBitmap *block_copy_zero_bitmap(BlockCopyState *s)
+{
+    if (!s->zero_bitmap) {
+        s->zero_bitmap = hbitmap_alloc(s->len, ctz32(s->cluster_size));

Hmm why it's ctz32() when cluster_size is int64_t ? Is this intentional or an oversight?

Intentional, and it is the same assumption the file already makes a few lines up: copy_bitmap is created by bdrv_create_dirty_bitmap(), whose granularity parameter is a uint32_t, and that call is handed the very same s->cluster_size. block/dirty-bitmap.c then reaches hbitmap_alloc() through ctz32() as well, so zero_bitmap and copy_bitmap end up with the same granularity by the same route.

The type is int64_t because the block layer passes sizes around as int64_t. The value cannot need more: it comes from bdi.cluster_size, which is an int. The one way to push it past 4G is an x-perf min-cluster-size above that, and copy_bitmap would truncate before zero_bitmap did - a pre-existing gap in the parameter checking rather than something this series introduces.

Thank you for review,
    Den

#14 lore raw

PATCH 8/9 block/backup: pre-fill zero_bitmap for full/bitmap

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

Only sync=top runs an up-front scan, so the previous patch did nothing for the other modes. FULL and BITMAP know their complete copy_bitmap before copying starts, and the same copy-before-write guarantee holds:
a cluster still dirty when the copy loop reaches it has not been written since the scan.

Add block_copy_calculate_zero_bitmap(), driven one query at a time from backup_scan_source() so the graph rdlock and the pause point are taken per query, and query each confirmed span once however many dirty areas it covers. The scan only fills zero_bitmap and never clears copy_bitmap, so sync=full still writes zeroes for clusters the source never allocated; it just stops re-querying to find that out. Unlike the per-task queries it replaces the scan is serial, so a sparsely dirtied job against a slow source may spend more time here than it saves. The sync=top loop had the same shape, so both fold into backup_scan_source().

sync=none keeps the per-task query. Its bitmap says "anything may be copied", not "this will be copied", and it only ever copies what the guest writes during the fleecing window, so scanning the whole image at attach is the wrong trade.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
---
 block/backup.c             | 94 ++++++++++++++++++++++++--------------
 block/block-copy.c         | 41 +++++++++++++++++
 include/block/block-copy.h |  4 ++
 3 files changed, 105 insertions(+), 34 deletions(-)
block/backup.c +60 -34
index 11d70243e2..b6e559a97e 100644
@@ -247,59 +247,85 @@ static void backup_init_bcs_bitmap(BackupBlockJob *job)
     job_progress_set_remaining(&job->common.job, estimate);
 }
 
-static int coroutine_fn backup_run(Job *job, Error **errp)
+/*
+ * Walk the source before copying starts: fill zero_bitmap and, for sync=top,
+ * drop the clusters that are not allocated above the backing.
+ */
+static int coroutine_fn backup_scan_source(BackupBlockJob *s)
 {
-    BackupBlockJob *s = container_of(job, BackupBlockJob, common.job);
-    int ret;
-
-    backup_init_bcs_bitmap(s);
-
-    if (s->sync_mode == MIRROR_SYNC_MODE_TOP) {
-        int64_t offset = 0;
-        int64_t count;
+    Job *job = &s->common.job;
+    bool top = s->sync_mode == MIRROR_SYNC_MODE_TOP;
+    int64_t offset, cached_end = 0, count;
+    int ret = 0;
 
-        for (offset = 0; offset < s->len; ) {
-            if (job_is_cancelled(job)) {
-                return -ECANCELED;
-            }
+    for (offset = 0; offset < s->len; offset += count) {
+        if (job_is_cancelled(job)) {
+            return -ECANCELED;
+        }
 
-            job_pause_point(job);
+        job_pause_point(job);
 
-            if (job_is_cancelled(job)) {
-                return -ECANCELED;
-            }
+        if (job_is_cancelled(job)) {
+            return -ECANCELED;
+        }
 
-            /* rdlock protects the subsequent call to bdrv_is_allocated() */
-            bdrv_graph_co_rdlock();
+        /* rdlock protects the block-status queries below */
+        bdrv_graph_co_rdlock();
+        if (top) {
             ret = block_copy_reset_unallocated(s->bcs, offset, &count);
-            bdrv_graph_co_rdunlock();
-            if (ret < 0) {
-                return ret;
-            }
+        } else {
+            block_copy_calculate_zero_bitmap(s->bcs, offset, &cached_end,
+                                             &count);
+        }
+        bdrv_graph_co_rdunlock();
 
-            offset += count;
+        if (ret < 0) {
+            return ret;
         }
+    }
+
+    if (top) {
         block_copy_set_skip_unallocated(s->bcs, false);
-        block_copy_set_zero_bitmap_valid(s->bcs);
     }
+    block_copy_set_zero_bitmap_valid(s->bcs);
 
-    if (s->sync_mode == MIRROR_SYNC_MODE_NONE) {
+    return 0;
+}
+
+static int coroutine_fn backup_run(Job *job, Error **errp)
+{
+    BackupBlockJob *s = container_of(job, BackupBlockJob, common.job);
+    int ret;
+
+    backup_init_bcs_bitmap(s);
+
+    switch (s->sync_mode) {
+    case MIRROR_SYNC_MODE_TOP:
+    case MIRROR_SYNC_MODE_FULL:
+    case MIRROR_SYNC_MODE_BITMAP:
+        ret = backup_scan_source(s);
+        if (ret < 0) {
+            return ret;
+        }
+        break;
+
+    case MIRROR_SYNC_MODE_NONE:
         /*
          * All bits are set in bcs bitmap to allow any cluster to be copied.
-         * This does not actually require them to be copied.
+         * This does not actually require them to be copied. Yield until the
+         * job is cancelled and let the before_write notify callback service
+         * CoW requests.
          */
         while (!job_is_cancelled(job)) {
-            /*
-             * Yield until the job is cancelled.  We just let our before_write
-             * notify callback service CoW requests.
-             */
             job_yield(job);
         }
-    } else {
-        return backup_loop(s);
+        return 0;
+
+    default:
+        break;
     }
 
-    return 0;
+    return backup_loop(s);
 }
 
 static void coroutine_fn backup_pause(Job *job)
block/block-copy.c +41 -0

47 lines not on this page · raw message

include/block/block-copy.h +4 -0
index e4e5b56753..3a61066b55 100644
@@ -44,6 +44,10 @@ void block_copy_reset(BlockCopyState *s, int64_t offset, int64_t bytes);
 int64_t coroutine_fn GRAPH_RDLOCK
 block_copy_reset_unallocated(BlockCopyState *s, int64_t offset, int64_t *count);
 
+void coroutine_fn GRAPH_RDLOCK
+block_copy_calculate_zero_bitmap(BlockCopyState *s, int64_t offset,
+                                 int64_t *cached_end, int64_t *count);
+
 int coroutine_fn block_copy(BlockCopyState *s, int64_t offset, int64_t bytes,
                             bool ignore_ratelimit, uint64_t timeout_ns,
                             BlockCopyAsyncCallbackFunc cb,
Signature · 1 line
2.53.0
Reviewed-by on v1 8/9
#15 lore raw

Re: [PATCH 8/9] block/backup: pre-fill zero_bitmap for full/bitmap

Quoted 134 lines

Only sync=top runs an up-front scan, so the previous patch did nothing for the other modes. FULL and BITMAP know their complete copy_bitmap before copying starts, and the same copy-before-write guarantee holds:
a cluster still dirty when the copy loop reaches it has not been written since the scan.

Add block_copy_calculate_zero_bitmap(), driven one query at a time from backup_scan_source() so the graph rdlock and the pause point are taken per query, and query each confirmed span once however many dirty areas it covers. The scan only fills zero_bitmap and never clears copy_bitmap, so sync=full still writes zeroes for clusters the source never allocated; it just stops re-querying to find that out. Unlike the per-task queries it replaces the scan is serial, so a sparsely dirtied job against a slow source may spend more time here than it saves. The sync=top loop had the same shape, so both fold into backup_scan_source().

sync=none keeps the per-task query. Its bitmap says "anything may be copied", not "this will be copied", and it only ever copies what the guest writes during the fleecing window, so scanning the whole image at attach is the wrong trade.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
block/backup.c +55 -29
index 11d70243e24..b6e559a97e9 100644
@@ -247,59 +247,85 @@ static void backup_init_bcs_bitmap(BackupBlockJob *job)
     job_progress_set_remaining(&job->common.job, estimate);
 }
 
-static int coroutine_fn backup_run(Job *job, Error **errp)
+/*
+ * Walk the source before copying starts: fill zero_bitmap and, for sync=top,
+ * drop the clusters that are not allocated above the backing.
+ */
+static int coroutine_fn backup_scan_source(BackupBlockJob *s)
 {
-    BackupBlockJob *s = container_of(job, BackupBlockJob, common.job);
-    int ret;
-
-    backup_init_bcs_bitmap(s);
-
-    if (s->sync_mode == MIRROR_SYNC_MODE_TOP) {
-        int64_t offset = 0;
-        int64_t count;
+    Job *job = &s->common.job;
+    bool top = s->sync_mode == MIRROR_SYNC_MODE_TOP;
+    int64_t offset, cached_end = 0, count;
+    int ret = 0;
 
-        for (offset = 0; offset < s->len; ) {
-            if (job_is_cancelled(job)) {
-                return -ECANCELED;
-            }
+    for (offset = 0; offset < s->len; offset += count) {
+        if (job_is_cancelled(job)) {
+            return -ECANCELED;
+        }
 
-            job_pause_point(job);
+        job_pause_point(job);
 
-            if (job_is_cancelled(job)) {
-                return -ECANCELED;
-            }
+        if (job_is_cancelled(job)) {
+            return -ECANCELED;
+        }
 
-            /* rdlock protects the subsequent call to bdrv_is_allocated() */
-            bdrv_graph_co_rdlock();
+        /* rdlock protects the block-status queries below */
+        bdrv_graph_co_rdlock();
+        if (top) {
             ret = block_copy_reset_unallocated(s->bcs, offset, &count);
-            bdrv_graph_co_rdunlock();
-            if (ret < 0) {
-                return ret;
-            }
+        } else {
+            block_copy_calculate_zero_bitmap(s->bcs, offset, &cached_end,
+                                             &count);
+        }
+        bdrv_graph_co_rdunlock();
 
-            offset += count;
+        if (ret < 0) {
+            return ret;
         }
+    }
+
+    if (top) {
         block_copy_set_skip_unallocated(s->bcs, false);
-        block_copy_set_zero_bitmap_valid(s->bcs);
     }
+    block_copy_set_zero_bitmap_valid(s->bcs);
 
-    if (s->sync_mode == MIRROR_SYNC_MODE_NONE) {
+    return 0;
+}
+
+static int coroutine_fn backup_run(Job *job, Error **errp)
+{
+    BackupBlockJob *s = container_of(job, BackupBlockJob, common.job);
+    int ret;
+
+    backup_init_bcs_bitmap(s);
+
+    switch (s->sync_mode) {
+    case MIRROR_SYNC_MODE_TOP:
+    case MIRROR_SYNC_MODE_FULL:
+    case MIRROR_SYNC_MODE_BITMAP:
+        ret = backup_scan_source(s);
+        if (ret < 0) {
+            return ret;
+        }
+        break;
+
+    case MIRROR_SYNC_MODE_NONE:
         /*
          * All bits are set in bcs bitmap to allow any cluster to be copied.
-         * This does not actually require them to be copied.
+         * This does not actually require them to be copied. Yield until the
+         * job is cancelled and let the before_write notify callback service
+         * CoW requests.
          */
         while (!job_is_cancelled(job)) {
-            /*
-             * Yield until the job is cancelled.  We just let our before_write

block/backup.c static void backup_init_bcs_bitmap(BackupBlockJob *job) · line 325

Quoted 10 lines
block/backup.c +4 -4
-             * notify callback service CoW requests.
-             */
             job_yield(job);
         }
-    } else {
-        return backup_loop(s);
+        return 0;
+
+    default:
+        break;

The only mode left is MIRROR_SYNC_MODE_INCREMENTAL, and we can't get here with this mode: it's asserted away in backup_job_create(). So how about g_assert_not_reached() in the default case?

With that applied:

Signature · 1 line
Andrey Drobyshev <[email protected]>
#16 lore raw

PATCH 9/9 block/block-copy: coalesce write-zeroes tasks

In reply to Denis V. Lunev

From: Denis V. Lunev <[email protected]>

Task size was capped to block_copy_chunk_size() regardless of method, which sizes a task by the copy buffer. A write-zeroes task carries no buffer, so that cap only splits one long known-zero run into a crowd of small COPY_WRITE_ZEROES tasks, each with its own request against the target.

block_copy_task_create() already decides from zero_bitmap how far a task may run, so add block_copy_widen_zero_area() to that decision: for a write-zeroes task, re-search the dirty area under BLOCK_COPY_MAX_ZERO_CHUNK instead of the buffer chunk size, and let the existing clamp cut it back to where the zero run ends. Widening is safe:
an overlapping caller waits on the task's BlockReq via reqlist_wait_one() rather than observing it mid-flight.

The 256M cap stays well under BDRV_REQUEST_MAX_BYTES, where block_copy_do_copy() would trip assert(nbytes < INT_MAX), keeps the rate limiter usable, leaves enough tasks to fill BLOCK_COPY_MAX_WORKERS and bounds how long a cancel waits on one request. It is aligned at the use site rather than in the constant, since nothing bounds cluster_size.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
---
 block/block-copy.c | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
block/block-copy.c +33 -0
index c0a3359938..16b76484cb 100644
@@ -37,6 +37,8 @@
 #define BLOCK_COPY_MAX_WORKERS 64
 #define BLOCK_COPY_SLICE_TIME 100000000ULL /* ns */
 #define BLOCK_COPY_CLUSTER_SIZE_DEFAULT (1 << 16)
+/* Bounded by BDRV_REQUEST_MAX_BYTES, rate limiting and cancel latency. */
+#define BLOCK_COPY_MAX_ZERO_CHUNK (256 * MiB)
 
 typedef enum {
     COPY_READ_WRITE_CLUSTER,
@@ -187,6 +189,34 @@ static int64_t block_copy_chunk_size(BlockCopyState *s)
     }
 }
 
+/*
+ * A write-zeroes task carries no buffer, so it may cover far more than
+ * block_copy_chunk_size(). Return how far it may run; the caller clamps it
+ * to where the zero run ends.
+ */
+static int64_t block_copy_widen_zero_area(BlockCopyState *s,
+                                          BlockCopyCallState *call_state,
+                                          int64_t offset, int64_t search_end,
+                                          int64_t bytes)
+{
+    int64_t aligned = QEMU_ALIGN_DOWN(BLOCK_COPY_MAX_ZERO_CHUNK,
+                                      s->cluster_size);
+    int64_t zero_chunk = MIN_NON_ZERO(MAX(aligned, s->cluster_size),
+                                      call_state->max_chunk);
+    int64_t wide_offset, wide_bytes;
+
+    if (!bdrv_dirty_bitmap_next_dirty_area(s->copy_bitmap, offset, search_end,
+                                           zero_chunk, &wide_offset,
+                                           &wide_bytes)) {
+        return bytes;
+    }
+
+    /* @offset is dirty, so the search cannot have moved past it. */
+    assert(wide_offset == offset);
+
+    return wide_bytes;
+}
+
 /*
  * Search for the first dirty area in offset/bytes range and create task at
  * the beginning of it.
@@ -198,6 +228,7 @@ block_copy_task_create(BlockCopyState *s, BlockCopyCallState *call_state,
     BlockCopyTask *task;
     BlockCopyMethod method;
     int64_t max_chunk;
+    int64_t search_end = offset + bytes;
 
     QEMU_LOCK_GUARD(&s->lock);
     max_chunk = MIN_NON_ZERO(block_copy_chunk_size(s), call_state->max_chunk);
@@ -219,6 +250,8 @@ block_copy_task_create(BlockCopyState *s, BlockCopyCallState *call_state,
 
         if (hbitmap_get(s->zero_bitmap, offset)) {
             method = COPY_WRITE_ZEROES;
+            bytes = block_copy_widen_zero_area(s, call_state, offset,
+                                               search_end, bytes);
             boundary = hbitmap_next_zero(s->zero_bitmap, offset, bytes);
         } else {
             boundary = hbitmap_next_dirty(s->zero_bitmap, offset, bytes);
Signature · 1 line
2.53.0
#17 lore raw

Re: [PATCH 9/9] block/block-copy: coalesce write-zeroes tasks

Quoted 30 lines

Task size was capped to block_copy_chunk_size() regardless of method, which sizes a task by the copy buffer. A write-zeroes task carries no buffer, so that cap only splits one long known-zero run into a crowd of small COPY_WRITE_ZEROES tasks, each with its own request against the target.

block_copy_task_create() already decides from zero_bitmap how far a task may run, so add block_copy_widen_zero_area() to that decision: for a write-zeroes task, re-search the dirty area under BLOCK_COPY_MAX_ZERO_CHUNK instead of the buffer chunk size, and let the existing clamp cut it back to where the zero run ends. Widening is safe:
an overlapping caller waits on the task's BlockReq via reqlist_wait_one() rather than observing it mid-flight.

The 256M cap stays well under BDRV_REQUEST_MAX_BYTES, where block_copy_do_copy() would trip assert(nbytes < INT_MAX), keeps the rate limiter usable, leaves enough tasks to fill BLOCK_COPY_MAX_WORKERS and bounds how long a cancel waits on one request. It is aligned at the use site rather than in the constant, since nothing bounds cluster_size.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
block/block-copy.c +0 -0
index c0a33599384..16b76484cbd 100644

block/block-copy.c line 41

Quoted 5 lines
block/block-copy.c +2 -0
@@ -37,6 +37,8 @@
 #define BLOCK_COPY_MAX_WORKERS 64
 #define BLOCK_COPY_SLICE_TIME 100000000ULL /* ns */
 #define BLOCK_COPY_CLUSTER_SIZE_DEFAULT (1 << 16)
+/* Bounded by BDRV_REQUEST_MAX_BYTES, rate limiting and cancel latency. */
+#define BLOCK_COPY_MAX_ZERO_CHUNK (256 * MiB)

AFAIU with this new cap we enlarge the range, a guest IO to which will trigger CBW. It used to be 1M or 16M depending on copy method, now it's 256M. If the target is qcow2 - then write_zeroes() is size-independent and is a simple metadata write. But what if target doesn't support fast write_zeroes() operation? Then guest IO will be stalled for the entire CBW, and the latency increases. Please correct me if I'm wrong.

If it's true - shouldn't we probe for write_zeroes support adding BDRV_REQ_NO_FALLBACK to the flags? And if -ENOTSUP is returned - don't widen zero area.

Andrey

Signature · 1 line
Andrey Drobyshev <[email protected]>
#18 lore raw

Re: [PATCH 9/9] block/block-copy: coalesce write-zeroes tasks

Quoted 42 lines · Andrey Drobyshev
Quoted 30 lines

Task size was capped to block_copy_chunk_size() regardless of method, which sizes a task by the copy buffer. A write-zeroes task carries no buffer, so that cap only splits one long known-zero run into a crowd of small COPY_WRITE_ZEROES tasks, each with its own request against the target.

block_copy_task_create() already decides from zero_bitmap how far a task may run, so add block_copy_widen_zero_area() to that decision: for a write-zeroes task, re-search the dirty area under BLOCK_COPY_MAX_ZERO_CHUNK instead of the buffer chunk size, and let the existing clamp cut it back to where the zero run ends. Widening is safe:
an overlapping caller waits on the task's BlockReq via reqlist_wait_one() rather than observing it mid-flight.

The 256M cap stays well under BDRV_REQUEST_MAX_BYTES, where block_copy_do_copy() would trip assert(nbytes < INT_MAX), keeps the rate limiter usable, leaves enough tasks to fill BLOCK_COPY_MAX_WORKERS and bounds how long a cancel waits on one request. It is aligned at the use site rather than in the constant, since nothing bounds cluster_size.

CC Vladimir Sementsov-Ogievskiy <[email protected]>
CC John Snow <[email protected]>
CC Andrey Drobyshev <[email protected]>
block/block-copy.c +0 -0
index c0a33599384..16b76484cbd 100644

block/block-copy.c line 41

Quoted 5 lines
block/block-copy.c +2 -0
@@ -37,6 +37,8 @@
 #define BLOCK_COPY_MAX_WORKERS 64
 #define BLOCK_COPY_SLICE_TIME 100000000ULL /* ns */
 #define BLOCK_COPY_CLUSTER_SIZE_DEFAULT (1 << 16)
+/* Bounded by BDRV_REQUEST_MAX_BYTES, rate limiting and cancel latency. */
+#define BLOCK_COPY_MAX_ZERO_CHUNK (256 * MiB)

AFAIU with this new cap we enlarge the range, a guest IO to which will trigger CBW. It used to be 1M or 16M depending on copy method, now it's 256M. If the target is qcow2 - then write_zeroes() is size-independent and is a simple metadata write. But what if target doesn't support fast write_zeroes() operation? Then guest IO will be stalled for the entire CBW, and the latency increases. Please correct me if I'm wrong.

Quoted 6 lines

If it's true - shouldn't we probe for write_zeroes support adding BDRV_REQ_NO_FALLBACK to the flags? And if -ENOTSUP is returned - don't widen zero area.

Andrey

v2 probes as you suggest. CBW itself cannot grow, though:
block_copy_task_create() searches within the range of the block_copy() call it serves, so a copy driven by a guest write covers that write and nothing more. The wait comes the other way round, a guest write landing on a widened background task and waiting through reqlist_wait_one().

supported_zero_flags rules out the targets which cannot zero cheaply at all, qcow2 v2 and iscsi among them, but is optimistic for the rest:
file-posix advertises NO_FALLBACK at open and finds out from the first fallocate that fails. So the first widened request carries the flag. A target which would write the zeroes out fails it without writing, that range then goes out in buffer-sized chunks, and widening stays off for the run.

The cap is therefore BDRV_REQUEST_MAX_BYTES rather than 256M, aligned down to the cluster size. On a 16G source holding 1G of data, sync=full:
1088 block-copy tasks for qcow2 v3 and raw targets, 16384 for qcow2 v2, every target identical to the source.

Thank you for your time,
    Den