Skip to contentSkip to conversation

Fix data corruption within preallocation

PATCH Superseded Andrey Drobyshev 2 participants 4 messages Jul 11, 2024 – Jul 12, 2024 Block layer

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

cover Fix data corruption within preallocation

When there's an image with preallocation filter on top of it, there might be a race where 2 async write requests try to simultaneously do preallocation at the end of the file. And this results into data being zeroed after the actual write operation is performed.

Here we introduce a coroutine context lock within the preallocation filter to protect file_end field, and the test which does fail without the locking.

Note: the lock is only added to the operations which run in the coroutine context and it seems to make the problem with async write requests go away. However there're other operations which are run outside of the coroutine context and which also modify the file_end field, e.g. preallocate_set_perm() and preallocate_child_perm(). Comments on how to protect the field properly regardless of the context are welcome.

Andrey Drobyshev (1):
iotests/298: add testcase for async writes with preallocation filter

Denis V. Lunev (1):
block: zero data data corruption using prealloc-filter

 block/preallocate.c        | 11 +++++++++++
 tests/qemu-iotests/298     | 34 ++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/298.out |  4 ++--
 3 files changed, 47 insertions(+), 2 deletions(-)

--
2.39.3

#1 lore raw

PATCH 1/2 block: zero data data corruption using prealloc-filter

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

We have observed that some clusters in the QCOW2 files are zeroed while preallocation filter is used.

We are able to trace down the following sequence when prealloc-filter is used:

    co=0x55e7cbed7680 qcow2_co_pwritev_task()
    co=0x55e7cbed7680 preallocate_co_pwritev_part()
    co=0x55e7cbed7680 handle_write()
    co=0x55e7cbed7680 bdrv_co_do_pwrite_zeroes()
    co=0x55e7cbed7680 raw_do_pwrite_zeroes()
    co=0x7f9edb7fe500 do_fallocate()

Here coroutine 0x55e7cbed7680 is being blocked waiting while coroutine 0x7f9edb7fe500 will finish with fallocate of the file area. OK. It is time to handle next coroutine, which

    co=0x55e7cbee91b0 qcow2_co_pwritev_task()
    co=0x55e7cbee91b0 preallocate_co_pwritev_part()
    co=0x55e7cbee91b0 handle_write()
    co=0x55e7cbee91b0 bdrv_co_do_pwrite_zeroes()
    co=0x55e7cbee91b0 raw_do_pwrite_zeroes()
    co=0x7f9edb7deb00 do_fallocate()

The trouble comes here. Coroutine 0x55e7cbed7680 has not advanced file_end yet and coroutine 0x55e7cbee91b0 will start fallocate() for the same area. This means that if (once fallocate is started inside 0x7f9edb7deb00) original fallocate could end and the real write will be executed. In that case write() request is handled at the same time as fallocate().

Normally we should protect s->file_end while it is detected that preallocation is need. The patch introduces file_end_lock for it to be protected when run in the coroutine context.

Note: the lock is taken only once it is detected that the preallocation is really required. This is not a frequent case due to the preallocation nature thus the patch should not have performance impact.

---
 block/preallocate.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
block/preallocate.c +11 -0
index d215bc5d6d..9cb2c97635 100644
@@ -78,6 +78,8 @@ typedef struct BDRVPreallocateState {
 
     /* Gives up the resize permission on children when parents don't need it */
     QEMUBH *drop_resize_bh;
+
+    CoMutex file_end_lock;
 } BDRVPreallocateState;
 
 static int preallocate_drop_resize(BlockDriverState *bs, Error **errp);
@@ -170,6 +172,8 @@ static int preallocate_open(BlockDriverState *bs, QDict *options, int flags,
         ((BDRV_REQ_FUA | BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK) &
             bs->file->bs->supported_zero_flags);
 
+    qemu_co_mutex_init(&s->file_end_lock);
+
     return 0;
 }
 
@@ -342,6 +346,7 @@ handle_write(BlockDriverState *bs, int64_t offset, int64_t bytes,
             return false;
         }
 
+        QEMU_LOCK_GUARD(&s->file_end_lock);
         if (s->file_end < 0) {
             s->file_end = s->data_end;
         }
