Linux kernel -stable discussions
 help / color / mirror / Atom feed
* [PATCH] btrfs: subpage: do not end writeback of blocks owned by async submission
@ 2026-12-04 23:10 Harry Yoo (Meta)
  2026-12-04 23:13 ` Harry Yoo
  2026-12-04 23:16 ` Qu Wenruo
  0 siblings, 2 replies; 3+ messages in thread
From: Harry Yoo (Meta) @ 2026-12-04 23:10 UTC (permalink / raw)
  To: David Sterba, Chris Mason, Nick Terrell, Qu Wenruo
  Cc: kernel-team, linux-btrfs, Boris Burkov, Leo Martins, stable,
	Harry Yoo (Meta)

In the Meta fleet, we observed hung tasks on ARM64 hosts with 64k
pages, where a task waits forever for writeback (btrfs, 4k blocks,
compression enabled).

While it was observed on ARM64 systems, it also reproduces on x86
systems with large folios (which was introduced in v7.2) on btrfs:

  INFO: task repro:246 blocked in I/O wait for more than 30 seconds.
  Call Trace:
   folio_wait_bit+0xda/0x1e0
   folio_wait_writeback+0x34/0xa0
   truncate_inode_partial_folio+0xa2/0x3b0
   truncate_inode_pages_range+0x240/0x480
   truncate_pagecache+0x49/0x70
   btrfs_setattr+0xd1/0x330
   notify_change+0x380/0x570
   do_truncate+0xc9/0xf0
   do_ftruncate+0xa2/0x1a0

The task hangs because the folio has the PG_writeback flag set but
nothing clears it, ever.

This happens due to a race between 1) a truncation, 2) writeback of a
folio, and 3) the async compression worker writing back other blocks of
the same folio.

When extent_writepage_io() doesn't submit any block due to a truncation
(as every block subject to writeback is beyond i_size), it clears the
dirty tag of the folio without actual writeback:

	if (!submitted_io && !found_error) {
		btrfs_folio_set_writeback(fs_info, folio, start, len);
		btrfs_folio_clear_writeback(fs_info, folio, start, len);
	}

However, the task performing writeback on a folio can race with the
async compression worker writing back other blocks of the same folio,
when both find all of their blocks beyond i_size.

Task A (writeback)             Task B (compression worker)
----------------------------   ----------------------------------
extent_writepage()
 writepage_delalloc()
  blocks 6-10:
   run_delalloc_compressed() -->
                               compress_file_range()
                                blocks 6-10 >= i_size,
                                not compressed
  block 12:
   cow_file_range()
  submit_bitmap = 0x1000 (block 12)
 extent_writepage_io(0, 64K)
  block 12 >= i_size,
  submitted_io == false
                               submit_compressed_extents()
                                submit_uncompressed_range()
                                 extent_write_locked_range()
                                  extent_writepage_io(24K, 20K)
                                   submit_bitmap = 0x7c0 (blocks 6-10)
                                   all blocks >= i_size,
                                   submitted_io == false
  btrfs_folio_set_writeback(0, 64K)
    wb bitmap 0x0000 -> 0xffff
    folio writeback flag set
                                   btrfs_folio_set_writeback(24K, 20K)
                                     wb bitmap stays 0xffff
  btrfs_folio_clear_writeback(0, 64K)
    wb bitmap 0xffff -> 0x0000
    folio_end_writeback()
                                   btrfs_folio_clear_writeback(24K, 20K)
                                     wb bitmap already 0x0000
                                     folio_end_writeback() again (!)
                                     ^ PG_writeback is set and never
                                       cleared.

With CONFIG_BTRFS_ASSERT=y, an assertion failure shows up:

  assertion failed: folio_test_writeback(folio), in fs/btrfs/subpage.c:494
  kernel BUG at fs/btrfs/subpage.c:494!
  RIP: 0010:btrfs_subpage_clear_writeback.cold+0x20/0x22
  Call Trace:
   extent_writepage_io+0x45d/0x480
   extent_write_locked_range+0x1db/0x380
   run_delalloc_cow.constprop.0+0x6c/0xd0
   submit_uncompressed_range+0x82/0x110
   submit_compressed_extents+0x309/0x500
   btrfs_work_helper+0x138/0x370

