mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* [PATCH 0/6] btrfs: trim unused space when relocating data extents
@ 2026-11-29 13:31 Ismael Luceno
  2026-11-29 13:31 ` [PATCH 1/6] btrfs: add prealloc helper for sharing one allocation Ismael Luceno
                   ` (6 more replies)
  0 siblings, 7 replies; 8+ messages in thread
From: Ismael Luceno @ 2026-11-29 13:31 UTC (permalink / raw)
  To: linux-btrfs, David Sterba, Chris Mason
  Cc: Ismael Luceno, linux-kernel, Qu Wenruo, Anand Jain, Filipe Manana

A data balance copies every data extent whole, including bytes that no
file references. Those dead bytes stay allocated, and an overwritten
file keeps its old extents until every reference to them is gone.

This series copies only the referenced bytes. For each old extent, the
referenced ranges are collected and laid out in one new allocation, and
each file extent is remapped to its own range. Dead bytes are not copied,
so they are freed with the old block group.

Patches 2-6 support this change: a helper that preallocates one allocation
for several file extents, NOCOW writeback into relocation extents, a scan
of the running transaction for references, a retry for references that
survive the update stage, and a group length derived from its members.

Testing

Measured in QEMU guests, one run per kernel. Base is f2805cb. Series is
this six-patch series. Every run passed btrfs check. Timings are not
reported, because they varied more between runs than between kernels.

- Holes: a 64 MiB extent with 16 dead 1 MiB holes, then a balance. Data
  used 80 MiB -> 64 MiB (base -> series). Extents stay at 33.
- Random overwrites: a 256 MiB file with 600 random 4 KiB overwrites, then
  a balance. Data used 258.32 MiB -> 258.32 MiB (base) and 258.32 MiB ->
  256.00 MiB (series).
- Read: a 64 MiB file written as 32 2 MiB chunks with 1 MiB overwritten in
  the middle of each, then a direct sequential read. Device read requests
  136 -> 136 (base) and 136 -> 134 (series).
- Overhead: the same layout, a balance, then a rewrite of the first 80%.
  Whole extent bytes are the distinct on-disk extents the file references,
  at full size. Overhead is whole minus referenced (64 MiB).

  Base: whole 96 -> 96 -> 72 MiB; overhead 32 -> 32 -> 8 MiB (write,
        balance, rewrite)
  Series: whole 96 -> 64 -> 65 MiB; overhead 32 -> 0 -> 1 MiB

  Metadata after the balance: base 288 KiB, series 240 KiB.

- xfstests: the existing trim test passes on the series. The new tests in
  the xfstests series (btrfs/361-363) pass on the series with zero bytes
  left beyond the file size, and fail on base with 16 MiB, 2.33 MiB and 8
  MiB left.

The three tests are sent to fstests@vger.kernel.org as a separate series,
submitted together with this one:
"[PATCH 0/3] btrfs: test that balance frees dead bytes of data extents".

Ismael Luceno (6):
  btrfs: add prealloc helper for sharing one allocation
  btrfs: allow NOCOW writeback into data relocation extents
  btrfs: relocate only referenced bytes of a data extent
  btrfs: scan the running transaction for data extent references
  btrfs: retry a block group that references survive the update stage
  btrfs: derive relocation group length from its members

 fs/btrfs/btrfs_inode.h | 14 ++
 fs/btrfs/inode.c       | 182 ++++++++++++++-
 fs/btrfs/relocation.c  | 505 ++++++++++++++++++++++++++++++++++-------
 3 files changed, 613 insertions(+), 88 deletions(-)

-- 
2.56.0


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

* [PATCH 1/6] btrfs: add prealloc helper for sharing one allocation
  2026-11-29 13:31 [PATCH 0/6] btrfs: trim unused space when relocating data extents Ismael Luceno
