]> git.hungrycats.org Git - linux/commitdiff
btrfs: stripe_alloc: gate data admission on claimable whole-stripe supply
authorZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Sat, 19 Sep 2026 17:17:56 +0000 (13:17 -0400)
committerZygo Blaxell <ce3g8jdj@umail.furryterror.org>
Sun, 8 Nov 2026 23:37:50 +0000 (18:37 -0500)
Wire stripe_claimable into the DATA reservation path so write() returns -ENOSPC
when there is no fully-free whole stripe to place the write crash-safely --
matching statfs f_bavail, which already subtracts the trapped partial-stripe
space.  Add stripe_claimable_admit() and AND it into the two data-admit sites:
__reserve_bytes() and btrfs_try_granting_tickets() (the latter is required, or a
flushed data ticket would be granted by the plain used<=total rule, bypassing the
gate).  Scoped to raid56 stripe_alloc DATA (stripe_margin_unit != 0); metadata,
non-raid56 and zoned space_infos are unaffected.

The gate refuses at reservation time, before the range becomes delalloc and later
parks at writeback with nowhere to land -- so ENOSPC is clean and there is no
fill-edge parking collapse.

Phase 1 is pessimistic: it gates on bytes_stripe_claimable alone, which errs LOW,
so it can refuse a write that would have landed in a partially-open stripe
(over-refuses by the open remainder, healed by the commit rescan raising claimable
and the FLUSH_DATA ticket retry).  A later change adds bytes_stripe_open to the
bound for statfs-exact behavior.

What the gate charges, and what it holds against:

- A data reservation is charged need(L): the largest roundup(L, f) over
  the full-stripe widths f of the filesystem's raid56 data groups, with L
  its data bytes without the per-extent probe margin.  The margin is
  collateral that stays accounted (in bytes_may_use as the probe, then in
  bytes_stripe_margin) until the extent is written, so later admissions
  already see it; charging it inside the roundup would ask the supply for
  it twice.  Groups narrow at the fill edge, which the max over widths
  covers.  fs_info records the distinct widths next to stripe_margin_unit
  and never forgets one; with more widths than it holds, the charge falls
  back to L + unit - sectorsize.  The probe margin reaches the gate through
  btrfs_reserve_data_bytes(), __reserve_bytes() and the ticket.  Rounding is
  by division (stripe_round_up(), div64_u64()): the widths are not powers
  of two, and round_up() would charge 512K for 384K of 192K stripes.

- The held margin, bytes_stripe_margin, is added to the admitted bytes:
  it is owed to writers already admitted, and each commit shrinks the
  supply by the tails it traps.

- The delalloc probe margin is not released until the metadata
  reservation has charged it into bytes_stripe_margin (buffered write,
  page_mkwrite, block truncation, direct IO, log-tail carry,
  btrfs_delalloc_reserve_space()), so concurrent writers cannot be
  admitted into each other's released margins.  The v1 cache write-out,
  which reserves no metadata, releases it at once.

- A preallocation has no outstanding extent, so it holds one stripe in
  bytes_stripe_margin from the reservation until its allocations land.
  The hold is charged inside __reserve_bytes(), in the section that grants
  the bytes (directly or by btrfs_try_granting_tickets()), and handed back
  through btrfs_alloc_data_chunk_ondemand_held() /
  btrfs_reserve_data_bytes_held() to fallocate, zero-range, relocation's
  cluster preallocation and the encoded write.

- Relocation is not charged the per-extent margin for extents already
  allocated; its reservation is charged roundup(L, unit) plus one stripe,
  what its own open runs can lose at the next commit.  It has its own
  flush type, BTRFS_RESERVE_FLUSH_DATA_RELOC, under the same bound but
  never waiting: a relocation waiting on the gate held the exclusive
  operation and the group it was emptying while the gate waited for the
  stripes it was to free.  Since a reservation that cannot ticket never
  reaches the flush states that allocate data chunks, a refused relocation
  reservation forces data chunk allocations while they succeed and
  retries, and fails only when that does not help.

- The group dedicated to relocation (fs_info->data_reloc_bg) serves only
  relocation, so its claimable bytes are tracked as
  bytes_stripe_claimable_reloc and ordinary reservations are admitted
  against the supply without them.  Relocation is admitted against the
  whole supply.

- inc_block_group_ro() refuses the read-only transition while the
  admitted bytes would no longer fit in the claimable supply without the
  group; scrub, balance and reclaim retry later.  The subtraction
  saturates, since the group's claimable value can be read ahead of the
  space_info total.

- The reclaim worker allocates a chunk before it relocates a stripe group
  whose live bytes exceed the claimable supply of the other groups (the
  reservation path does not: a live device shrink must fail cleanly at
  its reservation rather than grow the data space_info).

[zygo: 7.3 port: 7.3 still has BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE (v1
space cache): BTRFS_RESERVE_FLUSH_DATA_RELOC goes next to it, in the
6.18 order; btrfs_add_bg_to_space_info() still takes fs_info.]

