]> git.hungrycats.org Git - linux/commitdiff
btrfs: stripe_alloc: persist nocow runs across commits and remounts
authorZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Sat, 19 Sep 2026 17:17:41 +0000 (13:17 -0400)
committerZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Sun, 8 Nov 2026 23:37:58 +0000 (18:37 -0500)
A nodatacow inode's private stripe run used to close at every
transaction commit like all runs, so a slowly appended nocow file burned
a fresh stripe per commit -- and after a remount its partial stripe's
free tail was abandoned outright.  Neither cost buys anything: the run
machinery's commit-time closing exists for invariant I2, and a nocow
stripe holds only the owner's write-hole-waived data, so there is
nothing for I2 to protect.

Keep NOCOW-class runs open across commits: the commit-time retirement
and its drain predicate skip them (their extents insert without the
window-sequence deferral, which is fine -- the data is on disk when the
ordered extent finishes, and later same-stripe writes can tear only the
owner's own data).  They still close on forced quiescing (read-only,
removal, unmount) and now on the owning inode's eviction, so a cached
but idle inode cannot pin a claimed tail forever.

Across remounts, re-adopt instead: when a nocow allocation's hint
points into a partial stripe that the committed extent tree proves is
wholly owned by the allocating inode, claim exactly the stripe's free
tail (a new exact-range claim that verifies every byte is free before
removing; nothing else can consume free space inside a partially used
stripe, so verify-then-remove cannot race) and continue the run at the
old frontier.  Appends to a nocow file then pack sequentially through
commits, evictions and remounts alike.

The re-adoption lookup must not block.  It runs from
btrfs_alloc_from_inode_stripe_run(), i.e. inside find_free_extent(),
which holds space_info->groups_sem for read, and stripe_extents_owned_by()
does a full btrfs_search_slot() on the extent tree.  The reverse order is
longstanding upstream -- delayed ref processing holds extent tree locks
and then calls find_free_extent(), which takes groups_sem -- so waiting
here closes a cycle.  Both sides only take groups_sem for read, which is
not enough: it is an rw_semaphore and block group creation and removal
take it for write, so a writer queued between the two readers blocks the
second one.  The check cannot be hoisted above the lock, since it is a
question about the specific stripe the allocator has just settled on, but
it does not have to block: it is read-only and advisory, and every caller
already treats "not provably ours" as a reason to decline the
optimisation rather than as a fact about the extents.  So set path->nowait
for the groups_sem caller and let -EAGAIN fall into the existing error
paths; the cost on contention is a re-adoption that does not happen.
btrfs_stripe_nocow_writable() keeps the blocking search -- it runs from
the nocow check with no groups_sem held, and a spurious "not ours" there
would force COW on an extent that does not need it.

Whether a nocow extent can be written in place at all is decided by the
stripe_alloc_allow_rmw policy, and with nothing waived btrfs_stripe_nocow_
writable() forces COW for every such write.  A private run would then hold
only COWed extents and unwritten preallocation, and its survival would
only strand the whole stripes freed inside its range (an fsstress fill to
ENOSPC left hundreds of such runs in one group, holding 99% of its free
whole stripes).  So prealloc and nodatacow extents are steered into a
NOCOW run only when the policy lets that kind of extent be written in
place, and a NOCOW run outlives commits only when the policy allowed
in-place writes when it was opened.  The verdict is recorded in the run,
so the commit's close and settle predicates agree when the policy changes
underneath them.

full_stripe_len is a power of two only when the data stripe count is
(raid5 over 4 devices gives 192K), so stripes are rounded and tested for
alignment by division, in one helper each, never with round_down() or
IS_ALIGNED().