@ 2026-11-29 13:31 ` Ismael Luceno
  2026-11-29 13:31 ` [PATCH 2/6] btrfs: allow NOCOW writeback into data relocation extents Ismael Luceno
                   ` (5 subsequent siblings)
  6 siblings, 0 replies; 8+ messages in thread
From: Ismael Luceno @ 2026-11-29 13:31 UTC (permalink / raw)
  To: linux-btrfs, David Sterba, Chris Mason
  Cc: Ismael Luceno, linux-kernel, Qu Wenruo, Anand Jain, Filipe Manana

Data relocation is going to copy only the referenced bytes of an extent
and lay them out back to back. The copied pieces then have to share one
disk allocation, while btrfs_prealloc_file_range() only handles a single
range with its own allocation.

Add btrfs_prealloc_file_range_shared(), which takes an array of pieces,
each a file range and its offset inside a single allocation of total_len
bytes. It reserves that allocation once, inserts one preallocated file
extent item per piece, updates the extent maps and i_size like the
existing helper, and frees the reservation again if nothing was inserted.

The qgroup reservation for every piece is released up front, because
only the first inserted item charges the extent with it. Releasing it
per piece would leak the reservation of every later piece.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
---
 fs/btrfs/btrfs_inode.h |  14 ++++
 fs/btrfs/inode.c       | 165 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 179 insertions(+)

diff --git a/fs/btrfs/btrfs_inode.h b/fs/btrfs/btrfs_inode.h
index fbcf8ca05fb74..1c5a007eae8c4 100644
--- a/fs/btrfs/btrfs_inode.h
+++ b/fs/btrfs/btrfs_inode.h
@@ -593,6 +593,20 @@ int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size);
 void btrfs_add_delayed_iput(struct btrfs_inode *inode);
 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info);
 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info);
+/*
+ * One piece of a shared preallocation: the file range starting at
+ * @file_start, @len bytes long, is backed by the allocation at @data_offset.
+ */
+struct btrfs_prealloc_piece {
+	u64 file_start;
+	u64 data_offset;
+	u64 len;
+};
+
+int btrfs_prealloc_file_range_shared(struct inode *inode,
+				     const struct btrfs_prealloc_piece *pieces,
+				     unsigned int nr_pieces, u64 total_len,
+				     u64 *alloc_hint);
 int btrfs_prealloc_file_range(struct inode *inode, int mode,
 			      u64 start, u64 num_bytes, u64 min_size,
 			      loff_t actual_len, u64 *alloc_hint,
diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
index 4b29b82eb1804..7592588fec64c 100644
--- a/fs/btrfs/inode.c
+++ b/fs/btrfs/inode.c
@@ -9165,6 +9165,171 @@ static struct btrfs_trans_handle *insert_prealloc_file_extent(
 	return ERR_PTR(ret);
 }
 
+/*
+ * Preallocate one extent of @total_len bytes and back several file ranges
+ * with it. Piece k covers [file_start, file_start + len) of the file and is
+ * stored at data_offset inside the allocation. The allocation is a single
+ * extent item, and every piece adds a reference to it.
+ *
+ * The caller must have reserved the data space. The allocation must be one
+ * contiguous extent, so this fails if the allocator can't provide one.
+ */
+int btrfs_prealloc_file_range_shared(struct inode *inode,
+				     const struct btrfs_prealloc_piece *pieces,
+				     unsigned int nr_pieces, u64 total_len,
+				     u64 *alloc_hint)
+{
+	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
+	struct btrfs_root *root = BTRFS_I(inode)->root;
+	struct btrfs_replace_extent_info extent_info = { 0 };
+	struct btrfs_trans_handle *trans;
+	struct btrfs_path *path;
+	struct btrfs_key ins;
+	u64 qgroup_pending = 0;
+	unsigned int i;
+	int ret;
+
+	if (!nr_pieces)
+		return 0;
+
+	ret = btrfs_reserve_extent(root, total_len, total_len, total_len, 0,
+				   *alloc_hint, &ins, true, false);
+	if (ret)
+		return ret;
+
+	/*
+	 * Release the qgroup reservation of every piece up front. Only the
+	 * first insert consumes it, and it charges the whole allocation at once,
+	 * so the pieces after it must not release anything of their own.
+	 */
+	for (i = 0; i < nr_pieces; i++) {
+		u64 released = 0;
+
+		ret = btrfs_qgroup_release_data(BTRFS_I(inode),
+						pieces[i].file_start,
+						pieces[i].len, &released);
+		if (ret)
+			goto out_fail;
+		qgroup_pending += released;
+	}
+
+	extent_info.is_new_extent = true;
+	extent_info.disk_offset = ins.objectid;
+	extent_info.disk_len = total_len;
+
+	for (i = 0; i < nr_pieces; i++) {
+		const struct btrfs_prealloc_piece *p = &pieces[i];
+		struct btrfs_file_extent_item stack_fi;
+
+		memset(&stack_fi, 0, sizeof(stack_fi));
+		btrfs_set_stack_file_extent_type(&stack_fi,
+						 BTRFS_FILE_EXTENT_PREALLOC);
+		btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, ins.objectid);
+		btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, total_len);
+		btrfs_set_stack_file_extent_offset(&stack_fi, p->data_offset);
+		btrfs_set_stack_file_extent_num_bytes(&stack_fi, p->len);
+		btrfs_set_stack_file_extent_ram_bytes(&stack_fi, p->len);
+		btrfs_set_stack_file_extent_compression(&stack_fi,
+							BTRFS_COMPRESS_NONE);
+
+		extent_info.data_offset = p->data_offset;
+		extent_info.data_len = p->len;
+		extent_info.file_offset = p->file_start;
+		extent_info.extent_buf = (char *)&stack_fi;
+		extent_info.qgroup_reserved = qgroup_pending;
+
+		path = btrfs_alloc_path();
+		if (!path) {
+			ret = -ENOMEM;
+			goto out_fail;
+		}
+		ret = btrfs_replace_file_extents(BTRFS_I(inode), path,
+						 p->file_start,
+						 p->file_start + p->len - 1,
+						 &extent_info, true, &trans);
+		btrfs_free_path(path);
+		/* The first piece turned the reservation into an extent item. */
+		if (i == 0)
+			btrfs_dec_block_group_reservations(fs_info, ins.objectid);
+		if (ret)
+			goto out_fail;
+		/* The first insert charged the qgroup reservation. */
+		qgroup_pending = 0;
+
+		{
+			struct extent_map *em = btrfs_alloc_extent_map();
+
+			if (!em) {
+				btrfs_end_transaction(trans);
+				ret = -ENOMEM;
+				goto out_fail;
+			}
+			em->start = p->file_start;
+			em->len = p->len;
+			em->disk_bytenr = ins.objectid;
+			em->offset = p->data_offset;
+			em->disk_num_bytes = total_len;
+			em->ram_bytes = p->len;
+			em->flags |= EXTENT_FLAG_PREALLOC;
+			em->generation = trans->transid;
+
+			ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em,
+							     true);
+			btrfs_free_extent_map(em);
+		}
+		if (ret) {
+			btrfs_abort_transaction(trans, ret);
+			btrfs_end_transaction(trans);
+			return ret;
+		}
+
+		inode_inc_iversion(inode);
+		inode_set_ctime_current(inode);
+		BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
+		/* Like btrfs_prealloc_file_range(), grow i_size to cover the piece. */
+		if (p->file_start + p->len > inode->i_size) {
+			u64 new_size = p->file_start + p->len;
+			u64 range_start = round_down(inode->i_size,
+						     fs_info->sectorsize);
+			u64 range_end = round_up(new_size, fs_info->sectorsize);
+
+			ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
+					range_start, range_end - range_start);
+			if (ret) {
+				btrfs_abort_transaction(trans, ret);
+				btrfs_end_transaction(trans);
+				return ret;
+			}
+			i_size_write(inode, new_size);
+			btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
+		}
+		ret = btrfs_update_inode(trans, BTRFS_I(inode));
+		if (ret) {
+			btrfs_abort_transaction(trans, ret);
+			btrfs_end_transaction(trans);
+			return ret;
+		}
+		btrfs_end_transaction(trans);
+	}
+
+	*alloc_hint = ins.objectid + total_len;
+	return 0;
+
+out_fail:
+	/*
+	 * Nothing was inserted yet, so the reservation can go back. Once an
+	 * extent item exists the allocation has references and can't be freed
+	 * here; the error then propagates and the balance fails.
+	 */
+	if (qgroup_pending)
+		btrfs_qgroup_free_refroot(fs_info, btrfs_root_id(root),
+					  qgroup_pending, BTRFS_QGROUP_RSV_DATA);
+	if (extent_info.insertions == 0)
+		btrfs_free_reserved_extent(fs_info, ins.objectid, total_len,
+					   false);
+	return ret;
+}
+
 int btrfs_prealloc_file_range(struct inode *inode, int mode,
 			      u64 start, u64 num_bytes, u64 min_size,
 			      loff_t actual_len, u64 *alloc_hint,
-- 
2.56.0


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

* [PATCH 2/6] btrfs: allow NOCOW writeback into data relocation extents
  2026-11-29 13:31 [PATCH 0/6] btrfs: trim unused space when relocating data extents Ismael Luceno
  2026-11-29 13:31 ` [PATCH 1/6] btrfs: add prealloc helper for sharing one allocation Ismael Luceno