Assisted-by: Claude:claude-opus-4-8
Assisted-by: Claude:claude-fable-5
Assisted-by: Claude:claude-fable-5-1
Assisted-by: Claude:claude-opus-5-5
fs/btrfs/block-group.c
fs/btrfs/delalloc-space.c
fs/btrfs/delalloc-space.h
fs/btrfs/extent-tree.c
fs/btrfs/file.c
fs/btrfs/free-space-cache.c
fs/btrfs/fs.h
fs/btrfs/inode.c
fs/btrfs/relocation.c
fs/btrfs/space-info.c
fs/btrfs/space-info.h

index 7811df8f11b1de3c9812c6cf9fcb6988ad7d5dc0..88f5da29160967377898bd7de72785b76e099f92 100644 (file)
@@ -1751,6 +1751,7 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
        list_for_each_entry(sinfo, &fs_info->space_info, list) {
                u64 total = 0;
                u64 total_claimable = 0;
+               u64 total_claimable_reloc = 0;
                int raid;
 
                if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
@@ -1786,6 +1787,9 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
                                        total += READ_ONCE(bg->stripe_unusable);
                                        total_claimable +=
                                                READ_ONCE(bg->stripe_claimable);
+                                       if (bg->start == READ_ONCE(fs_info->data_reloc_bg))
+                                               total_claimable_reloc +=
+                                                       READ_ONCE(bg->stripe_claimable);
                                }
                        }
                }
@@ -1794,6 +1798,7 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
                spin_lock(&sinfo->lock);
                sinfo->bytes_stripe_unusable = total;
                sinfo->bytes_stripe_claimable = total_claimable;
+               sinfo->bytes_stripe_claimable_reloc = total_claimable_reloc;
                /*
                 * The rescan usually lowers the counter (mid-transaction
                 * incremental adds overcount conservatively); admission
@@ -1835,10 +1840,19 @@ void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg)
 {
        struct btrfs_fs_info *fs_info = bg->fs_info;
 
+       bool cleared = false;
+
        spin_lock(&fs_info->relocation_bg_lock);
-       if (fs_info->data_reloc_bg == bg->start)
+       if (fs_info->data_reloc_bg == bg->start) {
                fs_info->data_reloc_bg = 0;
+               cleared = true;
+       }
        spin_unlock(&fs_info->relocation_bg_lock);
+       if (cleared && bg->space_info) {
+               spin_lock(&bg->space_info->lock);
+               bg->space_info->bytes_stripe_claimable_reloc = 0;
+               spin_unlock(&bg->space_info->lock);
+       }
 }
 
 /*
@@ -1862,6 +1876,11 @@ void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info)
        bg = btrfs_lookup_block_group(fs_info, bytenr);
        if (!bg)
                return;
+       if (bg->space_info) {
+               spin_lock(&bg->space_info->lock);
+               bg->space_info->bytes_stripe_claimable_reloc = 0;
+               spin_unlock(&bg->space_info->lock);
+       }
        btrfs_close_bg_open_stripes(bg);
        btrfs_put_block_group(bg);
 }
@@ -2932,6 +2951,31 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
                 */
                if (sinfo_used - trapped + num_bytes <= sinfo->total_bytes)
                        ret = 0;