The cleaner does not delete an unused block group while a stripe run
still covers it (a persistent nocow run whose extents were all freed, or
the running transaction's metadata run): a run's unallocated remainder is
counted in none of used, reserved and pinned, and its tail would later be
added to the removed group's free space cache.  The group stays read-only
and is left for a later pass; its runs close by the next commit.

The nocow check passes an IOCB_NOWAIT write's nowait down to its extent
tree search; when that cannot answer, the extent is treated as not the
inode's own and the write falls back to COW, which a NOWAIT write refuses
with -EAGAIN.

Assisted-by: Claude:claude-fable-5
Assisted-by: Claude:claude-opus-5
Assisted-by: Claude:claude-opus-5-5
fs/btrfs/block-group.c
fs/btrfs/block-group.h
fs/btrfs/extent-tree.c
fs/btrfs/free-space-cache.c
fs/btrfs/free-space-cache.h
fs/btrfs/fs.h
fs/btrfs/inode.c
fs/btrfs/sysfs.c
fs/btrfs/tests/free-space-tests.c

index 02db80be2abd2700dda412095d549878e3005867..4a680d5496458ec6a648787efa40fadf06c0f951 100644 (file)
@@ -484,6 +484,12 @@ void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
  * runs left, or by btrfs_free_open_stripe_runs() at teardown.
  */
 
+static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
+                                   u64 root_id, u64 ino, u64 start, u64 len,
+                                   u64 *frontier, bool nowait);
+static bool stripe_range_run_free(struct btrfs_block_group *bg, u64 start,
+                                 u64 len);
+
 struct btrfs_open_stripe_run {
        struct list_head list;          /* bg->open_stripe_runs */
        struct btrfs_block_group *bg;
@@ -495,6 +501,7 @@ struct btrfs_open_stripe_run {
        u64 owner;                      /* LOG class: btrfs_ino of the owner */
        enum btrfs_stripe_run_class class;
        bool open;                      /* accepting allocations */
+       bool persistent;                /* survives commits; see close_block_group_stripe_runs() */
        /*
         * Relocation's run: kept after it closes and drains, until relocation
         * releases it (btrfs_release_stripe_reloc_runs()).  See
@@ -523,6 +530,19 @@ static bool open_stripe_run_drained(const struct btrfs_open_stripe_run *run)
        return !run->open && run->inflight_bytes == 0;
 }
 
+/*
+ * Round to a full stripe.
+ *
+ * full_stripe_len is nr_data_stripes * stripe_len, which is not a power of
+ * two for most raid56 geometries (3 data stripes: 192K), so the mask-based
+ * round_down(), round_up() and IS_ALIGNED() must not be used.  Divide
+ * instead.
+ */
+static u64 stripe_round_down(u64 val, u64 fsl)
+{
+       return div64_u64(val, fsl) * fsl;
+}
+
 /*
  * Band for a run with @remaining bytes of unallocated space: the power-of-two
  * bucket of its remaining sectors (band k == remaining in [2^k, 2^(k+1))
@@ -601,6 +621,27 @@ static void run_live_set(struct btrfs_open_stripe_run *run, u64 start, u64 len,
                bitmap_clear(run->live, first, nr);
 }
 
+/*
+ * A run is dead when every byte it handed out has been freed again
+ * (btrfs_stripe_run_note_free() clears the live bits).  It then protects no
+ * data, and the whole free stripes inside its range stay unclaimable
+ * (btrfs_stripe_run_range_usable()) until it is closed.
+ *
+ * Requires inflight_bytes == 0, since an in-flight write must keep its
+ * stripes, and a valid live map (live_nbits == 0 means liveness is
+ * unknown).  Caller holds bg->stripe_run_lock.
+ */
+static bool open_stripe_run_dead(const struct btrfs_open_stripe_run *run)
+{
+       if (run->inflight_bytes)
+               return false;
+       if (run->offset <= run->start)
+               return false;
+       if (!run->live || !run->live_nbits)
+               return false;
+       return bitmap_empty(run->live, run->live_nbits);
+}
+
 /* Free a drained run.  Caller holds bg->stripe_run_lock. */
 static void free_open_stripe_run(struct btrfs_block_group *bg,
                                 struct btrfs_open_stripe_run *run)
@@ -891,6 +932,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
        }
        new_run->bg = bg;
        new_run->class = class;
+       new_run->persistent = false;
        new_run->retained = class == BTRFS_STRIPE_RUN_RELOC;
        if (new_run->retained)
                atomic64_inc(&fs_info->stripe_run_stats.reloc_run_retained);
@@ -947,13 +989,15 @@ out:
  * Returns 0 and sets *ret_offset, -ENOSPC if no fully-free stripe run in
  * this block group can satisfy the allocation, or -ENOMEM.
  */
-int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
+                                     struct btrfs_inode *inode,
                                      enum btrfs_stripe_run_class class,
-                                     u64 num_bytes, u64 *ret_offset,
-                                     u64 *available)
+                                     u64 num_bytes, u64 readopt_hint,
+                                     u64 *ret_offset, u64 *available)
 {
        struct btrfs_fs_info *fs_info = bg->fs_info;
        const u64 fsl = bg->full_stripe_len;
+       const u64 ino = btrfs_ino(inode);
        struct btrfs_open_stripe_run *new_run;
        struct btrfs_open_stripe_run *run;
        unsigned long flags;
@@ -996,6 +1040,49 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
        if (!new_run)
                return -ENOMEM;
 
+       /*
+        * Re-adoption (nocow only): after a remount (or eviction) the
+        * inode's last partial stripe has no run, and a fresh claim would
+        * abandon its free tail forever.  When the allocation hint points
+        * into a stripe wholly owned by this inode, adopt the tail as the
+        * private run instead: every byte below the frontier is provably
+        * the inode's own committed data, and nothing else can consume a
+        * partial stripe's free space (see btrfs_claim_stripe_tail()).
+        */
+       if (class == BTRFS_STRIPE_RUN_NOCOW && readopt_hint &&
+           readopt_hint >= bg->start &&
+           readopt_hint < bg->start + bg->length) {
+               u64 stripe = bg->start +
+                            stripe_round_down(readopt_hint - bg->start, fsl);
+               u64 frontier = 0;
+               u64 tlen;
+
+               /*
+                * Under space_info->groups_sem (we are inside
+                * find_free_extent()), so the lookup must not block -- see
+                * stripe_extents_owned_by().  A trylock failure just declines
+                * the re-adoption and falls through to a fresh claim below,
+                * costing this stripe's free tail, not correctness.
+                */
+               if (stripe_extents_owned_by(fs_info, btrfs_root_id(inode->root),
+                                           ino, stripe, fsl, &frontier, true) &&
+                   frontier > stripe && frontier < stripe + fsl &&
+                   num_bytes <= stripe + fsl - frontier) {
+                       tlen = stripe + fsl - frontier;
+                       /*
+                        * btrfs_stripe_run_range_usable() is for whole-stripe
+                        * claims (it rejects anything shorter than a full
+                        * stripe); a tail needs only the run-overlap check.
+                        */
+                       if (stripe_range_run_free(bg, frontier, tlen) &&
+                           !btrfs_claim_stripe_tail(bg, frontier, tlen)) {
+                               start = frontier;
+                               len = tlen;
+                               goto install;
+                       }
+               }
+       }
+
        ret = btrfs_claim_free_stripe_run(bg,
                        div64_u64(num_bytes + fsl - 1, fsl) * fsl,
                        &start, &len);
@@ -1009,6 +1096,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
                goto out;
        }
 