@ 2026-11-29 13:31 ` Ismael Luceno
  2026-11-29 13:31 ` [PATCH 3/6] btrfs: relocate only referenced bytes of a data extent Ismael Luceno
                   ` (4 subsequent siblings)
  6 siblings, 0 replies; 8+ messages in thread
From: Ismael Luceno @ 2026-11-29 13:31 UTC (permalink / raw)
  To: linux-btrfs, David Sterba, Chris Mason
  Cc: Ismael Luceno, linux-kernel, Qu Wenruo, Anand Jain, Filipe Manana

can_nocow_file_extent() refuses NOCOW when another inode references the
same disk extent, because a NOCOW write would then change data the other
reference sees. Data relocation writes its destination extents with NOCOW
into preallocated space, and a compacted destination is referenced by
several file extents of the data reloc inode on purpose: one per copied
segment.

Those references can't be seen by anything else before the update stage
remaps them, so the cross reference check only refuses the write. Skip it
for the data reloc root.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
---
 fs/btrfs/inode.c | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)

diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
index 7592588fec64c..90886e5e31f16 100644
--- a/fs/btrfs/inode.c
+++ b/fs/btrfs/inode.c
@@ -1833,10 +1833,19 @@ static int can_nocow_file_extent(struct btrfs_path *path,
 	 */
 	btrfs_release_path(path);
 
-	ret = btrfs_cross_ref_exist(inode, key->offset - args->file_extent.offset,
-				    args->file_extent.disk_bytenr, path);
-	if (ret != 0)
-		goto out;
+	/*
+	 * The data relocation inode's destination extents are private to it
+	 * until the update stage, and a compacted extent is referenced by
+	 * several of its file extents on purpose, so they can't be cross
+	 * referenced by anything else. Checking them would only refuse NOCOW.
+	 */
+	if (!btrfs_is_data_reloc_root(inode->root)) {
+		ret = btrfs_cross_ref_exist(inode,
+					    key->offset - args->file_extent.offset,
+					    args->file_extent.disk_bytenr, path);
+		if (ret != 0)
+			goto out;
+	}
 
 	if (args->free_path) {
 		/*
-- 
2.56.0


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

* [PATCH 3/6] btrfs: relocate only referenced bytes of a data extent
  2026-11-29 13:31 [PATCH 0/6] btrfs: trim unused space when relocating data extents Ismael Luceno
  2026-11-29 13:31 ` [PATCH 1/6] btrfs: add prealloc helper for sharing one allocation Ismael Luceno
  2026-11-29 13:31 ` [PATCH 2/6] btrfs: allow NOCOW writeback into data relocation extents Ismael Luceno
@ 2026-11-29 13:31 ` Ismael Luceno
  2026-11-29 13:31 ` [PATCH 4/6] btrfs: scan the running transaction for data extent references Ismael Luceno
                   ` (3 subsequent siblings)
  6 siblings, 0 replies; 8+ messages in thread
From: Ismael Luceno @ 2026-11-29 13:31 UTC (permalink / raw)
  To: linux-btrfs, David Sterba, Chris Mason
  Cc: Ismael Luceno, linux-kernel, Qu Wenruo, Anand Jain, Filipe Manana

Instead of relocating extents whole, dead gaps included, let's collect
the referenced ranges of the extent from every leaf, so each file extent
item contributes the range it maps (and contiguous/overlapping ranges
get merged).

Compressed extents are atomic, so they are still copied whole, and so
is an extent whose references can't be found.

Referenced ranges are copied laid out back to back, so the result has
no dead bytes and each file extent item maps to the offset of its range
inside that allocation. Copies are grouped into the clusters that the
move stage already writes, so the clusters keep the per-member end and
offset they need.

replace_file_extents() no longer requires the new file extent offset to
be zero. It adds the file extent's offset and the offset of the range
inside the new allocation.

If a reference survives the update stage, the old block group still
has used bytes. Removing its chunk would leave that reference dangling,
so relocate_block_group() now fails with -EUCLEAN and the chunk is kept.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
---
 fs/btrfs/relocation.c | 472 ++++++++++++++++++++++++++++++++++--------
 1 file changed, 388 insertions(+), 84 deletions(-)

diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
index c7b5a655e89f0..a9da7a6468fa5 100644
--- a/fs/btrfs/relocation.c
+++ b/fs/btrfs/relocation.c
@@ -133,6 +133,16 @@ struct file_extent_cluster {
 	u64 start;
 	u64 end;
 	u64 boundary[MAX_EXTENTS];
+	/* Last byte of the referenced range of each member. */
+	u64 member_end[MAX_EXTENTS];
+	/* Offset of each member inside its allocation. */
+	u64 data_offset[MAX_EXTENTS];
+	/*
+	 * Consecutive members with the same group_start are segments of one old
+	 * extent. They share one allocation of group_len bytes.
+	 */
+	u64 group_start[MAX_EXTENTS];
+	u64 group_len[MAX_EXTENTS];
 	unsigned int nr;
 	u64 owning_root;
 };
@@ -156,6 +166,8 @@ struct reloc_control {
 	struct btrfs_backref_cache backref_cache;
 
 	struct file_extent_cluster cluster;
+	/* Where the next cluster's allocations should start looking. */
+	u64 alloc_hint;
 	/* tree blocks have been processed */
 	struct extent_io_tree processed_blocks;
 	/* map start of tree root to corresponding reloc tree */
@@ -867,14 +879,29 @@ int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
 /*
  * get new location of data
  */
+/*
+ * Find the relocated location of the referenced range [@bytenr, @bytenr +
+ * @num_bytes) of an old data extent.
+ *
+ * The data relocation inode holds one file extent per copied segment, at the
+ * segment's old address. Each one points into its new disk extent, at the
+ * segment's offset there. The
+ * range must lie entirely inside one such file extent. On return
+ * @new_bytenr and @new_disk_num_bytes describe the new disk extent, and
+ * @new_offset is where the range starts inside it.
+ */
 static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
+			    u64 *new_disk_num_bytes, u64 *new_offset,
 			    u64 bytenr, u64 num_bytes)
 {
 	struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
 	struct btrfs_fs_info *fs_info = root->fs_info;
 	BTRFS_PATH_AUTO_FREE(path);
 	struct btrfs_file_extent_item *fi;
+	struct btrfs_key key;
 	struct extent_buffer *leaf;
+	u64 ino = btrfs_ino(BTRFS_I(reloc_inode));
+	u64 fi_len;
 	int ret;
 
 	path = btrfs_alloc_path();
@@ -882,49 +909,58 @@ static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
 		return -ENOMEM;
 
 	bytenr -= BTRFS_I(reloc_inode)->reloc_block_group_start;
-	ret = btrfs_lookup_file_extent(NULL, root, path,
-			btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
+	ret = btrfs_lookup_file_extent(NULL, root, path, ino, bytenr, 0);
 	if (ret < 0)
 		return ret;
-	if (ret > 0)
-		return -ENOENT;
+	if (ret > 0) {
+		/* The covering item is the one before the insertion point. */
+		if (path->slots[0] == 0)
+			return -ENOENT;
+		path->slots[0]--;
+	}
 
 	leaf = path->nodes[0];
+	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
+	if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
+		return -ENOENT;
 	fi = btrfs_item_ptr(leaf, path->slots[0],
 			    struct btrfs_file_extent_item);
 	if (unlikely(btrfs_file_extent_type(leaf, fi) == BTRFS_FILE_EXTENT_INLINE)) {
 		btrfs_print_leaf(leaf);
 		btrfs_err(fs_info,
 	"unexpected inline file extent item for data reloc inode %llu key offset %llu",
-			  btrfs_ino(BTRFS_I(reloc_inode)), bytenr);
-		return -EUCLEAN;
-	}
-
-	/*
-	 * The cluster-boundary key searched above is always written by
-	 * relocation with offset 0: either by insert_prealloc_file_extent()
-	 * (memsets the stack item to 0) or by the front portion of a partial
-	 * writeback (offset=0 by construction). A non-zero value here means
-	 * the on-disk leaf does not match what relocation wrote, i.e.
-	 * corruption. The other encoding fields are caught earlier by
-	 * tree-checker's check_extent_data_item().
-	 */
-	if (unlikely(btrfs_file_extent_offset(leaf, fi))) {
-		btrfs_print_leaf(leaf);
-		btrfs_err(fs_info,
-"unexpected non-zero offset in file extent item for data reloc inode %llu key offset %llu offset %llu",
-			  btrfs_ino(BTRFS_I(reloc_inode)), bytenr,
-			  btrfs_file_extent_offset(leaf, fi));
+			  ino, bytenr);
 		return -EUCLEAN;
 	}
 
-	if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi))
-		return -EINVAL;
+	/* The range must be covered by this one segment. */
+	fi_len = btrfs_file_extent_num_bytes(leaf, fi);
+	if (key.offset > bytenr || bytenr + num_bytes > key.offset + fi_len)
+		return -ENOENT;
 
 	*new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