+
+               /*
+                * The stripe_alloc gate admitted writers against whole
+                * stripes (bytes_may_use plus the held margin must fit in
+                * bytes_stripe_claimable).  Going read-only removes this
+                * group's claimable stripes from that supply, so refuse while
+                * the bytes already admitted would no longer be placeable:
+                * otherwise their writebacks fail and the data is dropped.
+                */
+               if (!ret && READ_ONCE(cache->stripe_unusable_ready)) {
+                       /*
+                        * stripe_claimable_mod() updates the group's value
+                        * under the free-space tree lock and only then the
+                        * aggregate under sinfo->lock, so a reader here can see
+                        * the group ahead of the total: saturate, or the
+                        * difference wraps and waves the transition through.
+                        */
+                       const u64 supply = sinfo->bytes_stripe_claimable;
+                       const u64 mine = min(supply,
+                                            READ_ONCE(cache->stripe_claimable));
+
+                       if (sinfo->bytes_may_use + sinfo->bytes_stripe_margin >
+                           supply - mine)
+                               ret = -ENOSPC;
+               }
        } else {
                /*
                 * We overcommit metadata, so we need to do the
index 4f540877b19317cbd095caff53691e180d0b9756..82506b87505bfba1590805a1e8e09eb654062c7b 100644 (file)
@@ -124,11 +124,26 @@ static inline struct btrfs_space_info *data_sinfo_for_inode(const struct btrfs_i
 }
 
 int btrfs_alloc_data_chunk_ondemand(const struct btrfs_inode *inode, u64 bytes)
+{
+       return btrfs_alloc_data_chunk_ondemand_held(inode, bytes, NULL);
+}
+
+/*
+ * With @stripe_held: a preallocation, which claims whole stripes under
+ * stripe_alloc; the reservation charges one stripe of collateral together
+ * with the bytes and returns it for btrfs_stripe_prealloc_release().
+ */
+int btrfs_alloc_data_chunk_ondemand_held(const struct btrfs_inode *inode,
+                                        u64 bytes, u64 *stripe_held)
 {
        struct btrfs_root *root = inode->root;
        struct btrfs_fs_info *fs_info = root->fs_info;
        enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_DATA;
 
+       /* Relocation's prealloc clusters must not wait on the stripe_alloc gate. */
+       if (btrfs_is_data_reloc_root(root))
+               flush = BTRFS_RESERVE_FLUSH_DATA_RELOC;
+
        /* Make sure bytes are sectorsize aligned */
        bytes = ALIGN(bytes, fs_info->sectorsize);
 
@@ -137,7 +152,8 @@ int btrfs_alloc_data_chunk_ondemand(const struct btrfs_inode *inode, u64 bytes)
        else if (btrfs_is_zoned(fs_info) && btrfs_is_data_reloc_root(root))
                flush = BTRFS_RESERVE_FLUSH_ZONED_RELOCATION;
 
-       return btrfs_reserve_data_bytes(data_sinfo_for_inode(inode), bytes, flush);
+       return btrfs_reserve_data_bytes_held(data_sinfo_for_inode(inode), bytes,
+                                            flush, stripe_held);
 }
 
 int btrfs_check_data_free_space(struct btrfs_inode *inode,
@@ -179,7 +195,7 @@ int btrfs_check_data_free_space(struct btrfs_inode *inode,
        }
 
        ret = btrfs_reserve_data_bytes(data_sinfo_for_inode(inode),
-                                      len + stripe_margin, flush);
+                                      len + stripe_margin, stripe_margin, flush);
        if (ret < 0)
                return ret;
        if (stripe_margin && !stripe_held)
index c464cf0a88d9bfab71a3b69b5af177ff65306fc0..37860ced7a72372b36a85f50c21f9b8b38e35571 100644 (file)
@@ -10,6 +10,8 @@ struct btrfs_inode;
 struct btrfs_fs_info;
 
 int btrfs_alloc_data_chunk_ondemand(const struct btrfs_inode *inode, u64 bytes);
+int btrfs_alloc_data_chunk_ondemand_held(const struct btrfs_inode *inode,
+                                        u64 bytes, u64 *stripe_held);
 int btrfs_check_data_free_space(struct btrfs_inode *inode,
                        struct extent_changeset **reserved, u64 start, u64 len,
                        bool noflush, u64 *stripe_held);
index 374cdd06af1d00a7acda226e9e32839677394027..6f7f0929c133a91566c0ec05fce3ea6b6b40d8e6 100644 (file)
@@ -4255,6 +4255,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;
+       bool dedicated_now = false;
        u64 available = 0;
        u64 num_bytes;
        u64 offset;
@@ -4271,8 +4272,10 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
        spin_lock(&fs_info->relocation_bg_lock);
        if (ffe_ctl->for_data_reloc) {
                class = BTRFS_STRIPE_RUN_RELOC;
-               if (!fs_info->data_reloc_bg)
+               if (!fs_info->data_reloc_bg) {
                        fs_info->data_reloc_bg = block_group->start;
+                       dedicated_now = true;
+               }
        }
        if (fs_info->data_reloc_bg &&
            (ffe_ctl->for_data_reloc !=
@@ -4289,6 +4292,13 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
                        skip = true;
        }
        spin_unlock(&fs_info->relocation_bg_lock);
+       if (dedicated_now && block_group->space_info) {
+               /* its claimable stripes now belong to relocation alone */
+               spin_lock(&block_group->space_info->lock);
+               block_group->space_info->bytes_stripe_claimable_reloc =
+                       READ_ONCE(block_group->stripe_claimable);
+               spin_unlock(&block_group->space_info->lock);
+       }
        if (skip)
                return 1;
 
index a4e69980aad88954a58254539a445a61b22b6bbd..e95d9d42401f67df746036de8ae6c85348d09d75 100644 (file)
@@ -39,6 +39,7 @@
 #include "file.h"
 #include "super.h"
 #include "print-tree.h"
+#include "space-info.h"
 
 /*
  * Unlock folio after btrfs_file_write() is done with it.
@@ -2972,6 +2973,7 @@ static int btrfs_zero_range(struct inode *inode,
        u64 alloc_start = round_down(offset, sectorsize);
        u64 alloc_end = round_up(offset + len, sectorsize);
        u64 bytes_to_reserve = 0;
+       u64 stripe_held = 0;
        bool space_reserved = false;
 
        em = btrfs_get_extent(BTRFS_I(inode), NULL, alloc_start,
@@ -3097,8 +3099,9 @@ reserve_space:
                const u64 lockend = alloc_end - 1;
 
                bytes_to_reserve = alloc_end - alloc_start;
-               ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
-                                                     bytes_to_reserve);
+               ret = btrfs_alloc_data_chunk_ondemand_held(BTRFS_I(inode),
+                                                          bytes_to_reserve,
+                                                          &stripe_held);
                if (ret < 0)
                        goto out;
                space_reserved = true;
@@ -3115,6 +3118,8 @@ reserve_space:
                                                alloc_end - alloc_start,
                                                fs_info->sectorsize,
                                                offset + len, &alloc_hint);
+               btrfs_stripe_prealloc_release(fs_info, stripe_held);
+               stripe_held = 0;
                btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
                                    &cached_state);
                /* btrfs_prealloc_file_range releases reserved space on error */
@@ -3125,6 +3130,7 @@ reserve_space:
        }
        ret = btrfs_fallocate_update_isize(inode, offset + len, mode);
  out:
+       btrfs_stripe_prealloc_release(fs_info, stripe_held);
        if (ret && space_reserved)
                btrfs_free_reserved_data_space(BTRFS_I(inode), data_reserved,
                                               alloc_start, bytes_to_reserve);
@@ -3151,6 +3157,7 @@ static long btrfs_fallocate(struct file *file, int mode,
        u64 actual_end = 0;
        u64 data_space_needed = 0;
        u64 data_space_reserved = 0;
+       u64 stripe_held = 0;
        u64 qgroup_reserved = 0;
        struct extent_map *em;
        int blocksize = BTRFS_I(inode)->root->fs_info->sectorsize;
@@ -3275,8 +3282,9 @@ static long btrfs_fallocate(struct file *file, int mode,
                 * We are safe to reserve space here as we can't have delalloc
                 * in the range, see above.
                 */
-               ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
-                                                     data_space_needed);
+               ret = btrfs_alloc_data_chunk_ondemand_held(BTRFS_I(inode),
+                                                          data_space_needed,
+                                                          &stripe_held);
                if (!ret)
                        data_space_reserved = data_space_needed;
        }
@@ -3311,6 +3319,7 @@ static long btrfs_fallocate(struct file *file, int mode,
                list_del(&range->list);
                kfree(range);
        }
+       btrfs_stripe_prealloc_release(inode_to_fs_info(inode), stripe_held);
        if (ret < 0)
                goto out_unlock;
 
index 6dbab0f6f576c1f430418acf9026e0c8148b6ff1..0388f450cac57a8b80ddb8e31ae300c830f7fba8 100644 (file)
@@ -2805,6 +2805,12 @@ static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta)
                sinfo->bytes_stripe_claimable = 0;
        else
                btrfs_space_info_update_bytes_stripe_claimable(sinfo, delta);