+install:
        /* Sleeps, so it has to happen before the locks below. */
        new_run->live = alloc_run_live_map(bg, len, &new_run->live_nbits);
        new_run->written = new_run->live_nbits ?
@@ -1032,6 +1120,17 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
        }
        new_run->bg = bg;
        new_run->class = class;
+       /*
+        * A NOCOW run outlives commits only while the stripe_alloc_allow_rmw
+        * policy lets nocow data be written in place at all (see
+        * close_block_group_stripe_runs()).  Decided once, here: the commit
+        * path's close and settle predicates must agree with each other for
+        * the run's whole life, whatever the policy does meanwhile.
+        */
+       new_run->persistent = class == BTRFS_STRIPE_RUN_NOCOW &&
+                             (btrfs_stripe_allow_rmw(fs_info) &
+                              (BTRFS_STRIPE_RMW_NODATACOW |
+                               BTRFS_STRIPE_RMW_PREALLOC));
        if (class == BTRFS_STRIPE_RUN_NOCOW)
                atomic64_inc(&fs_info->stripe_run_stats.nocow_run_opened);
        new_run->owner = ino;
@@ -1061,6 +1160,50 @@ out:
        return ret;
 }
 
+/*
+ * An extent inside a stripe run's range has been freed: its sectors no longer
+ * hold data anyone intends to write, so clear their live bits.
+ *
+ * This is what makes a run detectably dead (open_stripe_run_dead()), so the
+ * next commit can close it and release its stripes.  Without it a nodatacow
+ * or preallocating inode's private run hoards its stripes until the inode is
+ * evicted.  A partial write to one of those stripes can also pad over the
+ * freed sectors now instead of falling back to a read-modify-write.
+ *
+ * Takes only bg->stripe_run_lock, and the callers hold no free space lock
+ * yet, so no nesting rule applies.  The range is clamped to the run: a free
+ * may span a run's boundary, and running off the live map would retire it.
+ */
+void btrfs_stripe_run_note_free(struct btrfs_block_group *bg, u64 bytenr,
+                               u64 size)
+{
+       struct btrfs_open_stripe_run *run;
+       unsigned long flags;
+
+       if (!btrfs_is_stripe_alloc_bg(bg))
+               return;
+       spin_lock_irqsave(&bg->stripe_run_lock, flags);
+       list_for_each_entry(run, &bg->open_stripe_runs, list) {
+               u64 start = max(bytenr, run->start);
+               u64 end = min(bytenr + size, run->offset);
+
+               /*
+                * Only the persistent runs, which are the only ones that can
+                * outlive their own data.  Every other class is closed and
+                * freed by the commit it belongs to, so its live map is never
+                * consulted after its bytes could have been freed, and
+                * clearing bits there would change padding decisions for no
+                * gain here.
+                */
+               if (!run->persistent)
+                       continue;
+               if (end <= start)
+                       continue;
+               run_live_set(run, start, end - start, false);
+       }
+       spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+}
+
 /*
  * A run's range must not be claimed again while the run object exists, even
  * if every byte of one of its stripes is back in the free space cache
@@ -1198,12 +1341,20 @@ int btrfs_parse_stripe_rmw(const char *value, size_t len, u32 *mask)
  * @ino in @root_id -- exactly one reference, a plain data ref, count 1?
  * Any metadata block, shared reference, or foreign owner fails.  Caller
  * limits the range to full stripes; uncommitted allocations need not be
- * visible because nothing can allocate into a partially used stripe (the
- * fully-free claim rule), so a foreign extent can only appear here after
- * the whole stripe frees and commits -- which the extent tree shows.
+ * visible because nothing can allocate into a partially used stripe, so a
+ * foreign extent can only appear after the whole stripe frees and commits.
+ *
+ * Callers holding space_info->groups_sem (anything reached from
+ * find_free_extent()) must pass @nowait: delayed ref processing takes
+ * extent tree locks and then groups_sem, so blocking on an extent tree lock
+ * here can deadlock behind a queued groups_sem writer.  Callers that must
+ * not block for other reasons pass it too.  With @nowait a contended lock
+ * fails the search and the answer is false, which every caller treats only
+ * as a reason to skip an optimisation.
  */
 static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
