And the default extent size threshold is 256K, which is already beyond the compressed extent max size. This means, by default btrfs defrag ioctl will mark all compressed extent which is not adjacent to a hole/preallocated range for defrag. [FIX] Introduce a helper to grab the maximum extent size, and then in defrag_collect_targets() and defrag_check_next_extent(), reject extents which are already at their max capacity. Reported-by: Filipe Manana <fdmanana@xxxxxxxx> CC: stable@xxxxxxxxxxxxxxx # 5.16 Reviewed-by: Filipe Manana <fdmanana@xxxxxxxx> Signed-off-by: Qu Wenruo <wqu@xxxxxxxx> Signed-off-by: David Sterba <dsterba@xxxxxxxx> Signed-off-by: Greg Kroah-Hartman <gregkh@xxxxxxxxxxxxxxxxxxx> --- fs/btrfs/ioctl.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) --- a/fs/btrfs/ioctl.c +++ b/fs/btrfs/ioctl.c @@ -1020,6 +1020,13 @@ static struct extent_map *defrag_lookup_ return em; } +static u32 get_extent_max_capacity(const struct extent_map *em) +{ + if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) + return BTRFS_MAX_COMPRESSED; + return BTRFS_MAX_EXTENT_SIZE; +} + static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em, bool locked) { @@ -1036,6 +1043,12 @@ static bool defrag_check_next_extent(str goto out; if (test_bit(EXTENT_FLAG_PREALLOC, &next->flags)) goto out; + /* + * If the next extent is at its max capacity, defragging current extent + * makes no sense, as the total number of extents won't change. + */ + if (next->len >= get_extent_max_capacity(em)) + goto out; /* Physically adjacent and large enough */ if ((em->block_start + em->block_len == next->block_start) && (em->block_len > SZ_128K && next->block_len > SZ_128K)) @@ -1233,6 +1246,13 @@ static int defrag_collect_targets(struct if (range_len >= extent_thresh) goto next; + /* + * Skip extents already at its max capacity, this is mostly for + * compressed extents, which max cap is only 128K. + */ + if (em->len >= get_extent_max_capacity(em)) + goto next; + next_mergeable = defrag_check_next_extent(&inode->vfs_inode, em, locked); if (!next_mergeable) { Patches currently in stable-queue which might be from wqu@xxxxxxxx are queue-5.16/btrfs-defrag-don-t-try-to-merge-regular-extents-with-preallocated-extents.patch queue-5.16/btrfs-defrag-allow-defrag_one_cluster-to-skip-large-extent-which-is-not-a-target.patch queue-5.16/btrfs-autodefrag-only-scan-one-inode-once.patch queue-5.16/btrfs-reduce-extent-threshold-for-autodefrag.patch queue-5.16/btrfs-defrag-don-t-defrag-extents-which-are-already-at-max-capacity.patch queue-5.16/btrfs-defrag-remove-an-ambiguous-condition-for-rejection.patch