+       if (bg->start == READ_ONCE(bg->fs_info->data_reloc_bg)) {
+               if (delta < 0 && sinfo->bytes_stripe_claimable_reloc < (u64)-delta)
+                       sinfo->bytes_stripe_claimable_reloc = 0;
+               else
+                       sinfo->bytes_stripe_claimable_reloc += delta;
+       }
        spin_unlock(&sinfo->lock);
 }
 
@@ -3554,6 +3560,8 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
                                                              -(s64)trapped);
                btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
                                                               -(s64)claimable);
+               if (bg->start == READ_ONCE(bg->fs_info->data_reloc_bg))
+                       bg->space_info->bytes_stripe_claimable_reloc = 0;
                spin_unlock(&bg->space_info->lock);
        }
 }
index 1e8e47f6ecd097a1b74689f00382a18d2e020db7..c56f9f59496ab2fa5535294a52c439472a5e6e3d 100644 (file)
@@ -512,6 +512,9 @@ struct btrfs_free_space;
 /* Refuse absurd deadlines: a parked rbio holds its stripe lock. */
 #define BTRFS_RBIO_PARK_TIMEOUT_MS_MAX 60000
 
+/* Distinct raid56 data full-stripe widths tracked for stripe_alloc. */
+#define BTRFS_STRIPE_WIDTHS_MAX                8
+
 struct btrfs_fs_info {
        u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
        unsigned long flags;
@@ -979,6 +982,17 @@ struct btrfs_fs_info {
         * raid56 data.  Grows monotonically as block groups appear.
         */
        u64 stripe_margin_unit;
+       /*
+        * The distinct full-stripe widths of raid56 DATA block groups, for
+        * the stripe_alloc admission charge (stripe_whole_need()).  Grows as
+        * block groups appear and never shrinks: a width no group has any
+        * more only makes the charge more conservative.  More widths than
+        * fit leave nr_stripe_widths past the array, and the charge falls
+        * back to a bound that holds for every width up to
+        * stripe_margin_unit.  Written under the data space_info's lock.
+        */
+       u64 stripe_widths[BTRFS_STRIPE_WIDTHS_MAX];
+       int nr_stripe_widths;
 
        /* Block groups and devices containing active swapfiles. */
        spinlock_t swapfile_pins_lock;
index 13aaf748e96620e904cb4e8762de767c08278cd5..66f0d5f5aa403c3f1772b8937fd418465151d00a 100644 (file)
@@ -10035,6 +10035,7 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
        u64 num_bytes, ram_bytes, disk_num_bytes;
        struct btrfs_key ins;
        bool extent_reserved = false;
+       u64 stripe_held = 0;
        struct extent_map *em;
        ssize_t ret;
 
@@ -10176,7 +10177,8 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
         * We don't use the higher-level delalloc space functions because our
         * num_bytes and disk_num_bytes are different.
         */
-       ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
+       ret = btrfs_alloc_data_chunk_ondemand_held(inode, disk_num_bytes,
+                                                  &stripe_held);
        if (ret)
                goto out_unlock;
        ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
@@ -10204,6 +10206,8 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
 
        ret = btrfs_reserve_extent(root, inode, disk_num_bytes, disk_num_bytes,
                                   disk_num_bytes, 0, 0, &ins, true, true);
+       btrfs_stripe_prealloc_release(fs_info, stripe_held);
+       stripe_held = 0;
        if (ret)
                goto out_delalloc_release;
        extent_reserved = true;
@@ -10252,6 +10256,7 @@ out_qgroup_free_data:
        if (ret < 0)
                btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes, NULL);
 out_free_data_space:
+       btrfs_stripe_prealloc_release(fs_info, stripe_held);
        /*
         * If btrfs_reserve_extent() succeeded, then we already decremented
         * bytes_may_use.
index a3eb5272ed436cab536b4e8091831663a0c7df49..76db68baf202189c5017e33f178e15f41d4995e4 100644 (file)
@@ -2799,6 +2799,7 @@ static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control
        u64 prealloc_start = cluster->start - offset;
        u64 prealloc_end = cluster->end - offset;
        u64 cur_offset = prealloc_start;
+       u64 stripe_held;
 
        /*
         * For blocksize < folio size case (either bs < page size or large folios),
@@ -2816,8 +2817,9 @@ static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control
                return ret;
 
        BUG_ON(cluster->start != cluster->boundary[0]);
-       ret = btrfs_alloc_data_chunk_ondemand(inode,
-                                             prealloc_end + 1 - prealloc_start);
+       ret = btrfs_alloc_data_chunk_ondemand_held(inode,
+                                       prealloc_end + 1 - prealloc_start,
+                                       &stripe_held);
        if (ret)
                return ret;
 
@@ -2842,6 +2844,7 @@ static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control
                        break;
        }
        btrfs_inode_unlock(inode, 0);
+       btrfs_stripe_prealloc_release(inode->root->fs_info, stripe_held);
 
        if (cur_offset < prealloc_end)
                btrfs_free_reserved_data_space_noquota(inode,
index d67a80b02fe0011cccc1a5781e0bc43172d22cc4..5ead2a20114d82a4ef4e689dc6e3c53b666a990f 100644 (file)
@@ -187,6 +187,18 @@ struct reserve_ticket {
        u64 bytes;
        int error;
        bool steal;
+       /*
+        * A preallocation: one whole stripe of collateral is charged into
+        * bytes_stripe_margin in the same critical section that grants the
+        * bytes (stripe_hold_locked()), and handed back through @held.
+        */
+       bool hold_stripe;
+       u64 held;
+       /*
+        * The stripe_alloc collateral inside @bytes (the delalloc probe
+        * margin), which stripe_claimable_admit() leaves out of the charge.
+        */
+       u64 stripe_margin;
        struct list_head list;
        wait_queue_head_t wait;
        spinlock_t lock;
@@ -449,6 +461,12 @@ void btrfs_stripe_margin_mod(struct btrfs_inode *inode, int mod)
 
        if (!unit || !sinfo || mod == 0)
                return;
+       /*
+        * Relocation's extents are already placed; its reservations are
+        * charged a margin of their own in stripe_claimable_admit().
+        */
+       if (btrfs_is_data_reloc_root(inode->root))
+               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) {
@@ -471,6 +489,41 @@ void btrfs_stripe_margin_mod(struct btrfs_inode *inode, int mod)
        spin_unlock(&sinfo->lock);
 }
 