+	*new_disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
+	*new_offset = btrfs_file_extent_offset(leaf, fi) + (bytenr - key.offset);
 	return 0;
 }
 
+/*
+ * Map a referenced range of an old disk extent to its relocated location.
+ *
+ * @bytenr is the start of the old disk extent, @extent_offset is where the
+ * file extent starts inside it and @num_bytes is the file extent's length.
+ * See get_new_location() for the outputs.
+ */
+static int map_relocated_range(struct reloc_control *rc, u64 bytenr,
+			       u64 extent_offset, u64 num_bytes,
+			       u64 *new_bytenr, u64 *new_disk_num_bytes,
+			       u64 *new_extent_offset)
+{
+	return get_new_location(rc->data_inode, new_bytenr, new_disk_num_bytes,
+				new_extent_offset, bytenr + extent_offset,
+				num_bytes);
+}
+
 /*
  * update file extent items in the tree leaf to point to
  * the new locations.
@@ -942,6 +978,10 @@ int replace_file_extents(struct btrfs_trans_handle *trans,
 	u64 parent;
 	u64 bytenr;
 	u64 new_bytenr = 0;
+	u64 new_extent_offset = 0;
+	u64 new_disk_num_bytes = 0;
+	u64 extent_offset;
+	u64 fs_len;
 	u64 num_bytes;
 	u64 end;
 	u32 nritems;
@@ -1016,8 +1056,11 @@ int replace_file_extents(struct btrfs_trans_handle *trans,
 			}
 		}
 
-		ret = get_new_location(rc->data_inode, &new_bytenr,
-				       bytenr, num_bytes);
+		extent_offset = btrfs_file_extent_offset(leaf, fi);
+		fs_len = btrfs_file_extent_num_bytes(leaf, fi);
+		ret = map_relocated_range(rc, bytenr, extent_offset, fs_len,
+					  &new_bytenr, &new_disk_num_bytes,
+					  &new_extent_offset);
 		if (ret) {
 			/*
 			 * Don't have to abort since we've not changed anything
@@ -1027,15 +1070,17 @@ int replace_file_extents(struct btrfs_trans_handle *trans,
 		}
 
 		btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
+		btrfs_set_file_extent_disk_num_bytes(leaf, fi, new_disk_num_bytes);
+		btrfs_set_file_extent_offset(leaf, fi, new_extent_offset);
 
-		key.offset -= btrfs_file_extent_offset(leaf, fi);
 		ref.action = BTRFS_ADD_DELAYED_REF;
 		ref.bytenr = new_bytenr;
-		ref.num_bytes = num_bytes;
+		ref.num_bytes = new_disk_num_bytes;
 		ref.parent = parent;
 		ref.owning_root = btrfs_root_id(root);
 		ref.ref_root = btrfs_header_owner(leaf);
-		btrfs_init_data_ref(&ref, key.objectid, key.offset,
+		btrfs_init_data_ref(&ref, key.objectid,
+				    key.offset - new_extent_offset,
 				    btrfs_root_id(root), false);
 		ret = btrfs_inc_extent_ref(trans, &ref);
 		if (unlikely(ret)) {
@@ -1049,7 +1094,8 @@ int replace_file_extents(struct btrfs_trans_handle *trans,
 		ref.parent = parent;
 		ref.owning_root = btrfs_root_id(root);
 		ref.ref_root = btrfs_header_owner(leaf);
-		btrfs_init_data_ref(&ref, key.objectid, key.offset,
+		btrfs_init_data_ref(&ref, key.objectid,
+				    key.offset - extent_offset,
 				    btrfs_root_id(root), false);
 		ret = btrfs_free_extent(trans, &ref);
 		if (unlikely(ret)) {
@@ -2784,20 +2830,29 @@ int relocate_tree_blocks(struct btrfs_trans_handle *trans,
 	return ret;
 }
 
+/* Total bytes of the allocations a cluster needs. */
+static u64 cluster_allocation_bytes(const struct file_extent_cluster *cluster)
+{
+	u64 total = 0;
+	unsigned int i;
+
+	for (i = 0; i < cluster->nr; i++)
+		if (i == 0 || cluster->group_start[i] != cluster->group_start[i - 1])
+			total += cluster->group_len[i];
+	return total;
+}
+
 static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control *rc)
 {
 	const struct file_extent_cluster *cluster = &rc->cluster;
 	struct btrfs_inode *inode = BTRFS_I(rc->data_inode);
-	u64 alloc_hint = 0;
-	u64 start;
-	u64 end;
+	struct btrfs_prealloc_piece *pieces;
 	u64 offset = inode->reloc_block_group_start;
-	u64 num_bytes;
-	int nr;
-	int ret = 0;
 	u64 prealloc_start = cluster->start - offset;
 	u64 prealloc_end = cluster->end - offset;
-	u64 cur_offset = prealloc_start;
+	u64 reserved;
+	unsigned int nr = 0;
+	int ret;
 
 	/*
 	 * For blocksize < folio size case (either bs < page size or large folios),
@@ -2815,36 +2870,57 @@ static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control
 		return ret;
 
 	BUG_ON(cluster->start != cluster->boundary[0]);
-	ret = btrfs_alloc_data_chunk_ondemand(inode,
-					      prealloc_end + 1 - prealloc_start);
+	reserved = cluster_allocation_bytes(cluster);
+	ret = btrfs_alloc_data_chunk_ondemand(inode, reserved);
 	if (ret)
 		return ret;
 
+	pieces = kmalloc_array(MAX_EXTENTS, sizeof(*pieces), GFP_NOFS);
+	if (!pieces) {
+		btrfs_free_reserved_data_space_noquota(inode, reserved);
+		return -ENOMEM;
+	}
+
 	btrfs_inode_lock(inode, 0);
-	for (nr = 0; nr < cluster->nr; nr++) {
+	while (nr < cluster->nr) {
 		struct extent_state *cached_state = NULL;
-
-		start = cluster->boundary[nr] - offset;
-		if (nr + 1 < cluster->nr)
-			end = cluster->boundary[nr + 1] - 1 - offset;
-		else
-			end = cluster->end - offset;
-
-		btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
-		num_bytes = end + 1 - start;
-		ret = btrfs_prealloc_file_range(&inode->vfs_inode, 0, start,
-						num_bytes, num_bytes,
-						end + 1, &alloc_hint, true);
-		cur_offset = end + 1;
-		btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
-		if (ret)
+		unsigned int last = nr;
+		unsigned int n = 0;
+		u64 group = cluster->group_start[nr];
+		u64 group_len = cluster->group_len[nr];
+		u64 lock_end;
+		unsigned int i;
+
+		while (last < cluster->nr && cluster->group_start[last] == group)
+			last++;
+		for (i = nr; i < last; i++) {
+			pieces[n].file_start = cluster->boundary[i] - offset;
+			pieces[n].data_offset = cluster->data_offset[i];
+			pieces[n].len = cluster->member_end[i] + 1 -
+					cluster->boundary[i];
+			n++;
+		}
+		lock_end = pieces[n - 1].file_start + pieces[n - 1].len - 1;
+
+		btrfs_lock_extent(&inode->io_tree, pieces[0].file_start, lock_end,
+				  &cached_state);
+		ret = btrfs_prealloc_file_range_shared(&inode->vfs_inode, pieces,
+						       n, group_len, &rc->alloc_hint);
+		btrfs_unlock_extent(&inode->io_tree, pieces[0].file_start,
+				    lock_end, &cached_state);
+		if (ret) {
+			/* This group's bytes were consumed by the attempt. */
+			reserved -= group_len;
 			break;
+		}
+		reserved -= group_len;
+		nr = last;
 	}
 	btrfs_inode_unlock(inode, 0);
 
