]> git.hungrycats.org Git - linux/commitdiff
btrfs: stripe_alloc: pessimistic data reservation margin
authorZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Sat, 19 Sep 2026 17:17:46 +0000 (13:17 -0400)
committerZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Sun, 8 Nov 2026 23:37:45 +0000 (18:37 -0500)
A byte-counted data reservation holds no collateral against the stripe
claim rule.  Between admission at write() time and the allocation at
writeback, the trapped-space picture keeps moving: commits close open
stripe runs and trap their sub-stripe tails, and free space returning
mid-transaction (unpinned deletions, same-transaction frees, drained
run tails, freed reservations) lands in the free space cache as
fragments the claim rule can never hand out but that no counter yet
reflects.  The counters were honest at every instant for NEW
admissions while OLD admissions were left holding air; delalloc
writeback gets no second chance, so the pages were dropped.  Measured
at the fill edge: ~19 MiB of orphaned bytes_may_use with accounting
and allocator in perfect agreement, and in a later round the admitted
may_use+margin exactly equaled the phantom mid-transaction fragments.

Be pessimistic at reservation time and optimistic at allocation time,
the same shape metadata reservations already use:

- bytes_stripe_margin: one full stripe width (fs_info->
  stripe_margin_unit, the widest raid56 data full stripe) per
  outstanding delalloc extent, charged and released inside
  btrfs_mod_outstanding_extents() so it stays exact across delalloc
  merges and splits -- including async compression, where the io-tree
  split hook grows the margin to one stripe per compressed piece,
  matching the true worst case.  Counted in btrfs_space_info_used()
  so it holds back admissions.  The margin exists only for in-flight
  dirty data; steady-state capacity and statfs are untouched.

- Admission probes len + margin through the ticketed FLUSH_DATA path
  (then immediately re-releases the probe, which the delalloc hooks
  re-charge), so a writer that cannot be covered waits for the
  flusher -- commits convert pinned deletions into claimable whole
  stripes -- and receives an honest ENOSPC at write(2) if flushing
  cannot produce cover.

- Every btrfs_add_free_space() into an armed group counts the added
  range's sub-stripe head and tail fragments as trapped immediately;
  whole stripes fully inside the range are trivially fully free and
  stay claimable.  A bounded overcount in the safe direction, never
  an undercount; the commit rescan remains the authority and
  reconciles (and now grants tickets when it lowers the counter,
  since admission waiters may be blocked on exactly that headroom).
  This closes the retire-to-rescan window the previous patch left
  open, and closes it in the one place every returning range passes
  through: counting at the individual close/drain call sites instead
  misses paths (the drain returns have two) and gets the arithmetic
  wrong (round_up() on the non-power-of-two 448K stripe width).

- When a margin-backed data allocation must split across free space
  fragments, every non-final piece is trimmed to whole stripes of the
  group it lands in, so at most one piece per delalloc extent can strand
  a tail -- the margin pre-paid exactly one.  The trim is done in
  do_allocation_stripe() for the group being tried, not up front in
  btrfs_reserve_extent(): groups narrow at the fill edge (8 devices of
  which two are small give 448K and then 320K full stripes), and a piece
  sized for the widest stripe strands a tail in every narrower group it
  lands in.  btrfs_reserve_extent() only marks the split
  (ffe_ctl->split_bytes, the untrimmed length, so a group that undoes its
  allocation does not pass a trimmed length on).  A piece shorter than one
  stripe of the group is left alone: that is the tail the margin pays
  for.

- A data writeback allocation returning ENOSPC anyway is loudly
  warned: the margin should make it impossible, and the pages are
  dropped.

With this, the fill-to-ENOSPC harness goes fully clean for the first
time: zero writeback drops, zero warnings, zero allocation failures,
margin drains to zero at idle, and fill capacity is unchanged.  A
writeback ENOSPC retry loop that this replaces is dropped entirely.

Known bounds, accepted: compressed writes are probed one unit per
128M range but charged per 128K piece (probe optimistic, charge
honest); direct IO is probed but carries no margin (its reserve-to-
allocate window is one syscall); clearing the property with dirty
delalloc drains the counter (charges are gated on the policy,
releases are not, and the counter clamps at zero).