+/*
+ * Charge one whole stripe of margin for a preallocation, under
+ * space_info->lock in the same critical section that admits its bytes.  A
+ * preallocation has no outstanding extent to carry a margin, yet its
+ * allocation claims its bytes rounded up to whole stripes.  The hold keeps
+ * that stripe out of the supply other writers are admitted against until
+ * btrfs_stripe_prealloc_release().  Charged after admission, with the lock
+ * dropped in between, two preallocations could share one stripe of supply.
+ * Returns the bytes held, or 0 when stripe_alloc does not apply.
+ */
+static u64 stripe_hold_locked(struct btrfs_space_info *space_info)
+{
+       struct btrfs_fs_info *fs_info = space_info->fs_info;
+       const u64 unit = READ_ONCE(fs_info->stripe_margin_unit);
+
+       lockdep_assert_held(&space_info->lock);
+       if (!unit || !(space_info->flags & BTRFS_BLOCK_GROUP_DATA) ||
+           !btrfs_test_opt(fs_info, STRIPE_ALLOC))
+               return 0;
+       space_info->bytes_stripe_margin += unit;
+       return unit;
+}
+
+void btrfs_stripe_prealloc_release(struct btrfs_fs_info *fs_info, u64 held)
+{
+       struct btrfs_space_info *sinfo = fs_info->data_sinfo;
+
+       if (!held || !sinfo)
+               return;
+       spin_lock(&sinfo->lock);
+       sinfo->bytes_stripe_margin -= min(held, 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)
@@ -643,6 +696,105 @@ static void remove_ticket(struct btrfs_space_info *space_info,
        spin_unlock(&ticket->lock);
 }
 
+/*
+ * The most whole stripes that @bytes of data can claim when writeback
+ * allocates them: in a group of full stripe f, an allocation claims
+ * roundup(bytes, f), so the most over every width a data group has.  The
+ * widths are not powers of two for most geometries (3 data stripes: 192K),
+ * so divide.  If there were more widths than fs_info tracks, fall back to
+ * bytes + unit - sectorsize, which bounds roundup(bytes, f) for every
+ * f <= unit (all sector multiples).
+ */
+static u64 stripe_whole_need(struct btrfs_fs_info *fs_info, u64 bytes, u64 unit)
+{
+       const int nr = smp_load_acquire(&fs_info->nr_stripe_widths);
+       u64 need = 0;
+
+       if (nr > BTRFS_STRIPE_WIDTHS_MAX)
+               return bytes + unit - fs_info->sectorsize;
+       for (int i = 0; i < nr; i++) {
+               const u64 w = READ_ONCE(fs_info->stripe_widths[i]);
+
+               need = max(need, div64_u64(bytes + w - 1, w) * w);
+       }
+       /* stripe_margin_unit is set first: no width recorded yet */
+       if (!need)
+               need = div64_u64(bytes + unit - 1, unit) * unit;
+       return need;
+}
+
+/*
+ * stripe_alloc data admission gate.  A raid56 stripe_alloc data write can
+ * only be placed crash-safely in a fully free stripe, so admit a data
+ * reservation only while the claimable whole-stripe supply covers all
+ * outstanding reservations, their margins and this one.  This turns a write
+ * that could not be placed into ENOSPC at write() rather than dropped data
+ * at writeback.  It is pessimistic: open runs' remainders are not counted,
+ * and the commit rescan and FLUSH_DATA ticket retry recover that space.
+ * Space infos without raid56 data are unaffected (stripe_margin_unit is
+ * 0).  Caller holds space_info->lock.
+ *
+ * @margin is the stripe_alloc collateral inside @bytes (the delalloc probe
+ * margin).  It is not charged: once granted it is accounted in
+ * bytes_may_use, then in bytes_stripe_margin, where every later admission
+ * sees it.
+ */
+static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 bytes,
+                                  u64 margin, bool reloc)
+{
+       struct btrfs_fs_info *fs_info = space_info->fs_info;
+       const u64 unit = READ_ONCE(fs_info->stripe_margin_unit);
+
+       if (!btrfs_test_opt(fs_info, STRIPE_ALLOC) ||
+           !(space_info->flags & BTRFS_BLOCK_GROUP_DATA) || !unit)
+               return true;
+       /*
+        * Relocation carries no per-extent margin (its extents are already
+        * placed): charge it whole stripes plus one, the tail its own open
+        * runs can lose at the next commit.
+        */
+       {
+               u64 supply = space_info->bytes_stripe_claimable;
+               const u64 dedicated = space_info->bytes_stripe_claimable_reloc;
+
+               if (reloc) {
+                       /*
+                        * Against the whole supply, dedicated group included:
+                        * when its group runs dry, relocation moves on to
+                        * another.  Whole stripes of the widest group; unit is
+                        * not a power of two for most geometries, so divide.
+                        */
+                       bytes = div64_u64(bytes + unit - 1, unit) * unit + unit;
+               } else {
+                       /* ...and that group is out of reach for everyone else */
+                       supply -= min(supply, dedicated);
+                       /*
+                        * Charge what writeback can claim for the data: whole
+                        * stripes of whichever group it lands in.  Not the
+                        * collateral: the data plus its collateral (the probe
+                        * margin, then one unit in bytes_stripe_margin, or a
+                        * preallocation's hold) stays accounted until the
+                        * extent is written, and covers that claim, so the
+                        * accounted total of every outstanding extent bounds
+                        * what they can still claim.  Charging the collateral
+                        * as well would ask the supply for it twice.
+                        */
+                       bytes = stripe_whole_need(fs_info, bytes - min(bytes, margin),
+                                                 unit);
+               }
+               /*
+                * Outstanding data extents hold their margin
+                * (bytes_stripe_margin) against the commit that traps their
+                * runs' tails.  btrfs_space_info_used() counts it against
+                * total_bytes, but it is owed out of the whole-stripe supply,
+                * so every later admission, relocation included, must leave it
+                * there.
+                */
+               bytes += space_info->bytes_stripe_margin;
+               return space_info->bytes_may_use + bytes <= supply;
+       }
+}
+
 /*
  * This is for space we already have accounted in space_info->bytes_may_use, so
  * basically when we're returning space from block_rsv's.
@@ -665,9 +817,13 @@ again:
                used_after = used + ticket->bytes;
 
                /* Check and see if our ticket can be satisfied now. */