-	if (cur_offset < prealloc_end)
-		btrfs_free_reserved_data_space_noquota(inode,
-						       prealloc_end + 1 - cur_offset);
+	kfree(pieces);
+	if (reserved)
+		btrfs_free_reserved_data_space_noquota(inode, reserved);
 	return ret;
 }
 
@@ -2891,12 +2967,7 @@ ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
 static u64 get_cluster_boundary_end(const struct file_extent_cluster *cluster,
 				    int cluster_nr)
 {
-	/* Last extent, use cluster end directly */
-	if (cluster_nr >= cluster->nr - 1)
-		return cluster->end;
-
-	/* Use next boundary start*/
-	return cluster->boundary[cluster_nr + 1] - 1;
+	return cluster->member_end[cluster_nr];
 }
 
 static int relocate_one_folio(struct reloc_control *rc,
@@ -3095,15 +3166,176 @@ static int relocate_file_extent_cluster(struct reloc_control *rc)
 	return ret;
 }
 
-static noinline_for_stack int relocate_data_extent(struct reloc_control *rc,
-					   const struct btrfs_key *extent_key)
+/*
+ * One referenced range of an old data extent. @offset is relative to the
+ * start of the disk extent, not the file.
+ */
+struct extent_segment {
+	u64 offset;
+	u64 len;
+};
+
+struct extent_segments {
+	struct extent_segment *segs;
+	unsigned int nr;
+	unsigned int alloc;
+	/* Compressed extents are atomic and must be copied whole. */
+	bool compressed;
+};
+
+static int add_extent_segment(struct extent_segments *es, u64 offset, u64 len)
+{
+	struct extent_segment *new;
+	unsigned int nalloc;
+
+	if (es->nr == es->alloc) {
+		nalloc = max(16U, es->alloc * 2);
+		new = krealloc_array(es->segs, nalloc, sizeof(*new), GFP_NOFS);
+		if (!new)
+			return -ENOMEM;
+		es->segs = new;
+		es->alloc = nalloc;
+	}
+	es->segs[es->nr].offset = offset;
+	es->segs[es->nr].len = len;
+	es->nr++;
+	return 0;
+}
+
+static int cmp_extent_segment(const void *a, const void *b)
+{
+	const struct extent_segment *sa = a;
+	const struct extent_segment *sb = b;
+
+	if (sa->offset < sb->offset)
+		return -1;
+	if (sa->offset > sb->offset)
+		return 1;
+	return 0;
+}
+
+/*
+ * Sort the segments and merge the ones that overlap or touch, so each
+ * remaining segment is a maximal referenced range.
+ */
+static void normalize_extent_segments(struct extent_segments *es)
+{
+	unsigned int i;
+	unsigned int out = 0;
+
+	if (es->nr == 0)
+		return;
+	sort(es->segs, es->nr, sizeof(*es->segs), cmp_extent_segment, NULL);
+	for (i = 0; i < es->nr; i++) {
+		struct extent_segment *cur = &es->segs[i];
+
+		if (out) {
+			struct extent_segment *prev = &es->segs[out - 1];
+
+			if (prev->offset + prev->len >= cur->offset) {
+				u64 end = max(prev->offset + prev->len,
+					      cur->offset + cur->len);
+
+				prev->len = end - prev->offset;
+				continue;
+			}
+		}
+		es->segs[out++] = *cur;
+	}
+	es->nr = out;
+}
+
+/*
+ * Collect the referenced ranges of the data extent described by @extent_key
+ * from every leaf that holds a reference to it.
+ */
+static int collect_extent_segments(struct reloc_control *rc,
+				   const struct btrfs_key *extent_key,
+				   struct extent_segments *es)
+{
+	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
+	struct btrfs_backref_walk_ctx ctx = { 0 };
+	struct ulist_iterator leaf_uiter;
+	struct ulist_node *ref_node;
+	const u64 bytenr = extent_key->objectid;
+	const u64 num_bytes = extent_key->offset;
+	int ret;
+
+	ctx.bytenr = bytenr;
+	ctx.skip_inode_ref_list = true;
+	ctx.fs_info = fs_info;
+
+	ret = btrfs_find_all_leafs(&ctx);
+	if (ret < 0)
+		return ret;
+
+	ULIST_ITER_INIT(&leaf_uiter);
+	while ((ref_node = ulist_next(ctx.refs, &leaf_uiter))) {
+		struct btrfs_tree_parent_check check = { 0 };
+		struct extent_buffer *eb;
+		int slot;
+
+		eb = read_tree_block(fs_info, ref_node->val, &check);
+		if (IS_ERR(eb)) {
+			ret = PTR_ERR(eb);
+			break;
+		}
+		for (slot = 0; slot < btrfs_header_nritems(eb); slot++) {
+			struct btrfs_file_extent_item *fi;
+			struct btrfs_key key;
+
+			btrfs_item_key_to_cpu(eb, &key, slot);
+			if (key.type != BTRFS_EXTENT_DATA_KEY)
+				continue;
+			fi = btrfs_item_ptr(eb, slot,
+					    struct btrfs_file_extent_item);
+			if (btrfs_file_extent_type(eb, fi) ==
+			    BTRFS_FILE_EXTENT_INLINE)
+				continue;
+			if (btrfs_file_extent_disk_bytenr(eb, fi) != bytenr)
+				continue;
+			if (btrfs_file_extent_disk_num_bytes(eb, fi) !=
+			    num_bytes) {
+				ret = -EUCLEAN;
+				break;
+			}
+			if (btrfs_file_extent_compression(eb, fi) !=
+			    BTRFS_COMPRESS_NONE) {
+				es->compressed = true;
+				continue;
+			}
+			ret = add_extent_segment(es,
+					btrfs_file_extent_offset(eb, fi),
+					btrfs_file_extent_num_bytes(eb, fi));
+			if (ret)
+				break;
+		}
+		free_extent_buffer(eb);
+		if (ret)
+			break;
+	}
+	ulist_free(ctx.refs);
+	if (ret)
+		return ret;
+
+	normalize_extent_segments(es);
+	return 0;
+}
+
+/*
+ * Start a new allocation group in the cluster. A group must not be split, so
+ * flush the cluster first if the group does not follow the last member
+ * directly or does not fit in the remaining slots.
+ */
+static int cluster_begin_group(struct reloc_control *rc, u64 start,
+			       unsigned int count)
 {
-	struct inode *inode = rc->data_inode;
 	struct file_extent_cluster *cluster = &rc->cluster;
+	struct btrfs_root *root = BTRFS_I(rc->data_inode)->root;
 	int ret;
-	struct btrfs_root *root = BTRFS_I(inode)->root;
 
-	if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
+	if (cluster->nr > 0 &&
+	    (start != cluster->end + 1 || cluster->nr + count > MAX_EXTENTS)) {
 		ret = relocate_file_extent_cluster(rc);
 		if (ret)
 			return ret;
@@ -3137,24 +3369,87 @@ static noinline_for_stack int relocate_data_extent(struct reloc_control *rc,
 		/* And reset it back for the current extent's owning root. */
 		root->relocation_src_root = tmp;
 	}
+	return 0;
+}
 
-	if (!cluster->nr) {
-		cluster->start = extent_key->objectid;
-		cluster->owning_root = root->relocation_src_root;
-	}
-	else
-		BUG_ON(cluster->nr >= MAX_EXTENTS);
-	cluster->end = extent_key->objectid + extent_key->offset - 1;
-	cluster->boundary[cluster->nr] = extent_key->objectid;
+/* Append one referenced range to the cluster as a member. */
+static void cluster_add_member(struct reloc_control *rc, u64 start, u64 len,
+			       u64 group_start, u64 group_len, u64 data_offset)
+{
+	struct file_extent_cluster *cluster = &rc->cluster;
+	unsigned int nr = cluster->nr;
+
+	BUG_ON(nr >= MAX_EXTENTS);
+	if (!nr) {
+		cluster->start = start;
+		cluster->owning_root = BTRFS_I(rc->data_inode)->root->relocation_src_root;
+	}
+	cluster->end = start + len - 1;
+	cluster->boundary[nr] = start;
+	cluster->member_end[nr] = start + len - 1;
+	cluster->data_offset[nr] = data_offset;
+	cluster->group_start[nr] = group_start;
+	cluster->group_len[nr] = group_len;
 	cluster->nr++;
+}
 
-	if (cluster->nr >= MAX_EXTENTS) {
-		ret = relocate_file_extent_cluster(rc);
+/*
+ * Relocate one data extent. Only the bytes that are referenced are copied.
+ * The referenced ranges of an extent are laid out back to back in one
+ * allocation, so the relocated extent has no dead bytes in it. Compressed
+ * extents are atomic and are copied whole, and so is an extent whose
+ * references can't be found, which keeps the old behaviour for it.
+ */
+static noinline_for_stack int relocate_data_extent(struct reloc_control *rc,
+						   const struct btrfs_key *extent_key)
+{
+	struct extent_segments es = { 0 };
+	struct extent_segment whole = { .offset = 0, .len = extent_key->offset };
+	u64 start = extent_key->objectid;
+	unsigned int i;
+	int ret;
+
+	ret = collect_extent_segments(rc, extent_key, &es);
+	if (ret)
+		goto out;
+
+	if (es.compressed || es.nr == 0) {
+		kfree(es.segs);
+		es.segs = &whole;
+		es.nr = 1;
+		es.alloc = 0;
+	}
+
+	/*
+	 * Split the segments into groups of at most MAX_EXTENTS pieces, each
+	 * with its own allocation.
+	 */
+	for (i = 0; i < es.nr; ) {
+		unsigned int count = min_t(unsigned int, es.nr - i, MAX_EXTENTS);
+		u64 group_start = start + es.segs[i].offset;
+		u64 group_len = 0;
+		u64 data_offset = 0;
+		unsigned int j;
+
+		for (j = i; j < i + count; j++)
+			group_len += es.segs[j].len;
+
+		ret = cluster_begin_group(rc, group_start, count);
 		if (ret)
-			return ret;
-		cluster->nr = 0;
+			goto out;
+
+		for (j = i; j < i + count; j++) {
+			cluster_add_member(rc, start + es.segs[j].offset,
+					   es.segs[j].len, group_start, group_len,
+					   data_offset);
+			data_offset += es.segs[j].len;
+		}
+		i += count;
 	}
-	return 0;
+out:
+	if (es.segs != &whole)
+		kfree(es.segs);
+	return ret;
 }
 
 /*
@@ -5426,7 +5721,16 @@ static int do_nonremap_reloc(struct btrfs_fs_info *fs_info, bool verbose,
 
 	WARN_ON(rc->block_group->pinned > 0);
 	WARN_ON(rc->block_group->reserved > 0);
-	WARN_ON(rc->block_group->used > 0);
+	/*
+	 * A live reference into the old block group would dangle once the
+	 * chunk is removed. Keep the chunk instead of removing it.
+	 */
+	if (rc->block_group->used > 0) {
+		btrfs_warn(fs_info,
+			  "relocation left %llu bytes referenced in block group %llu",
+			  rc->block_group->used, rc->block_group->start);
+		return -EUCLEAN;
+	}
 
 	return 0;
 }
-- 
2.56.0


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

* [PATCH 4/6] btrfs: scan the running transaction for data extent references
  2026-11-29 13:31 [PATCH 0/6] btrfs: trim unused space when relocating data extents Ismael Luceno
                   ` (2 preceding siblings ...)
  2026-11-29 13:31 ` [PATCH 3/6] btrfs: relocate only referenced bytes of a data extent Ismael Luceno
@ 2026-11-29 13:31 ` Ismael Luceno
  2026-11-29 13:31 ` [PATCH 5/6] btrfs: retry a block group that references survive the update stage Ismael Luceno
                   ` (2 subsequent siblings)
  6 siblings, 0 replies; 8+ messages in thread
From: Ismael Luceno @ 2026-11-29 13:31 UTC (permalink / raw)
  To: linux-btrfs, David Sterba, Chris Mason
  Cc: Ismael Luceno, linux-kernel, Qu Wenruo, Anand Jain, Filipe Manana

The reference scan of a data extent walks the trees without a transaction
handle, so the backref walk reads the commit root. A reference made by
the running transaction, such as a reflink made during balance, is not
in the commit root, so the scan misses it, while the extent item already
counts it.

Run the scan under a joined transaction, so the walk sees the running
transaction and its pending delayed refs. The transaction is not flushed:
the walk accounts for pending refs itself.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
---
 fs/btrfs/relocation.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)

diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
index a9da7a6468fa5..75300c21fe06e 100644
--- a/fs/btrfs/relocation.c
+++ b/fs/btrfs/relocation.c
@@ -3255,19 +3255,31 @@ static int collect_extent_segments(struct reloc_control *rc,
 {
 	struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
 	struct btrfs_backref_walk_ctx ctx = { 0 };
+	struct btrfs_trans_handle *trans;
 	struct ulist_iterator leaf_uiter;
 	struct ulist_node *ref_node;
 	const u64 bytenr = extent_key->objectid;
 	const u64 num_bytes = extent_key->offset;
 	int ret;
 
+	/*
+	 * Walk the running transaction, delayed refs included, so the scan sees
+	 * the references made by it. They are not flushed.
+	 */
+	trans = btrfs_join_transaction(rc->extent_root);
+	if (IS_ERR(trans))
+		return PTR_ERR(trans);
+
 	ctx.bytenr = bytenr;
 	ctx.skip_inode_ref_list = true;
 	ctx.fs_info = fs_info;
+	ctx.trans = trans;
 
 	ret = btrfs_find_all_leafs(&ctx);
-	if (ret < 0)
+	if (ret < 0) {
+		btrfs_end_transaction(trans);
 		return ret;
+	}
 
 	ULIST_ITER_INIT(&leaf_uiter);
 	while ((ref_node = ulist_next(ctx.refs, &leaf_uiter))) {
@@ -3315,6 +3327,7 @@ static int collect_extent_segments(struct reloc_control *rc,
 			break;
 	}
 	ulist_free(ctx.refs);
+	btrfs_end_transaction(trans);
 	if (ret)
 		return ret;
 
-- 
2.56.0


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

* [PATCH 5/6] btrfs: retry a block group that references survive the update stage
  2026-11-29 13:31 [PATCH 0/6] btrfs: trim unused space when relocating data extents Ismael Luceno
                   ` (3 preceding siblings ...)
  2026-11-29 13:31 ` [PATCH 4/6] btrfs: scan the running transaction for data extent references Ismael Luceno
@ 2026-11-29 13:31 ` Ismael Luceno
  2026-11-29 13:31 ` [PATCH 6/6] btrfs: derive relocation group length from its members Ismael Luceno
  2026-11-29 21:00 ` [PATCH 0/6] btrfs: trim unused space when relocating data extents Qu Wenruo
  6 siblings, 0 replies; 8+ messages in thread
From: Ismael Luceno @ 2026-11-29 13:31 UTC (permalink / raw)
  To: linux-btrfs, David Sterba, Chris Mason
  Cc: Ismael Luceno, linux-kernel, Qu Wenruo, Anand Jain, Filipe Manana

A reference added during the update stage can survive it. Its bytes were
not moved, and the block group keeps used bytes. Failing the balance
right away is safe, since the chunk is kept, but it throws away the work
already done for a case that is rare.

Move the leftover bytes again instead. The pass runs with a fresh data
reloc inode, because the mappings of the first pass are keyed by the same
logical offsets. Up to RELOC_MAX_LEFTOVER_PASSES extra passes are made.
If the block group still has used bytes after them, it is kept and the
balance fails with -EUCLEAN, with an error message naming the block group.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
---
 fs/btrfs/relocation.c | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
index 75300c21fe06e..9bf0f9bc794c4 100644
--- a/fs/btrfs/relocation.c
+++ b/fs/btrfs/relocation.c
@@ -5751,6 +5751,9 @@ static int do_nonremap_reloc(struct btrfs_fs_info *fs_info, bool verbose,
 /*
  * function to relocate all extents in a block group.
  */
+/* Extra passes over a block group that a reference left behind. */
+#define RELOC_MAX_LEFTOVER_PASSES 3
+
 int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
 			       bool verbose)
 {
@@ -5873,7 +5876,30 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
 
 		btrfs_delete_unused_bgs(fs_info);
 	} else {
+		unsigned int pass = 0;
+
 		ret = do_nonremap_reloc(fs_info, verbose, rc);
+		/*
+		 * A reference added during the update stage can survive it. Its
+		 * bytes were not moved, so move what is left again with a fresh
+		 * data inode. Only this rare case pays for another pass.
+		 */
+		while (ret == -EUCLEAN && pass++ < RELOC_MAX_LEFTOVER_PASSES) {
+			iput(rc->data_inode);
+			rc->data_inode = create_reloc_inode(rc->block_group);
+			if (IS_ERR(rc->data_inode)) {
+				ret = PTR_ERR(rc->data_inode);
+				rc->data_inode = NULL;
+				break;
+			}
+			rc->stage = MOVE_DATA_EXTENTS;
+			rc->found_file_extent = false;
+			ret = do_nonremap_reloc(fs_info, verbose, rc);
+		}
+		if (ret == -EUCLEAN)
+			btrfs_err(fs_info,
+				  "block group %llu kept: references still point into it after %d passes",
+				  rc->block_group->start, RELOC_MAX_LEFTOVER_PASSES + 1);
 	}
 
 out:
-- 
2.56.0


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

* [PATCH 6/6] btrfs: derive relocation group length from its members
  2026-11-29 13:31 [PATCH 0/6] btrfs: trim unused space when relocating data extents Ismael Luceno
                   ` (4 preceding siblings ...)
  2026-11-29 13:31 ` [PATCH 5/6] btrfs: retry a block group that references survive the update stage Ismael Luceno
@ 2026-11-29 13:31 ` Ismael Luceno
  2026-11-29 21:00 ` [PATCH 0/6] btrfs: trim unused space when relocating data extents Qu Wenruo
  6 siblings, 0 replies; 8+ messages in thread
From: Ismael Luceno @ 2026-11-29 13:31 UTC (permalink / raw)
  To: linux-btrfs, David Sterba, Chris Mason
  Cc: Ismael Luceno, linux-kernel, Qu Wenruo, Anand Jain, Filipe Manana

A relocation group is the set of members that share one allocation. Its
length was stored per member, and cluster_add_member() copied the same
value into every member of the group. Nothing needs a stored value: the
length is the sum of the members' lengths, and prealloc can compute it
when it issues the group.

Compute the group length in prealloc_file_extent_cluster() and the
cluster's allocation size from the members. No behaviour changes. This
lets the next change grow a group past the extents it started with.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
---
 fs/btrfs/relocation.c | 18 ++++++------------
 1 file changed, 6 insertions(+), 12 deletions(-)

diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
index 9bf0f9bc794c4..3b6dd9f9ec7e0 100644
--- a/fs/btrfs/relocation.c
+++ b/fs/btrfs/relocation.c
@@ -139,10 +139,9 @@ struct file_extent_cluster {
 	u64 data_offset[MAX_EXTENTS];
 	/*
 	 * Consecutive members with the same group_start are segments of one old
-	 * extent. They share one allocation of group_len bytes.
+	 * extent. They share one allocation, as big as the sum of their lengths.
 	 */
 	u64 group_start[MAX_EXTENTS];
-	u64 group_len[MAX_EXTENTS];
 	unsigned int nr;
 	u64 owning_root;
 };
@@ -2837,8 +2836,7 @@ static u64 cluster_allocation_bytes(const struct file_extent_cluster *cluster)
 	unsigned int i;
 
 	for (i = 0; i < cluster->nr; i++)
-		if (i == 0 || cluster->group_start[i] != cluster->group_start[i - 1])
-			total += cluster->group_len[i];
+		total += cluster->member_end[i] + 1 - cluster->boundary[i];
 	return total;
 }
 