This supports that the folio's PG_writeback flag has already been
cleared when the async compression worker clears writeback on its
blocks, which matches the scenario above.

This has become a real problem with commit 1d2fbb7f1f9e ("btrfs: allow
compression even if the range is not page aligned") in v6.13 (and under
CONFIG_BTRFS_EXPERIMENTAL until v6.16) as it allows compression for
non-page-aligned ranges when the block size is smaller than the folio
size. Before the commit, all blocks of a folio were written either by
extent_writepage() or by the compression worker, and no folio had blocks
owned by different contexts.

It has become easier to trigger with commit 59615e2c1f63 ("btrfs:
reject single block sized compression early") in v7.0 as it made a
single block delalloc range inside a compressed inode take the
synchronous path while the rest of the folio still goes through
compression.

To fix this, set and clear writeback only for the blocks in
bio_ctrl->submit_bitmap. Blocks owned by an asynchronous submission keep
their writeback bits and the folio writeback ends exactly once when
the last owner clears its bits.

Fixes: 1d2fbb7f1f9e ("btrfs: allow compression even if the range is not page aligned")
CC: stable@vger.kernel.org
Signed-off-by: Harry Yoo (Meta) <harry@kernel.org>
---
 fs/btrfs/extent_io.c | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)

diff --git a/fs/btrfs/extent_io.c b/fs/btrfs/extent_io.c
index d92dee95b290..3c1e8ec1e2fc 100644
--- a/fs/btrfs/extent_io.c
+++ b/fs/btrfs/extent_io.c
@@ -1993,15 +1993,27 @@ static noinline_for_stack int extent_writepage_io(struct btrfs_inode *inode,
 	 * cleared but PAGECACHE_TAG_DIRTY is not cleared (only cleared
 	 * by folio_start_writeback() if the folio is not dirty).
 	 *
-	 * Here we set writeback and clear for the range. If the full folio
-	 * is no longer dirty then we clear the PAGECACHE_TAG_DIRTY tag.
+	 * Here we set and clear writeback for the blocks in submit_bitmap,
+	 * which clears PAGECACHE_TAG_DIRTY if the folio is no longer dirty.
+	 * Do not touch other blocks in the range as they may be owned by
+	 * a different context, e.g. an async compression worker.
 	 *
 	 * If we hit any error, the corresponding sector will have its dirty
 	 * flag cleared and writeback finished, thus no need to handle the error case.
 	 */
 	if (!submitted_io && !found_error) {
-		btrfs_folio_set_writeback(fs_info, folio, start, len);
-		btrfs_folio_clear_writeback(fs_info, folio, start, len);
+		unsigned int start_bit;
+		unsigned int end_bit;
+
+		for_each_set_bitrange(start_bit, end_bit, bio_ctrl->submit_bitmap,
+				      blocks_per_folio) {
+			const u64 block_start = folio_start +
+				(start_bit << fs_info->sectorsize_bits);
+			const u32 block_len = (end_bit - start_bit) << fs_info->sectorsize_bits;
+
+			btrfs_folio_set_writeback(fs_info, folio, block_start, block_len);
+			btrfs_folio_clear_writeback(fs_info, folio, block_start, block_len);
+		}
 	}
 	return found_error;
 }

---
base-commit: d7a35bfad47f033380f6f6d42d186adc1d9fe406
change-id: 20261204-btrfs-subpage-writeback-fix-3b36f61756a8

Best regards,
--  
Cheers,
Harry / Hyeonggon


^ permalink raw reply related	[flat|nested] 3+ messages in thread

* Re: [PATCH] btrfs: subpage: do not end writeback of blocks owned by async submission
  2026-12-04 23:10 [PATCH] btrfs: subpage: do not end writeback of blocks owned by async submission Harry Yoo (Meta)
@ 2026-12-04 23:13 ` Harry Yoo
  2026-12-04 23:16 ` Qu Wenruo
  1 sibling, 0 replies; 3+ messages in thread
