]> git.hungrycats.org Git - linux/commitdiff
btrfs: reflink: never block on space reservations while the locked range has delalloc
authorZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Sun, 16 Aug 2026 07:31:14 +0000 (03:31 -0400)
committerZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Fri, 6 Nov 2026 06:05:42 +0000 (01:05 -0500)
The previous commit made clone_copy_inline_extent() take its transaction
handle before dirtying a folio in the locked destination range, closing a
flushoncommit deadlock for the single-extent inline clone.  Two gaps
remained, and one of them was captured live on a test box within hours:

1) A source file can have an inline extent at offset 0 followed by more
   items (e.g. created small, then extended by an append).  After the
   inline extent's data is copied into a folio - leaving delalloc inside
   the locked destination range - the clone loop continues to the next
   item and btrfs_replace_file_extents() starts more transactions under
   the lock.  The captured deadlock (drgn against a live hung kernel):

     dedupe:    btrfs_replace_file_extents() at [4096,40959], blocked in
                __reserve_bytes() on a metadata reservation ticket, while
                holding the dst range lock with extent_state [0,4095] =
                EXTENT_LOCKED | EXTENT_DELALLOC (dirtied by the inline
                copy of the source's first item)
     reclaim:   flush_space() -> btrfs_commit_current_transaction() ->
                btrfs_start_delalloc_flush() -> try_to_writeback_inodes_sb()
     flusher:   find_lock_delalloc_range() on that inode's [0,4095],
                blocked on the dedupe's extent lock

   Everything else on the filesystem then queues behind the starved
   ticket.  Note the blocking point here is a reservation ticket, not
   TRANS_STATE_COMMIT_START: ticket servicing commits the transaction,
   so with flushoncommit ANY blocking reservation made while the locked
   range has delalloc can deadlock.

   Fix: once the inline copy's inode update is committed, unlock the
   dirtied block before the clone continues.  Every byte still locked is
   clean, so the commit-time flusher never needs our lock, and i_rwsem
   (held for the whole remap) keeps writers away from the unlocked block
   until the clone finishes.

   Both callers, btrfs_extent_same_range() and btrfs_clone_files(),
   unlock the whole destination range when btrfs_clone() returns, that
   block included, so lock the block again at the end of btrfs_clone()
   to keep their unlock balanced.  Without that, a task that locked the
   block in between - writeback of the copied data (the commit-time
   flusher under flushoncommit, the periodic flusher, range writeback) or
   a read - would have its lock dropped by the caller's unlock while it
   still works on the range, and a third task could then lock the block
   at the same time.  The callers lock block-aligned ranges since commit
   e7f4c05a8307 ("btrfs: use aligned range for locking in reflink"), so
   the block lies inside their range.  Release the path first; then no
   transaction handle or tree lock is held, writeback of the copied block
   has no reason to lock the rest of our range, which has no delalloc,
   and btrfs_lock_extent() drops the part of a range it got before
   waiting for the rest, so a read covering more than the block does not
   keep it while waiting for us.

2) Delalloc may already exist inside the range when it is first locked:
   the pre-lock flush waits for ordered extents, but compressed writeback
   is asynchronous and may not have created them yet.  Check for
   EXTENT_DELALLOC after locking; if present, unlock, flush and retry.
   Both inodes' i_rwsem and i_mmap_lock are held, so nothing can add
   delalloc after a flush: delalloc that survives two flushes is a leaked
   EXTENT_DELALLOC bit that no retry can clear.  Warn with the root, inode
   and range, and fail with -EUCLEAN rather than -EAGAIN, which would have
   userspace (e.g. a dedupe agent) retry the same range forever.

Fixes: 05a5a7621ce6 ("Btrfs: implement full reflink support for inline extents")
Assisted-by: Claude:claude-fable-5
Assisted-by: Claude:claude-opus-5-5
fs/btrfs/reflink.c