@@ -2887,7 +2885,7 @@ static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control
 		unsigned int last = nr;
 		unsigned int n = 0;
 		u64 group = cluster->group_start[nr];
-		u64 group_len = cluster->group_len[nr];
+		u64 group_len = 0;
 		u64 lock_end;
 		unsigned int i;
 
@@ -2898,6 +2896,7 @@ static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control
 			pieces[n].data_offset = cluster->data_offset[i];
 			pieces[n].len = cluster->member_end[i] + 1 -
 					cluster->boundary[i];
+			group_len += pieces[n].len;
 			n++;
 		}
 		lock_end = pieces[n - 1].file_start + pieces[n - 1].len - 1;
@@ -3387,7 +3386,7 @@ static int cluster_begin_group(struct reloc_control *rc, u64 start,
 
 /* Append one referenced range to the cluster as a member. */
 static void cluster_add_member(struct reloc_control *rc, u64 start, u64 len,
-			       u64 group_start, u64 group_len, u64 data_offset)
+			       u64 group_start, u64 data_offset)
 {
 	struct file_extent_cluster *cluster = &rc->cluster;
 	unsigned int nr = cluster->nr;
@@ -3402,7 +3401,6 @@ static void cluster_add_member(struct reloc_control *rc, u64 start, u64 len,
 	cluster->member_end[nr] = start + len - 1;
 	cluster->data_offset[nr] = data_offset;
 	cluster->group_start[nr] = group_start;
-	cluster->group_len[nr] = group_len;
 	cluster->nr++;
 }
 
@@ -3440,20 +3438,16 @@ static noinline_for_stack int relocate_data_extent(struct reloc_control *rc,
 	for (i = 0; i < es.nr; ) {
 		unsigned int count = min_t(unsigned int, es.nr - i, MAX_EXTENTS);
 		u64 group_start = start + es.segs[i].offset;
-		u64 group_len = 0;
 		u64 data_offset = 0;
 		unsigned int j;
 
-		for (j = i; j < i + count; j++)
-			group_len += es.segs[j].len;
-
 		ret = cluster_begin_group(rc, group_start, count);
 		if (ret)
 			goto out;
 
 		for (j = i; j < i + count; j++) {
 			cluster_add_member(rc, start + es.segs[j].offset,
-					   es.segs[j].len, group_start, group_len,
+					   es.segs[j].len, group_start,
 					   data_offset);
 			data_offset += es.segs[j].len;
 		}
-- 
2.56.0


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

* Re: [PATCH 0/6] btrfs: trim unused space when relocating data extents
  2026-11-29 13:31 [PATCH 0/6] btrfs: trim unused space when relocating data extents Ismael Luceno
                   ` (5 preceding siblings ...)
  2026-11-29 13:31 ` [PATCH 6/6] btrfs: derive relocation group length from its members Ismael Luceno
@ 2026-11-29 21:00 ` Qu Wenruo
  6 siblings, 0 replies; 8+ messages in thread
From: Qu Wenruo @ 2026-11-29 21:00 UTC (permalink / raw)
  To: Ismael Luceno, linux-btrfs, David Sterba, Chris Mason
  Cc: linux-kernel, Qu Wenruo, Anand Jain, Filipe Manana



在 2026/11/30 00:01, Ismael Luceno 写道:
> A data balance copies every data extent whole, including bytes that no
> file references. Those dead bytes stay allocated, and an overwritten
> file keeps its old extents until every reference to them is gone.
> 
> This series copies only the referenced bytes. For each old extent, the
> referenced ranges are collected and laid out in one new allocation, and
> each file extent is remapped to its own range. Dead bytes are not copied,
> so they are freed with the old block group.

Won't this introduce extra backref walk during relocation?
That can be very expensive for heavily shared data extents, meanwhile 
may even not result any space saving.


Despite the above backref overhead, the idea of removing bookend extents 
at relocation time is pretty clever.
This solution avoids the heavy backref tax at extent truncation time.


But sashiko is already reporting 9 high level problems and 11 medium 
level bugs, I think you would like to get them addressed.

Thanks,
Qu

> 
> Patches 2-6 support this change: a helper that preallocates one allocation
> for several file extents, NOCOW writeback into relocation extents, a scan
> of the running transaction for references, a retry for references that
> survive the update stage, and a group length derived from its members.
> 
> Testing
> 
> Measured in QEMU guests, one run per kernel. Base is f2805cb. Series is
> this six-patch series. Every run passed btrfs check. Timings are not
> reported, because they varied more between runs than between kernels.
> 
> - Holes: a 64 MiB extent with 16 dead 1 MiB holes, then a balance. Data
>    used 80 MiB -> 64 MiB (base -> series). Extents stay at 33.
> - Random overwrites: a 256 MiB file with 600 random 4 KiB overwrites, then
>    a balance. Data used 258.32 MiB -> 258.32 MiB (base) and 258.32 MiB ->
>    256.00 MiB (series).
> - Read: a 64 MiB file written as 32 2 MiB chunks with 1 MiB overwritten in
>    the middle of each, then a direct sequential read. Device read requests
>    136 -> 136 (base) and 136 -> 134 (series).
> - Overhead: the same layout, a balance, then a rewrite of the first 80%.
>    Whole extent bytes are the distinct on-disk extents the file references,
>    at full size. Overhead is whole minus referenced (64 MiB).
> 
>    Base: whole 96 -> 96 -> 72 MiB; overhead 32 -> 32 -> 8 MiB (write,
>          balance, rewrite)
>    Series: whole 96 -> 64 -> 65 MiB; overhead 32 -> 0 -> 1 MiB
> 
>    Metadata after the balance: base 288 KiB, series 240 KiB.
> 
> - xfstests: the existing trim test passes on the series. The new tests in
>    the xfstests series (btrfs/361-363) pass on the series with zero bytes
>    left beyond the file size, and fail on base with 16 MiB, 2.33 MiB and 8
>    MiB left.
> 
> The three tests are sent to fstests@vger.kernel.org as a separate series,
> submitted together with this one:
> "[PATCH 0/3] btrfs: test that balance frees dead bytes of data extents".
> 
> Ismael Luceno (6):
>    btrfs: add prealloc helper for sharing one allocation
>    btrfs: allow NOCOW writeback into data relocation extents
>    btrfs: relocate only referenced bytes of a data extent
>    btrfs: scan the running transaction for data extent references
>    btrfs: retry a block group that references survive the update stage
>    btrfs: derive relocation group length from its members
> 
>   fs/btrfs/btrfs_inode.h | 14 ++
>   fs/btrfs/inode.c       | 182 ++++++++++++++-
>   fs/btrfs/relocation.c  | 505 ++++++++++++++++++++++++++++++++++-------
>   3 files changed, 613 insertions(+), 88 deletions(-)
> 


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

end of thread, other threads:[~2026-11-29 21:00 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-29 13:31 [PATCH 0/6] btrfs: trim unused space when relocating data extents Ismael Luceno
2026-11-29 13:31 ` [PATCH 1/6] btrfs: add prealloc helper for sharing one allocation Ismael Luceno
2026-11-29 13:31 ` [PATCH 2/6] btrfs: allow NOCOW writeback into data relocation extents Ismael Luceno
2026-11-29 13:31 ` [PATCH 3/6] btrfs: relocate only referenced bytes of a data extent Ismael Luceno
2026-11-29 13:31 ` [PATCH 4/6] btrfs: scan the running transaction for data extent references Ismael Luceno
2026-11-29 13:31 ` [PATCH 5/6] btrfs: retry a block group that references survive the update stage Ismael Luceno
2026-11-29 13:31 ` [PATCH 6/6] btrfs: derive relocation group length from its members Ismael Luceno
2026-11-29 21:00 ` [PATCH 0/6] btrfs: trim unused space when relocating data extents Qu Wenruo

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

all inboxes | Powered by JetHome®