From: Harry Yoo @ 2026-12-04 23:13 UTC (permalink / raw)
  To: David Sterba, Chris Mason, Nick Terrell, Qu Wenruo
  Cc: linux-btrfs, Boris Burkov, Leo Martins, stable

Hi, I wrote this patch with LLM assistance while debugging a problem
in production. I should add that I have a limited background on btrfs
(I am an MM developer!).

However, I invested quite a lot of time to review and refine the patch
and make sure it is readable by human.

Huge thanks to Leo Martins for providing a second eye and invested time
to investigate and discuss the problem.

How to reproduce on x86
=======================

It reproduces on an x86 VM when data folios are large, which needs
CONFIG_TRANSPARENT_HUGEPAGE=y and either v7.2 or later or
CONFIG_BTRFS_EXPERIMENTAL=y. With CONFIG_BTRFS_ASSERT=y the assertion in
the changelog fires within seconds. Without it, the truncating task
hangs in folio_wait_writeback().

Kernel config:

  CONFIG_BTRFS_FS=y
  CONFIG_BTRFS_ASSERT=y
  CONFIG_TRANSPARENT_HUGEPAGE=y
  CONFIG_DETECT_HUNG_TASK=y
  CONFIG_DEFAULT_HUNG_TASK_TIMEOUT=30

With virtme-ng, from a directory that has repro.c and run-repro.sh:

  $ gcc -O2 -pthread -o repro repro.c
  $ truncate -s 10G disk.img
  $ vng -r <linux>/arch/x86/boot/bzImage --cpus 16 --memory 8G \
        --disk disk.img --user root --exec "./run-repro.sh /dev/vda 120"

On another VM, run "./run-repro.sh <scratch device>" as root. It
prints "REPRODUCED after N s" and the splat.

run-repro.sh:

  #!/bin/sh
  # Run inside the VM as root: ./run-repro.sh <scratch-dev> [seconds]
  # Expects ./repro (gcc -O2 -pthread -o repro repro.c) in the current directory.
  dev=${1:?usage: $0 <scratch-dev> [seconds]}
  secs=${2:-60}
  mnt=$(mktemp -d)

  mkfs.btrfs -q -f -s 4k "$dev" || exit 1
  mount -o compress-force=zstd:3 "$dev" $mnt || exit 1
  dmesg -C

  ./repro $mnt 1 "$secs" 0 16 2 &
  pid=$!
  start=$(date +%s)
  while kill -0 $pid 2>/dev/null; do
  	sleep 1
  	if dmesg | grep -q -E 'assertion failed: folio_test_writeback|INFO: task repro'; then
  		echo "REPRODUCED after $(($(date +%s) - start)) s"
  		dmesg | grep -A 24 -E 'assertion failed|INFO: task'
  		exit 1
  	fi
  done
  echo "not reproduced in $secs s"
  umount $mnt