-                                   u64 root_id, u64 ino, u64 start, u64 len)
+                                   u64 root_id, u64 ino, u64 start, u64 len,
+                                   u64 *frontier, bool nowait)
 {
        struct btrfs_root *extent_root = btrfs_extent_root(fs_info, start);
        struct btrfs_path *path;
@@ -1216,6 +1367,11 @@ static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
        path = btrfs_alloc_path();
        if (!path)
                return false;
+       /*
+        * Read-only search, so nowait is allowed, and every step of the walk
+        * below honours it (btrfs_next_leaf() runs with time_seq 0).
+        */
+       path->nowait = nowait;
 
        key.objectid = start;
        key.type = BTRFS_EXTENT_ITEM_KEY;
@@ -1314,6 +1470,8 @@ static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
                        ret = false;
                        goto out;
                }
+               if (frontier && key.objectid + key.offset > *frontier)
+                       *frontier = min(key.objectid + key.offset, start + len);
                path->slots[0]++;
        }
 out:
@@ -1333,7 +1491,7 @@ out:
  * overwrite passes.
  */
 bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
-                                u64 num_bytes, u32 which)
+                                u64 num_bytes, u32 which, bool nowait)
 {
        struct btrfs_fs_info *fs_info = inode->root->fs_info;
        struct btrfs_block_group *bg;
@@ -1356,7 +1514,7 @@ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
        }
 
        fsl = bg->full_stripe_len;
-       cur = bg->start + round_down(start - bg->start, fsl);
+       cur = bg->start + stripe_round_down(start - bg->start, fsl);
        end = start + num_bytes;
        while (cur < end) {
                struct btrfs_open_stripe_run *run;
@@ -1376,8 +1534,17 @@ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
                }
                spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
 
+               /*
+                * No groups_sem here (this runs from the nocow check, not
+                * from the allocator), so the reliable blocking search is
+                * both safe and wanted: a spurious "not ours" would force
+                * COW on an extent that does not need it.  A NOWAIT write
+                * must not block, so it gets the nonblocking search, and
+                * COW (which it cannot do either) when that cannot answer.
+                */
                if (verdict == 0 &&
-                   !stripe_extents_owned_by(fs_info, root_id, ino, cur, fsl))
+                   !stripe_extents_owned_by(fs_info, root_id, ino, cur, fsl,
+                                            NULL, nowait))
                        verdict = -1;
                if (verdict < 0) {
                        ret = false;
@@ -1564,6 +1731,122 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
 }
 
 