-               if (used_after <= space_info->total_bytes ||
-                   can_overcommit(space_info, used, ticket->bytes, flush)) {
+               if ((used_after <= space_info->total_bytes ||
+                    can_overcommit(space_info, used, ticket->bytes, flush)) &&
+                   stripe_claimable_admit(space_info, ticket->bytes,
+                                          ticket->stripe_margin, false)) {
                        btrfs_space_info_update_bytes_may_use(space_info, ticket->bytes);
+                       if (ticket->hold_stripe)
+                               ticket->held = stripe_hold_locked(space_info);
                        remove_ticket(space_info, ticket, 0);
                        space_info->tickets_id++;
                        used = used_after;
@@ -1753,6 +1909,7 @@ static int handle_reserve_ticket(struct btrfs_space_info *space_info,
 
        switch (flush) {
        case BTRFS_RESERVE_FLUSH_DATA:
+       case BTRFS_RESERVE_FLUSH_DATA_RELOC:
        case BTRFS_RESERVE_FLUSH_ALL:
        case BTRFS_RESERVE_FLUSH_ALL_STEAL:
                wait_reserve_ticket(space_info, ticket);
@@ -1831,8 +1988,13 @@ static inline bool can_steal(enum btrfs_reserve_flush_enum flush)
  */
 static inline bool can_ticket(enum btrfs_reserve_flush_enum flush)
 {
+       /*
+        * Relocation never waits for space: at the fill edge the stripes it
+        * would wait for are the ones only it can free (stripe_alloc).
+        */
        return (flush != BTRFS_RESERVE_NO_FLUSH &&
-               flush != BTRFS_RESERVE_FLUSH_EMERGENCY);
+               flush != BTRFS_RESERVE_FLUSH_EMERGENCY &&
+               flush != BTRFS_RESERVE_FLUSH_DATA_RELOC);
 }
 
 /*
@@ -1849,8 +2011,9 @@ static inline bool can_ticket(enum btrfs_reserve_flush_enum flush)
  * regain reservations will be made and this will fail if there is not enough
  * space already.
  */
-static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
-                        enum btrfs_reserve_flush_enum flush)
+static int __reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
+                          u64 stripe_margin,
+                          enum btrfs_reserve_flush_enum flush, u64 *held)
 {
        struct btrfs_fs_info *fs_info = space_info->fs_info;
        struct work_struct *async_work;
@@ -1874,7 +2037,8 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
                ASSERT(flush != BTRFS_RESERVE_FLUSH_EVICT, "flush=%d", flush);
        }
 
-       if (flush == BTRFS_RESERVE_FLUSH_DATA)
+       if (flush == BTRFS_RESERVE_FLUSH_DATA ||
+           flush == BTRFS_RESERVE_FLUSH_DATA_RELOC)
                async_work = &fs_info->async_data_reclaim_work;
        else
                async_work = &fs_info->async_reclaim_work;
@@ -1899,8 +2063,12 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
         */
        if (!pending_tickets &&
            ((used + orig_bytes <= space_info->total_bytes) ||
-            can_overcommit(space_info, used, orig_bytes, flush))) {
+            can_overcommit(space_info, used, orig_bytes, flush)) &&
+           stripe_claimable_admit(space_info, orig_bytes, stripe_margin,
+                                  flush == BTRFS_RESERVE_FLUSH_DATA_RELOC)) {
                btrfs_space_info_update_bytes_may_use(space_info, orig_bytes);
+               if (held)
+                       *held = stripe_hold_locked(space_info);
                ret = 0;
        }
 