index 7a2f5095682edd8d5fdf99853cdfe3d18aac8b07..976eaa8b51efcbba445dfd2df69a4a510c5dfdbb 100644 (file)
@@ -154,7 +154,8 @@ static int clone_copy_inline_extent(struct btrfs_inode *inode,
                                    const u64 size,
                                    const u8 comp_type,
                                    char *inline_data,
-                                   struct btrfs_trans_handle **trans_out)
+                                   struct btrfs_trans_handle **trans_out,
+                                   bool *copied_to_page)
 {
        struct btrfs_root *root = inode->root;
        struct btrfs_fs_info *fs_info = root->fs_info;
@@ -321,13 +322,17 @@ copy_to_page:
                btrfs_delalloc_release_space(inode, data_reserved,
                                             new_key->offset,
                                             fs_info->sectorsize, true);
-       } else if (new_key->offset + datal > i_size_read(&inode->vfs_inode)) {
-               /*
-                * Keep i_size ahead of a folio we dirtied beyond EOF, so that
-                * writeback sends it to disk instead of discarding it through
-                * folio invalidation (see commit b48c980b6a7e).
-                */
-               i_size_write(&inode->vfs_inode, new_key->offset + datal);
+       } else {
+               *copied_to_page = true;
+               if (new_key->offset + datal > i_size_read(&inode->vfs_inode)) {
+                       /*
+                        * Keep i_size ahead of a folio we dirtied beyond EOF,
+                        * so that writeback sends it to disk instead of
+                        * discarding it through folio invalidation (see commit
+                        * b48c980b6a7e).
+                        */
+                       i_size_write(&inode->vfs_inode, new_key->offset + datal);
+               }
        }
        btrfs_delalloc_release_extents(inode, fs_info->sectorsize);
 
@@ -361,6 +366,8 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
        const u64 len = olen_aligned;
        u64 last_dest_end = destoff;
        u64 prev_extent_end = off;
+       u64 unlocked_start = 0;
+       u64 unlocked_end = 0;
 
        ret = -ENOMEM;
        buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
@@ -387,6 +394,7 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
                u64 datao = 0, datal = 0;
                u8 comp;
                u64 drop_start;
+               bool copied_to_page = false;
 
                /* Note the key will change type as we walk through the tree */
                ret = btrfs_search_slot(NULL, src->root, &key, path, 0, 0);
@@ -535,7 +543,8 @@ process_slot:
 
                        ret = clone_copy_inline_extent(inode, path, &new_key,
                                                       drop_start, datal, size,
-                                                      comp, buf, &trans);
+                                                      comp, buf, &trans,
+                                                      &copied_to_page);
                        if (ret)
                                goto out;
                }
@@ -566,6 +575,21 @@ process_slot:
                                                destoff, olen, no_time_update);
                if (ret)
                        goto out;
+               /*
+                * The inline copy left delalloc in our caller's locked range,
+                * and the rest of the clone may wait for a commit or a
+                * reservation ticket whose flushoncommit writeback would block
+                * on our lock. Unlock the dirtied block so that only clean data
+                * stays locked; i_rwsem keeps writers out of it until the clone
+                * finishes.
+                */
+               if (copied_to_page) {
+                       unlocked_start = new_key.offset;
+                       unlocked_end = ALIGN(new_key.offset + datal,
+                                            fs_info->sectorsize) - 1;
+                       btrfs_unlock_extent(&inode->io_tree,
+                                           unlocked_start, unlocked_end, NULL);
+               }
                if (new_key.offset + datal >= destoff + len)
                        break;
 
@@ -617,6 +641,19 @@ process_slot:
        }
 
 out:
