]> git.hungrycats.org Git - linux/commitdiff
btrfs: defrag: prevent inode truncated to zero from not being defragged again
authorFilipe Manana <fdmanana@suse.com>
Tue, 13 Oct 2026 16:04:00 +0000 (17:04 +0100)
committerDavid Sterba <dsterba@suse.com>
Fri, 30 Oct 2026 20:36:16 +0000 (21:36 +0100)
If we add an inode to autodefrag and the inode is truncated to an i_size
of zero before it's picked by autodefrag (run by the cleaner kthread),
we exit btrfs_run_defrag_inode() leaving the BTRFS_INODE_IN_DEFRAG flag
set in the inode, which prevents the inode from being auto defragged in
the future until it's evicted, loaded again and small writes happen to
it again.

Fix this by clearing BTRFS_INODE_IN_DEFRAG before we check if the current
offset is at or beyond the inode's i_size.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
fs/btrfs/defrag.c

index 7010d714cfe100d673a95bad364571e04136c098..cbc532b49c67d7eefea3439314096c6d379ee401 100644 (file)
@@ -242,13 +242,22 @@ again:
                goto cleanup;
        }
 
+       /*
+        * Clear the flag right away. On the first iteration (cur == 0) if the
+        * inode happened to have been truncated to 0 after it was added to
+        * autodefrag and before we were called, then we need to clear the flag,
+        * otherwise if writes are done to the inode we won't be able to add it
+        * to autodefrag again (unless the inode is evicted, loaded again, and
+        * small writes to it happen again).
+        */
+       clear_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags);
+
        if (cur >= i_size_read(&inode->vfs_inode)) {
                iput(&inode->vfs_inode);
                goto cleanup;
        }
 
        /* Do a chunk of defrag */
-       clear_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags);
        memset(&range, 0, sizeof(range));
        range.len = (u64)-1;
        range.start = cur;