[zygo: 7.3 port: 7.3's btrfs_add_bg_to_space_info() still takes fs_info;
context adjusted.  7.3 still has the v1 space cache, so
cache_save_setup()'s btrfs_check_data_free_space() call takes the new
stripe_held argument as NULL (the free space inode reserves with
FLUSH_FREE_SPACE_INODE, which carries no margin)]

Assisted-by: Claude:claude-fable-5
Assisted-by: Claude:claude-opus-5-5
14 files changed:
fs/btrfs/block-group.c
fs/btrfs/btrfs_inode.h
fs/btrfs/delalloc-space.c
fs/btrfs/delalloc-space.h
fs/btrfs/direct-io.c
fs/btrfs/extent-tree.c
fs/btrfs/extent-tree.h
fs/btrfs/file.c
fs/btrfs/free-space-cache.c
fs/btrfs/fs.h
fs/btrfs/inode.c
fs/btrfs/space-info.c
fs/btrfs/space-info.h
fs/btrfs/sysfs.c

index 9a13ee9e3d936798ffcd58917439a49c59d30eb2..b9f134df9856f54e0cf0ced161e742794954bbaf 100644 (file)
@@ -1486,6 +1486,12 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
 
                spin_lock(&sinfo->lock);
                sinfo->bytes_stripe_unusable = total;
+               /*
+                * The rescan usually lowers the counter (mid-transaction
+                * incremental adds overcount conservatively); admission
+                * tickets may be waiting on exactly that headroom.
+                */
+               btrfs_try_granting_tickets(sinfo);
                spin_unlock(&sinfo->lock);
        }
 }
@@ -4814,7 +4820,7 @@ again:
        cache_size *= fs_info->sectorsize;
 
        ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
-                                         cache_size, false);
+                                         cache_size, false, NULL);
        if (ret)
                goto out_put;
 
index f76056ebfa22ac58de9f65cf6d9e31dd109e74fe..0005fa3b96dd7c6843876820e9912ebc40e8de86 100644 (file)
@@ -406,6 +406,8 @@ static inline bool is_data_inode(const struct btrfs_inode *inode)
        return btrfs_ino(inode) != BTRFS_BTREE_INODE_OBJECTID;
 }
 