+/*
+ * Disk end of @inode's last regular file extent, or 0: the re-adoption
+ * candidate for a nocow allocation arriving with no allocation hint --
+ * after a remount or eviction the extent maps are gone, so the normal
+ * em-based hint is empty exactly when re-adoption matters most.
+ */
+u64 btrfs_nocow_alloc_hint(struct btrfs_inode *inode)
+{
+       struct btrfs_root *root = inode->root;
+       struct btrfs_path *path;
+       struct btrfs_key key;
+       struct btrfs_file_extent_item *fi;
+       u64 hint = 0;
+       int ret;
+
+       path = btrfs_alloc_path();
+       if (!path)
+               return 0;
+       key.objectid = btrfs_ino(inode);
+       key.type = BTRFS_EXTENT_DATA_KEY;
+       key.offset = (u64)-1;
+       ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
+       if (ret < 0)
+               goto out;
+       ret = btrfs_previous_item(root, path, key.objectid,
+                                 BTRFS_EXTENT_DATA_KEY);
+       if (ret)
+               goto out;
+       btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
+       fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
+                           struct btrfs_file_extent_item);
+       if (btrfs_file_extent_type(path->nodes[0], fi) ==
+                                               BTRFS_FILE_EXTENT_INLINE)
+               goto out;
+       if (btrfs_file_extent_disk_bytenr(path->nodes[0], fi))
+               hint = btrfs_file_extent_disk_bytenr(path->nodes[0], fi) +
+                      btrfs_file_extent_disk_num_bytes(path->nodes[0], fi);
+out:
+       btrfs_free_path(path);
+       return hint;
+}
+
+/* Does no run object (open or draining) overlap [start, start + len)? */
+static bool stripe_range_run_free(struct btrfs_block_group *bg, u64 start,
+                                 u64 len)
+{
+       struct btrfs_open_stripe_run *run;
+       unsigned long flags;
+       bool ret = true;
+
+       spin_lock_irqsave(&bg->stripe_run_lock, flags);
+       list_for_each_entry(run, &bg->open_stripe_runs, list) {
+               if (run->start < start + len && run->end > start) {
+                       ret = false;
+                       break;
+               }
+       }
+       spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+       return ret;
+}
+
+/* Does any stripe run, open or draining, still cover part of @bg? */
+bool btrfs_block_group_has_stripe_runs(struct btrfs_block_group *bg)
+{
+       unsigned long flags;
+       bool ret;
+
+       spin_lock_irqsave(&bg->stripe_run_lock, flags);
+       ret = !list_empty(&bg->open_stripe_runs);
+       spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+       return ret;
+}
+
+/*
+ * Close every private stripe run owned by @inode, of any class: called at
+ * inode eviction so a persistent nocow run's claimed tail does not stay
+ * unusable for the rest of the mount (log-class runs would close at the
+ * next commit anyway; closing them here is merely tidy).  The runs' tails
+ * return to the free space cache.
+ */
+void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
+{
+       struct btrfs_fs_info *fs_info = inode->root->fs_info;
+       const u64 ino = btrfs_ino(inode);
+       struct btrfs_block_group *bg;
+
+       if (list_empty_careful(&fs_info->open_stripe_bgs))
+               return;
+restart:
+       spin_lock(&fs_info->open_stripe_lock);
+       list_for_each_entry(bg, &fs_info->open_stripe_bgs,
+                           open_stripe_bg_list) {
+               struct btrfs_open_stripe_run *run;
+               unsigned long flags;
+               u64 tail_start = 0;
+               u64 tail_len = 0;
+
+               spin_lock_irqsave(&bg->stripe_run_lock, flags);
+               list_for_each_entry(run, &bg->open_stripe_runs, list) {
+                       if (!run->open || run->owner != ino)
+                               continue;
+                       tail_len = close_open_stripe_run(bg, run, &tail_start);
+                       break;
+               }
+               spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+               if (tail_len) {
+                       btrfs_get_block_group(bg);
+                       spin_unlock(&fs_info->open_stripe_lock);
+                       btrfs_add_free_space(bg, tail_start, tail_len);
+                       btrfs_put_block_group(bg);
+                       goto restart;
+               }
+       }
+       spin_unlock(&fs_info->open_stripe_lock);
+}
+
 /*
  * Can stripe-exclusive allocation be enabled on this filesystem?  Called for
  * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
@@ -2021,6 +2304,7 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
 static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
                                          u64 seq)
 {
+       struct btrfs_fs_info *fs_info = bg->fs_info;
        struct btrfs_open_stripe_run *run;
        unsigned long flags;
        int class, band;
@@ -2033,6 +2317,20 @@ restart:
 
                if (!run->open || run->open_seq >= seq)
                        continue;
+               /*
+                * A persistent NOCOW run holds only its inode's
+                * write-hole-waived data, so commit retirement protects
+                * nothing there, and closing it each commit would waste a
+                * stripe per commit on a slowly appended file.  It closes at
+                * forced quiescing (seq == U64_MAX), at the inode's eviction,
+                * or once it is dead.
+                */
+               if (run->persistent && seq != U64_MAX) {
+                       /* A dead run protects nothing, only strands stripes. */
+                       if (!open_stripe_run_dead(run))
+                               continue;
+                       atomic64_inc(&fs_info->stripe_run_stats.nocow_run_dead_closed);
+               }
                for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
                        for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++)
                                if (bg->open_stripe[class][band] == run)
@@ -2071,6 +2369,9 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
 
        spin_lock_irqsave(&bg->stripe_run_lock, flags);
        list_for_each_entry(run, &bg->open_stripe_runs, list) {
+               /* Persistent nocow runs are not part of any commit window. */
+               if (run->persistent && seq != U64_MAX)
+                       continue;
                /* Nor are retained relocation runs, once nothing is in flight. */
                if (run->retained && open_stripe_run_drained(run) &&
                    seq != U64_MAX)
@@ -3786,6 +4087,21 @@ void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
                        goto next;
                }
 