@@ -353,6 +358,8 @@ handle_write(BlockDriverState *bs, int64_t offset, int64_t bytes,
 
     /* We have valid s->data_end, and request writes beyond it. */
 
+    QEMU_LOCK_GUARD(&s->file_end_lock);
+
     s->data_end = end;
     if (s->zero_start < 0 || !want_merge_zero) {
         s->zero_start = end;
@@ -428,6 +435,8 @@ preallocate_co_truncate(BlockDriverState *bs, int64_t offset,
     BDRVPreallocateState *s = bs->opaque;
     int ret;
 
+    QEMU_LOCK_GUARD(&s->file_end_lock);
+
     if (s->data_end >= 0 && offset > s->data_end) {
         if (s->file_end < 0) {
             s->file_end = bdrv_co_getlength(bs->file->bs);
@@ -501,6 +510,8 @@ preallocate_co_getlength(BlockDriverState *bs)
         return s->data_end;
     }
 
+    QEMU_LOCK_GUARD(&s->file_end_lock);
+
     ret = bdrv_co_getlength(bs->file->bs);
 
     if (has_prealloc_perms(bs)) {
Signature · 1 line
2.39.3
#2 lore raw

Re: [PATCH 1/2] block: zero data data corruption using prealloc-filter

Quoted 96 lines · Andrey Drobyshev

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

We have observed that some clusters in the QCOW2 files are zeroed while preallocation filter is used.

We are able to trace down the following sequence when prealloc-filter is used:

     co=0x55e7cbed7680 qcow2_co_pwritev_task()
     co=0x55e7cbed7680 preallocate_co_pwritev_part()
     co=0x55e7cbed7680 handle_write()
     co=0x55e7cbed7680 bdrv_co_do_pwrite_zeroes()
     co=0x55e7cbed7680 raw_do_pwrite_zeroes()
     co=0x7f9edb7fe500 do_fallocate()

Here coroutine 0x55e7cbed7680 is being blocked waiting while coroutine 0x7f9edb7fe500 will finish with fallocate of the file area. OK. It is time to handle next coroutine, which

     co=0x55e7cbee91b0 qcow2_co_pwritev_task()
     co=0x55e7cbee91b0 preallocate_co_pwritev_part()
     co=0x55e7cbee91b0 handle_write()
     co=0x55e7cbee91b0 bdrv_co_do_pwrite_zeroes()
     co=0x55e7cbee91b0 raw_do_pwrite_zeroes()
     co=0x7f9edb7deb00 do_fallocate()

The trouble comes here. Coroutine 0x55e7cbed7680 has not advanced file_end yet and coroutine 0x55e7cbee91b0 will start fallocate() for the same area. This means that if (once fallocate is started inside 0x7f9edb7deb00) original fallocate could end and the real write will be executed. In that case write() request is handled at the same time as fallocate().

Normally we should protect s->file_end while it is detected that preallocation is need. The patch introduces file_end_lock for it to be protected when run in the coroutine context.

Note: the lock is taken only once it is detected that the preallocation is really required. This is not a frequent case due to the preallocation nature thus the patch should not have performance impact.

---
  block/preallocate.c | 11 +++++++++++
  1 file changed, 11 insertions(+)
block/preallocate.c +9 -0
index d215bc5d6d..9cb2c97635 100644
@@ -78,6 +78,8 @@ typedef struct BDRVPreallocateState {
 
      /* Gives up the resize permission on children when parents don't need it */
      QEMUBH *drop_resize_bh;
+
+    CoMutex file_end_lock;
  } BDRVPreallocateState;
 
  static int preallocate_drop_resize(BlockDriverState *bs, Error **errp);
@@ -170,6 +172,8 @@ static int preallocate_open(BlockDriverState *bs, QDict *options, int flags,
          ((BDRV_REQ_FUA | BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK) &
              bs->file->bs->supported_zero_flags);
 
+    qemu_co_mutex_init(&s->file_end_lock);
+
      return 0;
  }
 
@@ -342,6 +346,7 @@ handle_write(BlockDriverState *bs, int64_t offset, int64_t bytes,
              return false;
          }
 
+        QEMU_LOCK_GUARD(&s->file_end_lock);
          if (s->file_end < 0) {
              s->file_end = s->data_end;
          }
@@ -353,6 +358,8 @@ handle_write(BlockDriverState *bs, int64_t offset, int64_t bytes,
 
      /* We have valid s->data_end, and request writes beyond it. */
 
+    QEMU_LOCK_GUARD(&s->file_end_lock);
+
      s->data_end = end;
      if (s->zero_start < 0 || !want_merge_zero) {
          s->zero_start = end;
@@ -428,6 +435,8 @@ preallocate_co_truncate(BlockDriverState *bs, int64_t offset,
      BDRVPreallocateState *s = bs->opaque;
      int ret;
 
+    QEMU_LOCK_GUARD(&s->file_end_lock);
+
      if (s->data_end >= 0 && offset > s->data_end) {
          if (s->file_end < 0) {
              s->file_end = bdrv_co_getlength(bs->file->bs);

block/preallocate.c preallocate_co_getlength(BlockDriverState *bs) · line 517

Quoted 8 lines
block/preallocate.c +2 -0
@@ -501,6 +510,8 @@ preallocate_co_getlength(BlockDriverState *bs)
          return s->data_end;
      }
 
+    QEMU_LOCK_GUARD(&s->file_end_lock);
+
      ret = bdrv_co_getlength(bs->file->bs);
 
      if (has_prealloc_perms(bs)) {

Hmm, seems preallocate driver not thread-safe neither coroutine-safe. I think co-mutex is good idea. Still, protecting only s->file_end may be not enough

- we do want to keep data_end / zero_start / file_end variables correct
- probably, just make the whole preallocation code a critical section? Maybe, atomic read of variables for fast-path (for writes which doesn't need preallocation)

Signature · 2 lines
Best regards,
Vladimir
#3 lore raw

PATCH 2/2 iotests/298: add testcase for async writes with preallocation filter

In reply to Andrey Drobyshev

The testcase simply creates a 64G image with 1M clusters, generates a list of 1M aligned offsets and feeds aio_write commands with those offsets to qemu-io run with '--aio native --nocache'. Then we check the data written at each of the offsets. Before the previous commit this could result into a race within the preallocation filter which would zeroize some clusters after actually writing data to them.

Note: the test doesn't fail in 100% cases as there's a race involved, but the failures are pretty consistent so it should be good enough for detecting the problem.

---
 tests/qemu-iotests/298     | 34 ++++++++++++++++++++++++++++++++++
 tests/qemu-iotests/298.out |  4 ++--
 2 files changed, 36 insertions(+), 2 deletions(-)
tests/qemu-iotests/298 +34 -0
index 09c9290711..d1bf5ee0df 100755
@@ -20,8 +20,10 @@
 
 import os
 import iotests
+import random
 
 MiB = 1024 * 1024
+GiB = MiB * 1024
 disk = os.path.join(iotests.test_dir, 'disk')
 overlay = os.path.join(iotests.test_dir, 'overlay')
 refdisk = os.path.join(iotests.test_dir, 'refdisk')
@@ -176,5 +178,37 @@ class TestTruncate(iotests.QMPTestCase):
         self.do_test('off', '150M')
 
 
+class TestPreallocAsyncWrites(iotests.QMPTestCase):
+    def setUp(self):
+        # Make sure we get reproducible write patterns on each run
+        random.seed(42)
+        iotests.qemu_img_create('-f', iotests.imgfmt, disk, '-o',
+                                f'cluster_size={MiB},lazy_refcounts=on',
+                                str(64 * GiB))
+
+    def tearDown(self):
+        os.remove(disk)
+
+    def test_prealloc_async_writes(self):
+        requests = 1024 # Number of write/read requests to feed to qemu-io
+        total_clusters = 64 * 1024 # 64G / 1M
+
+        offsets = random.sample(range(0, total_clusters), requests)
+        aio_write_cmds = [f'aio_write -P 0xaa {off}M 1M' for off in offsets]
+        read_cmds = [f'read -P 0xaa {off}M 1M' for off in offsets]
+
+        proc = iotests.QemuIoInteractive('--aio', 'native', '--nocache',
+                                         '--image-opts', drive_opts)
+        for cmd in aio_write_cmds:
+            proc.cmd(cmd)
+        proc.close()
+
+        proc = iotests.QemuIoInteractive('-f', iotests.imgfmt, disk)
+        for cmd in read_cmds:
+            out = proc.cmd(cmd)
+            self.assertFalse('Pattern verification failed' in str(out))
+        proc.close()
+
+
 if __name__ == '__main__':
     iotests.main(supported_fmts=['qcow2'], required_fmts=['preallocate'])
tests/qemu-iotests/298.out +2 -2
index fa16b5ccef..6323079e08 100644
@@ -1,5 +1,5 @@
-.............
+..............
 ----------------------------------------------------------------------
-Ran 13 tests
+Ran 14 tests
 
 OK
Signature · 1 line
2.39.3