+void btrfs_stripe_margin_mod(struct btrfs_inode *inode, int mod);
+
 static inline void btrfs_mod_outstanding_extents(struct btrfs_inode *inode,
                                                 int mod)
 {
@@ -415,6 +417,7 @@ static inline void btrfs_mod_outstanding_extents(struct btrfs_inode *inode,
                return;
        trace_btrfs_inode_mod_outstanding_extents(inode->root, btrfs_ino(inode),
                                                  mod, inode->outstanding_extents);
+       btrfs_stripe_margin_mod(inode, mod);
 }
 
 /*
index d357ed7efd99bdb70502070ddb5b4361cca4a450..4f540877b19317cbd095caff53691e180d0b9756 100644 (file)
@@ -142,10 +142,11 @@ int btrfs_alloc_data_chunk_ondemand(const struct btrfs_inode *inode, u64 bytes)
 
 int btrfs_check_data_free_space(struct btrfs_inode *inode,
                                struct extent_changeset **reserved, u64 start,
-                               u64 len, bool noflush)
+                               u64 len, bool noflush, u64 *stripe_held)
 {
        struct btrfs_fs_info *fs_info = inode->root->fs_info;
        enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_DATA;
+       u64 stripe_margin = 0;
        int ret;
 
        /* align the range */
@@ -158,13 +159,42 @@ int btrfs_check_data_free_space(struct btrfs_inode *inode,
        else if (btrfs_is_free_space_inode(inode))
                flush = BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE;
 
-       ret = btrfs_reserve_data_bytes(data_sinfo_for_inode(inode), len, flush);
+       /*
+        * stripe_alloc: reserve the pessimistic margin on top of the bytes, so
+        * the flush below must produce enough claimable whole stripes for this
+        * write's worst case, and a write that cannot be covered gets ENOSPC
+        * here rather than being dropped at writeback.  The metadata
+        * reservation re-charges the margin into bytes_stripe_margin
+        * (btrfs_mod_outstanding_extents()).  With @stripe_held the probe stays
+        * in bytes_may_use until then (btrfs_release_data_margin_probe()), so
+        * no other writer is admitted into the gap; otherwise it is released
+        * at once.
+        */
+       if (flush == BTRFS_RESERVE_FLUSH_DATA &&
+           btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
+               const u64 unit = READ_ONCE(fs_info->stripe_margin_unit);
+
+               if (unit)
+                       stripe_margin = (u64)count_max_extents(fs_info, len) * unit;
+       }
+
+       ret = btrfs_reserve_data_bytes(data_sinfo_for_inode(inode),
+                                      len + stripe_margin, flush);
        if (ret < 0)
                return ret;
+       if (stripe_margin && !stripe_held)
+               btrfs_space_info_free_bytes_may_use(data_sinfo_for_inode(inode),
+                                                   stripe_margin);
+       if (stripe_held)
+               *stripe_held = stripe_margin;
 
        /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
        ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
        if (ret < 0) {
+               if (stripe_held) {
+                       btrfs_release_data_margin_probe(inode, stripe_margin);
+                       *stripe_held = 0;
+               }
                btrfs_free_reserved_data_space_noquota(inode, len);
                extent_changeset_free(*reserved);
                *reserved = NULL;
@@ -174,6 +204,13 @@ int btrfs_check_data_free_space(struct btrfs_inode *inode,
        return ret;
 }
 
+
+/* Release the probe margin btrfs_check_data_free_space() handed back in @stripe_held. */
+void btrfs_release_data_margin_probe(struct btrfs_inode *inode, u64 held)
+{
+       if (held)
+               btrfs_space_info_free_bytes_may_use(data_sinfo_for_inode(inode), held);
+}
 /*
  * Called if we need to clear a data reservation for this inode
  * Normally in a error case.
@@ -502,12 +539,14 @@ void btrfs_delalloc_shrink_extents(struct btrfs_inode *inode, u64 reserved_len,
 int btrfs_delalloc_reserve_space(struct btrfs_inode *inode,
                        struct extent_changeset **reserved, u64 start, u64 len)
 {
+       u64 held = 0;
        int ret;
 
-       ret = btrfs_check_data_free_space(inode, reserved, start, len, false);
+       ret = btrfs_check_data_free_space(inode, reserved, start, len, false, &held);
        if (ret < 0)
                return ret;
        ret = btrfs_delalloc_reserve_metadata(inode, len, len, false);
+       btrfs_release_data_margin_probe(inode, held);
        if (ret < 0) {
                btrfs_free_reserved_data_space(inode, *reserved, start, len);
                extent_changeset_free(*reserved);
index 6119c0d3f883cdc0fb8474cf660352568db41982..c464cf0a88d9bfab71a3b69b5af177ff65306fc0 100644 (file)
@@ -12,7 +12,8 @@ struct btrfs_fs_info;
 int btrfs_alloc_data_chunk_ondemand(const struct btrfs_inode *inode, u64 bytes);
 int btrfs_check_data_free_space(struct btrfs_inode *inode,
                        struct extent_changeset **reserved, u64 start, u64 len,
-                       bool noflush);
+                       bool noflush, u64 *stripe_held);
+void btrfs_release_data_margin_probe(struct btrfs_inode *inode, u64 held);
 void btrfs_free_reserved_data_space(struct btrfs_inode *inode,
                        struct extent_changeset *reserved, u64 start, u64 len);
 void btrfs_delalloc_release_space(struct btrfs_inode *inode,
index 9aad7931fa914416878fa5220807d0bea0eb363f..dfcfcb5a390cf228fcfaa9fda4b48464abfd3011 100644 (file)
@@ -18,6 +18,8 @@ struct btrfs_dio_data {
        struct extent_changeset *data_reserved;
        struct btrfs_ordered_extent *ordered;
        bool data_space_reserved;
+       /* stripe_alloc probe margin held in bytes_may_use until the metadata reservation */
+       u64 stripe_held;
        bool nocow_done;
        bool updated_isize;
 };
@@ -452,7 +454,8 @@ static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
        if (write && !(flags & IOMAP_NOWAIT)) {
                ret = btrfs_check_data_free_space(BTRFS_I(inode),
                                                  &dio_data->data_reserved,
-                                                 start, data_alloc_len, false);
+                                                 start, data_alloc_len, false,
+                                                 &dio_data->stripe_held);
                if (!ret)
                        dio_data->data_space_reserved = true;
                else if (!(BTRFS_I(inode)->flags &
@@ -539,6 +542,8 @@ static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
        if (write) {
                ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
                                                    start, &len, flags);
+               btrfs_release_data_margin_probe(BTRFS_I(inode), dio_data->stripe_held);
+               dio_data->stripe_held = 0;
                if (ret < 0)
                        goto unlock_err;
                /* Recalc len in case the new em is smaller than requested */
@@ -609,6 +614,8 @@ unlock_err:
        btrfs_clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend,
                               EXTENT_LOCKED | EXTENT_DIO_LOCKED, &cached_state);
 err:
+       btrfs_release_data_margin_probe(BTRFS_I(inode), dio_data->stripe_held);
+       dio_data->stripe_held = 0;
        if (dio_data->data_space_reserved) {
                btrfs_free_reserved_data_space(BTRFS_I(inode),
                                               dio_data->data_reserved,
index 1be533dec10e66a0dcaf1b95d6ef4cac1f65d247..15aee9b82b65cc7cf80173692ab79e3ff22f60cc 100644 (file)
@@ -4211,6 +4211,44 @@ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
               (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK);
 }
 
+/*
+ * The length to ask this group's stripe allocator for.  A piece of a split
+ * allocation (ffe_ctl->split_bytes) is trimmed to whole stripes of this
+ * group: an allocation claims whole stripes, and the claimed stripes' tail
+ * past it is stranded when its run closes.  The reservation margin pays
+ * for one such tail per delalloc extent, the final piece's, so every
+ * other piece must leave none.  The piece size cannot be chosen before
+ * the group is: groups narrow at the fill edge, where a 448K multiple
+ * claims a third 320K stripe and strands 192K, once per piece.  A piece
+ * shorter than one stripe of the group (or whose whole stripes fall short
+ * of the caller's minimum) is left alone.
+ */
+static u64 stripe_split_bytes(const struct btrfs_block_group *block_group,
+                             const struct find_free_extent_ctl *ffe_ctl)
+{
+       const u64 fsl = block_group->full_stripe_len;
+       const u64 bytes = ffe_ctl->split_bytes;
+       u64 whole;
+
+       if (!bytes)
+               return ffe_ctl->num_bytes;
+       /* Not a power of two: divide. */
+       whole = div64_u64(bytes, fsl) * fsl;
+       if (!whole || whole < ffe_ctl->min_alloc_size)
+               return bytes;
+       return whole;
+}
+
+/* The trimmed piece was allocated: it is what find_free_extent() returns. */
+static void stripe_split_taken(struct find_free_extent_ctl *ffe_ctl,
+                              u64 num_bytes)
+{
+       if (!ffe_ctl->split_bytes)
+               return;
+       ffe_ctl->num_bytes = num_bytes;
+       ffe_ctl->ram_bytes = num_bytes;
+}
+
 static int do_allocation_stripe(struct btrfs_block_group *block_group,
                                struct find_free_extent_ctl *ffe_ctl,
                                struct btrfs_block_group **bg_ret)
@@ -4218,6 +4256,7 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
        struct btrfs_fs_info *fs_info = block_group->fs_info;
        enum btrfs_stripe_run_class class = BTRFS_STRIPE_RUN_COW;
        u64 available = 0;
+       u64 num_bytes;
        u64 offset;
        bool skip = false;
        int ret;
@@ -4260,6 +4299,7 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
         * the shared runs: the data is then placed exactly as before 3b.1
         * and the log-commit settling keeps it safe, just less cheaply.
         */
+       num_bytes = stripe_split_bytes(block_group, ffe_ctl);
        if (ffe_ctl->for_log_inode) {
                struct btrfs_inode *log_inode = ffe_ctl->for_log_inode;
 
@@ -4269,6 +4309,7 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
                if (ret == -ENOMEM)
                        return ret;
                if (!ret) {
+                       stripe_split_taken(ffe_ctl, num_bytes);
                        WRITE_ONCE(log_inode->log_run_hint, offset);
                        ffe_ctl->found_offset = offset;
                        ffe_ctl->search_start = offset;
@@ -4278,7 +4319,7 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
                        ffe_ctl->max_extent_size = available;
        }
 
-       ret = btrfs_alloc_from_open_stripe(block_group, ffe_ctl->num_bytes,
+       ret = btrfs_alloc_from_open_stripe(block_group, num_bytes,
                                           class, &offset, &available);
        if (ret == -ENOMEM)
                return ret;
@@ -4290,6 +4331,7 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
                        btrfs_clear_data_reloc_bg(block_group);
                return 1;
        }
+       stripe_split_taken(ffe_ctl, num_bytes);
        ffe_ctl->found_offset = offset;
        ffe_ctl->search_start = offset;
        return 0;
@@ -5018,6 +5060,7 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
        struct btrfs_fs_info *fs_info = root->fs_info;
        struct find_free_extent_ctl ffe_ctl = {};
        bool final_tried = num_bytes == min_alloc_size;
+       u64 split_bytes = 0;
        u64 flags;
        int ret;
        bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
@@ -5054,6 +5097,7 @@ again:
        ffe_ctl.for_treelog = for_treelog;
        ffe_ctl.for_data_reloc = for_data_reloc;
        ffe_ctl.for_log_inode = for_log_inode;
+       ffe_ctl.split_bytes = split_bytes;
 
        ret = find_free_extent(root, ins, &ffe_ctl);
        if (!ret && !is_data) {
@@ -5067,6 +5111,18 @@ again:
                        ram_bytes = num_bytes;
                        if (num_bytes == min_alloc_size)
                                final_tried = true;
+                       /*
+                        * stripe_alloc: when a data allocation must be split
+                        * across free space fragments, keep every non-final
+                        * piece a whole-stripe multiple so at most one piece
+                        * per delalloc extent can strand a sub-stripe tail.
+                        * The reservation margin pre-paid exactly one tail;
+                        * splitting must not mint more.  Whole stripes of the
+                        * group the piece lands in: do_allocation_stripe()
+                        * trims it there (stripe_split_bytes()).
+                        */
+                       if (is_data && btrfs_test_opt(fs_info, STRIPE_ALLOC))
+                               split_bytes = num_bytes;
                        goto again;
                } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
                        struct btrfs_space_info *sinfo;
@@ -5078,6 +5134,16 @@ again:
                        if (sinfo)
                                btrfs_dump_space_info(sinfo, num_bytes, 1);
                }
+               /*
+                * The pessimistic reservation margin should make a data
+                * writeback allocation failure impossible: admission held
+                * back a full stripe per delalloc extent.  If it happens
+                * anyway the pages are dropped, so say so loudly.
+                */
+               if (is_data && delalloc && btrfs_test_opt(fs_info, STRIPE_ALLOC))
+                       btrfs_warn_rl(fs_info,
+       "stripe_alloc: data writeback allocation of %llu bytes returned ENOSPC despite reservation margin; buffered data in this range will be dropped",
+                                     num_bytes);
        }
 
        return ret;
index a75eb49437030f17c03da2959749611b2981ce32..45a4a7e38d810862c951c57ed523cdb3f006a7a9 100644 (file)
@@ -79,6 +79,14 @@ struct find_free_extent_ctl {
        /* Max contiguous hole found */
        u64 max_extent_size;
 
+       /*
+        * stripe_alloc: a data allocation that btrfs_reserve_extent() split
+        * because nothing held it whole.  The caller takes whatever length
+        * comes back, so a stripe-exclusive group trims the piece to its own
+        * whole stripes; this is the length asked for, before any trim.
+        */
+       u64 split_bytes;
+
        /* Total free space from free space cache, not always contiguous */
        u64 total_free_space;
 
index e674a6fc10feedd931b745070a853510f8986833..0ddd1643ed1b4044fb64b7ce78d091017d7727e5 100644 (file)
@@ -1104,9 +1104,11 @@ static ssize_t reserve_space(struct btrfs_inode *inode,
        const struct btrfs_fs_info *fs_info = inode->root->fs_info;
        const unsigned int block_offset = (start & (fs_info->sectorsize - 1));
        size_t reserve_bytes;
+       u64 held = 0;
        int ret;
 
-       ret = btrfs_check_data_free_space(inode, data_reserved, start, *len, nowait);
+       ret = btrfs_check_data_free_space(inode, data_reserved, start, *len, nowait,
+                                         &held);
        if (ret < 0) {
                int can_nocow;
 
@@ -1131,6 +1133,7 @@ static ssize_t reserve_space(struct btrfs_inode *inode,
        WARN_ON(reserve_bytes == 0);
        ret = btrfs_delalloc_reserve_metadata(inode, reserve_bytes,
                                              reserve_bytes, nowait);
+       btrfs_release_data_margin_probe(inode, held);
        if (ret) {
                if (!*only_release_metadata)
                        btrfs_free_reserved_data_space(inode, *data_reserved,
@@ -1886,6 +1889,7 @@ static vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
        struct btrfs_fs_info *fs_info = inode->root->fs_info;
        struct extent_io_tree *io_tree = &inode->io_tree;
        struct btrfs_ordered_extent *ordered;
+       u64 held = 0;
        struct extent_state *cached_state = NULL;
        struct extent_changeset *data_reserved = NULL;
        unsigned long zero_start;
@@ -1914,7 +1918,7 @@ static vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
         * being processed by btrfs_page_mkwrite() function.
         */
        ret = btrfs_check_data_free_space(inode, &data_reserved, page_start,
-                                         reserved_space, false);
+                                         reserved_space, false, &held);
        if (ret < 0) {
                size_t write_bytes = reserved_space;
 
@@ -1934,6 +1938,7 @@ static vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
        }
        ret = btrfs_delalloc_reserve_metadata(inode, reserved_space,
                                              reserved_space, false);
+       btrfs_release_data_margin_probe(inode, held);
        if (ret < 0) {
                if (!only_release_metadata)
                        btrfs_free_reserved_data_space(inode, data_reserved,
index f8a282cde6069fccf6522bdc320c66517ff2220b..40c6af1c55ffe17985b538a982e36eb24bc21e7c 100644 (file)
@@ -2750,6 +2750,43 @@ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
 
 static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
 
+/*
+ * Count the sub-stripe head and tail of a returning free range as trapped
+ * at once: reservations read bytes_stripe_unusable mid-transaction, and the
+ * commit rescan only corrects it later.  Whole stripes inside the range are
+ * claimable and not counted.  The head and tail count even if neighbouring
+ * free space completes their stripes; that over-count (an early ENOSPC
+ * until the rescan) is the safe direction.
+ */
+static void stripe_unusable_account_add(struct btrfs_block_group *bg,
+                                       u64 bytenr, u64 size)
+{
+       struct btrfs_space_info *sinfo = bg->space_info;
+       const u64 fsl = bg->full_stripe_len;
+       u64 rel_start, rel_end, aligned_start, aligned_end, frag;
+
+       if (!READ_ONCE(bg->stripe_unusable_ready) || !sinfo)
+               return;
+       if (!btrfs_is_stripe_alloc_bg(bg))
+               return;
+
+       rel_start = bytenr - bg->start;
+       rel_end = rel_start + size;
+       aligned_start = div64_u64(rel_start + fsl - 1, fsl) * fsl;
+       aligned_end = div64_u64(rel_end, fsl) * fsl;
+
+       if (aligned_end > aligned_start)
+               frag = size - (aligned_end - aligned_start);
+       else
+               frag = size;
+       if (!frag)
+               return;
+
+       spin_lock(&sinfo->lock);
+       sinfo->bytes_stripe_unusable += frag;
+       spin_unlock(&sinfo->lock);
+}
+
 int btrfs_add_free_space(struct btrfs_block_group *block_group,
                         u64 bytenr, u64 size)
 {
@@ -2766,6 +2803,7 @@ int btrfs_add_free_space(struct btrfs_block_group *block_group,
                trim_state = BTRFS_TRIM_STATE_TRIMMED;
 
        stripe_unusable_mark_dirty(block_group);
+       stripe_unusable_account_add(block_group, bytenr, size);
        return __btrfs_add_free_space(block_group, bytenr, size, trim_state);
 }
 
index 874e62bf289b4c62bef82c921fd991e2ee6028b2..4d5d73531d0b92445dd2be7d8b34cd0eab985496 100644 (file)
@@ -917,6 +917,14 @@ struct btrfs_fs_info {
         */
        u64 max_extent_size;
 
+       /*
+        * Widest full-stripe width among raid56 DATA block groups; the unit
+        * of the stripe_alloc pessimistic reservation margin (one unit per
+        * outstanding delalloc extent).  Zero when the filesystem has no
+        * raid56 data.  Grows monotonically as block groups appear.
+        */
+       u64 stripe_margin_unit;
+
        /* Block groups and devices containing active swapfiles. */
        spinlock_t swapfile_pins_lock;
        struct rb_root swapfile_pins;
index 6f2a52a13330550e2927a0cf43d2e9467d31524b..13aaf748e96620e904cb4e8762de767c08278cd5 100644 (file)
@@ -5171,6 +5171,7 @@ int btrfs_truncate_block(struct btrfs_inode *inode, u64 offset, u64 start, u64 e
        struct extent_changeset *data_reserved = NULL;
        bool only_release_metadata = false;
        u32 blocksize = fs_info->sectorsize;
+       u64 held = 0;
        pgoff_t index = (offset >> PAGE_SHIFT);
        struct folio *folio;
        gfp_t mask = btrfs_alloc_write_mask(mapping);
@@ -5223,7 +5224,7 @@ int btrfs_truncate_block(struct btrfs_inode *inode, u64 offset, u64 start, u64 e
        block_end = block_start + blocksize - 1;
 
        ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
-                                         blocksize, false);
+                                         blocksize, false, &held);
        if (ret < 0) {
                size_t write_bytes = blocksize;
 
@@ -5237,6 +5238,7 @@ int btrfs_truncate_block(struct btrfs_inode *inode, u64 offset, u64 start, u64 e
                }
        }
        ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
+       btrfs_release_data_margin_probe(inode, held);
        if (ret < 0) {
                if (!only_release_metadata)
                        btrfs_free_reserved_data_space(inode, data_reserved,
index 39a28e1bec8ad85c17028940aaf5ca08d7d2f671..cf354c1d38270e1b3c2db37ef45e450fb48c5945 100644 (file)
@@ -16,6 +16,7 @@
 #include "extent-tree.h"
 #include "zoned.h"
 #include "delayed-inode.h"
+#include "btrfs_inode.h"
 
 /*
  * HOW DOES SPACE RESERVATION WORK
@@ -387,6 +388,18 @@ void btrfs_add_bg_to_space_info(struct btrfs_fs_info *info,
 
        factor = btrfs_bg_type_to_factor(block_group->flags);
 
+       /*
+        * The widest raid56 data full stripe is the unit of the stripe_alloc
+        * reservation margin.  Pure geometry: whether a margin is charged is
+        * decided per reservation.
+        */
+       if ((block_group->flags & BTRFS_BLOCK_GROUP_DATA) &&
+           (block_group->flags & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
+           block_group->full_stripe_len >
+           READ_ONCE(block_group->fs_info->stripe_margin_unit))
+               WRITE_ONCE(block_group->fs_info->stripe_margin_unit,
+                          block_group->full_stripe_len);
+
        spin_lock(&space_info->lock);
 
        if (!(block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED) ||
@@ -412,6 +425,53 @@ void btrfs_add_bg_to_space_info(struct btrfs_fs_info *info,
        up_write(&space_info->groups_sem);
 }
 
+/*
+ * stripe_alloc pessimistic reservation margin.
+ *
+ * Between admission at write() and allocation at writeback, each commit
+ * closes open stripe runs and traps their sub-stripe tails, turning bytes a
+ * data reservation counted on into bytes_stripe_unusable, and delalloc
+ * writeback cannot fail cleanly.  So pre-pay the worst case: one full stripe
+ * per outstanding delalloc extent, released when the extent is allocated or
+ * its delalloc range dropped.
+ *
+ * The charge rides btrfs_mod_outstanding_extents(), so it stays exact across
+ * delalloc merges and splits.  Charges require stripe_alloc and releases do
+ * not (they clamp at zero), so disabling the policy with dirty delalloc
+ * drains the counter instead of stranding it.
+ */
+void btrfs_stripe_margin_mod(struct btrfs_inode *inode, int mod)
+{
+       struct btrfs_fs_info *fs_info = inode->root->fs_info;
+       struct btrfs_space_info *sinfo = fs_info->data_sinfo;
+       const u64 unit = READ_ONCE(fs_info->stripe_margin_unit);
+       u64 bytes;
+
+       if (!unit || !sinfo || mod == 0)
+               return;
+       if (btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
+               /* charges and releases both live */
+       } else if (mod > 0 || READ_ONCE(sinfo->bytes_stripe_margin) == 0) {
+               /*
+                * stripe_alloc off: never charge, and skip the lock once the
+                * counter has drained (with no charges it only falls, so
+                * reading zero is stable).
+                */
+               return;
+       }
+
+       bytes = (u64)abs(mod) * unit;
+       spin_lock(&sinfo->lock);
+       if (mod > 0) {
+               sinfo->bytes_stripe_margin += bytes;
+       } else {
+               sinfo->bytes_stripe_margin -= min(bytes, sinfo->bytes_stripe_margin);
+               btrfs_try_granting_tickets(sinfo);
+       }
+       spin_unlock(&sinfo->lock);
+}
+
+
 struct btrfs_space_info *btrfs_find_space_info(const struct btrfs_fs_info *info,
                                               u64 flags)
 {
@@ -655,10 +715,12 @@ static void __btrfs_dump_space_info(const struct btrfs_space_info *info)
                   (s64)(info->total_bytes - btrfs_space_info_used(info, true)),
                   info->full ? "" : "not ");
        btrfs_info(fs_info,
-"space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu",
+"space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu stripe_unusable=%llu stripe_open=%llu stripe_margin=%llu",
                info->total_bytes, info->bytes_used, info->bytes_pinned,
                info->bytes_reserved, info->bytes_may_use,
-               info->bytes_readonly, info->bytes_zone_unusable);
+               info->bytes_readonly, info->bytes_zone_unusable,
+               info->bytes_stripe_unusable, info->bytes_stripe_open,
+               info->bytes_stripe_margin);
 }
 
 void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
index 344ce480099c6e71534df4cdf1c2c86d562482a8..0f8aad3db40b7fd3eb40847d2759904d8c02b44a 100644 (file)
@@ -168,6 +168,16 @@ struct btrfs_space_info {
                                           reservations must not count on it
                                           either.  Synced from the block groups'
                                           stripe_open_remainder. */
+       u64 bytes_stripe_margin;        /* stripe_alloc pessimistic reservation
+                                          margin: one full stripe width per
+                                          outstanding delalloc extent.  Pre-pays
+                                          the worst-case sub-stripe tail each
+                                          future extent can strand when its run
+                                          closes, so commits between write() and
+                                          writeback can never trap space out
+                                          from under an admitted reservation.
+                                          Charged and released in lockstep with
+                                          the inodes' outstanding_extents. */
 
        u64 max_extent_size;    /* This will hold the maximum extent size of
                                   the space info if we had an ENOSPC in the
@@ -328,10 +338,14 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
                s_info->bytes_pinned + s_info->bytes_readonly +
                s_info->bytes_zone_unusable +
                s_info->bytes_stripe_unusable + s_info->bytes_stripe_open +
+               s_info->bytes_stripe_margin +
                (may_use_included ? s_info->bytes_may_use : 0);
 }
 
+struct btrfs_inode;
+
 int btrfs_init_space_info(struct btrfs_fs_info *fs_info);
+void btrfs_stripe_margin_mod(struct btrfs_inode *inode, int mod);
 void btrfs_add_bg_to_space_info(struct btrfs_fs_info *info,
                                struct btrfs_block_group *block_group);
 void btrfs_update_space_info_chunk_size(struct btrfs_space_info *space_info,
index 2d10ad6e2d5e9c0a022dfaf46b48c3c1f99bd493..f79a9b1a7c72455db3a3d17c59bb32d2c8fa1b40 100644 (file)
@@ -930,6 +930,8 @@ SPACE_INFO_ATTR(bytes_may_use);
 SPACE_INFO_ATTR(bytes_readonly);
 SPACE_INFO_ATTR(bytes_zone_unusable);
 SPACE_INFO_ATTR(bytes_stripe_unusable);
+SPACE_INFO_ATTR(bytes_stripe_open);
+SPACE_INFO_ATTR(bytes_stripe_margin);
 SPACE_INFO_ATTR(disk_used);
 SPACE_INFO_ATTR(disk_total);
 SPACE_INFO_ATTR(reclaim_count);
@@ -1060,6 +1062,8 @@ static struct attribute *space_info_attrs[] = {
        BTRFS_ATTR_PTR(space_info, bytes_readonly),
        BTRFS_ATTR_PTR(space_info, bytes_zone_unusable),
        BTRFS_ATTR_PTR(space_info, bytes_stripe_unusable),
+       BTRFS_ATTR_PTR(space_info, bytes_stripe_open),
+       BTRFS_ATTR_PTR(space_info, bytes_stripe_margin),
        BTRFS_ATTR_PTR(space_info, disk_used),
        BTRFS_ATTR_PTR(space_info, disk_total),
        BTRFS_ATTR_PTR(space_info, bg_reclaim_threshold),