+               /*
+                * A stripe run can still own space here that is neither used
+                * nor reserved: the free tail of a persistent nocow run, or
+                * the running transaction's metadata run.  Its close would
+                * return that space to a removed group.  The group goes back
+                * to read-write for the retry: a persistent run closes at the
+                * next commit once it is dead, a metadata run in
+                * btrfs_retire_meta_stripes(); try again after that commit.
+                */
+               if (btrfs_block_group_has_stripe_runs(block_group)) {
+                       btrfs_dec_block_group_ro(block_group);
+                       btrfs_link_bg_list(block_group, &retry_list);
+                       goto next;
+               }
+
                ret = btrfs_zone_finish(block_group);
                if (ret < 0) {
                        btrfs_dec_block_group_ro(block_group);
index a079afa3da52af8e4402389dda838f5aa4111b8a..a695a21795fd0c3f73b22192f9cf486c4dd76c11 100644 (file)
@@ -486,10 +486,14 @@ void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg);
 int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
                                 enum btrfs_stripe_run_class class,
                                 u64 *ret_offset, u64 *available);
-int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
+                                     struct btrfs_inode *inode,
                                      enum btrfs_stripe_run_class class,
-                                     u64 num_bytes, u64 *ret_offset,
-                                     u64 *available);
+                                     u64 num_bytes, u64 readopt_hint,
+                                     u64 *ret_offset, u64 *available);
+bool btrfs_block_group_has_stripe_runs(struct btrfs_block_group *bg);
+void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode);
+u64 btrfs_nocow_alloc_hint(struct btrfs_inode *inode);
 void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
                                  u64 num_bytes);
 void btrfs_open_stripe_write_abandoned(struct btrfs_block_group *bg, u64 start,
@@ -514,6 +518,8 @@ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
 u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
                                      u64 nstripes);
 bool btrfs_stripe_run_strands(struct btrfs_block_group *bg, u64 stripe);