+       /*
+        * Our caller unlocks the whole destination range, so lock the block
+        * unlocked above again, or its unlock could drop a lock that writeback
+        * or a read took meanwhile. With the path released we hold no
+        * transaction or tree lock, and nobody holding this block waits for the
+        * rest of our range (it is clean, and btrfs_lock_extent() drops a
+        * partial range before it waits), so this cannot deadlock.
+        */
+       if (unlocked_end) {
+               btrfs_release_path(path);
+               btrfs_lock_extent(&inode->io_tree, unlocked_start,
+                                 unlocked_end, NULL);
+       }
        clear_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &inode->runtime_flags);
 
        return ret;
@@ -650,8 +687,34 @@ static int btrfs_extent_same_range(struct btrfs_inode *src, u64 loff, u64 len,
         * we are safe from concurrency with relocation of source extents
         * because we have already locked the inode's i_mmap_lock in exclusive
         * mode.
+        *
+        * The locked range must also have no delalloc: the clone reserves space
+        * and starts transactions under the lock, and with flushoncommit a
+        * commit (including one serving a reservation ticket) writes back dirty
+        * inodes and would block on our lock. Compressed writeback is
+        * asynchronous and can leave delalloc after the pre-lock flush, so wait
+        * and retry. Both inodes' i_rwsem and i_mmap_lock are held, so delalloc
+        * that survives two waits is a leaked EXTENT_DELALLOC bit: fail with
+        * -EUCLEAN, since -EAGAIN would have userspace retry forever.
         */
-       btrfs_lock_extent(&dst->io_tree, dst_loff, end, &cached_state);
+       for (int i = 0; ; i++) {
+               btrfs_lock_extent(&dst->io_tree, dst_loff, end, &cached_state);
+               if (!btrfs_test_range_bit_exists(&dst->io_tree, dst_loff, end,
+                                                EXTENT_DELALLOC))
+                       break;
+               btrfs_unlock_extent(&dst->io_tree, dst_loff, end, &cached_state);
+               if (i == 2) {
+                       btrfs_warn_rl(fs_info,
+"leaked delalloc in locked reflink destination: root %llu ino %llu range [%llu, %llu]",
+                                     btrfs_root_id(dst->root), btrfs_ino(dst),
+                                     dst_loff, end);
+                       WARN_ON_ONCE(1);
+                       return -EUCLEAN;
+               }
+               ret = btrfs_wait_ordered_range(dst, dst_loff, end + 1 - dst_loff);
+               if (ret)
+                       return ret;
+       }
        ret = btrfs_clone(src, dst, loff, len, ALIGN(len, bs), dst_loff, true);
        btrfs_unlock_extent(&dst->io_tree, dst_loff, end, &cached_state);
 
@@ -750,9 +813,29 @@ static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
         * we are safe from concurrency with relocation of source extents
         * because we have already locked the inode's i_mmap_lock in exclusive
         * mode.
+        *
+        * The locked range must also have no delalloc, see
+        * btrfs_extent_same_range().
         */
        end = round_up(destoff + len, bs) - 1;
-       btrfs_lock_extent(&inode->io_tree, destoff, end, &cached_state);
+       for (int i = 0; ; i++) {
+               btrfs_lock_extent(&inode->io_tree, destoff, end, &cached_state);
+               if (!btrfs_test_range_bit_exists(&inode->io_tree, destoff, end,
+                                                EXTENT_DELALLOC))
+                       break;
+               btrfs_unlock_extent(&inode->io_tree, destoff, end, &cached_state);
+               if (i == 2) {
+                       btrfs_warn_rl(fs_info,
+"leaked delalloc in locked reflink destination: root %llu ino %llu range [%llu, %llu]",
+                                     btrfs_root_id(inode->root), btrfs_ino(inode),
+                                     destoff, end);
+                       WARN_ON_ONCE(1);
+                       return -EUCLEAN;
+               }
+               ret = btrfs_wait_ordered_range(inode, destoff, end + 1 - destoff);
+               if (ret)
+                       return ret;
+       }
        ret = btrfs_clone(src, inode, off, olen, len, destoff, false);
        btrfs_unlock_extent(&inode->io_tree, destoff, end, &cached_state);
        if (ret < 0)