@@ -1931,6 +2099,9 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
                init_waitqueue_head(&ticket.wait);
                spin_lock_init(&ticket.lock);
                ticket.steal = can_steal(flush);
+               ticket.hold_stripe = held != NULL;
+               ticket.held = 0;
+               ticket.stripe_margin = stripe_margin;
                if (trace_btrfs_reserve_ticket_enabled())
                        start_ns = ktime_get_ns();
 
@@ -1978,7 +2149,10 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
        if (!ret || !can_ticket(flush))
                return ret;
 
-       return handle_reserve_ticket(space_info, &ticket, start_ns, orig_bytes, flush);
+       ret = handle_reserve_ticket(space_info, &ticket, start_ns, orig_bytes, flush);
+       if (!ret && held)
+               *held = ticket.held;
+       return ret;
 }
 
 /*
@@ -2001,7 +2175,7 @@ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
 {
        int ret;
 
-       ret = reserve_bytes(space_info, orig_bytes, flush);
+       ret = __reserve_bytes(space_info, orig_bytes, 0, flush, NULL);
        if (ret == -ENOSPC) {
                struct btrfs_fs_info *fs_info = space_info->fs_info;
 
@@ -2014,6 +2188,28 @@ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
        return ret;
 }
 
+/*
+ * Relocation never waits for data space (see can_ticket()), so its
+ * reservation never reaches the flush states that allocate a data chunk.
+ * When it does not fit in the chunks already there, allocate one and let the
+ * caller retry.  Returns true if a chunk was allocated.
+ */
+static bool reloc_alloc_data_chunk(struct btrfs_space_info *space_info)
+{
+       struct btrfs_fs_info *fs_info = space_info->fs_info;
+       struct btrfs_trans_handle *trans;
+       int ret;
+
+       trans = btrfs_join_transaction(fs_info->tree_root);
+       if (IS_ERR(trans))
+               return false;
+       ret = btrfs_chunk_alloc(trans, space_info,
+                               btrfs_get_alloc_profile(fs_info, space_info->flags),
+                               CHUNK_ALLOC_FORCE);
+       btrfs_end_transaction(trans);
+       return ret > 0;
+}
+
 /*
  * Try to reserve data bytes for an allocation.
  *
@@ -2024,21 +2220,62 @@ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
  * This will reserve bytes from the data space info.  If there is not enough
  * space then we will attempt to flush space as specified by flush.
  */