repro.c:

  // SPDX-License-Identifier: GPL-2.0
  /*
   * repro: aim writeback at one large folio holding a clean block 0, an async
   * (compressed) delalloc range and single-block sync delalloc ranges, right
   * after a truncate-down made all of them >= i_size.
   *
   * Usage: repro <dir> <files> <secs> <tail_folios> <nsync_blocks>
   *              <syncers_per_file> [bblocks=5] [folio_kb=64]
   */
  #define _GNU_SOURCE
  #include <fcntl.h>
  #include <pthread.h>
  #include <sched.h>
  #include <stdatomic.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <sys/stat.h>
  #include <time.h>
  #include <unistd.h>

  #define BS 4096

  static int nfiles, tail, ns, nsy;
  static int bblocks = 5;
  static int folio_kb = 64;
  static atomic_int stop;

  static struct fstate {
  	int fd;
  	atomic_int trunc;
  	atomic_long cycles;
  } *fs;

  static char *mkbuf(void)
  {
  	char *b = malloc(1 << 20);

  	for (int i = 0; i < (1 << 20); i++)
  		b[i] = (i / 64) & 1 ? 'a' + i % 13 : (char)rand();
  	return b;
  }

  static void *cyc(void *arg)
  {
  	struct fstate *f = arg;
  	char *buf = mkbuf();
  	int fd = f->fd;
  	int fb = folio_kb * 1024;

  	while (!stop) {
  		ftruncate(fd, 0);
  		/* One large folio, all dirty. */
  		pwrite(fd, buf, fb, 0);
  		sync_file_range(fd, 0, fb, SYNC_FILE_RANGE_WAIT_BEFORE |
  				SYNC_FILE_RANGE_WRITE | SYNC_FILE_RANGE_WAIT_AFTER);
  		/*
  		 * Re-dirty: block 0 stays clean, [1, bblocks] is the async
  		 * range, then a gap, then ns single blocks separated by gaps.
  		 */
  		pwrite(fd, buf, bblocks * BS, BS);
  		for (int i = 0; i < ns; i++)
  			pwrite(fd, buf, BS, (long)(bblocks + 2 + 2 * i) * BS);
  		for (int i = 0; i < tail; i++)
  			pwrite(fd, buf, BS, fb + (long)i * 2 * BS);
  		atomic_store(&f->trunc, 1);
  		ftruncate(fd, BS);
  		atomic_store(&f->trunc, 0);
  		atomic_fetch_add(&f->cycles, 1);
  	}
  	return NULL;
  }

  static void *syncer(void *arg)
  {
  	struct fstate *f = arg;
  	struct stat st;
  	int fb = folio_kb * 1024;

  	while (!stop) {
  		if (!atomic_load(&f->trunc)) {
  			sched_yield();
  			continue;
  		}
  		fstat(f->fd, &st);
  		if (st.st_size > BS)
  			continue;
  		while (atomic_load(&f->trunc))
  			sync_file_range(f->fd, 0, fb, SYNC_FILE_RANGE_WRITE);
  	}
  	return NULL;
  }

  int main(int argc, char **argv)
  {
  	char path[4096];
  	pthread_t t;
  	int secs;

  	if (argc < 7)
  		return 1;
  	nfiles = atoi(argv[2]);
  	secs = atoi(argv[3]);
  	tail = atoi(argv[4]);
  	ns = atoi(argv[5]);
  	nsy = atoi(argv[6]);
  	if (argc > 7)
  		bblocks = atoi(argv[7]);
  	if (argc > 8)
  		folio_kb = atoi(argv[8]);

  	fs = calloc(nfiles, sizeof(*fs));
  	for (int i = 0; i < nfiles; i++) {
  		snprintf(path, sizeof(path), "%s/n%d", argv[1], i);
  		fs[i].fd = open(path, O_RDWR | O_CREAT | O_TRUNC, 0600);
  		pthread_create(&t, NULL, cyc, &fs[i]);
  		for (int j = 0; j < nsy; j++)
  			pthread_create(&t, NULL, syncer, &fs[i]);
  	}

  	for (int s = 0; s < secs; s += 10) {
  		long c = 0;

  		sleep(10);
  		for (int i = 0; i < nfiles; i++)
  			c += atomic_load(&fs[i].cycles);
  		printf("t=%ds cycles=%ld\n", s + 10, c);
  		fflush(stdout);
  	}
  	stop = 1;
  	return 0;
  }

-- 
Cheers,
Harry / Hyeonggon

^ permalink raw reply	[flat|nested] 3+ messages in thread

* Re: [PATCH] btrfs: subpage: do not end writeback of blocks owned by async submission
  2026-12-04 23:10 [PATCH] btrfs: subpage: do not end writeback of blocks owned by async submission Harry Yoo (Meta)
  2026-12-04 23:13 ` Harry Yoo
@ 2026-12-04 23:16 ` Qu Wenruo
  1 sibling, 0 replies; 3+ messages in thread
From: Qu Wenruo @ 2026-12-04 23:16 UTC (permalink / raw)
  To: Harry Yoo (Meta), David Sterba, Chris Mason, Nick Terrell,
	Qu Wenruo
  Cc: kernel-team, linux-btrfs, Boris Burkov, Leo Martins, stable