+void btrfs_stripe_run_note_free(struct btrfs_block_group *bg, u64 bytenr,
+                               u64 size);
 bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
                                   u64 run_start, u64 *run_len);
 /*
@@ -541,7 +547,7 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
                               unsigned long *unwritten,
                               struct btrfs_stripe_pad_info *info);
 bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
-                                u64 num_bytes, u32 which);
+                                u64 num_bytes, u32 which, bool nowait);
 int btrfs_parse_stripe_rmw(const char *value, size_t len, u32 *mask);
 int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
 int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
index cccc0fcdf014d75911ab7c063450d5ebb8deae42..a4995b119407c756f7843ecdc9a2ce80b9ff56b5 100644 (file)
@@ -4331,8 +4331,9 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
                struct btrfs_inode *steer_inode = ffe_ctl->steer_inode;
 
                ret = btrfs_alloc_from_inode_stripe_run(block_group,
-                               btrfs_ino(steer_inode), ffe_ctl->steer_class,
-                               ffe_ctl->num_bytes, &offset, &available);
+                               steer_inode, ffe_ctl->steer_class,
+                               num_bytes, ffe_ctl->hint_byte,
+                               &offset, &available);
                if (ret == -ENOMEM)
                        return ret;
                if (!ret) {
@@ -5101,17 +5102,22 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
        enum btrfs_stripe_run_class steer_class = BTRFS_STRIPE_RUN_COW;
 
        /*
-        * Steer this inode's data into a private per-inode stripe run,
-        * seeded with the run's location as the search hint.  NOCOW class
-        * for preallocated extents and nodatacow files' extents (candidates
-        * for future write-in-place, which must never share a stripe with
-        * any other file's data); LOG class for log-active inodes (see
-        * BTRFS_INODE_LOG_ALLOC).  Purely placement: any allocation that
-        * cannot be served from a private run falls back to the shared runs.
+        * Steer this inode's data into a private stripe run, using its last
+        * private allocation as the search hint.  Placement only: what a
+        * private run cannot serve falls back to the shared runs.
+        *  - NOCOW class for preallocated and nodatacow extents, but only while
+        *    stripe_alloc_allow_rmw lets them be written in place; otherwise
+        *    they are COWed anyway, and a private run, which outlives commits,
+        *    would only strand whole stripes.
+        *  - LOG class for log-active inodes (BTRFS_INODE_LOG_ALLOC).
         */
        if (inode && is_data && !for_data_reloc &&
            btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
-               if (for_prealloc || (inode->flags & BTRFS_INODE_NODATACOW)) {
+               const u32 rmw = btrfs_stripe_allow_rmw(fs_info);
+
+               if ((for_prealloc && (rmw & BTRFS_STRIPE_RMW_PREALLOC)) ||
+                   (!for_prealloc && (inode->flags & BTRFS_INODE_NODATACOW) &&
+                    (rmw & BTRFS_STRIPE_RMW_NODATACOW))) {
                        steer_inode = inode;
                        steer_class = BTRFS_STRIPE_RUN_NOCOW;
                } else if (test_bit(BTRFS_INODE_LOG_ALLOC,
@@ -5124,6 +5130,9 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
 
                        if (run_hint)
                                hint_byte = run_hint;
+                       else if (steer_class == BTRFS_STRIPE_RUN_NOCOW &&
+                                !hint_byte)
+                               hint_byte = btrfs_nocow_alloc_hint(inode);
                }
        }
 
index 225d161277201939d089134b0c2e5d9087ce5d60..6d803fb87af28240531cc9cc8bbf400a1c684dab 100644 (file)
@@ -3006,6 +3006,7 @@ int btrfs_add_free_space(struct btrfs_block_group *block_group,
 
        stripe_unusable_mark_dirty(block_group);
        stripe_unusable_account_add(block_group, bytenr, size);
+       btrfs_stripe_run_note_free(block_group, bytenr, size);
        return __btrfs_add_free_space(block_group, bytenr, size, trim_state);
 }
 
@@ -3752,6 +3753,90 @@ static bool find_stripe_run_in_bitmap(struct btrfs_free_space_ctl *ctl,
        return false;
 }
 
+static bool claim_stripe_run_pieces(struct btrfs_block_group *block_group,
+                                   u64 start, u64 len,
+                                   struct btrfs_free_space *spare);
+
+/*
+ * Claim exactly [start, start + len) from the free space cache, failing
+ * (-ENOSPC) unless every byte of it is currently free.  Used to re-adopt
+ * the free tail of a partial stripe wholly owned by one nodatacow inode.
+ * The count and the removal are one tree_lock section, so of two racing
+ * claims of the same tail one wins and the other gets -ENOSPC, and a range
+ * that discard has taken out of the cache for the moment is not claimed.
+ */
+int btrfs_claim_stripe_tail(struct btrfs_block_group *block_group,
+                           u64 start, u64 len)
+{
+       struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
+       const u64 end = start + len;
+       struct btrfs_free_space *spare;
+       u64 found = 0;
+       struct rb_node *n;
+       int ret = 0;
+
+       /* For the one extent entry the tail may lie strictly inside. */
+       spare = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
+       if (!spare)
+               return -ENOMEM;
+
+       spin_lock(&ctl->tree_lock);
+       for (n = rb_first(&ctl->free_space_offset); n; n = rb_next(n)) {
+               struct btrfs_free_space *e =
+                       rb_entry(n, struct btrfs_free_space, offset_index);
+               u64 e_start = e->offset;
+               u64 e_end;
+
+               if (e->bitmap) {
+                       const u64 unit = block_group->fs_info->sectorsize;
+                       unsigned long b = 0;
+
+                       e_end = e_start + (u64)BITS_PER_BITMAP * unit;
+                       if (e_end <= start || e_start >= end)
+                               continue;
+                       while (b < BITS_PER_BITMAP) {
+                               unsigned long z;
+                               u64 f_start, f_end;
+
+                               b = find_next_bit(e->bitmap, BITS_PER_BITMAP, b);
+                               if (b >= BITS_PER_BITMAP)
+                                       break;
+                               z = find_next_zero_bit(e->bitmap,
+                                                      BITS_PER_BITMAP, b);
+                               f_start = max(start, e_start + (u64)b * unit);
+                               f_end = min(end, e_start + (u64)z * unit);
+                               if (f_end > f_start)
+                                       found += f_end - f_start;
+                               b = z;
+                       }
+                       continue;
+               }
+               e_end = e_start + e->bytes;
+               if (e_end <= start || e_start >= end)
+                       continue;
+               found += min(end, e_end) - max(start, e_start);
+       }
+       if (found == len) {
+               /* As btrfs_remove_free_space() accounts a removal. */
+               if (btrfs_is_stripe_alloc_bg(block_group))
+                       stripe_claimable_mod(block_group,
+                               -(s64)stripe_touched_bytes(block_group, start,
+                                                          len));
+               if (claim_stripe_run_pieces(block_group, start, len, spare))
+                       spare = NULL;
+               btrfs_discard_update_discardable(block_group);
+       } else {
+               ret = -ENOSPC;
+       }
+       spin_unlock(&ctl->tree_lock);
+       if (spare)
+               kmem_cache_free(btrfs_free_space_cachep, spare);
+       /* The tail was trapped space: recount it at the next scan. */
+       if (!ret)
+               stripe_unusable_mark_dirty(block_group);
+       return ret;
+}
+
 /*
  * Find a fully free, stripe-aligned run of up to @want_bytes.
  *
index b37d324d28e7a921c095b3e2ee11143518c9cd14..ea6c5224bdc488807ac7c20ac616154ee5d65d4e 100644 (file)
@@ -138,6 +138,8 @@ bool btrfs_is_free_space_trimmed(struct btrfs_block_group *block_group);
 u64 btrfs_find_space_for_alloc(struct btrfs_block_group *block_group,
                               u64 offset, u64 bytes, u64 empty_size,
                               u64 *max_extent_size);
+int btrfs_claim_stripe_tail(struct btrfs_block_group *block_group,
+                           u64 start, u64 len);
 int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
                                u64 want_bytes, u64 *start, u64 *len);
 void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *block_group);
index 3b0461199a3d475c57b2dfaa05a0dd79fa082f99..d419b85914953d09391b9b7fdd1d3c813d35740a 100644 (file)
@@ -903,6 +903,8 @@ struct btrfs_fs_info {
                atomic64_t strand_scan_bytes;
                /* rescans requested by a freed run to credit its stripes back */
                atomic64_t strand_rescan_marks;
+               /* persistent nocow runs closed at commit for being dead */
+               atomic64_t nocow_run_dead_closed;
                /* Relocation runs retained past their drain, and released. */
                atomic64_t reloc_run_retained;
                atomic64_t reloc_run_released;
index bfae983bd42c5751734e9c3265af33d53d8e5fe3..0195c2ba3bc488bbfd5bbcb501e86bab9bbad4ca 100644 (file)
@@ -1907,7 +1907,8 @@ static int can_nocow_file_extent(struct btrfs_path *path,
                                         args->file_extent.num_bytes,
                                         extent_type == BTRFS_FILE_EXTENT_PREALLOC ?
                                                BTRFS_STRIPE_RMW_PREALLOC :
-                                               BTRFS_STRIPE_RMW_NODATACOW))
+                                               BTRFS_STRIPE_RMW_NODATACOW,
+                                        nowait))
                goto out;
 
        /*
@@ -5778,6 +5779,7 @@ void btrfs_evict_inode(struct inode *inode)
                goto clear_inode;
 
        fs_info = inode_to_fs_info(inode);
+       btrfs_close_inode_stripe_runs(BTRFS_I(inode));
        evict_inode_truncate_pages(inode);
 
        if (inode->i_nlink &&
index 2097a0047151a7303945e1a196b3663b6457dc2f..4855f10c4c9997f6e8f4eb703b4a96696e3776ac 100644 (file)
@@ -1292,11 +1292,13 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
                "nocow_run_opened %lld\n"
                "claim_refused_live_run %lld\n"
                "strand_scan_bytes %lld\n"
-               "strand_rescan_marks %lld\n",
+               "strand_rescan_marks %lld\n"
+               "nocow_run_dead_closed %lld\n",
                atomic64_read(&fs_info->stripe_run_stats.nocow_run_opened),
                atomic64_read(&fs_info->stripe_run_stats.claim_refused_live_run),
                atomic64_read(&fs_info->stripe_run_stats.strand_scan_bytes),
-               atomic64_read(&fs_info->stripe_run_stats.strand_rescan_marks));
+               atomic64_read(&fs_info->stripe_run_stats.strand_rescan_marks),
+               atomic64_read(&fs_info->stripe_run_stats.nocow_run_dead_closed));
 }
 BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
 
index 4022cadcd9e4c750a8541c27a74cf67d76e2ee5b..5da244e148321a88cc7d0038ee90f637f699e517 100644 (file)
@@ -1193,6 +1193,35 @@ static int test_stripe_claim(struct btrfs_block_group *cache, u32 sectorsize)
                goto out;
        }
 
+       /* The same split as a stripe tail, claimed twice: one claim wins. */
+       ret = test_add_free_space_entry(cache, fsl + sectorsize,
+                                       fsl / 2 - sectorsize, 1);
+       if (ret) {
+               test_err("error adding bitmap entry %d", ret);
+               goto out;
+       }
+       ret = test_add_free_space_entry(cache, fsl + fsl / 2, fsl / 2, 0);
+       if (ret) {
+               test_err("error adding extent entry %d", ret);
+               goto out;
+       }
+       ret = btrfs_claim_stripe_tail(cache, fsl + sectorsize, fsl - sectorsize);
+       if (ret) {
+               test_err("tail claim failed %d", ret);
+               goto out;
+       }
+       ret = btrfs_claim_stripe_tail(cache, fsl + sectorsize, fsl - sectorsize);
+       if (ret != -ENOSPC) {
+               test_err("second tail claim returned %d", ret);
+               ret = -EINVAL;
+               goto out;
+       }
+       ret = check_cache_empty(cache);
+       if (ret) {
+               test_err("tail claim left free space behind");
+               goto out;
+       }
+
        /* Non-power-of-two full stripe length (e.g. 3 data stripes). */
        cache->full_stripe_len = fsl_np2;
        ret = btrfs_add_free_space(cache, sectorsize, 4 * fsl_np2);