+static int reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
+                             u64 stripe_margin,
+                             enum btrfs_reserve_flush_enum flush, u64 *held);
+
 int btrfs_reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
+                            u64 stripe_margin,
                             enum btrfs_reserve_flush_enum flush)
+{
+       return reserve_data_bytes(space_info, bytes, stripe_margin, flush, NULL);
+}
+
+/*
+ * Like btrfs_reserve_data_bytes(), for a preallocation: with @held the
+ * reservation also charges one whole stripe of stripe_alloc collateral,
+ * atomically with the bytes, and returns it for
+ * btrfs_stripe_prealloc_release() once the caller's allocations are done.
+ */
+int btrfs_reserve_data_bytes_held(struct btrfs_space_info *space_info, u64 bytes,
+                                 enum btrfs_reserve_flush_enum flush, u64 *held)
+{
+       return reserve_data_bytes(space_info, bytes, 0, flush, held);
+}
+
+static int reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
+                             u64 stripe_margin,
+                             enum btrfs_reserve_flush_enum flush, u64 *held)
 {
        struct btrfs_fs_info *fs_info = space_info->fs_info;
        int ret;
 
        ASSERT(flush == BTRFS_RESERVE_FLUSH_DATA ||
+              flush == BTRFS_RESERVE_FLUSH_DATA_RELOC ||
               flush == BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE ||
               flush == BTRFS_RESERVE_FLUSH_ZONED_RELOCATION ||
               flush == BTRFS_RESERVE_NO_FLUSH, "flush=%d", flush);
-       ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_DATA,
+       ASSERT(!current->journal_info ||
+              (flush != BTRFS_RESERVE_FLUSH_DATA &&
+               flush != BTRFS_RESERVE_FLUSH_DATA_RELOC),
               "current->journal_info=0x%lx flush=%d",
               (unsigned long)current->journal_info, flush);
 
-       ret = reserve_bytes(space_info, bytes, flush);
+       if (held)
+               *held = 0;
+       ret = __reserve_bytes(space_info, bytes, stripe_margin, flush, held);
+       /*
+        * Relocation does not wait for data space (can_ticket()), but must not
+        * fail while unallocated space remains, so allocate data chunks until
+        * the reservation fits.  One chunk may not be enough: relocation
+        * reserves a whole cluster at once, and a new chunk can be smaller (the
+        * chunk size cap shrinks with the filesystem during a device remove).
+        * Each success consumes unallocated space, so the loop ends.
+        */
+       while (ret == -ENOSPC && flush == BTRFS_RESERVE_FLUSH_DATA_RELOC &&
+              reloc_alloc_data_chunk(space_info))
+               ret = __reserve_bytes(space_info, bytes, stripe_margin, flush,
+                                     held);
        if (ret == -ENOSPC) {
                trace_btrfs_space_reservation(fs_info, "space_info:enospc",
                                              space_info->flags, bytes, 1);
index 85a9edfdc7d9b89aa25cb66802a261b8a08201b8..5766ffaac56d9b5ff5c1de67aa64f7d546f7f399 100644 (file)
@@ -66,6 +66,14 @@ enum btrfs_reserve_flush_enum {
         * Can be interrupted by a fatal signal.
         */
        BTRFS_RESERVE_FLUSH_DATA,
+
+       /*
+        * Data reservation for relocation: flushes like FLUSH_DATA but
+        * never waits on a ticket when the stripe_alloc whole-stripe gate
+        * refuses it -- relocation is what frees whole stripes, so it must
+        * not wait for them; it fails at once and is retried later.
+        */
+       BTRFS_RESERVE_FLUSH_DATA_RELOC,
        BTRFS_RESERVE_FLUSH_FREE_SPACE_INODE,
        BTRFS_RESERVE_FLUSH_ALL,
 
@@ -160,6 +168,11 @@ struct btrfs_space_info {
                                           stripes stranded behind live runs.
                                           Counted as used, and subtracted in
                                           statfs. */
+       u64 bytes_stripe_claimable_reloc;       /* the part of bytes_stripe_claimable
+                                          in the group dedicated to data
+                                          relocation (fs_info->data_reloc_bg):
+                                          out of reach for other allocations
+                                          while the dedication lasts */
        u64 bytes_stripe_claimable;     /* sum of armed groups' directly
                                           measured claimable whole-stripe
                                           bytes; see stripe_claimable in
@@ -351,6 +364,9 @@ 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);
+int btrfs_reserve_data_bytes_held(struct btrfs_space_info *space_info, u64 bytes,
+                                 enum btrfs_reserve_flush_enum flush, u64 *held);
+void btrfs_stripe_prealloc_release(struct btrfs_fs_info *fs_info, u64 held);
 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,
@@ -377,6 +393,7 @@ static inline void btrfs_space_info_free_bytes_may_use(
        spin_unlock(&space_info->lock);
 }
 int btrfs_reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
+                            u64 stripe_margin,
                             enum btrfs_reserve_flush_enum flush);
 void btrfs_dump_space_info_for_trans_abort(struct btrfs_fs_info *fs_info);
 void btrfs_init_async_reclaim_work(struct btrfs_fs_info *fs_info);