在 2026/12/5 09:40, Harry Yoo (Meta) 写道:
> In the Meta fleet, we observed hung tasks on ARM64 hosts with 64k
> pages, where a task waits forever for writeback (btrfs, 4k blocks,
> compression enabled).
> 
> While it was observed on ARM64 systems, it also reproduces on x86
> systems with large folios (which was introduced in v7.2) on btrfs:
> 
>    INFO: task repro:246 blocked in I/O wait for more than 30 seconds.
>    Call Trace:
>     folio_wait_bit+0xda/0x1e0
>     folio_wait_writeback+0x34/0xa0
>     truncate_inode_partial_folio+0xa2/0x3b0
>     truncate_inode_pages_range+0x240/0x480
>     truncate_pagecache+0x49/0x70
>     btrfs_setattr+0xd1/0x330
>     notify_change+0x380/0x570
>     do_truncate+0xc9/0xf0
>     do_ftruncate+0xa2/0x1a0
> 
> The task hangs because the folio has the PG_writeback flag set but
> nothing clears it, ever.
> 
> This happens due to a race between 1) a truncation, 2) writeback of a
> folio, and 3) the async compression worker writing back other blocks of
> the same folio.
> 
> When extent_writepage_io() doesn't submit any block due to a truncation
> (as every block subject to writeback is beyond i_size), it clears the
> dirty tag of the folio without actual writeback:
> 
> 	if (!submitted_io && !found_error) {
> 		btrfs_folio_set_writeback(fs_info, folio, start, len);
> 		btrfs_folio_clear_writeback(fs_info, folio, start, len);
> 	}
> 
> However, the task performing writeback on a folio can race with the
> async compression worker writing back other blocks of the same folio,
> when both find all of their blocks beyond i_size.
> 
> Task A (writeback)             Task B (compression worker)
> ----------------------------   ----------------------------------
> extent_writepage()
>   writepage_delalloc()
>    blocks 6-10:
>     run_delalloc_compressed() -->
>                                 compress_file_range()
>                                  blocks 6-10 >= i_size,
>                                  not compressed
>    block 12:
>     cow_file_range()
>    submit_bitmap = 0x1000 (block 12)
>   extent_writepage_io(0, 64K)
>    block 12 >= i_size,
>    submitted_io == false
>                                 submit_compressed_extents()
>                                  submit_uncompressed_range()
>                                   extent_write_locked_range()
>                                    extent_writepage_io(24K, 20K)
>                                     submit_bitmap = 0x7c0 (blocks 6-10)
>                                     all blocks >= i_size,
>                                     submitted_io == false
>    btrfs_folio_set_writeback(0, 64K)
>      wb bitmap 0x0000 -> 0xffff
>      folio writeback flag set
>                                     btrfs_folio_set_writeback(24K, 20K)
>                                       wb bitmap stays 0xffff
>    btrfs_folio_clear_writeback(0, 64K)
>      wb bitmap 0xffff -> 0x0000
>      folio_end_writeback()
>                                     btrfs_folio_clear_writeback(24K, 20K)
>                                       wb bitmap already 0x0000
>                                       folio_end_writeback() again (!)
>                                       ^ PG_writeback is set and never
>                                         cleared.
> 
> With CONFIG_BTRFS_ASSERT=y, an assertion failure shows up:
> 
>    assertion failed: folio_test_writeback(folio), in fs/btrfs/subpage.c:494
>    kernel BUG at fs/btrfs/subpage.c:494!
>    RIP: 0010:btrfs_subpage_clear_writeback.cold+0x20/0x22
>    Call Trace:
>     extent_writepage_io+0x45d/0x480
>     extent_write_locked_range+0x1db/0x380
>     run_delalloc_cow.constprop.0+0x6c/0xd0
>     submit_uncompressed_range+0x82/0x110
>     submit_compressed_extents+0x309/0x500
>     btrfs_work_helper+0x138/0x370
> 
> This supports that the folio's PG_writeback flag has already been
> cleared when the async compression worker clears writeback on its
> blocks, which matches the scenario above.
> 
> This has become a real problem with commit 1d2fbb7f1f9e ("btrfs: allow
> compression even if the range is not page aligned") in v6.13 (and under
> CONFIG_BTRFS_EXPERIMENTAL until v6.16) as it allows compression for
> non-page-aligned ranges when the block size is smaller than the folio
> size. Before the commit, all blocks of a folio were written either by
> extent_writepage() or by the compression worker, and no folio had blocks
> owned by different contexts.
> 
> It has become easier to trigger with commit 59615e2c1f63 ("btrfs:
> reject single block sized compression early") in v7.0 as it made a
> single block delalloc range inside a compressed inode take the
> synchronous path while the rest of the folio still goes through
> compression.
> 
> To fix this, set and clear writeback only for the blocks in
> bio_ctrl->submit_bitmap. Blocks owned by an asynchronous submission keep
> their writeback bits and the folio writeback ends exactly once when
> the last owner clears its bits.
> 
> Fixes: 1d2fbb7f1f9e ("btrfs: allow compression even if the range is not page aligned")
> CC: stable@vger.kernel.org
> Signed-off-by: Harry Yoo (Meta) <harry@kernel.org>

Reviewed-by: Qu Wenruo <wqu@suse.com>

Thanks for catching this. I had a feeling something would go wrong when 
a folio contains mixed compression and non-compression write.

But didn't notice this until now.

Thanks,
Qu

> ---
>   fs/btrfs/extent_io.c | 20 ++++++++++++++++----
>   1 file changed, 16 insertions(+), 4 deletions(-)
> 
> diff --git a/fs/btrfs/extent_io.c b/fs/btrfs/extent_io.c
> index d92dee95b290..3c1e8ec1e2fc 100644
> --- a/fs/btrfs/extent_io.c
> +++ b/fs/btrfs/extent_io.c
> @@ -1993,15 +1993,27 @@ static noinline_for_stack int extent_writepage_io(struct btrfs_inode *inode,
>   	 * cleared but PAGECACHE_TAG_DIRTY is not cleared (only cleared
>   	 * by folio_start_writeback() if the folio is not dirty).
>   	 *
> -	 * Here we set writeback and clear for the range. If the full folio
> -	 * is no longer dirty then we clear the PAGECACHE_TAG_DIRTY tag.
> +	 * Here we set and clear writeback for the blocks in submit_bitmap,
> +	 * which clears PAGECACHE_TAG_DIRTY if the folio is no longer dirty.
> +	 * Do not touch other blocks in the range as they may be owned by
> +	 * a different context, e.g. an async compression worker.
>   	 *
>   	 * If we hit any error, the corresponding sector will have its dirty
>   	 * flag cleared and writeback finished, thus no need to handle the error case.
>   	 */
>   	if (!submitted_io && !found_error) {
> -		btrfs_folio_set_writeback(fs_info, folio, start, len);
> -		btrfs_folio_clear_writeback(fs_info, folio, start, len);
> +		unsigned int start_bit;
> +		unsigned int end_bit;
> +
> +		for_each_set_bitrange(start_bit, end_bit, bio_ctrl->submit_bitmap,
> +				      blocks_per_folio) {
> +			const u64 block_start = folio_start +
> +				(start_bit << fs_info->sectorsize_bits);
> +			const u32 block_len = (end_bit - start_bit) << fs_info->sectorsize_bits;
> +
> +			btrfs_folio_set_writeback(fs_info, folio, block_start, block_len);
> +			btrfs_folio_clear_writeback(fs_info, folio, block_start, block_len);
> +		}
>   	}
>   	return found_error;
>   }
> 
> ---
> base-commit: d7a35bfad47f033380f6f6d42d186adc1d9fe406
> change-id: 20261204-btrfs-subpage-writeback-fix-3b36f61756a8
> 
> Best regards,
> --
> Cheers,
> Harry / Hyeonggon


^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2026-12-04 23:17 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-04 23:10 [PATCH] btrfs: subpage: do not end writeback of blocks owned by async submission Harry Yoo (Meta)
2026-12-04 23:13 ` Harry Yoo
2026-12-04 23:16 ` Qu Wenruo

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox