These are the `misc-next/topics/*` branches of the misc-next lane,
exported with `git format-patch`, one directory per branch. They are
-the submission candidates, plus a few series that are not meant for
-upstream at all (see the table).
+the submission candidates. Commits and topics that are not meant for
+upstream are left out (see "What is not exported").
| | |
|---|---|
-| base of every series | `99bc6552614f` ("btrfs: === misc-next on b-for-next ==="): btrfs/for-next `0713fa6a4356` plus a marker commit, the misc-next lane base (`misc-next/testing^1`, rebased 2026-10-25) |
-| integration branch | `misc-next/testing` `e8519e93c9a2` (octopus of all 20 topics) |
-| lane head | `zygo-misc-next-zb64` `315863b5a610`; its own commits on top of `testing` (kernel configs, `covers/`) are not exported |
+| base of every series | `bf921b86bdf2` ("btrfs: === misc-next on b-for-next ==="): btrfs/for-next `20b89f65c3ee` plus a marker commit, the misc-next lane base (`misc-next/testing^1`, rebased 2026-10-28) |
+| integration branch | `misc-next/testing` `d88841f5cf02` (octopus of 23 topics; 21 exported) |
+| lane head | `zygo-misc-next-zb64` `db4cce38a238`; its own commits on top of `testing` (kernel configs, `covers/`) are not exported |
The base is not a published commit: the lane rebuilds it from
btrfs/for-next plus David Sterba's queue. It lives in the
`topics/<branch>/0000-cover-letter.patch`, ready for `git send-email`.
Edit the subject title and the text above the shortlog in place.
-`scripts/export.sh` re-exports every branch and regenerates
-`fixups/post-merge.patch`, then checks both against the lane. It keeps
+`scripts/export.sh` re-exports every branch, leaving out what is not
+for upstream, regenerates `fixups/post-merge.patch`, then checks both
+against the lane. It keeps
each cover letter's title and text, and regenerates only the mail
headers, the shortlog, the diffstat and the `base-commit:` line. It
reports any series whose patch count changed, so its cover text can be
topics/<branch>/NNNN-<subject>.patch the patches, in branch order
fixups/post-merge.patch what integrating all series needs (below)
scripts/export.sh re-export from ~/share/linux, keeping the cover letters
+scripts/exclude.txt what the export leaves out besides marked commits
+scripts/revert-resolutions/<sha>.patch hand resolutions for reverting a left-out commit from testing (below)
```
Every series has a cover letter, single-patch ones included (0/1); the
cover carries the `base-commit:` line. Series meant for the
list have `To: linux-btrfs@vger.kernel.org` already set.
+## What is not exported
+
+`scripts/export.sh` leaves out:
+
+- every lane commit whose subject or body says DO-NOT-UPSTREAM (any of
+ `DO-NOT-UPSTREAM`, `DO_NOT_UPSTREAM`, `DO NOT UPSTREAM`, any case), or
+ whose body says it is "dropped before upstream";
+- whatever `scripts/exclude.txt` lists: whole topics (`topic <branch>`,
+ whose directory is removed) and single commits by exact subject
+ (`subject <subject>`, for a ruling the lane has not marked yet).
+
+A topic that loses a commit is re-created without it: each later commit
+is replayed onto the filtered branch with its own author, committer,
+dates and message. If a later commit does not apply without the dropped
+one, the script stops (`STOP: ...`) and changes nothing here; the lane
+has to move the dropped commit or rework the later one. Likewise, the
+fixup is computed against `misc-next/testing` with the dropped commits
+reverted (the "fixup target"). If a revert conflicts, because testing
+holds the dropped commit's lines next to another topic's, the script
+looks for `scripts/revert-resolutions/<full SHA of the dropped
+commit>.patch`: a diff, against the target before that revert, of the
+conflicted files only. It must cover exactly the conflicted files, and
+is keyed by SHA, so any change to the dropped commit makes it unused and
+the script stops again. Without one, the script stops. It prints what
+it dropped and why, and the fixup target's tree.
+
+As of misc-next `testing` `d88841f5cf02` (2026-10-30):
+
+| left out | why |
+|---|---|
+| `dm-stripfault` (2 commits) | test fixtures; `topic` entry, both commits marked |
+| `test-knobs` (2 commits: the reclaim exclusive-operation gap, Zygo 2026-10-29 "do-not-upstream"; the rbio cache size debug knob) | test-only; `topic` entry, both commits marked |
+
+One stored resolution is in use: reverting the knob (`3213446fec93`)
+conflicts in `raid56.h`, where testing has the knob's declaration right
+above raid56-fixes' `btrfs_raid56_uncache_range()`; the resolution
+removes the knob's three lines only.
+
## The series
Listed in the merge order of `misc-next/testing`, which is also the order
-the integration recipe below uses.
-
-| directory | patches | branch tip | authors | cover letter | notes |
-|---|---|---|---|---|---|
-| `logical-ino-costs` | 3 | `f792976ba697` | Zygo, Kai Krakow | from misc-next `covers/`, updated: 0/3 and a paragraph on patch 3 | patch 3 is Kai's, already posted by him |
-| `balance-resume` | 3 | `6094381703cd` | Zygo | from misc-next `covers/`, current | patch 3 optional, offered for rejection |
-| `compress-fixes` | 5 | `9cf6495173d4` | Zygo | from misc-next `covers/`, current | |
-| `deadlock-fixes` | 3 | `78c0c9e6a02b` | Zygo | new | |
-| `dedupe-fixes` | 1 | `8e47d471e8a3` | Zygo | new, 0/1 (drafted 2026-10-18) | |
-| `delalloc-fixes` | 1 | `a49a18e6a3c7` | Zygo | from misc-next `covers/`, rewritten 2026-10-19 for 0/1 | patch 1 (delalloc leak) dropped 2026-10-19: fixed upstream by 095be159f3eb; 6.18 keeps it |
-| `dev-extent-defrag` | 1 | `34a8e85757bb` | Zygo | new, 0/1 (drafted 2026-10-18) | |
-| `prealloc-size` | 1 | `a69ecf626add` | Zygo | new, 0/1 (drafted 2026-10-18) | |
-| `raid56-fixes` | 12 | `796097dafc94` | Zygo | new; replaces `covers/raid56-rbio-fixes.txt` (2 of these patches) | **patch 12 is DO-NOT-UPSTREAM** (rbio cache size debug knob) |
-| `raid56-scrub-replace` | 12 | `b7b4005cacc4` | Zygo | new; 0/12 since 2026-10-25 | Filipe's -EIO fix (`ec0795c045c3`) is in the base now and was dropped from the series |
-| `stripe-alloc` | 116 | `bc8cd9cac405` | Zygo | rewritten 2026-10-22 by subtopic (rebuild planned, REORDER-PLAN.md) | RFC; subtopic 6 (debug) not for merging; stripe_meta may be dropped (STRIPE-META-CLAIMS.md) |
-| `low-space` | 3 | `087669d83341` | Zygo | from misc-next `covers/`, patch 3 paragraph added 2026-10-22 | reserve off by default; patch 3 fixes an upstream relocation abort (FLUSH_LIMIT merge refill) |
-| `dedupe-mtime` | 1 | `dcacae4b4bd8` | Ivan Kozik | new, 0/1 (drafted 2026-10-18) | Ivan's patch |
-| `dm-stripfault` | 2 | `0d13e1572fe7` | Zygo | new | **test fixtures, NOT for merge** (no `To:`) |
-| `allocator-hints` | 12 | `6944c7760536` | Kai Krakow, KeinNiemand, Zygo | new | Kai's series plus follow-ups; the authors' postings are authoritative |
-| `read-policies` | 9 | `ccf8a6c6d49b` | Kai Krakow | new | Kai's series; his postings are authoritative |
-| `replace-fixes` | 7 | `1c2676130104` | Zygo | new | patch 7 has a btrfs-progs counterpart (`topics/replace-abort-uncorrectable`) |
-| `dev-stats` | 1 | `a5160f442538` | Zygo | new, 0/1 (2026-10-21) | behaviour change, offered for rejection; independent of every other series |
-| `resize-missing` | 1 | `2d41f2a9495d` | Qu Wenruo, rewritten by Zygo | new, 0/1 (2026-10-21) | Qu's 2019 patch reworked: grow checks now return, absolute sizes checked; Zygo's Signed-off-by to be added before sending |
-| `read-repair-fixes` | 4 | `df4629dcf9ad` | Zygo | new 2026-10-22; 0/4 | read repair and scrub after an abort: NULL end_io (v6.3+), same csum root, no repair writes after abort; Cc stable on 1-2 only (the abort-write rule is under revision upstream); raid56 left as upstream |
+the integration recipe below uses. "on" names the series a stacked
+series applies on top of; the others apply to the base.
+
+| directory | patches | on | authors | notes |
+|---|---|---|---|---|
+| `logical-ino-costs` | 3 | | Zygo, Kai Krakow | patch 3 is Kai's, already posted by him |
+| `balance-resume` | 3 | | Zygo | patch 3 optional, offered for rejection |
+| `compress-fixes` | 5 | | Zygo | |
+| `deadlock-fixes` | 3 | | Zygo | the relock fix is folded into patch 2 (2026-10-30) |
+| `dedupe-fixes` | 1 | | Zygo | |
+| `delalloc-fixes` | 1 | | Zygo | |
+| `dev-extent-defrag` | 1 | | Zygo | |
+| `prealloc-size` | 1 | | Zygo | |
+| `raid56-fixes` | 12 | | Qu Wenruo, Zygo | patches 1-2 are Qu's (`git am --skip` them if merged first) |
+| `read-repair-fixes` | 4 | | Zygo | Cc stable on 1-2 only |
+| `raid56-scrub-replace` | 12 | `read-repair-fixes` | Zygo | |
+| `reclaim-fixes` | 3 | | Zygo | |
+| `stripe-alloc` | 85 | `reclaim-fixes` | Zygo | RFC; reordered by subtopic 2026-10-28; subtopic 6 (debug) not for merging; stripe_meta may be dropped |
+| `low-space` | 3 | `stripe-alloc` | Zygo | reserve off by default; patch 3 fixes an upstream relocation abort and stands alone |
+| `dedupe-mtime` | 1 | | Ivan Kozik | Ivan's patch |
+| `allocator-hints` | 12 | | Kai Krakow, KeinNiemand, Zygo | Kai's series plus follow-ups; the authors' postings are authoritative |
+| `read-policies` | 9 | | Kai Krakow | Kai's series; his postings are authoritative |
+| `replace-fixes` | 10 | | Zygo | patch 8 has a btrfs-progs counterpart |
+| `dev-stats` | 1 | | Zygo | behaviour change, offered for rejection |
+| `resize-missing` | 1 | | Qu Wenruo, rewritten by Zygo | Zygo's Signed-off-by to be added before sending |
+| `reflink-inline-fixes` | 2 | | Zygo | |
## Applying one series
```sh
cd ~/share/linux # any clone that has the base commit
-git checkout -b up/raid56-scrub-replace 99bc6552614f
+git checkout -b up/raid56-scrub-replace bf921b86bdf2
git am $(ls ~/share/linux-upstream/topics/raid56-scrub-replace/*.patch | grep -v 0000-cover-letter)
```
+A stacked series applies after the series it is on, on the same branch:
+`reclaim-fixes`, then `stripe-alloc`, then `low-space`; and
+`read-repair-fixes`, then `raid56-scrub-replace`. Their patches
+carry `prerequisite-patch-id:` lines for the series below them.
+
`git am` cannot apply the cover letter (it has no diff), so leave it out.
On a base that already contains a patch of the series, `git am` stops
at that patch; `git am --skip` drops it. Expected cases:
- `logical-ino-costs` patch 3 and the `allocator-hints` /
`read-policies` patches, if Kai's postings are merged first.
+- `raid56-fixes` patches 1-2, if Qu's postings are merged first.
## Integrating all series
-The series are independent branches on one base. Merged together, three
-of them conflict with series merged before them, and the lane's octopus
-merge also carries integration code that belongs to no single series.
-`fixups/post-merge.patch` holds both. Merge every series with
-`-X ours` (conflicting hunks keep the side merged so far), then apply the
-fixup:
+The series are branches on one base; three of them are stacked. Merged
+together, some conflict with series merged before them, and the lane's
+octopus merge also carries integration code that belongs to no single
+series. `fixups/post-merge.patch` holds both. Build each series on its
+own branch (a stacked one on top of the branch it is on), merge the
+branches that no other series is stacked on with `-X ours` (conflicting
+hunks keep the side merged so far), then apply the fixup:
```sh
cd ~/share/linux
P=~/share/linux-upstream
-B=99bc6552614f
+B=bf921b86bdf2
ORDER="logical-ino-costs balance-resume compress-fixes deadlock-fixes dedupe-fixes
- delalloc-fixes dev-extent-defrag prealloc-size raid56-fixes raid56-scrub-replace
- stripe-alloc low-space dedupe-mtime dm-stripfault allocator-hints read-policies
- replace-fixes dev-stats resize-missing read-repair-fixes"
+ delalloc-fixes dev-extent-defrag prealloc-size raid56-fixes read-repair-fixes
+ raid56-scrub-replace reclaim-fixes stripe-alloc low-space dedupe-mtime
+ allocator-hints read-policies replace-fixes dev-stats resize-missing
+ reflink-inline-fixes"
+declare -A ON=([raid56-scrub-replace]=read-repair-fixes
+ [stripe-alloc]=reclaim-fixes [low-space]=stripe-alloc)
for t in $ORDER; do
- git checkout -q -b up/$t $B
+ git checkout -q -b up/$t ${ON[$t]:+up/}${ON[$t]:-$B}
git am -q $(ls $P/topics/$t/*.patch | grep -v 0000-cover-letter)
done
git checkout -q -b up/testing $B
for t in $ORDER; do
+ case $t in read-repair-fixes|reclaim-fixes|stripe-alloc) continue ;; esac # stacked on
git merge -q --no-edit -X ours up/$t
done
git apply --index $P/fixups/post-merge.patch
git commit -m "post-merge fixups for the misc-next topics"
-git diff misc-next/testing # empty: same tree as the lane's testing
+git diff misc-next/testing # only the left-out commits ("What is not exported")
```
The series cannot be applied one after another on a single branch with
plain `git am`, because the later series conflict. Merging separate
branches is the supported way.
-Verified on the export: the patches of every directory, applied in order
-to `99bc6552614f`, give that branch's tree exactly. Merging all 20 in
-the order above with `-X ours` and applying `fixups/post-merge.patch`
-gives the tree of `misc-next/testing` exactly. The verification used
-git 2.47.
+What the export checks, every run:
+
+1. The patches of every directory, applied in order on the base (a
+ stacked series on top of the series it is on), give the tree of the
+ filtered branch.
+2. That tree equals the lane's branch with the left-out commits
+ reverted. For a series that lost nothing, the filtered branch is the
+ lane branch itself.
+3. Merging the series as above and applying `fixups/post-merge.patch`
+ gives the tree of `misc-next/testing` with the left-out commits
+ reverted. When nothing is left out of the octopus's topics, that is
+ `misc-next/testing` itself.
+
+The verification used git 2.47.
`fixups/post-merge.patch` is generated against git's `ort` merge results
with `-X ours`. If it does not apply (another git version may place a
### What the fixup contains
-The fixup adds 640 lines and removes 16, in 10 files.
+The fixup adds 636 lines and removes 2, in 6 files. None of it is new
+code: it is what `-X ours` drops from conflicting hunks, put back.
-1. **stripe-alloc merged after raid56-fixes** conflicts in `raid56.c`,
- `raid56.h`, `block-group.c` and `sysfs.c`.
+1. **stripe-alloc (in low-space) merged after raid56-fixes** conflicts in
+ `raid56.c`, `raid56.h` and `block-group.c`.
+ - `raid56.c`: stripe-alloc's RMW report and audit helpers
+ (`rmw_peek_eb_generation()`, `rmw_block_referenced()`,
+ `audit_uncovered_rmw()`, `report_uncovered_rmw()`) go after
+ `need_read_stripe_sectors()`, next to raid56-fixes' write-back
+ helpers (patch 12); keep both.
- `raid56.h`: keep both sets of declarations:
`btrfs_raid56_uncache_range()` from raid56-fixes, and the
parked-rbio and rbio-cache functions from stripe-alloc.
- - `cache_rbio()` in `raid56.c`: stripe-alloc's pinned rbios have to
- survive raid56-fixes' cache-size knob.
- - `rbio_needs_pin()` is evaluated first, so a cache size of 0 still
- keeps a pinned stripe ("even a disabled cache keeps a stripe its
- run has not finished").
- - raid56-fixes' prune loop becomes stripe-alloc's
- `rbio_cache_prune(table, rbio, limit)`.
- - `rmw_rbio()` in `raid56.c`: raid56-fixes' write-back helpers
- (patch 11) and stripe-alloc's RMW audit helpers are both inserted
- before `rmw_rbio()`; keep both, write-back's hunks inside
- `rmw_rbio()` unchanged.
- - `sysfs.c`: the debug attribute list keeps stripe-alloc's
- `stripe_rmw_audit` next to raid56-fixes' `rbio_cache_size`.
- - The `block-group.c` conflict needs nothing beyond what `-X ours`
- keeps. The fixup's `block-group.c` hunks all belong to item 2.
-2. **low-space merged after stripe-alloc** conflicts in `block-group.c`,
- `block-group.h`, `extent-tree.c`, `fs.h`, `space-info.c`,
- `space-info.h` and `sysfs.c`. The fixup also adds the integration of
- the two series, which exists only in the lane's octopus:
- - A group held for relocation counts only its claimable whole stripes
- as reserve, resynced at each commit-time stripe rescan. Its trapped
- space is already in `bytes_stripe_unusable`, and counting it twice
- made metadata read as over-full on a full raid6 filesystem.
- - Ordinary data writers' whole-stripe admission
- (`stripe_claimable_admit()`) excludes the held groups' stripes
- (`bytes_reloc_reserve`); relocation still sees them.
- - `bytes_reloc_reserve` joins `btrfs_space_info_used()`.
- - `reloc_adjusted_used()` is applied in `btrfs_can_overcommit()` and
- when granting tickets.
- - In `block-group.c`: `reloc_reserve_resync()` runs from the stripe
- rescan, and the read-only paths handle `BLOCK_GROUP_FLAG_RELOC_RESERVE`
- (`btrfs_reloc_reserve_rejoin()`). `block-group.h` gets the new flags.
- - `btrfs_reserve_extent()` passes `for_reloc` to `find_free_extent()`.
- - stripe_meta's `bytes_stripe_reserve` is not reduced by the held
- groups. It is an admission margin that keeps tree blocks off the
- reserve's emergency fallback.
+2. **stripe-alloc merged after delalloc-fixes** conflicts at the end of
+ `btrfs_inc_block_group_ro()` in `block-group.c`: on success the
+ group's stripe runs are retired (stripe-alloc), on failure the NOCOW
+ block is lifted (delalloc-fixes).
3. **read-policies merged after allocator-hints** conflicts in `Kconfig`,
`sysfs.c` and `volumes.c`. The resolution is the union of both series
(both add Kconfig options, devinfo sysfs attributes and `volumes.c`
- code), as on the 6.18 lane. Most of the fixup's `volumes.c` lines
- are read-policies code that `-X ours` dropped from the conflicting
- hunks.
+ code), as on the 6.18 lane. Most of the fixup's lines are
+ read-policies code that `-X ours` dropped from the conflicting hunks.
## Before sending
-- Drop `raid56-fixes` patch 12 and the whole `dm-stripfault` series.
-- `stripe-alloc`'s cover letter needs a rewrite.
-- `balance-resume` patch 3 is offered for rejection, as its cover letter
- says.
-- Re-export with `scripts/export.sh` after any lane change. The
- directories reflect the lane at `misc-next/testing` `e8519e93c9a2`.
- Commit the result with the misc-next SHAs that the script prints.
+- Nothing that is not for upstream is in `topics/`; check the "dropped"
+ list that `scripts/export.sh` prints.
+- `balance-resume` patch 3 and `dev-stats` are offered for rejection, as
+ their cover letters say.
+- `resize-missing` needs Zygo's Signed-off-by.
+- Re-export with `scripts/export.sh` after any lane change, and commit
+ the result with the misc-next SHAs that the script prints.
bool "Btrfs experimental features"
depends on BTRFS_FS
diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 681fd72ab9277ea30b95cb93999bb720f5e21230..f031f0329814ac9b13bdfae893275548f0e64ff1 100644
+index f6d8ae6db1f4327b2cce5271047bb62429dae51a..22daa929b07793056b5ab65f7a4edec1fcc69c8d 100644
--- a/fs/btrfs/block-group.c
+++ b/fs/btrfs/block-group.c
-@@ -3511,6 +3511,8 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
- * the counter can be made authoritative. Called after btrfs_finish_extent_commit
- * so the free space cache reflects this transaction's frees.
- */
-+static void reloc_reserve_resync(struct btrfs_block_group *bg);
-+
- void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- {
- struct btrfs_space_info *sinfo;
-@@ -3588,6 +3590,12 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- bg->stripe_claimable;
- nr_rw++;
- largest = max(largest, bg->length);
-+ if (test_bit(BLOCK_GROUP_FLAG_RELOC_RESERVE,
-+ &bg->runtime_flags)) {
-+ spin_lock(&bg->lock);
-+ reloc_reserve_resync(bg);
-+ spin_unlock(&bg->lock);
-+ }
- }
- unit = max(unit, bg->full_stripe_len);
- }
-@@ -4828,6 +4836,13 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
- */
- if (sinfo_used - trapped + num_bytes <= sinfo->total_bytes)
- ret = 0;
-+ /*
-+ * Or relocation has somewhere to put this group's live data:
-+ * that is what the relocation reserve is for, and a full
-+ * filesystem is exactly when the group needs relocating.
-+ */
-+ else if (sinfo->bytes_reloc_reserve >= cache->used)
-+ ret = 0;
-
- /*
- * The stripe_alloc gate admitted writers against whole
-@@ -7201,7 +7216,15 @@ int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
+@@ -7202,7 +7202,15 @@ int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
mutex_unlock(&fs_info->ro_block_group_mutex);
btrfs_end_transaction(trans);
btrfs_bg_unblock_nocow(cache);
return ret;
}
-@@ -7229,6 +7252,7 @@ void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
- sinfo->bytes_readonly -= btrfs_block_group_available_space(cache);
- list_del_init(&cache->ro_list);
- became_rw = true;
-+ btrfs_reloc_reserve_rejoin(cache);
- }
- spin_unlock(&cache->lock);
- spin_unlock(&sinfo->lock);
-@@ -8836,6 +8860,30 @@ static bool reloc_reserve_wanted(struct btrfs_fs_info *fs_info,
- return READ_ONCE(sinfo->reloc_reserve);
- }
-
-+/*
-+ * Under stripe_alloc / stripe_meta only a held group's whole claimable
-+ * stripes are relocation room; its trapped free space is counted in
-+ * bytes_stripe_unusable already, and counting it here too made the reserve
-+ * look full while relocation found no stripe to claim (claimable 3.3M
-+ * against a 34M reserve). Resync the group's share to its claimable
-+ * stripes at each commit-time rescan. Caller holds space_info->lock and
-+ * @bg->lock.
-+ */
-+static void reloc_reserve_resync(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_space_info *sinfo = bg->space_info;
-+ u64 want;
-+
-+ if (!test_bit(BLOCK_GROUP_FLAG_RELOC_RESERVE, &bg->runtime_flags) ||
-+ !READ_ONCE(bg->stripe_unusable_ready))
-+ return;
-+ want = min(reloc_reserve_free(bg), READ_ONCE(bg->stripe_claimable));
-+ sinfo->bytes_reloc_reserve -= min(sinfo->bytes_reloc_reserve,
-+ bg->reloc_reserve_bytes);
-+ bg->reloc_reserve_bytes = want;
-+ sinfo->bytes_reloc_reserve += want;
-+}
-+
- /*
- * @bg left the reserve to go read-only and is writable again (or never went
- * read-only): rejoin, unless the reserve is off. A surplus this makes is
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index c1aae3e1e396b859c368b0a1a1fe3f9e1000cf69..099df2453aa8e3093fc22da48a235c4877c19899 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -163,6 +163,16 @@ enum btrfs_block_group_flags {
- * write-hole debug check skips such groups (sticky, debug only).
- */
- BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED,
-+ /*
-+ * Held empty for relocation: only relocation may allocate here (see
-+ * btrfs_reloc_reserve_update()).
-+ */
-+ BLOCK_GROUP_FLAG_RELOC_RESERVE,
-+ /*
-+ * Left the relocation reserve to go read-only (scrub, replace, a
-+ * relocation that failed): rejoins it when writable again.
-+ */
-+ BLOCK_GROUP_FLAG_RELOC_RESERVE_LAPSED,
- /*
- * A RAID5/6 group with a single data stripe, which is mapped as
- * RAID1/RAID1C3 (its chunk map's type differs from on_disk_type). Its
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index cd3073cc60fe361602e0a154f1e7085dd76a4cc2..cfc0d9a2169a4448eb13ce64128db7adb00cc4f9 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -5152,6 +5152,7 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- u64 log_owner = for_treelog ? root->root_key.offset : 0;
- u64 log_transid = for_treelog ? root->log_transid : 0;
- bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
-+ bool use_reloc_reserve = false;
- struct btrfs_inode *steer_inode = NULL;
- enum btrfs_stripe_run_class steer_class = BTRFS_STRIPE_RUN_COW;
-
-@@ -5207,6 +5208,8 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- ffe_ctl.for_data_reloc = for_data_reloc;
- ffe_ctl.steer_inode = steer_inode;
- ffe_ctl.steer_class = steer_class;
-+ ffe_ctl.for_reloc = for_data_reloc || btrfs_is_reloc_task(fs_info) ||
-+ use_reloc_reserve;
-
- ret = find_free_extent(root, ins, &ffe_ctl);
- if (!ret && !is_data) {
diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 7cd95d273947a8d3b909ee5b12e1cb3fe5e57fa0..1aa93286f75b929e2a15ea07618778289f670c6f 100644
+index 39f391774a6964e067027434e79d0a0a39bc220e..e16368e6e8f3c93e4633b97e03dee4e4394612b0 100644
--- a/fs/btrfs/raid56.c
+++ b/fs/btrfs/raid56.c
-@@ -995,13 +995,15 @@ static void cache_rbio(struct btrfs_raid_bio *rbio)
- {
- struct btrfs_stripe_hash_table *table;
- const unsigned int limit = rbio_cache_limit(rbio->bioc->fs_info);
-+ bool pin;
-
- if (!test_bit(RBIO_CACHE_READY_BIT, &rbio->flags))
- return;
-- if (!limit)
-+ pin = rbio_needs_pin(rbio);
-+ /* Even a disabled cache keeps a stripe its run has not finished. */
-+ if (!limit && !pin)
- return;
-
-- pin = rbio_needs_pin(rbio);
- table = rbio->bioc->fs_info->stripe_hash_table;
-
- spin_lock(&table->cache_lock);
-@@ -1024,18 +1026,8 @@ static void cache_rbio(struct btrfs_raid_bio *rbio)
-
- spin_unlock(&rbio->bio_list_lock);
-
-- /* A loop, not one eviction: the limit can have been lowered. */
-- while (table->cache_size > limit) {
-- struct btrfs_raid_bio *found;
--
-- found = list_last_entry(&table->stripe_cache,
-- struct btrfs_raid_bio,
-- stripe_cache);
--
-- if (found == rbio)
-- break;
-- __remove_rbio_from_cache(found);
-- }
-+ /* Prunes as far as needed: the limit can have been lowered. */
-+ rbio_cache_prune(table, rbio, limit);
-
- spin_unlock(&table->cache_lock);
- }
-@@ -4049,6 +4041,258 @@ static bool need_read_stripe_sectors(struct btrfs_raid_bio *rbio)
+@@ -3935,6 +3935,258 @@ static bool need_read_stripe_sectors(struct btrfs_raid_bio *rbio)
return false;
}
* Return true if the rebuild of data sector @sector_nr of @stripe_nr can be
* trusted enough to write it back. It can when the sector has a csum: the
diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index 28241c31faa28bb6e68b1fe309e0901c280b986d..a00ef6881ce51e57c4305d5154583ddc580678f3 100644
+index 92e364e9e649292a2d3704a765b1e41842d22eaf..f1102e34a302ae6d091ea07fb3b2cb05e6e835d3 100644
--- a/fs/btrfs/raid56.h
+++ b/fs/btrfs/raid56.h
-@@ -329,5 +329,11 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_set_rbio_cache_size(struct btrfs_fs_info *info, unsigned int size);
- #endif
+@@ -334,5 +334,11 @@ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
+ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
+ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
void btrfs_raid56_uncache_range(struct btrfs_fs_info *info, u64 start, u64 len);
+void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
+ u64 num_bytes, bool force);
+void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info);
#endif
-diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 5801b68037a08e36a68939353ccd01d5767de4ed..4cd4f5a58dd3a71bc241410e67d111597e863400 100644
---- a/fs/btrfs/scrub.c
-+++ b/fs/btrfs/scrub.c
-@@ -1297,7 +1297,8 @@ static void scrub_stripe_read_repair_worker(struct work_struct *work)
- bitmap_andnot(&repaired, &errors.init_error_bitmap, &error,
- stripe->nr_sectors);
- if (!sctx->readonly && !bitmap_empty(&repaired, stripe->nr_sectors) &&
-- !test_bit(SCRUB_STRIPE_FLAG_OWN_SCRUB, &stripe->state)) {
-+ !test_bit(SCRUB_STRIPE_FLAG_OWN_SCRUB, &stripe->state) &&
-+ btrfs_can_submit_repair_write(fs_info)) {
- if (btrfs_is_zoned(fs_info)) {
- btrfs_repair_one_zone(fs_info, sctx->stripes[0].bg->start);
- } else {
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index c0273a10a97035d85e5cb1d3de4823787aead125..9f1809b9a598fbd15405e4b1e177d3c9af30b4cd 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -694,6 +694,7 @@ bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
- */
- if (reloc)
- used -= min(used, space_info->bytes_stripe_reserve);
-+ used = reloc_adjusted_used(space_info, used, reloc);
-
- return check_can_overcommit(space_info, used, bytes, flush);
- }
-@@ -772,6 +773,12 @@ static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 byte
- } else {
- /* ...and that group is out of reach for everyone else */
- supply -= min(supply, dedicated);
-+ /*
-+ * ...and so are the groups held for relocation (the
-+ * relocation reserve): whole stripes, but relocation's.
-+ */
-+ supply -= min(supply,
-+ READ_ONCE(space_info->bytes_reloc_reserve));
- /*
- * An allocation that opens a run claims
- * round_up(bytes, unit). A delalloc write's margin
-@@ -822,6 +829,7 @@ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info)
- tused = used;
- if (ticket->reloc)
- tused -= min(tused, space_info->bytes_stripe_reserve);
-+ tused = reloc_adjusted_used(space_info, tused, ticket->reloc);
-
- /* Check and see if our ticket can be satisfied now. */
- if ((tused + ticket->bytes <= space_info->total_bytes ||
-@@ -2141,7 +2149,6 @@ static int __reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
- space_info->reclaim_size += ticket.bytes;
- init_waitqueue_head(&ticket.wait);
- spin_lock_init(&ticket.lock);
-- ticket.reloc = reloc;
- ticket.steal = can_steal(flush);
- ticket.reloc = reloc;
- ticket.mount_cleanup =
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 63dd1dc79bef527c3daa470b29b84f535f96c0ca..88141644027aa0f87e08512f64b88cd328a14e97 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -382,7 +382,7 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
-
- return s_info->bytes_used + s_info->bytes_reserved +
- s_info->bytes_pinned + s_info->bytes_readonly +
-- s_info->bytes_zone_unusable +
-+ s_info->bytes_zone_unusable + s_info->bytes_reloc_reserve +
- s_info->bytes_stripe_unusable + s_info->bytes_stripe_open +
- s_info->bytes_stripe_margin +
- s_info->bytes_stripe_reserve +
diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 6c16cc96ff1fea35fe02dffbb0186ce574635744..5edefae1dd1c850306250226c6d4bcfe395f9a80 100644
+index 1644b1edfe15a6f98308e7377a40e9ebd520274d..90b62d7d59ffe1546cf1e27a5dd5cc873acc96cd 100644
--- a/fs/btrfs/sysfs.c
+++ b/fs/btrfs/sysfs.c
-@@ -616,6 +616,8 @@ BTRFS_ATTR(debug_mount, stripe_rmw_audit_stats,
- * Path: /sys/fs/btrfs/UUID/debug/
- */
- static const struct attribute *btrfs_debug_mount_attrs[] = {
-+ BTRFS_ATTR_PTR(debug_mount, stripe_rmw_audit),
-+ BTRFS_ATTR_PTR(debug_mount, stripe_rmw_audit_stats),
- BTRFS_ATTR_PTR(debug_mount, rbio_cache_size),
- NULL,
- };
-@@ -917,6 +919,7 @@ SPACE_INFO_ATTR(bytes_stripe_claimable);
- SPACE_INFO_ATTR(bytes_stripe_open);
- SPACE_INFO_ATTR(bytes_stripe_margin);
- SPACE_INFO_ATTR(bytes_stripe_reserve);
-+SPACE_INFO_ATTR(bytes_reloc_reserve);
- SPACE_INFO_ATTR(disk_used);
- SPACE_INFO_ATTR(disk_total);
- SPACE_INFO_ATTR(reclaim_count);
-@@ -2651,6 +2654,61 @@ static ssize_t btrfs_devinfo_type_store(struct kobject *kobj,
+@@ -2577,6 +2577,61 @@ static ssize_t btrfs_devinfo_type_store(struct kobject *kobj,
BTRFS_ATTR_RW(devid, type, btrfs_devinfo_type_show, btrfs_devinfo_type_store);
#endif /* CONFIG_BTRFS_ALLOCATOR_HINTS */
* Information about one device.
*
diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
-index babe6ad81716978f45a6f8f3b65fc745ee18dfe7..a966de1270bcb32580d5365bca1b3887a16207b9 100644
+index c1eb4f95ce7b9811c24d8ded80e3a0387ee900ce..9b09e06dd7587301f14706684721046e8800ca51 100644
--- a/fs/btrfs/volumes.c
+++ b/fs/btrfs/volumes.c
-@@ -6937,7 +6937,293 @@ bool btrfs_chunk_raid56_mirrored(struct btrfs_fs_info *fs_info, u64 logical)
+@@ -6967,7 +6967,293 @@ bool btrfs_chunk_raid56_mirrored(struct btrfs_fs_info *fs_info, u64 logical)
return ret;
}
--- /dev/null
+# What scripts/export.sh leaves out, besides the commits that carry the
+# marker (DO-NOT-UPSTREAM in the subject or body, or "drop(ped) before
+# upstream" in the body). One entry per line:
+#
+# topic <branch> the whole topic (it is removed from topics/)
+# subject <subject> the commit with exactly this subject, in any topic
+#
+# Give each entry the date and the reason. Prefer marking the lane commit;
+# a subject entry is for a ruling the lane has not caught up with yet.
+
+# dm-stripfault: test fixtures (dm-stripfault target, sysfs force_fs_error).
+# Both commits carry the marker; listed so the topic directory goes too.
+topic dm-stripfault
+
+# test-knobs: Zygo 2026-10-29 ruled the reclaim exclusive-operation gap
+# DO-NOT-UPSTREAM ("I'll defer to upstream on what they want to do about
+# reclaim starvation"); the 2026-10-30 restructure moved it, with the
+# raid56 rbio cache size knob, into this test-only topic. Both commits
+# carry the marker; listed so the topic directory never appears.
+topic test-knobs
#!/bin/bash
-# Re-export misc-next/topics/* into topics/<branch>/ and regenerate
+# Re-export the misc-next topic branches into topics/<branch>/ and regenerate
# fixups/post-merge.patch. Run from anywhere; needs ~/share/linux.
#
# Cover letters live HERE (topics/<branch>/0000-cover-letter.patch) and are
# sending; a changed patch count is reported (the body may need updating).
# Single-patch series get a 0/1 cover once one has been written for them.
# Every other non-patch file in topics/<branch>/ (TESTING.md) is kept.
+#
+# Left out (see README.md, "What is not exported"):
+# - every commit whose subject or body carries the marker
+# ($MARK below: "DO-NOT-UPSTREAM" in any spelling, or
+# "drop(ped) before upstream");
+# - the topics and commit subjects listed in scripts/exclude.txt.
+# The later commits of a topic are re-applied without the dropped ones
+# (git merge-tree, objects only: no ref is created or moved). A commit
+# that no longer applies stops the export; nothing is hand-resolved here.
+#
+# Stacked topics: a topic whose lane branch contains another topic's branch
+# is exported as the commits on top of that topic (its export parent), with
+# --base set to the lane base, so format-patch adds prerequisite-patch-id
+# lines for the parent's patches.
+#
+# Environment:
+# OUT output directory (default: this worktree). Use a scratch
+# directory for dry runs: everything below $OUT/topics and
+# $OUT/fixups that belongs to an exported or excluded topic
+# is rewritten.
+# SRC the kernel repository (default ~/share/linux)
+# TESTING the integration ref (default misc-next/testing); its first
+# parent is the base, the others are the topic tips
+# PFX ref prefix of the topic branches (default
+# refs/heads/misc-next/topics/)
+# EXCLUDE the exclusion list (default scripts/exclude.txt)
set -e -o pipefail
-OUT=$(cd "$(dirname "$0")/.." && pwd)
+HERE=$(cd "$(dirname "$0")/.." && pwd)
+OUT=${OUT:-$HERE}
+EXCLUDE=${EXCLUDE:-$HERE/scripts/exclude.txt}
SRC=${SRC:-$HOME/share/linux}
+TESTING=${TESTING:-misc-next/testing}
+PFX=${PFX:-refs/heads/misc-next/topics/}
+MARK='DO[-_ ]?NOT[-_ ]?UPSTREAM|dropp?(ed)? before upstream'
cd "$SRC"
-B=$(git rev-parse misc-next/testing^1)
-SAVE=$(mktemp -d); trap 'rm -rf "$SAVE"' EXIT
-for f in "$OUT"/topics/*/0000-cover-letter.patch; do
- [ -e "$f" ] || continue
- t=$(basename "$(dirname "$f")"); cp "$f" "$SAVE/$t"
+B=$(git rev-parse "$TESTING^1")
+TESTING_SHA=$(git rev-parse "$TESTING")
+TMP=$(mktemp -d); trap 'rm -rf "$TMP"' EXIT
+die() { echo "STOP: $*" >&2; exit 1; }
+
+# --- the exclusion list
+declare -A XTOPIC XSUBJ XSUBJ_HIT
+while IFS= read -r l; do
+ l=${l%%#*}; l=${l%"${l##*[![:space:]]}"}
+ [ -n "$l" ] || continue
+ case $l in
+ topic\ *) XTOPIC[${l#topic }]=1 ;;
+ subject\ *) XSUBJ[${l#subject }]=1 ;;
+ *) die "$EXCLUDE: cannot parse '$l'" ;;
+ esac
+done < <([ -e "$EXCLUDE" ] && cat "$EXCLUDE")
+
+# --- topics in the merge order of $TESTING
+order=$(for p in $(git log -1 --format=%P "$TESTING" | cut -d' ' -f2-); do
+ t=$(git for-each-ref --points-at "$p" --format='%(refname)' "$PFX" | head -1)
+ [ -n "$t" ] || die "testing parent $p is not a topic tip under $PFX"
+ echo "${t#"$PFX"}"
+done)
+
+declare -A NEWTIP EXPPARENT LANEPARENT
+dropped=() # "topic<TAB>sha<TAB>why<TAB>subject"
+exported=()
+for t in $order; do
+ tip=$(git rev-parse "$PFX$t")
+ [ "$(git rev-list --count --merges "$B..$tip")" = 0 ] || die "$t has merge commits"
+ # export parent: the processed topic with the most commits that this one contains
+ lp=$B; best=0; par=
+ for q in $order; do
+ [ "$q" = "$t" ] && break
+ qt=$(git rev-parse "$PFX$q")
+ git merge-base --is-ancestor "$qt" "$tip" || continue
+ n=$(git rev-list --count "$B..$qt")
+ [ "$n" -gt "$best" ] && { best=$n; lp=$qt; par=$q; }
+ done
+ if [ -n "${XTOPIC[$t]}" ]; then
+ for c in $(git rev-list --reverse "$lp..$tip"); do
+ dropped+=("$t $c topic in exclude.txt $(git log -1 --format=%s "$c")")
+ done
+ NEWTIP[$t]=EXCLUDED
+ continue
+ fi
+ if [ -n "$par" ]; then
+ [ "${NEWTIP[$par]}" = EXCLUDED ] && die "$t is stacked on $par, which is excluded"
+ new=${NEWTIP[$par]}
+ else
+ new=$B
+ fi
+ EXPPARENT[$t]=$new; LANEPARENT[$t]=$par
+ for c in $(git rev-list --reverse "$lp..$tip"); do
+ s=$(git log -1 --format=%s "$c")
+ why=
+ if git log -1 --format=%B "$c" | grep -qiE "$MARK"; then why=marker
+ elif [ -n "${XSUBJ[$s]}" ]; then why="subject in exclude.txt"; XSUBJ_HIT[$s]=1
+ fi
+ if [ -n "$why" ]; then
+ dropped+=("$t $c $why $s")
+ continue
+ fi
+ if [ "$(git rev-parse "$c^")" = "$new" ]; then
+ new=$c # nothing dropped below it: the lane commit itself
+ continue
+ fi
+ if ! tree=$(git merge-tree --write-tree --name-only --merge-base="$c^" "$new" "$c" 2>&1); then
+ echo "$tree" | sed -n '2,/^$/p' > "$TMP/conflicts"
+ die "$t: $(git log -1 --format='%h ("%s")' "$c") does not apply without the dropped commits (conflicts in: $(grep . "$TMP/conflicts" | sort -u | tr "\n" " "))"
+ fi
+ tree=$(echo "$tree" | head -1)
+ git cat-file commit "$c" | sed '1,/^$/d' > "$TMP/msg"
+ new=$(GIT_AUTHOR_NAME="$(git log -1 --format=%an "$c")" \
+ GIT_AUTHOR_EMAIL="$(git log -1 --format=%ae "$c")" \
+ GIT_AUTHOR_DATE="$(git log -1 --format=%ad --date=raw "$c")" \
+ GIT_COMMITTER_NAME="$(git log -1 --format=%cn "$c")" \
+ GIT_COMMITTER_EMAIL="$(git log -1 --format=%ce "$c")" \
+ GIT_COMMITTER_DATE="$(git log -1 --format=%cd --date=raw "$c")" \
+ git commit-tree "$tree" -p "$new" -F "$TMP/msg")
+ done
+ NEWTIP[$t]=$new
+ exported+=("$t")
+done
+for s in "${!XSUBJ[@]}"; do
+ [ -n "${XSUBJ_HIT[$s]}" ] || echo "NOTE exclude.txt: no commit has the subject '$s' (stale entry?)" >&2
+done
+
+for x in "${dropped[@]}"; do
+ IFS=' ' read -r t c why s <<< "$x"
+ echo "dropped $t $(git rev-parse --short=12 "$c") [$why] $s"
+done
+
+# --- post-merge fixup: the exported series merged in order, against
+# $TESTING with the dropped commits reverted. A series that a later one
+# is stacked on is merged as part of that one, not on its own.
+# Computed before anything is written, so that a STOP leaves $OUT alone.
+acc=$B
+for t in "${exported[@]}"; do
+ leaf=1
+ for u in "${exported[@]}"; do [ "${LANEPARENT[$u]}" = "$t" ] && leaf=; done
+ [ -n "$leaf" ] || continue
+ tree=$(git merge-tree --write-tree -X ours --merge-base="$B" "$acc" "${NEWTIP[$t]}" | head -1)
+ acc=$(git commit-tree "$tree" -p "$acc" -p "${NEWTIP[$t]}" -m "merge $t")
+done
+target=$TESTING_SHA
+RESOLVED=()
+for ((i=${#dropped[@]}-1; i>=0; i--)); do
+ IFS=' ' read -r t c why s <<< "${dropped[$i]}"
+ res=$HERE/scripts/revert-resolutions/$(git rev-parse "$c").patch
+ if tree=$(git merge-tree --write-tree --name-only --merge-base="$c" "$target" "$c^" 2>&1); then
+ tree=$(echo "$tree" | head -1)
+ elif [ -e "$res" ]; then
+ # a stored resolution: the conflicted files are taken from the
+ # target before this revert and the resolution diff is applied
+ echo "$tree" | sed -n '2,/^$/p' | grep . | sort -u > "$TMP/cfiles"
+ git apply --numstat "$res" | cut -f3 | sort -u > "$TMP/rfiles"
+ cmp -s "$TMP/cfiles" "$TMP/rfiles" || die "fixup: $(basename "$res") covers $(tr '\n' ' ' < "$TMP/rfiles")but the revert of $c conflicts in $(tr '\n' ' ' < "$TMP/cfiles")"
+ export GIT_INDEX_FILE=$TMP/index
+ git read-tree "$(echo "$tree" | head -1)"
+ while read -r f; do
+ git update-index --cacheinfo "$(git ls-tree "$target" -- "$f" | cut -f1 | awk '{print $1","$3}')","$f"
+ done < "$TMP/cfiles"
+ git apply --cached "$res" || die "fixup: $(basename "$res") does not apply"
+ tree=$(git write-tree)
+ unset GIT_INDEX_FILE
+ echo "NOTE fixup: revert of $(git rev-parse --short=12 "$c") resolved with scripts/revert-resolutions/$(basename "$res")" >&2
+ RESOLVED+=("$c")
+ else
+ die "fixup: $TESTING cannot be reverted mechanically without $t $(git log -1 --format='%h ("%s")' "$c") (conflicts in: $(echo "$tree" | sed -n '2,/^$/p' | tr '\n' ' ')); the integration carries code for a dropped commit; add a resolution as scripts/revert-resolutions/$(git rev-parse "$c").patch (README.md)"
+ fi
+ target=$(git commit-tree "$tree" -p "$target" -m "revert $c")
+done
+
+# --- write the series
+mkdir -p "$OUT/topics" "$OUT/fixups"
+SAVE=$TMP/covers; mkdir -p "$SAVE"
+for t in $order; do
+ d=$OUT/topics/$t
+ if [ "${NEWTIP[$t]}" = EXCLUDED ]; then
+ [ -d "$d" ] && { rm -rf "$d"; echo "NOTE $t: excluded, topics/$t removed" >&2; }
+ continue
+ fi
+ [ -e "$d/0000-cover-letter.patch" ] && cp "$d/0000-cover-letter.patch" "$SAVE/$t"
+ [ -d "$d" ] && find "$d" -maxdepth 1 -name '*.patch' -delete
done
for d in "$OUT"/topics/*/; do
[ -d "$d" ] || continue
t=$(basename "$d")
- for f in "$d"*; do
- case $f in *.patch) continue ;; esac
- mkdir -p "$SAVE/keep/$t"; cp -a "$f" "$SAVE/keep/$t/"
- done
+ echo " $order " | tr '\n' ' ' | grep -q " $t " || echo "NOTE topics/$t is not a topic of $TESTING; left as it is" >&2
done
-rm -rf "$OUT/topics" "$OUT/fixups"; mkdir -p "$OUT/topics" "$OUT/fixups"
-order=$(for p in $(git log -1 --format=%P misc-next/testing | cut -d' ' -f2-); do
- git for-each-ref --points-at "$p" --format='%(refname:short)' refs/heads/misc-next/topics/ | sed 's|misc-next/topics/||'
-done)
-for t in $order; do
- tip=misc-next/topics/$t; n=$(git rev-list --count "$B..$tip"); d=$OUT/topics/$t
- args=(--base="$B" -o "$d" --quiet)
- [ "$t" = dm-stripfault ] || args+=(--to=linux-btrfs@vger.kernel.org)
+for t in "${exported[@]}"; do
+ from=${EXPPARENT[$t]}; tip=${NEWTIP[$t]}; d=$OUT/topics/$t
+ n=$(git rev-list --count "$from..$tip")
+ if [ "$n" = 0 ]; then
+ echo "NOTE $t: nothing left to export" >&2; continue
+ fi
+ args=(--base="$B" -o "$d" --quiet --to=linux-btrfs@vger.kernel.org)
[ "$t" = stripe-alloc ] && args+=(--subject-prefix="RFC PATCH")
if [ "$n" -gt 1 ] || [ -e "$SAVE/$t" ]; then
- git format-patch "${args[@]}" --cover-letter "$B..$tip"
+ git format-patch "${args[@]}" --cover-letter "$from..$tip"
if [ -e "$SAVE/$t" ]; then
python3 -I - "$SAVE/$t" "$d/0000-cover-letter.patch" "$n" "$t" <<'PY'
import sys, re
echo "NOTE $t: new cover letter needed (placeholder left)" >&2
fi
else
- git format-patch "${args[@]}" "$B..$tip"
+ git format-patch "${args[@]}" "$from..$tip"
fi
- [ -d "$SAVE/keep/$t" ] && cp -a "$SAVE/keep/$t/." "$d/"
- echo "$t $n $(git rev-parse --short=12 "$tip")"
-done
-acc=$B
-for t in $order; do
- tip=$(git rev-parse "misc-next/topics/$t")
- tree=$(git merge-tree --write-tree -X ours --merge-base="$B" "$acc" "$tip" | head -1)
- acc=$(git commit-tree "$tree" -p "$acc" -p "$tip" -m "merge $t")
+ echo "$t $n $(git rev-parse --short=12 "$PFX$t")${LANEPARENT[$t]:+ on ${LANEPARENT[$t]}}"
done
-git diff --full-index "$acc" misc-next/testing > "$OUT/fixups/post-merge.patch"
-# verify: patches reproduce each topic, fixup reproduces testing
-idx=$(mktemp); rm -f "$idx"
-for t in $order; do
+
+git diff --full-index "$acc" "$target" > "$OUT/fixups/post-merge.patch"
+
+# --- verify
+# 1. each series, applied after its export parents' series, gives the
+# exported tip's tree;
+# 2. that tree is the lane topic's tree with the dropped commits reverted
+# (the lane topic's tree itself when nothing was dropped below it);
+# 3. the merged series plus the fixup give $TESTING minus the dropped commits.
+idx=$TMP/index
+for t in "${exported[@]}"; do
+ chain=($t); p=${LANEPARENT[$t]}
+ while [ -n "$p" ]; do chain=("$p" "${chain[@]}"); p=${LANEPARENT[$p]}; done
GIT_INDEX_FILE=$idx git read-tree "$B"
- for p in "$OUT"/topics/$t/*.patch; do
- case $p in */0000-cover-letter.patch) continue ;; esac
- GIT_INDEX_FILE=$idx git apply --cached "$p"
+ for u in "${chain[@]}"; do
+ for f in "$OUT"/topics/$u/*.patch; do
+ [ -e "$f" ] || continue
+ case $f in */0000-cover-letter.patch) continue ;; esac
+ GIT_INDEX_FILE=$idx git apply --cached "$f" || die "verify: $f does not apply"
+ done
+ done
+ got=$(GIT_INDEX_FILE=$idx git write-tree)
+ [ "$got" = "$(git rev-parse "${NEWTIP[$t]}^{tree}")" ] || die "verify: $t patches != exported tip"
+ want=$(git rev-parse "$PFX$t")
+ for x in "${dropped[@]}"; do
+ IFS=' ' read -r u c why s <<< "$x"
+ git merge-base --is-ancestor "$c" "$PFX$t" || continue
+ tree=$(git merge-tree --write-tree --name-only --merge-base="$c" "$want" "$c^" | head -1) || die "verify: $t minus $c does not revert cleanly"
+ want=$(git commit-tree "$tree" -p "$want" -m "revert $c")
done
- [ "$(GIT_INDEX_FILE=$idx git write-tree)" = "$(git rev-parse "misc-next/topics/$t^{tree}")" ] || { echo "VERIFY FAILED: $t" >&2; exit 1; }
+ [ "$got" = "$(git rev-parse "$want^{tree}")" ] || die "verify: $t patches != lane topic minus the dropped commits"
done
GIT_INDEX_FILE=$idx git read-tree "$acc"
-GIT_INDEX_FILE=$idx git apply --cached "$OUT/fixups/post-merge.patch"
-[ "$(GIT_INDEX_FILE=$idx git write-tree)" = "$(git rev-parse "misc-next/testing^{tree}")" ] || { echo "VERIFY FAILED: post-merge" >&2; exit 1; }
-rm -f "$idx"
-echo "verified; base $(git rev-parse --short=12 "$B") testing $(git rev-parse --short=12 misc-next/testing) zb64 $(git rev-parse --short=12 zygo-misc-next-zb64)"
+if [ -s "$OUT/fixups/post-merge.patch" ]; then
+ GIT_INDEX_FILE=$idx git apply --cached "$OUT/fixups/post-merge.patch"
+fi
+[ "$(GIT_INDEX_FILE=$idx git write-tree)" = "$(git rev-parse "$target^{tree}")" ] || die "verify: post-merge"
+echo "fixup target: tree $(git rev-parse "$target^{tree}") (testing without the dropped commits${RESOLVED:+; ${#RESOLVED[@]} revert(s) by stored resolution})"
+echo "fixup: $(git diff --shortstat "$acc" "$target" | sed 's/^ //;s/^$/empty/')"
+echo "verified; base $(git rev-parse --short=12 "$B") testing $(git rev-parse --short=12 "$TESTING") zb64 $(git rev-parse --short=12 zygo-misc-next-zb64)"
--- /dev/null
+Resolution for reverting test-knobs 3213446fec93 ("DO-NOT-UPSTREAM:
+btrfs: raid56: debug knob for the rbio stripe cache size") from
+misc-next/testing when computing the fixup target (2026-10-30).
+
+The knob's raid56.h declaration sits right above raid56-fixes'
+btrfs_raid56_uncache_range() line in the octopus, so the mechanical
+revert conflicts there. The resolution removes only the knob's three
+lines. The diff is against the file as it is in the target before
+this revert (here: misc-next/testing d88841f5cf02); export.sh takes
+the conflicted files from there and applies this diff. It is keyed
+by the full commit SHA, so any change to the commit makes it unused
+and the export stops again.
+
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index 5ff1c09..f1102e3 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -333,9 +333,6 @@ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
+
+ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
+ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
+-#ifdef CONFIG_BTRFS_DEBUG
+-void btrfs_set_rbio_cache_size(struct btrfs_fs_info *info, unsigned int size);
+-#endif
+ void btrfs_raid56_uncache_range(struct btrfs_fs_info *info, u64 start, u64 len);
+ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
+ u64 num_bytes, bool force);
-From 6944c77605368854e644f8c961ad38ffb741d873 Mon Sep 17 00:00:00 2001
+From b3af80d4e58b937314a4840129845611db1b825e Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:46 -0400
+Date: Fri, 30 Oct 2026 22:32:40 -0400
Subject: [PATCH 00/12] btrfs: allocator hints (Kai Krakow's series, as carried on misc-next)
To: linux-btrfs@vger.kernel.org
Patch 11 stores a changed type without running a transaction from the
sysfs store: the device is marked dirty (BTRFS_DEV_STATE_TYPE_DIRTY) and
the item is written by the next commit. Running a transaction from the
-store deadlocked against device remove.
+store deadlocked against device remove. The store orders the new type
+before the dirty bit, so a commit cannot write the old type and clear
+the bit.
Patch 12 makes the available space estimates honor the hints. The
allocator keeps data off METADATA_ONLY and NONE_ONLY devices and
fs/btrfs/dev-replace.c | 9 ++
fs/btrfs/space-info.c | 3 +-
fs/btrfs/super.c | 4 +
- fs/btrfs/sysfs.c | 99 +++++++++++++++
+ fs/btrfs/sysfs.c | 104 +++++++++++++++
fs/btrfs/transaction.c | 3 +
- fs/btrfs/volumes.c | 280 ++++++++++++++++++++++++++++++++++++++---
+ fs/btrfs/volumes.c | 282 ++++++++++++++++++++++++++++++++++++++---
fs/btrfs/volumes.h | 58 ++++++++-
- 8 files changed, 490 insertions(+), 20 deletions(-)
+ 8 files changed, 496 insertions(+), 21 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From 047b7c947d423dd8f3246d42d2aa48862b1a9ab8 Mon Sep 17 00:00:00 2001
+From af409ce5aeba16510d02a8c344f94001beabe239 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Fri, 10 Jul 2026 23:49:05 +0200
Subject: [PATCH 01/12] btrfs: add new Kconfig option for btrfs allocator hints
-From 3a82701b991baee17492c8fdb1911cef9d9a5344 Mon Sep 17 00:00:00 2001
+From 87fc4b5c2c1974db3f65fb1efc730af62045eeb2 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Sat, 11 Jul 2026 00:51:17 +0200
Subject: [PATCH 02/12] btrfs: add flags to give a hint to the chunk allocator
-From 894ba25b5c1bb9bcbafd5ed149503d86f04da31b Mon Sep 17 00:00:00 2001
+From 91e0e6d3c504d907e3884bda1192d6ccb934fef8 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Sat, 11 Jul 2026 00:22:50 +0200
Subject: [PATCH 03/12] btrfs: export dev_item.type in
-From 5c78cc5b6dfa6fca8616e11d75c9c71df39c7ba3 Mon Sep 17 00:00:00 2001
+From d908265472c1ecc2ec5422d102772c8d1a8b892d Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Sat, 11 Jul 2026 00:25:21 +0200
Subject: [PATCH 04/12] btrfs: change the DEV_ITEM 'type' field via sysfs
-From 957cad32902b12696afc0b263d70050cd204aa83 Mon Sep 17 00:00:00 2001
+From 6c61b29687de931f3b71949d973babca0bfc6c7c Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Sat, 11 Jul 2026 00:18:02 +0200
Subject: [PATCH 05/12] btrfs: add allocator_hint mode
-From d7add7cf6edfa308343ea12cb95ccabaf7305e2b Mon Sep 17 00:00:00 2001
+From e6522b0e9a45322c222d5498159e533a775a3107 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Sat, 11 Jul 2026 00:09:55 +0200
Subject: [PATCH 06/12] btrfs: add allocator_hint for no allocation preferred
-From b54d25e97ca7ae0cdd1706c872ee9035e430a6f2 Mon Sep 17 00:00:00 2001
+From 957e128e0135432355d6d9f352d2ab6556f1d456 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Fri, 10 Jul 2026 23:51:46 +0200
Subject: [PATCH 07/12] btrfs: add allocator_hint to disable allocation
-From 2763c25f8752709a108b4d07a5a8f734c5596ca8 Mon Sep 17 00:00:00 2001
+From ea8ce1d15132db90dc7067e3fbd4bdb5bebf77d9 Mon Sep 17 00:00:00 2001
From: KeinNiemand <18308201+KeinNiemand@users.noreply.github.com>
Date: Sun, 30 Aug 2026 14:50:54 +0200
Subject: [PATCH 08/12] btrfs: honor allocator hints for fixed-width mirrors
-From 1920847e6f57ae71dc0b18ab63fa9bbf147512bd Mon Sep 17 00:00:00 2001
+From fa99f98d377069191545f2d42062ad5c1c3aad65 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 4 Oct 2026 00:44:02 -0400
Subject: [PATCH 09/12] btrfs: allocator hints: move the hint values out of the
-From 51fc372ce6d49e87326aaa266d695d8b5b9db0aa Mon Sep 17 00:00:00 2001
+From 57b6931d10a94b5031d8e352a07386f48b1dde10 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 4 Oct 2026 00:44:58 -0400
Subject: [PATCH 10/12] btrfs: allocator hints: keep the hint across device
-From de1ee879d7873f5224ea97fa5066a8392cc30b9a Mon Sep 17 00:00:00 2001
+From 6bf6a73de3e2ea08417c5094587ac931b29fed85 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 4 Oct 2026 10:55:00 -0400
Subject: [PATCH 11/12] btrfs: allocator hints: don't run a transaction from
and refuse seed devices, which are read-only and not written by the
commit-time update.
+The store orders the new type before the dirty bit
+(smp_mb__before_atomic(); the commit's test_and_clear_bit() is the other
+half), and btrfs_update_device() reads the type with READ_ONCE(), so the
+commit cannot write the old type and clear the bit on a weakly ordered
+machine.
+
Assisted-by: Claude:claude-opus-5-5
---
fs/btrfs/Kconfig | 9 ++---
fs/btrfs/dev-replace.c | 3 ++
- fs/btrfs/sysfs.c | 86 +++++++++++++++---------------------------
+ fs/btrfs/sysfs.c | 89 ++++++++++++++++--------------------------
fs/btrfs/transaction.c | 3 ++
- fs/btrfs/volumes.c | 55 +++++++++++++++++++++++++++
+ fs/btrfs/volumes.c | 57 ++++++++++++++++++++++++++-
fs/btrfs/volumes.h | 7 ++++
- 6 files changed, 102 insertions(+), 61 deletions(-)
+ 6 files changed, 107 insertions(+), 61 deletions(-)
diff --git a/fs/btrfs/Kconfig b/fs/btrfs/Kconfig
index 038626bd24a68..f097f9631a857 100644
memcpy(uuid_tmp, tgt_device->uuid, sizeof(uuid_tmp));
memcpy(tgt_device->uuid, src_device->uuid, sizeof(tgt_device->uuid));
diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 6457b74d67f93..8a48b6895a9ae 100644
+index 6457b74d67f93..6e1d0636f9af9 100644
--- a/fs/btrfs/sysfs.c
+++ b/fs/btrfs/sysfs.c
@@ -19,7 +19,6 @@
ret = kstrtou64(buf, 0, &type);
if (ret < 0)
return -EINVAL;
-@@ -2051,55 +2041,39 @@ static ssize_t btrfs_devinfo_type_store(struct kobject *kobj,
+@@ -2051,55 +2041,44 @@ static ssize_t btrfs_devinfo_type_store(struct kobject *kobj,
if (!btrfs_dev_allocation_hint_valid(type))
return -EINVAL;
-
- ret = btrfs_update_device(trans, device);
-
-- /*
++ }
++ WRITE_ONCE(device->type, type);
+ /*
- * No dev item: the device is being removed, or lost its devid to a
- * replace that finished after the checks above. Nothing was changed,
- * so there is nothing to abort.
-- */
++ * The commit reads the type after it sees the bit, without
++ * chunk_mutex: order the store before the bit.
+ */
- if (ret == -ENOENT) {
- btrfs_end_transaction(trans);
- ret = -ENODEV;
- btrfs_abort_transaction(trans, ret);
- btrfs_end_transaction(trans);
- goto abort;
- }
-+ WRITE_ONCE(device->type, type);
+- }
++ smp_mb__before_atomic();
+ set_bit(BTRFS_DEV_STATE_TYPE_DIRTY, &device->dev_state);
+ mutex_unlock(&fs_info->chunk_mutex);
if (!test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &cur_trans->flags)) {
diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
-index eba473441b55a..ebc7be7858aa2 100644
+index eba473441b55a..4017a4c07ce0c 100644
--- a/fs/btrfs/volumes.c
+++ b/fs/btrfs/volumes.c
+@@ -3267,7 +3267,7 @@ int btrfs_update_device(struct btrfs_trans_handle *trans, struct btrfs_device *d
+ dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
+
+ btrfs_set_device_id(leaf, dev_item, device->devid);
+- btrfs_set_device_type(leaf, dev_item, device->type);
++ btrfs_set_device_type(leaf, dev_item, READ_ONCE(device->type));
+ btrfs_set_device_io_align(leaf, dev_item, device->io_align);
+ btrfs_set_device_io_width(leaf, dev_item, device->io_width);
+ btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
@@ -8730,6 +8730,61 @@ int btrfs_run_dev_stats(struct btrfs_trans_handle *trans)
return ret;
}
-From 6944c77605368854e644f8c961ad38ffb741d873 Mon Sep 17 00:00:00 2001
+From b3af80d4e58b937314a4840129845611db1b825e Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 18 Oct 2026 15:50:43 -0400
Subject: [PATCH 12/12] btrfs: allocator hints: make the available space
tier. Without CONFIG_BTRFS_ALLOCATOR_HINTS the data and metadata
estimates are identical and only one is computed.
+The estimates have been hint-blind since "btrfs: add allocator_hint
+mode", earlier in this series, taught the allocator the hints.
+
The fallback to fs_info->free_chunk_space (zoned filesystems, or a
failed estimate) and the reclaim thresholds that read it stay hint-blind.
abort and no lost files, and statfs reports the space data can really
use.
-Fixes: b35e5a63150a ("btrfs: add allocator_hint mode")
Assisted-by: Claude:claude-opus-5-5
---
fs/btrfs/space-info.c | 3 +-
/* align with stripe_len */
diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 8a48b6895a9ae..f744ebea1a8c4 100644
+index 6e1d0636f9af9..3732f58439c67 100644
--- a/fs/btrfs/sysfs.c
+++ b/fs/btrfs/sysfs.c
-@@ -2067,6 +2067,8 @@ static ssize_t btrfs_devinfo_type_store(struct kobject *kobj,
- }
- WRITE_ONCE(device->type, type);
+@@ -2072,6 +2072,8 @@ static ssize_t btrfs_devinfo_type_store(struct kobject *kobj,
+ */
+ smp_mb__before_atomic();
set_bit(BTRFS_DEV_STATE_TYPE_DIRTY, &device->dev_state);
+ /* The available space estimates depend on the hints. */
+ btrfs_update_per_profile_avail(fs_info);
/* We don't want to do full transaction commit from inside sysfs */
diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
-index ebc7be7858aa2..1c2981104646e 100644
+index 4017a4c07ce0c..39235ea12b746 100644
--- a/fs/btrfs/volumes.c
+++ b/fs/btrfs/volumes.c
@@ -200,7 +200,101 @@ static const int alloc_hint_map[BTRFS_DEV_ALLOCATION_MASK_COUNT] = {
-From 6094381703cd582ed0a4c84e2d28954696b2c616 Mon Sep 17 00:00:00 2001
+From 46b25327a7470027c3c6ad6314e9bef9c6da6a4e Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:33 -0400
+Date: Fri, 30 Oct 2026 22:32:34 -0400
Subject: [PATCH 0/3] btrfs: balance resume selects what the original request selected
To: linux-btrfs@vger.kernel.org
2 files changed, 85 insertions(+), 13 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From a9847e16418f7b9b1a8f3c91d629fc6426a12132 Mon Sep 17 00:00:00 2001
+From 3a4e04bb5fbc61a0b85d7919e17d3364357862a6 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Tue, 13 Oct 2026 01:05:21 -0400
Subject: [PATCH 1/3] btrfs: free queued remap chunks when balance bails out
-From fb89bec9e7b30c381f7d85b4ced60e5d5a21912e Mon Sep 17 00:00:00 2001
+From cff18d11ec6e4922138d46fdf89802343fab4c70 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Wed, 16 Sep 2026 02:29:10 -0400
Subject: [PATCH 2/3] btrfs: replace the usage=90 balance resume heuristic with
-From 6094381703cd582ed0a4c84e2d28954696b2c616 Mon Sep 17 00:00:00 2001
+From 46b25327a7470027c3c6ad6314e9bef9c6da6a4e Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Tue, 13 Oct 2026 14:24:01 -0400
Subject: [PATCH 3/3] btrfs: keep the usage=90 resume heuristic for balance
-From 9cf6495173d43a69008af6544c73cde1b59feb4d Mon Sep 17 00:00:00 2001
+From 420b87ed47953436d52528ef49be054222d039b7 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:34 -0400
+Date: Fri, 30 Oct 2026 22:32:34 -0400
Subject: [PATCH 0/5] btrfs: fix and simplify inode flag vs compression interactions
To: linux-btrfs@vger.kernel.org
5 files changed, 184 insertions(+), 28 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From cb00a6bf8255738f737545f961f141e9257e6fe9 Mon Sep 17 00:00:00 2001
+From 4abdf8c9bc525c0b8b990d4938b26228e9309178 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 16 Aug 2025 22:20:01 -0400
Subject: [PATCH 1/5] btrfs: fix nodatacow vs compression inode flag conflict
-From a7879c4a2fe1ee8092e0f2613915c1ca9d64e2a1 Mon Sep 17 00:00:00 2001
+From e862b18927ec88f831323b2ac4f050b837fbaf54 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 18 Oct 2026 15:44:15 -0400
Subject: [PATCH 2/5] btrfs: do not leave COMPRESS on an inode that gets
-From d1eafd0809350d1ee9c00b3f9e2097dcc74a2046 Mon Sep 17 00:00:00 2001
+From b87ce7ce09a2d2703dcd5aa193ae9f1e624578b5 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 17 Aug 2025 16:57:07 -0400
Subject: [PATCH 3/5] btrfs: allow NODATACOW | NOCOMPRESS
-From b009cddd89352180eb1b7b44222fdbea25960cfb Mon Sep 17 00:00:00 2001
+From 627b9f25057fbb9eb7abfb968f7528499df41cd1 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Thu, 6 Aug 2026 21:39:01 -0400
Subject: [PATCH 4/5] btrfs: props: add per-inode compression level support
-From 9cf6495173d43a69008af6544c73cde1b59feb4d Mon Sep 17 00:00:00 2001
+From 420b87ed47953436d52528ef49be054222d039b7 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 19 Jul 2026 14:33:53 -0400
Subject: [PATCH 5/5] btrfs: props: validate compression property values
-From 78c0c9e6a02b2aa9c27f19ecb73e0dc952d9caf9 Mon Sep 17 00:00:00 2001
+From 0b2a2621fdc37ab3063892db73bfa0cff0f0e29c Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:35 -0400
+Date: Fri, 30 Oct 2026 22:32:34 -0400
Subject: [PATCH 0/3] btrfs: deadlocks between reflink, relocation and space reservation
To: linux-btrfs@vger.kernel.org
Three deadlocks where a task holds a locked, dirty range or folio while
waiting for a space reservation or a transaction whose progress needs
-that range written back. All were captured on test machines running
-dedupe and balance under space pressure, with flushoncommit; each patch
-message has the cycle.
+that range written back. All were captured on test machines running dedupe and balance under
+space pressure, with flushoncommit; each patch message has the cycle.
Patch 1: clone_copy_inline_extent() dirtied a folio inside the locked
destination range before starting its transaction. b48c980b6a7e fixed
already in the range when it is locked (asynchronous compressed
writeback had not created its ordered extents yet; now detected after
locking, flushed and retried). Reflink no longer blocks on space
-reservations while the locked range has delalloc.
+reservations while the locked range has delalloc. Delalloc that
+survives two flushes under both inodes' i_rwsem and i_mmap_lock is a
+leaked EXTENT_DELALLOC bit: it is reported (root, inode, range) and the
+clone fails with -EUCLEAN, not -EAGAIN, which would have a dedupe agent
+retry the same range forever. Patch 2 unlocks the inline-copied
+destination block once its inode update is done and locks it again
+before btrfs_clone() returns, because both callers unlock the whole
+destination range then; that relies on the callers locking a
+block-aligned range (e7f4c05a8307, in mainline).
Patch 3: relocate_one_folio() takes a flushing delalloc reservation for
each slice of a folio while holding the folio locked and partly dirty;
flushoncommit commit pressure, deadlocks in 83 s with patch 2 reverted and
runs 600 s (720k dedupes) clean with it; the inline-only dedupe reproducer
and the relocation reproducer (900 s runs, a race) are clean with the
-series.
+series. The inline reflink tests check that umount returns (an earlier
+version that relocked an unaligned range left a block locked), the
+mixed-layout dedupe ran 607 s clean with the relock, and a forced stuck
+delalloc bit makes both lock loops return -EUCLEAN with the message.
Patches 1-2 carry Fixes: 05a5a7621ce6, patch 3 Fixes: c2832898126f.
range has delalloc
btrfs: relocation: reserve all of a folio's slices before dirtying any
- fs/btrfs/reflink.c | 255 ++++++++++++++++++++++++------------------
- fs/btrfs/relocation.c | 81 ++++++++++++--
- 2 files changed, 218 insertions(+), 118 deletions(-)
+ fs/btrfs/reflink.c | 296 +++++++++++++++++++++++++++---------------
+ fs/btrfs/relocation.c | 81 ++++++++++--
+ 2 files changed, 259 insertions(+), 118 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From f61edbb1fa430fdb64311a5fd1c808414280329e Mon Sep 17 00:00:00 2001
+From 4ec553632d4497d4ae8a2ccf6a546d152d32b16f Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 15 Aug 2026 22:21:10 -0400
Subject: [PATCH 1/3] btrfs: fix flushoncommit deadlock when cloning an inline
-From 97724c6881f7b5b79ac8bbb159a85e29aad5e3eb Mon Sep 17 00:00:00 2001
+From 52896b16014356c4176587554d6c379201533d36 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 16 Aug 2026 03:31:14 -0400
Subject: [PATCH 2/3] btrfs: reflink: never block on space reservations while
(held for the whole remap) keeps writers away from the unlocked block
until the clone finishes.
+ Both callers, btrfs_extent_same_range() and btrfs_clone_files(),
+ unlock the whole destination range when btrfs_clone() returns, that
+ block included, so lock the block again at the end of btrfs_clone()
+ to keep their unlock balanced. Without that, a task that locked the
+ block in between - writeback of the copied data (the commit-time
+ flusher under flushoncommit, the periodic flusher, range writeback) or
+ a read - would have its lock dropped by the caller's unlock while it
+ still works on the range, and a third task could then lock the block
+ at the same time. The callers lock block-aligned ranges since commit
+ e7f4c05a8307 ("btrfs: use aligned range for locking in reflink"), so
+ the block lies inside their range. Release the path first; then no
+ transaction handle or tree lock is held, writeback of the copied block
+ has no reason to lock the rest of our range, which has no delalloc,
+ and btrfs_lock_extent() drops the part of a range it got before
+ waiting for the rest, so a read covering more than the block does not
+ keep it while waiting for us.
+
2) Delalloc may already exist inside the range when it is first locked:
the pre-lock flush waits for ordered extents, but compressed writeback
is asynchronous and may not have created them yet. Check for
- EXTENT_DELALLOC after locking; if present, unlock, flush and retry,
- giving up with -EAGAIN after a few attempts.
+ EXTENT_DELALLOC after locking; if present, unlock, flush and retry.
+ Both inodes' i_rwsem and i_mmap_lock are held, so nothing can add
+ delalloc after a flush: delalloc that survives two flushes is a leaked
+ EXTENT_DELALLOC bit that no retry can clear. Warn with the root, inode
+ and range, and fail with -EUCLEAN rather than -EAGAIN, which would have
+ userspace (e.g. a dedupe agent) retry the same range forever.
Fixes: 05a5a7621ce6 ("Btrfs: implement full reflink support for inline extents")
Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/reflink.c | 92 ++++++++++++++++++++++++++++++++++++++++------
- 1 file changed, 81 insertions(+), 11 deletions(-)
+ fs/btrfs/reflink.c | 133 +++++++++++++++++++++++++++++++++++++++++----
+ 1 file changed, 122 insertions(+), 11 deletions(-)
diff --git a/fs/btrfs/reflink.c b/fs/btrfs/reflink.c
-index c487ab4a63322..7abb705977fd6 100644
+index c487ab4a63322..b7b7437482ead 100644
--- a/fs/btrfs/reflink.c
+++ b/fs/btrfs/reflink.c
@@ -157,7 +157,8 @@ static int clone_copy_inline_extent(struct btrfs_inode *inode,
}
btrfs_delalloc_release_extents(inode, fs_info->sectorsize);
-@@ -406,6 +411,7 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
+@@ -380,6 +385,8 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
+ const u64 len = olen_aligned;
+ u64 last_dest_end = destoff;
+ u64 prev_extent_end = off;
++ u64 unlocked_start = 0;
++ u64 unlocked_end = 0;
+
+ ret = -ENOMEM;
+ buf = kvmalloc(fs_info->nodesize, GFP_KERNEL);
+@@ -406,6 +413,7 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
u64 datao = 0, datal = 0;
u8 comp;
u64 drop_start;
/* Note the key will change type as we walk through the tree */
ret = btrfs_search_slot(NULL, src->root, &key, path, 0, 0);
-@@ -554,7 +560,8 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
+@@ -554,7 +562,8 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
ret = clone_copy_inline_extent(inode, path, &new_key,
drop_start, datal, size,
if (ret)
goto out;
}
-@@ -585,6 +592,28 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
+@@ -585,6 +594,29 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
destoff, olen, no_time_update);
if (ret)
goto out;
+ * clone finishes. The inode item for the copied data was
+ * already updated by clone_finish_inode_update() above.
+ */
-+ if (copied_to_page)
++ if (copied_to_page) {
++ unlocked_start = new_key.offset;
++ unlocked_end = ALIGN(new_key.offset + datal,
++ fs_info->sectorsize) - 1;
+ btrfs_unlock_extent(&inode->io_tree,
-+ new_key.offset,
-+ ALIGN(new_key.offset + datal,
-+ fs_info->sectorsize) - 1,
-+ NULL);
++ unlocked_start, unlocked_end, NULL);
++ }
if (new_key.offset + datal >= destoff + len)
break;
-@@ -669,8 +698,32 @@ static int btrfs_extent_same_range(struct btrfs_inode *src, u64 loff, u64 len,
+@@ -636,6 +668,22 @@ static int btrfs_clone(struct btrfs_inode *src, struct btrfs_inode *inode,
+ }
+
+ out:
++ /*
++ * Our caller unlocks the whole destination range when we return, so
++ * lock the block we unlocked above again, or the caller would unlock
++ * it a second time, possibly dropping a lock that writeback or a read
++ * took on it in the meantime. This cannot deadlock once the path is
++ * released: we hold no transaction handle or tree lock, writeback of
++ * the copied block has no reason to lock the rest of our range (it
++ * has no delalloc), and btrfs_lock_extent() drops the part of a range
++ * it got before waiting for the rest, so a read covering more than
++ * the block does not keep it while waiting for us.
++ */
++ if (unlocked_end) {
++ btrfs_release_path(path);
++ btrfs_lock_extent(&inode->io_tree, unlocked_start,
++ unlocked_end, NULL);
++ }
+ clear_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &inode->runtime_flags);
+
+ return ret;
+@@ -669,8 +717,47 @@ static int btrfs_extent_same_range(struct btrfs_inode *src, u64 loff, u64 len,
* we are safe from concurrency with relocation of source extents
* because we have already locked the inode's i_mmap_lock in exclusive
* mode.
+ * the range is clean and locked nothing can dirty it again (the only
+ * exception, copying an inline extent's data into a folio, unlocks
+ * the dirtied block before the clone continues - see btrfs_clone()).
++ *
++ * Each wait below writes back and waits for whatever delalloc is left
++ * in the range. Nothing can create more meanwhile: both inodes'
++ * i_rwsem and i_mmap_lock are held exclusively, so neither write(2) nor
++ * a page fault can dirty the range. Delalloc that survives two waits
++ * is therefore a leaked EXTENT_DELALLOC bit (e.g. left behind by a
++ * failed error path) that no amount of retrying clears, and cloning
++ * over it would reopen the deadlock above. Report it and fail with
++ * -EUCLEAN; -EAGAIN would invite userspace to retry forever.
*/
- btrfs_lock_extent(&dst->io_tree, dst_loff, end, &cached_state);
+ for (int i = 0; ; i++) {
+ EXTENT_DELALLOC))
+ break;
+ btrfs_unlock_extent(&dst->io_tree, dst_loff, end, &cached_state);
-+ if (i == 2)
-+ return -EAGAIN;
++ if (i == 2) {
++ btrfs_warn_rl(fs_info,
++"leaked delalloc in locked reflink destination: root %llu ino %llu range [%llu, %llu]",
++ btrfs_root_id(dst->root), btrfs_ino(dst),
++ dst_loff, end);
++ WARN_ON_ONCE(1);
++ return -EUCLEAN;
++ }
+ ret = btrfs_wait_ordered_range(dst, dst_loff, end + 1 - dst_loff);
+ if (ret)
+ return ret;
ret = btrfs_clone(src, dst, loff, len, ALIGN(len, bs), dst_loff, true);
btrfs_unlock_extent(&dst->io_tree, dst_loff, end, &cached_state);
-@@ -770,8 +823,25 @@ static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
+@@ -770,8 +857,32 @@ static noinline int btrfs_clone_files(struct file *file, struct file *file_src,
* because we have already locked the inode's i_mmap_lock in exclusive
* mode.
*/
+ * The locked range must also have no delalloc before the clone starts
+ * transactions or reserves space under the lock - see the comment in
+ * btrfs_extent_same_range() for the flushoncommit deadlock this
-+ * prevents.
++ * prevents, and for why delalloc left after the waits is reported as
++ * -EUCLEAN.
+ */
end = round_up(destoff + len, bs) - 1;
- btrfs_lock_extent(&inode->io_tree, destoff, end, &cached_state);
+ EXTENT_DELALLOC))
+ break;
+ btrfs_unlock_extent(&inode->io_tree, destoff, end, &cached_state);
-+ if (i == 2)
-+ return -EAGAIN;
++ if (i == 2) {
++ btrfs_warn_rl(fs_info,
++"leaked delalloc in locked reflink destination: root %llu ino %llu range [%llu, %llu]",
++ btrfs_root_id(inode->root), btrfs_ino(inode),
++ destoff, end);
++ WARN_ON_ONCE(1);
++ return -EUCLEAN;
++ }
+ ret = btrfs_wait_ordered_range(inode, destoff, end + 1 - destoff);
+ if (ret)
+ return ret;
-From 78c0c9e6a02b2aa9c27f19ecb73e0dc952d9caf9 Mon Sep 17 00:00:00 2001
+From 0b2a2621fdc37ab3063892db73bfa0cff0f0e29c Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 16 Aug 2026 16:26:54 -0400
Subject: [PATCH 3/3] btrfs: relocation: reserve all of a folio's slices before
Limits: case 2 (delalloc already in the range when it is locked) is not
driven.
-## Candidate fix to patch 2 (not promoted; 2026-10-26)
+## Relock fix to patch 2 (promoted 2026-10-27; folded into patch 2 2026-10-30)
+
+The series is 3 patches again: 1 inline clone, 2 never block (with the
+-EUCLEAN below and, since the 2026-10-30 restructure, the relock folded
+in), 3 relocation. From 2026-10-27 to 2026-10-30 the relock was a
+separate patch 3 (and relocation patch 4), with a Fixes: tag naming
+patch 2's lane commit; the fold removed that tag. The folded commit's
+tree equals the tree of the former relock commit on both lanes, so the
+results below apply to it unchanged.
"btrfs: reflink: relock the inline-copied block before returning"
-(Fixes: patch 2) is placed right after patch 2 on the candidates
+(Fixes: patch 2) was placed right after patch 2 on the candidates
`refs/cand/reflink/mn/deadlock-fixes` bfdd15368ad8 (relock 4a51e8a65d8a)
and `refs/cand/reflink/618/deadlock-fixes` 87e0137eb07a (relock
e1682b443773). Patch 2 unlocks the inline-copied destination block once
patch 2, not promoted): btrfs_warn_rl() naming root, inode and range,
WARN_ON_ONCE(), return -EUCLEAN, at both lock loops;
refs/cand/reflink/mn/deadlock-fixes 5f68685eacfa (patch 2 = f4a368cd3d65),
- 6.18 ab56f8dc2553 (9bc3ed94b2f0). The patch files here are still the
- lane's (-EAGAIN) until the candidate is promoted and re-exported.
+ 6.18 ab56f8dc2553 (9bc3ed94b2f0). PROMOTED 2026-10-27 both lanes; the
+ exported patch 2 has it.
Tested 2026-10-27 on ahive (KASAN+lockdep, forensics
reflink-euclean-20261026 in the harness): stuckbit-euclean-test.sh makes
the stuck bit (a failed inline decompress in a dedupe, on a test kernel
- Patch 2 case 2 (delalloc already in the range when it is locked, from
asynchronous compressed writeback) has no directed reproducer. Is one
wanted, or are the hunts enough?
-- The relock commit fixes patch 2 of this unsent series: fold it into
- patch 2 before sending, or keep it separate?
+- (answered 2026-10-30: the relock is folded into patch 2.)
-From 8e47d471e8a3a403a2cf9aebd061fc8ca404ae5c Mon Sep 17 00:00:00 2001
+From 53bbc18925a7d71dec81c68ff49a0c61b7f1c700 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:35 -0400
+Date: Fri, 30 Oct 2026 22:32:34 -0400
Subject: [PATCH 0/1] btrfs: one dedupe request, one extent reference
To: linux-btrfs@vger.kernel.org
1 file changed, 2 insertions(+), 19 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From 8e47d471e8a3a403a2cf9aebd061fc8ca404ae5c Mon Sep 17 00:00:00 2001
+From 53bbc18925a7d71dec81c68ff49a0c61b7f1c700 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Mon, 11 Nov 2024 20:32:54 -0500
Subject: [PATCH 1/1] btrfs: get rid of maximum dedupe length
-From dcacae4b4bd8f6257ab9d7656a0c3e176b360f07 Mon Sep 17 00:00:00 2001
+From b94af22598cb3e54b002e912db55bd91d27a7bd2 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:45 -0400
+Date: Fri, 30 Oct 2026 22:32:40 -0400
Subject: [PATCH 0/1] btrfs: keep mtime and ctime when a dedupe ends in a hole
To: linux-btrfs@vger.kernel.org
5 files changed, 13 insertions(+), 13 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From dcacae4b4bd8f6257ab9d7656a0c3e176b360f07 Mon Sep 17 00:00:00 2001
+From b94af22598cb3e54b002e912db55bd91d27a7bd2 Mon Sep 17 00:00:00 2001
From: Ivan Kozik <ivan@ludios.org>
Date: Wed, 30 Sep 2026 06:27:48 +0000
Subject: [PATCH 1/1] btrfs: don't update mtime and ctime when deduping a range
-From a49a18e6a3c7818f1de0871feb20199b5a6ef5e4 Mon Sep 17 00:00:00 2001
+From 1a0d757caa9243c08178c666fde88445e2c0d102 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:36 -0400
+Date: Fri, 30 Oct 2026 22:32:34 -0400
Subject: [PATCH 0/1] btrfs: drain pending NOCOW writes before a block group goes read-only
To: linux-btrfs@vger.kernel.org
5 files changed, 102 insertions(+), 5 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From a49a18e6a3c7818f1de0871feb20199b5a6ef5e4 Mon Sep 17 00:00:00 2001
+From 1a0d757caa9243c08178c666fde88445e2c0d102 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 12 Sep 2026 02:16:28 -0400
Subject: [PATCH 1/1] btrfs: drain pending NOCOW writes before making a block
-From 34a8e85757bbf8650972770b14d8682f4844a1f4 Mon Sep 17 00:00:00 2001
+From 7573a1e62c50390c9cbbdd8e2b30426a8f73cfc9 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:37 -0400
+Date: Fri, 30 Oct 2026 22:32:34 -0400
Subject: [PATCH 0/1] btrfs: allow setting the system chunk size through sysfs
To: linux-btrfs@vger.kernel.org
1 file changed, 13 insertions(+), 9 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From 34a8e85757bbf8650972770b14d8682f4844a1f4 Mon Sep 17 00:00:00 2001
+From 7573a1e62c50390c9cbbdd8e2b30426a8f73cfc9 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 30 Sep 2023 02:47:08 -0400
Subject: [PATCH 1/1] btrfs: allow changing system dev_extent size via sysfs
-From a5160f442538f1967dd37da26efe20d1b22e2622 Mon Sep 17 00:00:00 2001
+From ed41a6944651a6be3b301d67d2e7c479a69a98b1 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:48 -0400
+Date: Fri, 30 Oct 2026 22:32:41 -0400
Subject: [PATCH 0/1] btrfs: persist device stats counted without a transaction
To: linux-btrfs@vger.kernel.org
6 files changed, 82 insertions(+), 13 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From a5160f442538f1967dd37da26efe20d1b22e2622 Mon Sep 17 00:00:00 2001
+From ed41a6944651a6be3b301d67d2e7c479a69a98b1 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Tue, 20 Oct 2026 22:15:41 -0400
Subject: [PATCH 1/1] btrfs: write dirty device stats when no transaction is
+++ /dev/null
-From 0d13e1572fe71fd33e5cdb4d0eaa1111bbe9d179 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:46 -0400
-Subject: [PATCH 0/2] test fixtures: dm-stripfault target and a forced filesystem error (NOT for merge)
-
-Test fixtures carried on the lane for the raid56 tests; NOT for
-submission. Drop this series before sending anything upstream.
-
-Patch 1 adds dm-stripfault, a device-mapper target that makes every
-N-th block of a device silently bad (reads return fresh random bytes,
-writes are dropped) with a per-device phase, so that each raid5/6 full
-stripe has at most one bad strip. Every correct btrfs path survives
-that; a read-modify-write that folds an unverified read of a bad strip
-into parity does not.
-
-Patch 2 adds a CONFIG_BTRFS_DEBUG sysfs file, force_fs_error, that
-raises a logical filesystem error on demand, for directed tests of the
-error paths of the stripe allocator's drains.
-
-Zygo Blaxell (2):
- dm: add the stripfault target, a raid56 read-modify-write test fixture
- DO-NOT-UPSTREAM: btrfs: sysfs force_fs_error, to raise a logical abort
- on demand
-
- drivers/md/Kconfig | 13 ++
- drivers/md/Makefile | 1 +
- drivers/md/dm-stripfault.c | 244 +++++++++++++++++++++++++++++++++++++
- fs/btrfs/sysfs.c | 61 ++++++++++
- 4 files changed, 319 insertions(+)
- create mode 100644 drivers/md/dm-stripfault.c
-
-
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
---
-2.47.3
-
+++ /dev/null
-From 25e8c47ff024baacc813cf2981a3ebc1a8718762 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 2 Oct 2026 01:08:32 -0400
-Subject: [PATCH 1/2] dm: add the stripfault target, a raid56 read-modify-write
- test fixture
-
-dm-stripfault cuts a device into blocks of <block_sectors> and makes block N
-bad when (N + <base>) % <modulus> == 0, unless it holds a whitelisted sector.
-A bad block's reads complete with fresh random bytes every time, and its
-writes, write-zeroes and discards complete without reaching the device.
-Everything else is passed through like dm-linear.
-
-Laid under the members of a btrfs raid5/6 filesystem with a different
-<base> per member, it puts at most one bad strip in each full stripe. Every
-correct path survives that: full-stripe writes, and reads repaired from the
-other strips after a checksum mismatch. A read-modify-write that folds an
-unverified read of a bad strip into parity does not: the random bytes it
-read never come back, so the parity no longer reconstructs that strip. With
-<modulus> 1 on a single member it is a whole silently-failing device whose
-superblock copies (whitelisted) stay current.
-
- Table: <dev> <offset> <block_sectors> <modulus> <base> [<n> <sector>...]
- Status: <bad reads> <dropped writes> <dropped discards>
-
-Bios are split at block boundaries (max_io_len = block_sectors), so a bio
-never straddles a good and a bad block.
-
-This is a test fixture for the btrfs raid56 work (the strip-fault test and
-the octopus CORRUPT role of the validation harness), kept on its own topic
-so it can be dropped before upstream submission.
-
-Assisted-by: Claude:claude-opus-5-5
----
- drivers/md/Kconfig | 13 ++
- drivers/md/Makefile | 1 +
- drivers/md/dm-stripfault.c | 244 +++++++++++++++++++++++++++++++++++++
- 3 files changed, 258 insertions(+)
- create mode 100644 drivers/md/dm-stripfault.c
-
-diff --git a/drivers/md/Kconfig b/drivers/md/Kconfig
-index df27c7d066d23..57d01417be7f1 100644
---- a/drivers/md/Kconfig
-+++ b/drivers/md/Kconfig
-@@ -555,6 +555,19 @@ config DM_FLAKEY
- help
- A target that intermittently fails I/O for debugging purposes.
-
-+config DM_STRIPFAULT
-+ tristate "Strip fault target (raid56 test fixture)"
-+ depends on BLK_DEV_DM
-+ help
-+ A target that returns fresh random data for reads, and silently
-+ drops writes and discards, on a periodic pattern of blocks,
-+ passing the rest through. Under the members of a raid5/6 array
-+ it leaves at most one bad strip in each full stripe: every
-+ correct read and write path survives that, a read-modify-write
-+ that folds an unverified read into parity does not.
-+
-+ If unsure, say N.
-+
- config DM_VERITY
- tristate "Verity target support"
- depends on BLK_DEV_DM
-diff --git a/drivers/md/Makefile b/drivers/md/Makefile
-index 517d1f7d82888..45a620556d27a 100644
---- a/drivers/md/Makefile
-+++ b/drivers/md/Makefile
-@@ -59,6 +59,7 @@ obj-$(CONFIG_DM_INLINECRYPT) += dm-inlinecrypt.o
- obj-$(CONFIG_DM_DELAY) += dm-delay.o
- obj-$(CONFIG_DM_DUST) += dm-dust.o
- obj-$(CONFIG_DM_FLAKEY) += dm-flakey.o
-+obj-$(CONFIG_DM_STRIPFAULT) += dm-stripfault.o
- obj-$(CONFIG_DM_MULTIPATH) += dm-multipath.o dm-round-robin.o
- obj-$(CONFIG_DM_MULTIPATH_QL) += dm-queue-length.o
- obj-$(CONFIG_DM_MULTIPATH_ST) += dm-service-time.o
-diff --git a/drivers/md/dm-stripfault.c b/drivers/md/dm-stripfault.c
-new file mode 100644
-index 0000000000000..6a7259bd846a7
---- /dev/null
-+++ b/drivers/md/dm-stripfault.c
-@@ -0,0 +1,244 @@
-+// SPDX-License-Identifier: GPL-2.0
-+/*
-+ * dm-stripfault: a test fixture for raid56 read-modify-write bugs.
-+ *
-+ * The device is cut into blocks of <block_sectors>. Block N (counted from
-+ * the start of the target) is bad when (N + <base>) % <modulus> == 0, unless
-+ * it holds one of the whitelisted sectors. A bad block's reads complete with
-+ * fresh random bytes every time, and its writes and discards complete without
-+ * reaching the device. Everything else is passed through like dm-linear.
-+ *
-+ * Give each raid56 member a different <base> and at most one strip of a full
-+ * stripe is bad (see strip-fault-fixture.md for the parameter rules). Every
-+ * correct path survives that: full-stripe writes, and reads repaired from the
-+ * other strips after a checksum mismatch. A read-modify-write that folds an
-+ * unverified read of a bad strip into parity does not: the random bytes it
-+ * read never come back, so the parity no longer reconstructs that strip.
-+ *
-+ * Table: <dev> <offset> <block_sectors> <modulus> <base> [<n> <sector>...]
-+ * Status: <bad reads> <dropped writes> <dropped discards>
-+ */
-+#include <linux/module.h>
-+#include <linux/device-mapper.h>
-+#include <linux/bio.h>
-+#include <linux/random.h>
-+#include <linux/math64.h>
-+
-+#define DM_MSG_PREFIX "stripfault"
-+#define SF_MAX_WHITELIST 8
-+
-+struct stripfault_c {
-+ struct dm_dev *dev;
-+ sector_t start;
-+ u32 block; /* sectors per block, a power of two */
-+ u64 modulus; /* 0: no block is bad */
-+ u64 base;
-+ unsigned int nr_whitelist;
-+ u64 whitelist[SF_MAX_WHITELIST]; /* block numbers */
-+ atomic64_t bad_reads;
-+ atomic64_t dropped_writes;
-+ atomic64_t dropped_discards;
-+};
-+
-+static bool stripfault_bad(const struct stripfault_c *sc, sector_t rel)
-+{
-+ const u64 nr = rel >> ilog2(sc->block);
-+ unsigned int i;
-+ u64 rem;
-+
-+ if (!sc->modulus)
-+ return false;
-+ for (i = 0; i < sc->nr_whitelist; i++)
-+ if (sc->whitelist[i] == nr)
-+ return false;
-+ div64_u64_rem(nr + sc->base, sc->modulus, &rem);
-+ return rem == 0;
-+}
-+
-+static int stripfault_ctr(struct dm_target *ti, unsigned int argc, char **argv)
-+{
-+ struct stripfault_c *sc;
-+ unsigned long long tmp;
-+ unsigned int i;
-+ int ret;
-+
-+ if (argc < 5) {
-+ ti->error = "need <dev> <offset> <block_sectors> <modulus> <base> [<n> <sector>...]";
-+ return -EINVAL;
-+ }
-+ sc = kzalloc(sizeof(*sc), GFP_KERNEL);
-+ if (!sc) {
-+ ti->error = "out of memory";
-+ return -ENOMEM;
-+ }
-+ ret = -EINVAL;
-+ if (kstrtoull(argv[1], 10, &tmp)) {
-+ ti->error = "bad offset";
-+ goto bad;
-+ }
-+ sc->start = tmp;
-+ if (kstrtoull(argv[2], 10, &tmp) || !tmp || tmp > UINT_MAX ||
-+ !is_power_of_2(tmp)) {
-+ ti->error = "block_sectors must be a power of two";
-+ goto bad;
-+ }
-+ sc->block = tmp;
-+ if (kstrtoull(argv[3], 10, &sc->modulus) ||
-+ kstrtoull(argv[4], 10, &sc->base)) {
-+ ti->error = "bad modulus or base";
-+ goto bad;
-+ }
-+ if (argc > 5) {
-+ if (kstrtouint(argv[5], 10, &sc->nr_whitelist) ||
-+ sc->nr_whitelist > SF_MAX_WHITELIST ||
-+ argc != 6 + sc->nr_whitelist) {
-+ ti->error = "bad whitelist";
-+ goto bad;
-+ }
-+ for (i = 0; i < sc->nr_whitelist; i++) {
-+ if (kstrtoull(argv[6 + i], 10, &tmp)) {
-+ ti->error = "bad whitelist sector";
-+ goto bad;
-+ }
-+ sc->whitelist[i] = tmp >> ilog2(sc->block);
-+ }
-+ }
-+ ret = dm_get_device(ti, argv[0], dm_table_get_mode(ti->table), &sc->dev);
-+ if (ret) {
-+ ti->error = "device lookup failed";
-+ goto bad;
-+ }
-+ /* Split at block boundaries (relative to the target), never across one. */
-+ ret = dm_set_target_max_io_len(ti, sc->block);
-+ if (ret) {
-+ ti->error = "cannot set max_io_len";
-+ dm_put_device(ti, sc->dev);
-+ goto bad;
-+ }
-+ ti->num_flush_bios = 1;
-+ ti->num_discard_bios = 1;
-+ ti->num_write_zeroes_bios = 1;
-+ ti->private = sc;
-+ return 0;
-+bad:
-+ kfree(sc);
-+ return ret;
-+}
-+
-+static void stripfault_dtr(struct dm_target *ti)
-+{
-+ struct stripfault_c *sc = ti->private;
-+
-+ dm_put_device(ti, sc->dev);
-+ kfree(sc);
-+}
-+
-+static void stripfault_fill_random(struct bio *bio)
-+{
-+ struct bvec_iter iter;
-+ struct bio_vec bv;
-+
-+ bio_for_each_segment(bv, bio, iter) {
-+ void *p = bvec_kmap_local(&bv);
-+
-+ get_random_bytes(p, bv.bv_len);
-+ kunmap_local(p);
-+ }
-+}
-+
-+static int stripfault_map(struct dm_target *ti, struct bio *bio)
-+{
-+ struct stripfault_c *sc = ti->private;
-+ const sector_t rel = dm_target_offset(ti, bio->bi_iter.bi_sector);
-+
-+ if (bio_sectors(bio) && stripfault_bad(sc, rel)) {
-+ switch (bio_op(bio)) {
-+ case REQ_OP_READ:
-+ stripfault_fill_random(bio);
-+ atomic64_inc(&sc->bad_reads);
-+ bio_endio(bio);
-+ return DM_MAPIO_SUBMITTED;
-+ case REQ_OP_WRITE:
-+ case REQ_OP_WRITE_ZEROES:
-+ atomic64_inc(&sc->dropped_writes);
-+ bio_endio(bio);
-+ return DM_MAPIO_SUBMITTED;
-+ case REQ_OP_DISCARD:
-+ atomic64_inc(&sc->dropped_discards);
-+ bio_endio(bio);
-+ return DM_MAPIO_SUBMITTED;
-+ default:
-+ break;
-+ }
-+ }
-+ bio_set_dev(bio, sc->dev->bdev);
-+ if (bio_sectors(bio))
-+ bio->bi_iter.bi_sector = sc->start + rel;
-+ return DM_MAPIO_REMAPPED;
-+}
-+
-+static void stripfault_status(struct dm_target *ti, status_type_t type,
-+ unsigned int status_flags, char *result,
-+ unsigned int maxlen)
-+{
-+ struct stripfault_c *sc = ti->private;
-+ unsigned int sz = 0;
-+ unsigned int i;
-+
-+ switch (type) {
-+ case STATUSTYPE_INFO:
-+ DMEMIT("%lld %lld %lld", atomic64_read(&sc->bad_reads),
-+ atomic64_read(&sc->dropped_writes),
-+ atomic64_read(&sc->dropped_discards));
-+ break;
-+ case STATUSTYPE_TABLE:
-+ DMEMIT("%s %llu %u %llu %llu", sc->dev->name,
-+ (unsigned long long)sc->start, sc->block, sc->modulus,
-+ sc->base);
-+ if (sc->nr_whitelist) {
-+ DMEMIT(" %u", sc->nr_whitelist);
-+ for (i = 0; i < sc->nr_whitelist; i++)
-+ DMEMIT(" %llu", sc->whitelist[i] *
-+ (unsigned long long)sc->block);
-+ }
-+ break;
-+ case STATUSTYPE_IMA:
-+ *result = '\0';
-+ break;
-+ }
-+}
-+
-+static int stripfault_iterate_devices(struct dm_target *ti,
-+ iterate_devices_callout_fn fn, void *data)
-+{
-+ struct stripfault_c *sc = ti->private;
-+
-+ return fn(ti, sc->dev, sc->start, ti->len, data);
-+}
-+
-+static struct target_type stripfault_target = {
-+ .name = "stripfault",
-+ .version = {1, 0, 0},
-+ .module = THIS_MODULE,
-+ .ctr = stripfault_ctr,
-+ .dtr = stripfault_dtr,
-+ .map = stripfault_map,
-+ .status = stripfault_status,
-+ .iterate_devices = stripfault_iterate_devices,
-+};
-+
-+static int __init dm_stripfault_init(void)
-+{
-+ return dm_register_target(&stripfault_target);
-+}
-+
-+static void __exit dm_stripfault_exit(void)
-+{
-+ dm_unregister_target(&stripfault_target);
-+}
-+
-+module_init(dm_stripfault_init);
-+module_exit(dm_stripfault_exit);
-+
-+MODULE_DESCRIPTION("dm target: random reads and dropped writes on a block pattern (raid56 RMW test fixture)");
-+MODULE_LICENSE("GPL");
---
-2.47.3
-
+++ /dev/null
-From 0d13e1572fe71fd33e5cdb4d0eaa1111bbe9d179 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 24 Sep 2026 17:27:53 -0400
-Subject: [PATCH 2/2] DO-NOT-UPSTREAM: btrfs: sysfs force_fs_error, to raise a
- logical abort on demand
-
-Directed-test instrument for the stripe run retire bail branches
-(retire-bail-metaenospc-repro.sh). The bail needs BTRFS_FS_ERROR set by a
-task that is not the one parked in the drain, and every natural source of
-that is circular: the drain sits inside the transaction commit, so the
-commit cannot get to the delayed-ref accounting that would ENOSPC, and
-anything trying to raise one from outside blocks in wait_current_trans()
-behind that same commit. Device errors do not work either, since an
-errored bio still completes and reports its bytes, so the drain settles
-rather than bailing.
-
-Under CONFIG_BTRFS_DEBUG only. Carried in topics/dm-stripfault with the
-other test fixtures, to be dropped before upstream submission. Originally
-written 2026-09-24 for the A/B of the retire bail fixes (6b98b399d957),
-which only ever lived on test branches; without it the directed test has
-skipped on both lanes since.
-
-Assisted-by: Claude:claude-opus-5
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/sysfs.c | 61 ++++++++++++++++++++++++++++++++++++++++++++++++
- 1 file changed, 61 insertions(+)
-
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 89b0a4ef4063e..bae3351f9559e 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1124,6 +1124,64 @@ static ssize_t quota_override_store(struct kobject *kobj,
-
- BTRFS_ATTR_RW(, quota_override, quota_override_show, quota_override_store);
-
-+#ifdef CONFIG_BTRFS_DEBUG
-+/*
-+ * DO NOT UPSTREAM. Directed-test instrument for the stripe run retire bails.
-+ *
-+ * The retire bail branches (topics/stripe-alloc) need a filesystem error
-+ * raised by a task OTHER than the one parked in a retire drain. Every
-+ * natural source is circular: the drain runs inside the transaction commit,
-+ * so a commit cannot reach the delayed-ref accounting that would ENOSPC, and
-+ * a task that tries to raise one from outside blocks in wait_current_trans()
-+ * waiting for that same commit. Device errors are not an answer either: an
-+ * errored bio is a completed bio, so it reports its bytes and the drain
-+ * settles instead of bailing.
-+ *
-+ * Writing a negative errno here calls btrfs_handle_fs_error() directly: the
-+ * same logical abort a delayed-ref -ENOSPC produces, raised from a context
-+ * that is not waiting on anything.
-+ */
-+static ssize_t btrfs_force_fs_error_store(struct kobject *kobj,
-+ struct kobj_attribute *a,
-+ const char *buf, size_t len)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+ int error;
-+ int ret;
-+
-+ if (!fs_info)
-+ return -EPERM;
-+ if (!capable(CAP_SYS_ADMIN))
-+ return -EPERM;
-+
-+ ret = kstrtoint(buf, 10, &error);
-+ if (ret)
-+ return ret;
-+ /* Only errnos, and only ones a transaction abort would really carry. */
-+ if (error >= 0 || error < -MAX_ERRNO)
-+ return -EINVAL;
-+
-+ btrfs_handle_fs_error(fs_info, error,
-+ "injected through sysfs force_fs_error");
-+
-+ return len;
-+}
-+
-+static ssize_t btrfs_force_fs_error_show(struct kobject *kobj,
-+ struct kobj_attribute *a, char *buf)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+
-+ if (!fs_info)
-+ return -EPERM;
-+
-+ return sysfs_emit(buf, "%d\n", READ_ONCE(fs_info->fs_error));
-+}
-+
-+BTRFS_ATTR_RW(, force_fs_error, btrfs_force_fs_error_show,
-+ btrfs_force_fs_error_store);
-+#endif
-+
- static ssize_t btrfs_metadata_uuid_show(struct kobject *kobj,
- struct kobj_attribute *a, char *buf)
- {
-@@ -1444,6 +1502,9 @@ static const struct attribute *btrfs_attrs[] = {
- BTRFS_ATTR_PTR(, bg_reclaim_threshold),
- BTRFS_ATTR_PTR(, commit_stats),
- BTRFS_ATTR_PTR(, temp_fsid),
-+#ifdef CONFIG_BTRFS_DEBUG
-+ BTRFS_ATTR_PTR(, force_fs_error),
-+#endif
- NULL,
- };
-
---
-2.47.3
-
+++ /dev/null
-# Testing: dm-stripfault
-
-Test fixtures, NOT for merge. Patch 1 adds the stripfault device-mapper
-target: block N of a device is bad when (N + base) % modulus == 0 (unless
-whitelisted); bad blocks read fresh random bytes and drop writes and
-discards, everything else passes through like dm-linear. With a different
-base per raid56 member every full stripe has at most one bad strip, which
-every correct btrfs path survives and a read-modify-write that folds an
-unverified read into parity does not. Patch 2 adds a CONFIG_BTRFS_DEBUG
-sysfs file, force_fs_error, that raises a logical filesystem error on
-demand. Since these are instruments, testing them means two things: the
-instrument does exactly what the tests that use it assume (verified
-directly, not through btrfs), and the tests that use it still reach a
-verdict.
-
-Kernel under test for the "Current" column: misc-next zb64 568c45b64012
-(uname 7.3.0-rc7+ #5, KASAN + lockdep; DM_STRIPFAULT=y) unless a row says
-otherwise. Logs of this round: ahive `/root/tt-*/`, copied to
-`raid56-wh-harness/forensics/t-ahive-topics-20261018/`.
-
-## How the target itself is verified
-
-`stripfault-target-test.sh` checks the target against a backing file of
-labelled 4K blocks without any filesystem: which blocks are bad for a
-given modulus / base, that a bad block reads random bytes that differ from
-the backing and between two reads, that every good block reads the backing
-exactly, that writes to good blocks reach the backing and writes and
-discards to bad blocks do not, the status counters, the offset argument
-(badness counted from the target's start), the whitelist, modulus 0, and
-that malformed tables are refused. This is the check that a strip-fault
-PASS is not a PASS of a fixture that injects nothing.
-
-## Existing tests
-
-| test | verifies | patch(es) | duration | last result | date | kernel | harness | evidence |
-|---|---|---|---|---|---|---|---|---|
-| `strip-fault-test.sh` (default arms: control M=0 sa, fault-sa M=8, fault-stock M=8) | consumer of patch 1 (and of raid56-fixes' rbio cache knob): the control arm must verify with all counters 0; the fault arms must hit the faults | 1 | ~7 min | control PASS (counters 0, 2666 files verify); fault-sa PASS (bad reads 3-6549 / dropped writes 280-3727 per member, all files verify, scrub clean); fault-stock lost 24 files (0 wrong, scrub 2 uncorrectable): the expected stock-allocator RMW loss the stripe-alloc series fixes, so RESULT FAIL(2) is by design here, not a fixture fault. Previous: 8/8 arms PASS on fwpad2 (2026-10-02) | 2026-10-18 05:05 | misc-next zb64 568c45b64012 (ahive #5) | 1e003fb | t-ahive-topics-20261018/b1/sf |
-| `meta-crash-replay-test.sh` | consumer of patch 1: raid5 metadata, crash after 3000 fsyncs, replay through the faulted strips | 1 | ~30 min | PASS (every fault arm lost data before the stripe-alloc fix, none after) | 2026-10-03 | misc-next / 6.18 candidates of 10-03 | not recorded | forensics/meta-rmw-strip-fault-20261003 |
-| `retire-bail-metaenospc-repro.sh` (TARGET=commit) | consumer of patch 2: a balance parked in a stripe-run retire drain must bail when another task raises a filesystem error | 2 | ~15 min | PASS: the bail line fired, directed "SKIPPED (no verdict): none" | 2026-10-12 | misc-next zb64 69253254bc1c (dhive #107) | c252004 era | memory stripe-alloc-retire-wait-on-abort-hang |
-
-**strip-fault-test.sh.** 4 x 2 GiB raid5 members, each a stripfault
-device (64K blocks, modulus 8, bases 0 2 4 6), faults swapped in after mkfs
-and mount; files of 4K..124K, every third deleted, sync, full data balance,
-remount, verify every file, scrub. The control arm (modulus 0) must verify
-and its counters must stay 0; the fault arms must show bad reads and dropped
-writes (else the fault was never hit). It depends on the rbio cache knob
-(raid56-fixes patch 8, `SF_RBIO_CACHE=0`) to reach the RMW read path.
-Limits: it verifies btrfs under the target, and the target only through the
-counters; the direct check is stripfault-target-test.sh.
-
-**meta-crash-replay-test.sh.** strip-fault-test.sh with raid5 metadata,
-`SF_FSYNC=3000 SF_CRASH=1`: a crash via dm-flakey drop_writes right after
-the fsync phase, faults back on, log replay through the faulted strips.
-Limits: stripe-alloc specific in what it proves.
-
-**retire-bail-metaenospc-repro.sh.** The only consumer of patch 2: builds a
-6 x 1G raid6/raid6 filesystem with no unallocated space and nearly full
-metadata, holds writes outstanding on dm-delay, parks a balance in a retire
-drain (gated on /proc/<pid>/stack) and injects -ENOSPC through
-force_fs_error; the drain must bail. It SKIPs (77) without the knob, which
-is how the knob's absence was noticed on 2026-10-11.
-
-## New tests
-
-| test | verifies | patch(es) | duration | last result | date | kernel | harness | evidence |
-|---|---|---|---|---|---|---|---|---|
-| `stripfault-target-test.sh` | the target itself (see above) | 1 | ~20 s | PASS: M=4 base=1 -> 256 of 1024 blocks bad, random and fresh on every read, the other 768 exact; 512 bad reads counted (+7 from udev probing at create); good-block writes reached the backing, 256 bad-block writes dropped; discard of a bad block dropped and counted; offset, whitelist, modulus 0 correct; 4 malformed tables refused | 2026-10-18 05:32 | misc-next zb64 568c45b64012 (ahive #5) | 518cf36 | t-ahive-topics-20261018/b2/stripfault-target-test.sh |
-| `force-fs-error-test.sh` | the knob: reads 0; refuses 0, 5, "abc", below -MAX_ERRNO; -28 logs "injected through sysfs force_fs_error", forces read-only (EROFS), reads -28; a remount is clean and btrfs check passes | 2 | ~5 s | PASS (every check) | 2026-10-18 05:32 | misc-next zb64 568c45b64012 (ahive #5) | 518cf36 | t-ahive-topics-20261018/b2/force-fs-error-test.sh |
-
-**stripfault-target-test.sh.** No filesystem involved: a 64 MiB loop
-device of labelled 4K blocks (each names its index) under the target, 64K
-blocks. For M=4 base=1 every 64K block is read twice with O_DIRECT through
-the target and once from the backing: blocks with (N+1)%4==0 must differ
-from the backing and between the two reads, every other block must equal the
-backing. The bad-read counter must equal two per bad block (the udev/blkid
-probe of a newly created dm device reads a few blocks too; their count is
-taken before the scan and subtracted). A new labelled pattern written
-through the target must reach the backing exactly for good blocks and leave
-bad blocks at the old label; a discard of a bad block must not reach the
-backing. Then offset 2048 (target block N = backing block N+16, badness
-counted from the target), a whitelisted sector inside block 7 (block 7
-passes through), modulus 0 (nothing bad), and four malformed tables (block
-size not a power of two, 9 whitelist entries, missing base, wrong whitelist
-count) must be refused. It is its own negative control: the M=4 scan fails
-for a target that injects nothing, the modulus 0 scan for one that injects
-everywhere. Limits: one block size (64K, what the tests use); the random
-bytes are not checked for quality, only for differing.
-
-**force-fs-error-test.sh.** A 1 GiB single-device filesystem: the knob
-reads 0, refuses invalid values without changing anything, then -28 must log
-the injection, force the filesystem read-only (a new file gets EROFS) and
-read back -28; after unmount the next mount must be clean (knob 0, data
-intact, writable) and btrfs check must pass, i.e. the injected error is a
-logical abort that writes nothing bad. Limits: what the retire-bail test
-needs (a task parked in a drain seeing the error) is only covered by that
-test.
-
-## Not covered / open
-
-- Not for merge; nothing here is a submission gate.
-- `meta-crash-replay-test.sh` and `retire-bail-metaenospc-repro.sh` were not
- rerun this round (stripe-alloc tests; their last results are above).
-
-### Questions for Zygo
-
-(none)
-From f792976ba69796c4dc0c890bf9c2c72faa500c38 Mon Sep 17 00:00:00 2001
+From e0cc444349ea61d819ae8e23a77546608d8340d1 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:32 -0400
+Date: Fri, 30 Oct 2026 22:32:33 -0400
Subject: [PATCH 0/3] btrfs: reducing LOGICAL_INO costs
To: linux-btrfs@vger.kernel.org
4 files changed, 127 insertions(+), 21 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From f39e3249acc05e0ae076b074fbf46db3ca1699d9 Mon Sep 17 00:00:00 2001
+From 843be22c1b284a27d19ef3a1a4a0b87cccb86c65 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 17 Jul 2026 23:13:26 -0400
Subject: [PATCH 1/3] btrfs: backref: detect tree mod log rewind cycles in
-From fc805e8fbd3f23a8a358b28f9d5a695d5cf14e2b Mon Sep 17 00:00:00 2001
+From 2054b07c5457979a47e886f6bfdd4bb9edfe4c35 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 19 Sep 2026 12:36:42 -0400
Subject: [PATCH 2/3] btrfs: resume the delayed-ref merge walk instead of
-From f792976ba69796c4dc0c890bf9c2c72faa500c38 Mon Sep 17 00:00:00 2001
+From e0cc444349ea61d819ae8e23a77546608d8340d1 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Mon, 23 Jun 2025 13:56:36 +0200
Subject: [PATCH 3/3] btrfs: avoid RCU stall during backref list construction
-From 087669d83341b0e044a253146b2f633bc4f63534 Mon Sep 17 00:00:00 2001
+From 206f44fec60d023c07b8ebb664fa68bfbeb45902 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:45 -0400
+Date: Fri, 30 Oct 2026 22:32:39 -0400
Subject: [PATCH 0/3] btrfs: keep room to relocate on a full filesystem
To: linux-btrfs@vger.kernel.org
group to relocation (data_reloc_bg); regular filesystems have nothing,
for data or for metadata.
+The series applies on top of the stripe-alloc RFC series ("btrfs: close
+the raid56 write hole for datacow with stripe-exclusive allocation"),
+which applies on top of reclaim-fixes. Patch 2 needs it: it uses the
+relocating task that stripe_alloc records in fs_info->reloc_owner, the
+reloc flag stripe_alloc puts on reservations and tickets, and its
+five-argument btrfs_can_overcommit(), and it integrates the reserve with
+stripe_alloc's whole-stripe accounting. Patches 1 and 3 do not depend on
+either series and apply to the base on their own; patch 3 fixes an abort
+in upstream relocation code and can be taken without the rest.
+
Patch 1 is a small diagnostic found along the way: a failed background
reclaim logs "error relocating chunk <start>" without the error, so a
reservation ENOSPC, a read error and an active swapfile look the same
still covers the target. A chunk made for the reserve is claimed as
it is added, before anything can allocate from it.
+ - With stripe_alloc, a held group counts as reserve only its claimable
+ whole stripes (resynced at each commit-time stripe rescan), since its
+ trapped free space is already counted as stripe_unusable;
+ stripe_alloc's admission leaves the held groups' stripes out of
+ ordinary writers' supply; and stripe_meta's own relocation reserve is
+ not reduced by the held groups.
+
- A tree block that finds no room outside the reserve takes it from the
reserve rather than abort the transaction. Relocating a metadata
group leaves delayed refs and commit work that tasks other than the
series' base (misc-next at 80c2022bdf745) for raid1, raid5 data with
raid1 metadata and raid5 data with raid5 metadata, under KASAN.
+With stripe_alloc and stripe_meta on (raid5 data and metadata), the
+results are not settled. Until 2026-10-29 the data balance of the same
+test failed (rc=1): the reserve was counted in bytes, and relocation
+under stripe_alloc needs whole stripes. With patch 2 as posted (the
+share of a held group is capped at its claimable stripes between
+rescans, and a claimed run's remainder leaves it), one misc-next run
+completed both balances and every file verified, while the arm without
+the reserve aborted with ENOSPC; on 6.18 the same arm ran past 6000 and
+9000 s caps without a verdict, in the slow unlinks of a full metadata
+space (unlinks waiting on commits), which are slow without the reserve
+too (about 50 minutes). This is why the reserve stays off by default there too.
+
System chunks are not covered: balance -m relocates them too, and a
full filesystem can still fail there.
btrfs: hold block groups free for relocation
btrfs: relocation: flush fully before failing a merge reservation
- fs/btrfs/block-group.c | 366 ++++++++++++++++++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 23 +++
- fs/btrfs/disk-io.c | 6 +
- fs/btrfs/extent-tree.c | 34 +++-
- fs/btrfs/extent-tree.h | 3 +
- fs/btrfs/fs.h | 12 ++
- fs/btrfs/relocation.c | 13 +-
- fs/btrfs/space-info.c | 67 +++++++-
- fs/btrfs/space-info.h | 19 ++-
- fs/btrfs/super.c | 2 +
- fs/btrfs/sysfs.c | 48 ++++++
- fs/btrfs/volumes.c | 31 ++++
- 12 files changed, 614 insertions(+), 10 deletions(-)
-
-
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+ fs/btrfs/block-group.c | 440 +++++++++++++++++++++++++++++++++++-
+ fs/btrfs/block-group.h | 26 +++
+ fs/btrfs/disk-io.c | 6 +
+ fs/btrfs/extent-tree.c | 43 +++-
+ fs/btrfs/extent-tree.h | 3 +
+ fs/btrfs/free-space-cache.c | 6 +-
+ fs/btrfs/fs.h | 6 +
+ fs/btrfs/relocation.c | 11 +-
+ fs/btrfs/space-info.c | 69 +++++-
+ fs/btrfs/space-info.h | 19 +-
+ fs/btrfs/super.c | 2 +
+ fs/btrfs/sysfs.c | 48 ++++
+ fs/btrfs/volumes.c | 31 +++
+ 13 files changed, 700 insertions(+), 10 deletions(-)
+
+
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
+prerequisite-patch-id: d27f13acdb7e1fb211a9524027f3f1c8c119f80b
+prerequisite-patch-id: 3ba444b908adb7eb7dd36a0bac6a3816516935c4
+prerequisite-patch-id: 9eebec1e5af9c3767f7de46e5a2406a7d140b135
+prerequisite-patch-id: 6ddf787f364b4266e3f44a4c428354306bf0f390
+prerequisite-patch-id: 49273f0d3544b4eca8ed08d68d0d2643190a9d4d
+prerequisite-patch-id: 286cb3aab5ab4e541a0ad73b585c229e60f1de32
+prerequisite-patch-id: ede70867970deb31b4901d62caee95f6b21d0f76
+prerequisite-patch-id: fbddfe57a4ba54dd42fedb91994d83070ba5137c
+prerequisite-patch-id: df376f09d4836a310ee4891337ba83a29a2045f2
+prerequisite-patch-id: 1e37da203e145c65b831a6d48e7a136e1c8de001
+prerequisite-patch-id: 61bd9a71c37542c5ec45f97b86bb310ff8dd829c
+prerequisite-patch-id: 5e00b414505efd318f6b51686c03034bf34983cd
+prerequisite-patch-id: 2bc4d04ab2d4eb74272b292d93563b9128bb8a43
+prerequisite-patch-id: 2297c5fa2d7987dd96f1fbcd794ae6e11c67b3e7
+prerequisite-patch-id: 55e10f862f099d3fa95e2a2f27513b5807490101
+prerequisite-patch-id: dabb6a8b51b0c7008af4db42a6898de221f31e03
+prerequisite-patch-id: c87fceb780d86e1f8b9761d322a2b9682269e636
+prerequisite-patch-id: c1da18794b351cc7bd7eb6d401f62157f9f8094a
+prerequisite-patch-id: fadcec50502efe4691879d4e72b98ef3534fbe91
+prerequisite-patch-id: 5908cabf3f3cbb95c2cae44cbc9b80f4e4dcc0fe
+prerequisite-patch-id: e2623ee2d44358da8b269bb18167f0d8b86279f6
+prerequisite-patch-id: a7c7aadbf99ec2bb96075e030a62c2dae016f60d
+prerequisite-patch-id: c51f204e27e0ae691837524ce70a342bee609fae
+prerequisite-patch-id: b3cbfdc715c1386a20b1538a133f1bfe21a5ba87
+prerequisite-patch-id: 257ca55e5214ba13279509702475789efcbcec10
+prerequisite-patch-id: 462147b7e1b0501447766869edd98f22a8cc49e1
+prerequisite-patch-id: 74d63772c72114c1564ec7d1e8d199b47b8d447a
+prerequisite-patch-id: e4e71d36b60dd3af21b75a9dafd4593d31208628
+prerequisite-patch-id: 639331c65e84789cecbaec49bf0fb0554becb09e
+prerequisite-patch-id: 2f5b312b3742edfd6d4991d9c4e4c902f5479ab0
+prerequisite-patch-id: a3402b147fed8a730384b9a3542e84ee3e80c3c3
+prerequisite-patch-id: 35548859efd6be80da6b1368f1553901c060ab60
+prerequisite-patch-id: 5aa47934a761639afe976001514b8f945939e374
+prerequisite-patch-id: 47989453e8619250c5f64e697fc20114035477ef
+prerequisite-patch-id: 4e906ec46cb7ba48110c41dd83cefa9954eb1203
+prerequisite-patch-id: 435b29315f0bf2fd642f681680c4f15ee99f7de4
+prerequisite-patch-id: b4a6ac05bcfb88b07a188e058fd8d4d17600d5e4
+prerequisite-patch-id: 6e2a7a3f195b7c27649b9e17bfcc064c1435f4e0
+prerequisite-patch-id: b51d302c818e693c354a6159f1173f858e44480a
+prerequisite-patch-id: 7949e3f5ab8f10dc73abd55b436fc85b5db49eff
+prerequisite-patch-id: 475bc3c86b4aa57231420a42d1f7217c4d5a4eec
+prerequisite-patch-id: 466d9ec70ad95b10d3a53ad1b1118777f04c784d
+prerequisite-patch-id: 312df7fbc210e04014ef1011e531f3aecf9aadfb
+prerequisite-patch-id: 61579b63da7741ca672d0ee16bf51ab1cd60cc07
+prerequisite-patch-id: a8c8e49371cc725be6e2c3b081b1382295c5bc5a
+prerequisite-patch-id: c5a057852ff008d3e54e45ef5d3f624b7a798f22
+prerequisite-patch-id: 4632761ddc7ae4410a356bcb0343595f79200c8e
+prerequisite-patch-id: 9f849db09f6b70bcb72a862c714c1b97ab6dc67d
+prerequisite-patch-id: a672da3793b6a0f615449030545156a68ba827c9
+prerequisite-patch-id: 2c057685d67b52d61d43192a48fe8263597d9ece
+prerequisite-patch-id: 98027b4c68242209b1133de040981526196b40cc
+prerequisite-patch-id: 2e1f32d2fd9a3f7f821ce62458c1f69cfd8a793e
+prerequisite-patch-id: 60312836a14e5ee207b6db7696ab1d7bc01966bb
+prerequisite-patch-id: 42214bcb1b433d20621f8a7dac89332a883bec12
+prerequisite-patch-id: ab06cc070df429a975c7de766da62cd5e4f20d33
+prerequisite-patch-id: 64b9cd7a12134a06f5fc5c7056dc84fc6aca6182
+prerequisite-patch-id: aa989f9ea0ec5acad7bd709554bf96816a301f4c
+prerequisite-patch-id: 89537b30f4b3349c218fe366a1ed07c9cf8990bd
+prerequisite-patch-id: bea9d497aff938d7d7b7acb6b352993d6d35266e
+prerequisite-patch-id: 215cd1da72d6da2c8c7e332952032debb4f1a7de
+prerequisite-patch-id: 7ada8b997155737ce5f5d10ae09af5ad649e7a41
+prerequisite-patch-id: c6fd6a955b15b5a8a5556296b07b2e1f957e68fd
+prerequisite-patch-id: e2dfa80497cdb9a3e8394d71df38295df46e7d13
+prerequisite-patch-id: 21ec48c278bb89cdc368b47c0875beed082e6d31
+prerequisite-patch-id: a4e19a0893269a5b0a7f0251c84388bd76c75c59
+prerequisite-patch-id: e836550da533aa29947ba9f78d4f8e5d9d8c9639
+prerequisite-patch-id: 306752d755d49a4c93171fcc2cd85cd6a5eb613d
+prerequisite-patch-id: 7da23f7792ce226da8618a4c02d2158267f9bef0
+prerequisite-patch-id: bdf90c9d5602f0446305e5e4388999e0f616de8d
+prerequisite-patch-id: 85940568f3817e76739ae4d5ebda9c529358f1a9
+prerequisite-patch-id: 7d9579954c13ebcc1d5e7b2c48ec1731ab8c2515
+prerequisite-patch-id: f47b9acb23f08e4335f52636d777e885ef7c358f
+prerequisite-patch-id: 3c6380b660a3e9b109f9f5d606b866b8e57f9f93
+prerequisite-patch-id: 19503c50d9db92eefa091b02623ba5601149e167
+prerequisite-patch-id: 8cb55cba4be70421d6fd3ef6ee183a087c171e88
+prerequisite-patch-id: 5941d6e7304faac1576639a451d316c3261b9cbf
+prerequisite-patch-id: 8e495e963313803f599474bfcbfe86c7ca927fef
+prerequisite-patch-id: 6eb0678851529632d0eae15cab925201ffc8e12d
+prerequisite-patch-id: 69287ce278f599b188b4de89298da8f913d496fa
+prerequisite-patch-id: 0f1eddb75b0cb516386608570d4dcf57c7197c6c
+prerequisite-patch-id: 422e252c7906773f3a87831c31ce08a585ebbb5e
+prerequisite-patch-id: 2d5542c50e8090d0b9e7d46b3eb9264758b1b251
+prerequisite-patch-id: cfdf37baff63cf733cbeb49a46593ff9aa5de6cb
+prerequisite-patch-id: 02222236ce5f47432853510e38a2a3c3f2027a97
+prerequisite-patch-id: e8adf3fd375f57f415cb06749ceafa012578e527
+prerequisite-patch-id: f1ddaf798fd2a1e0edafa0d5e0d1f6e69833909f
+prerequisite-patch-id: 4887cec5ae407264b668f6b0516b62ca97d1da5b
+prerequisite-patch-id: 2583346498570387d00120057670c87fd71412a1
--
2.47.3
-From ff1a34bdfe8c76ac3624306f3882321c90fc0e5e Mon Sep 17 00:00:00 2001
+From 94fe7c66de3f69133168923088dc46b4596d7d8d Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sun, 27 Sep 2026 15:02:40 -0400
Subject: [PATCH 1/3] btrfs: print the error when reclaim fails to relocate a
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 027830a53f7dc..b0adf7aded255 100644
+index 4333b3067a44f..dfe7e5eb7511c 100644
--- a/fs/btrfs/block-group.c
+++ b/fs/btrfs/block-group.c
-@@ -2064,8 +2064,8 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+@@ -5598,8 +5598,8 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
}
if (ret) {
btrfs_dec_block_group_ro(bg);
-From 8ddf0ef4313d7d243c2323d679e443184c8c4510 Mon Sep 17 00:00:00 2001
+From b9b09749cf786650d281e2a005bed5c80b427e5a Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Mon, 28 Sep 2026 18:14:56 -0400
Subject: [PATCH 2/3] btrfs: hold block groups free for relocation
- Only relocation allocates from them: the data relocation inode's
extents, and tree blocks allocated by the task running
- btrfs_relocate_block_group() (recorded as fs_info->reloc_owner for
- the whole relocation, since tree blocks COWed in the COW-only roots
- during relocation cannot be told apart by their root).
+ btrfs_relocate_block_group(). That task is the one stripe_alloc
+ already records as fs_info->reloc_owner for the whole relocation
+ (tree blocks COWed in the COW-only roots during relocation cannot be
+ told apart by their root); btrfs_is_reloc_task() tests it.
- Their free bytes are accounted in space_info->bytes_reloc_reserve,
which btrfs_space_info_used() counts as used, so admission,
overcommit, chunk allocation and ticket granting treat the reserve as
unavailable -- except for reservations and tickets made by the
- relocating task. The per-group share is adjusted where bytes are
- reserved, freed or unpinned in a held group, so allocations the
- reserve serves are not counted twice.
+ relocating task (btrfs_is_reloc_task(); a ticket carries it as
+ reloc_reserve). stripe_alloc's reloc flag, which also admits the
+ transaction machinery's bounded reservations (NO_FLUSH, FLUSH_LIMIT,
+ EMERGENCY) to the stripe_meta reserve, does not extend to this one:
+ stripe_alloc's btrfs_can_overcommit() takes the relocation reserve
+ off "used", after the stripe_meta reserve, only when that flag is set
+ and the caller is the relocating task. The per-group share is
+ adjusted where bytes are reserved, freed or unpinned in a held group,
+ so allocations the reserve serves are not counted twice.
- statfs does not offer their space, the cleaner does not delete them
while they are empty, balance without a conversion filter skips them
group that goes read-only leaves the set.
- The relocating task keeps its exemption through the removal of the
- emptied chunk after relocation: that transaction reserves metadata
- too, and refused on a full filesystem it failed a relocation whose
- data had already moved, and kept the raw space the reserve refills
- from.
+ emptied chunk after relocation, which sets reloc_owner again around
+ that transaction: it reserves metadata too, and refused on a full
+ filesystem it failed a relocation whose data had already moved, and
+ kept the raw space the reserve refills from.
- A tree block that finds no room outside the reserve takes it from the
reserve rather than fail. The reservation layer admitted it already,
the transaction on a full filesystem. Data allocations have no such
fallback: a data writer gets ENOSPC.
- - A group may go read-only for relocation when the reserve can hold its
- live bytes, even if the rest of the space_info cannot: without that
- the first, non-forced read-only step of reclaim fails on exactly the
- full filesystems reclaim is needed for.
+ - A metadata group may go read-only for relocation when the reserve can
+ hold its live and reserved bytes, even if the rest of the space_info
+ cannot: without that the first, non-forced read-only step of reclaim
+ fails on exactly the full filesystems reclaim is needed for. An
+ empty group, or a space_info without a reserve, gets no exemption,
+ and neither does data: there the ordinary test fails only while
+ outstanding reservations depend on the group's free space, and data
+ writeback has no reserve to fall back on.
- A held group that goes read-only (scrub, device replace) leaves the
set and rejoins it when writable again, or at once if the read-only
groups: allocating chunks for it would take back the room the shrink
is freeing (a raid6 shrink failed in merge_reloc_roots with -ENOSPC).
+With stripe_alloc:
+
+ - A held group counts as reserve only its claimable whole stripes:
+ reloc_reserve_resync(), called from btrfs_scan_stripe_unusable() at
+ each commit-time rescan, resyncs its share to them. Its trapped
+ free space is in bytes_stripe_unusable already, and counting it in
+ the reserve too made the metadata space_info read over-full on a
+ full raid6 filesystem while relocation found no stripe to claim.
+ Between rescans the share is capped at the claimable stripes when a
+ group joins the reserve while armed or is armed while held, and a
+ claimed stripe run's remainder (bytes_stripe_open) leaves the share
+ with the claim.
+
+ - stripe_claimable_admit() leaves the held groups' stripes out of
+ ordinary writers' whole-stripe supply; relocation still sees them.
+ A held group's stripes are not counted again as the dedicated data
+ relocation group's (bytes_stripe_claimable_reloc), which the same
+ check subtracts.
+
+ - stripe_alloc's whole-stripe check in inc_block_group_ro() is for
+ data groups, which have no reserve exception (above).
+
+stripe_meta's bytes_stripe_reserve is not reduced by the held groups: it
+is an admission margin that keeps tree blocks off the reserve's
+emergency fallback, and without it a metadata fill consumed the reserve
+before any relocation (dhive sresmn raid5/raid5, 2026-09-29).
+
Relocation moves at most one block group's live data, so the set holds
at least as much as the largest block group of the space_info. That is
the largest existing group rather than the chunk allocator's caps: a new
Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/block-group.c | 362 ++++++++++++++++++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 23 +++
- fs/btrfs/disk-io.c | 6 +
- fs/btrfs/extent-tree.c | 34 +++-
- fs/btrfs/extent-tree.h | 3 +
- fs/btrfs/fs.h | 12 ++
- fs/btrfs/relocation.c | 2 +
- fs/btrfs/space-info.c | 67 +++++++-
- fs/btrfs/space-info.h | 19 ++-
- fs/btrfs/super.c | 2 +
- fs/btrfs/sysfs.c | 48 ++++++
- fs/btrfs/volumes.c | 31 ++++
- 12 files changed, 602 insertions(+), 7 deletions(-)
+ fs/btrfs/block-group.c | 436 +++++++++++++++++++++++++++++++++++-
+ fs/btrfs/block-group.h | 26 +++
+ fs/btrfs/disk-io.c | 6 +
+ fs/btrfs/extent-tree.c | 43 +++-
+ fs/btrfs/extent-tree.h | 3 +
+ fs/btrfs/free-space-cache.c | 6 +-
+ fs/btrfs/fs.h | 6 +
+ fs/btrfs/space-info.c | 69 +++++-
+ fs/btrfs/space-info.h | 19 +-
+ fs/btrfs/super.c | 2 +
+ fs/btrfs/sysfs.c | 48 ++++
+ fs/btrfs/volumes.c | 31 +++
+ 12 files changed, 688 insertions(+), 7 deletions(-)
diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index b0adf7aded255..f9c506b8c80d0 100644
+index dfe7e5eb7511c..8a5f45f15826c 100644
--- a/fs/btrfs/block-group.c
+++ b/fs/btrfs/block-group.c
-@@ -1424,6 +1424,18 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
+@@ -826,6 +826,14 @@ static void stripe_open_remainder_sync(struct btrfs_block_group *bg)
+ } else {
+ sinfo->bytes_stripe_open += delta;
+ }
++ /*
++ * A claimed run's remainder left the free space cache, but
++ * reloc_reserve_free() still counts it: move it out of a held
++ * group's share with it, or bytes_stripe_open and
++ * bytes_reloc_reserve both count it until the next commit's
++ * resync. Every writer of the share holds sinfo->lock.
++ */
++ btrfs_reloc_reserve_adjust(bg, -delta);
+ spin_unlock(&sinfo->lock);
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+@@ -3514,6 +3522,8 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
+ * the counter can be made authoritative. Called after btrfs_finish_extent_commit
+ * so the free space cache reflects this transaction's frees.
+ */
++static void reloc_reserve_resync(struct btrfs_block_group *bg);
++
+ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ {
+ struct btrfs_space_info *sinfo;
+@@ -3586,11 +3596,20 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ total += bg->stripe_unusable;
+ total_stranded += READ_ONCE(bg->stripe_stranded);
+ total_claimable += bg->stripe_claimable;
+- if (bg->start == READ_ONCE(fs_info->data_reloc_bg))
++ /* a held group's are in bytes_reloc_reserve */
++ if (bg->start == READ_ONCE(fs_info->data_reloc_bg) &&
++ !test_bit(BLOCK_GROUP_FLAG_RELOC_RESERVE,
++ &bg->runtime_flags))
+ total_claimable_reloc +=
+ bg->stripe_claimable;
+ nr_rw++;
+ largest = max(largest, bg->length);
++ if (test_bit(BLOCK_GROUP_FLAG_RELOC_RESERVE,
++ &bg->runtime_flags)) {
++ spin_lock(&bg->lock);
++ reloc_reserve_resync(bg);
++ spin_unlock(&bg->lock);
++ }
+ }
+ unit = max(unit, bg->full_stripe_len);
+ }
+@@ -4790,6 +4809,18 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
goto out;
}
num_bytes = btrfs_block_group_available_space(cache);
/*
-@@ -1441,6 +1453,13 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
- */
- if (sinfo_used + num_bytes <= sinfo->total_bytes)
+@@ -4879,6 +4910,20 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
+ if (btrfs_can_overcommit(sinfo, num_bytes - trapped,
+ BTRFS_RESERVE_NO_FLUSH, true))
ret = 0;
+ /*
-+ * Or relocation has somewhere to put this group's live data:
-+ * that is what the relocation reserve is for, and a full
-+ * filesystem is exactly when the group needs relocating.
++ * Or the relocation reserve can take this group's live tree
++ * blocks: a failed tree block allocation outside the reserve
++ * falls back into it. Only with a reserve and something to
++ * move: an empty group would pass "0 >= 0" with the reserve
++ * off. Data gets no such exemption: its test above fails only
++ * while bytes_may_use depends on this group's free space, and
++ * data writeback has no reserve to fall back on.
+ */
-+ else if (sinfo->bytes_reloc_reserve >= cache->used)
-+ ret = 0;
- } else {
- /*
- * We overcommit metadata, so we need to do the
-@@ -1450,6 +1469,8 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
- */
- if (btrfs_can_overcommit(sinfo, num_bytes, BTRFS_RESERVE_NO_FLUSH))
- ret = 0;
-+ else if (sinfo->bytes_reloc_reserve >= cache->used)
++ else if (sinfo->bytes_reloc_reserve &&
++ cache->used + cache->reserved &&
++ sinfo->bytes_reloc_reserve >=
++ cache->used + cache->reserved)
+ ret = 0;
}
if (!ret) {
-@@ -1464,6 +1485,8 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
+@@ -4893,6 +4938,8 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
}
out:
+ btrfs_reloc_reserve_rejoin(cache);
spin_unlock(&cache->lock);
spin_unlock(&sinfo->lock);
- if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
-@@ -1651,7 +1674,9 @@ void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
+ /*
+@@ -5090,7 +5137,9 @@ void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
((block_group->flags & BTRFS_BLOCK_GROUP_SYSTEM) &&
space_info->total_bytes - block_group->length <
system_space_target(space_info)) ||
/*
* We want to bail if we made new allocations or have
* outstanding allocations in this block group. We do
-@@ -3256,6 +3281,7 @@ void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
- }
+@@ -7131,6 +7180,7 @@ void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
sinfo->bytes_readonly -= btrfs_block_group_available_space(cache);
list_del_init(&cache->ro_list);
+ became_rw = true;
+ btrfs_reloc_reserve_rejoin(cache);
}
spin_unlock(&cache->lock);
spin_unlock(&sinfo->lock);
-@@ -3672,6 +3698,7 @@ int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
+@@ -7557,6 +7607,7 @@ int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
}
cache->reserved += num_bytes;
if (delalloc)
cache->delalloc_bytes += num_bytes;
-@@ -3720,6 +3747,8 @@ void btrfs_free_reserved_bytes(struct btrfs_block_group *cache, u64 num_bytes,
+@@ -7605,6 +7656,8 @@ void btrfs_free_reserved_bytes(struct btrfs_block_group *cache, u64 num_bytes,
spin_lock(&cache->lock);
bg_ro = cache->ro;
cache->reserved -= num_bytes;
btrfs_maybe_reset_size_class(cache);
if (is_delalloc)
cache->delalloc_bytes -= num_bytes;
-@@ -4684,3 +4713,334 @@ int btrfs_populate_fully_remapped_bgs_list(struct btrfs_fs_info *fs_info)
+@@ -8607,3 +8660,382 @@ int btrfs_populate_fully_remapped_bgs_list(struct btrfs_fs_info *fs_info)
return 0;
}
+ if (test_and_set_bit(BLOCK_GROUP_FLAG_RELOC_RESERVE, &bg->runtime_flags))
+ return;
+ bg->reloc_reserve_bytes = reloc_reserve_free(bg);
++ /*
++ * An armed group's trapped free space is in bytes_stripe_unusable and
++ * its open runs' remainders in bytes_stripe_open: only its claimable
++ * stripes are relocation room (see reloc_reserve_resync()). A group
++ * not armed yet is capped when it is (btrfs_reloc_reserve_cap()).
++ */
++ if (READ_ONCE(bg->stripe_unusable_ready))
++ bg->reloc_reserve_bytes = min(bg->reloc_reserve_bytes,
++ READ_ONCE(bg->stripe_claimable));
+ bg->space_info->bytes_reloc_reserve += bg->reloc_reserve_bytes;
+}
+
+}
+
+/*
++ * Lower @bg's share to at most @cap, for a group being armed for stripe_alloc
++ * or stripe_meta accounting: from then on only its claimable stripes are
++ * relocation room. Caller holds space_info->lock, which every writer of the
++ * share takes, but not @bg->lock.
++ */
++void btrfs_reloc_reserve_cap(struct btrfs_block_group *bg, u64 cap)
++{
++ lockdep_assert_held(&bg->space_info->lock);
++ if (test_bit(BLOCK_GROUP_FLAG_RELOC_RESERVE, &bg->runtime_flags) &&
++ bg->reloc_reserve_bytes > cap)
++ btrfs_reloc_reserve_adjust(bg,
++ -(s64)(bg->reloc_reserve_bytes - cap));
++}
++
++/*
+ * What the reserve must hold: the most live bytes any block group of
+ * @space_info can carry, its length less the superblock mirrors inside it. A
+ * relocation moves one existing group's live bytes, so the largest existing
+}
+
+/*
++ * Under stripe_alloc / stripe_meta only a held group's whole claimable
++ * stripes are relocation room; its trapped free space is counted in
++ * bytes_stripe_unusable already, and counting it here too made the reserve
++ * look full while relocation found no stripe to claim (claimable 3.3M
++ * against a 34M reserve). Resync the group's share to its claimable
++ * stripes at each commit-time rescan. Caller holds space_info->lock and
++ * @bg->lock.
++ */
++static void reloc_reserve_resync(struct btrfs_block_group *bg)
++{
++ struct btrfs_space_info *sinfo = bg->space_info;
++ u64 want;
++
++ if (!test_bit(BLOCK_GROUP_FLAG_RELOC_RESERVE, &bg->runtime_flags) ||
++ !READ_ONCE(bg->stripe_unusable_ready))
++ return;
++ want = min(reloc_reserve_free(bg), READ_ONCE(bg->stripe_claimable));
++ sinfo->bytes_reloc_reserve -= min(sinfo->bytes_reloc_reserve,
++ bg->reloc_reserve_bytes);
++ bg->reloc_reserve_bytes = want;
++ sinfo->bytes_reloc_reserve += want;
++}
++
++/*
+ * @bg left the reserve to go read-only and is writable again (or never went
+ * read-only): rejoin, unless the reserve is off. A surplus this makes is
+ * released by the next settle. Caller holds space_info->lock and @bg->lock.
+ btrfs_reloc_reserve_update(fs_info, true);
+}
diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index d567ed822e55d..ab7bcb7e82294 100644
+index 605e040421e45..b28f36ebcc5cd 100644
--- a/fs/btrfs/block-group.h
+++ b/fs/btrfs/block-group.h
-@@ -88,6 +88,16 @@ enum btrfs_block_group_flags {
- BLOCK_GROUP_FLAG_NEW,
- BLOCK_GROUP_FLAG_FULLY_REMAPPED,
- BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING,
+@@ -163,6 +163,16 @@ enum btrfs_block_group_flags {
+ * write-hole debug check skips such groups (sticky, debug only).
+ */
+ BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED,
+ /*
+ * Held empty for relocation: only relocation may allocate here (see
+ * btrfs_reloc_reserve_update()).
+ * relocation that failed): rejoins it when writable again.
+ */
+ BLOCK_GROUP_FLAG_RELOC_RESERVE_LAPSED,
- };
-
- enum btrfs_caching_type {
-@@ -265,6 +275,12 @@ struct btrfs_block_group {
+ /*
+ * A RAID5/6 group with a single data stripe, which is mapped as
+ * RAID1/RAID1C3 (its chunk map's type differs from on_disk_type). Its
+@@ -430,6 +440,14 @@ struct btrfs_block_group {
*/
u64 alloc_offset;
u64 zone_unusable;
+ /*
+ * While BLOCK_GROUP_FLAG_RELOC_RESERVE is set: this group's share of
-+ * space_info->bytes_reloc_reserve (its free bytes). Protected by
-+ * space_info->lock and this group's lock.
++ * space_info->bytes_reloc_reserve (its free bytes; under stripe_alloc
++ * or stripe_meta, its claimable stripes). Written under
++ * space_info->lock, mostly with this group's lock too; read under
++ * either.
+ */
+ u64 reloc_reserve_bytes;
u64 zone_capacity;
u64 meta_write_pointer;
struct btrfs_chunk_map *physical_map;
-@@ -340,6 +356,13 @@ void btrfs_remove_bg_from_sinfo(struct btrfs_block_group *bg);
+@@ -650,6 +668,14 @@ void btrfs_remove_bg_from_sinfo(struct btrfs_block_group *bg);
int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
struct btrfs_chunk_map *map);
void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info);
+void btrfs_reloc_reserve_rejoin(struct btrfs_block_group *bg);
+void btrfs_reloc_reserve_claim(struct btrfs_block_group *bg);
+void btrfs_reloc_reserve_adjust(struct btrfs_block_group *bg, s64 delta);
++void btrfs_reloc_reserve_cap(struct btrfs_block_group *bg, u64 cap);
+u64 btrfs_reloc_reserve_target(struct btrfs_space_info *space_info);
void btrfs_mark_bg_unused(struct btrfs_block_group *bg);
void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limit);
void btrfs_reclaim_bgs_work(struct work_struct *work);
diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index c628c5081d923..c8254d91f9e91 100644
+index 27faf262898f7..ff4e7b38f9f1e 100644
--- a/fs/btrfs/disk-io.c
+++ b/fs/btrfs/disk-io.c
-@@ -1519,6 +1519,9 @@ static int cleaner_kthread(void *arg)
+@@ -1520,6 +1520,9 @@ static int cleaner_kthread(void *arg)
*/
btrfs_delete_unused_bgs(fs_info);
/*
* Reclaim block groups in the reclaim_bgs list after we deleted
* all unused block_groups. This possibly gives us some more free
-@@ -3152,6 +3155,9 @@ int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
- }
+@@ -3171,6 +3174,9 @@ int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
up_read(&fs_info->cleanup_work_sem);
+ WRITE_ONCE(fs_info->mount_cleanup_task, NULL);
+ /* Log replay and orphan cleanup are done: hold the relocation reserve. */
+ btrfs_reloc_reserve_update(fs_info, true);
ret = btrfs_recover_relocation(fs_info);
mutex_unlock(&fs_info->cleaner_mutex);
diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 9b0a5c6b96f3c..b274006882407 100644
+index 1ad3d605e4543..112021e7c336f 100644
--- a/fs/btrfs/extent-tree.c
+++ b/fs/btrfs/extent-tree.c
-@@ -2900,6 +2900,9 @@ static int unpin_extent_range(struct btrfs_fs_info *fs_info,
+@@ -2911,6 +2911,9 @@ static int unpin_extent_range(struct btrfs_fs_info *fs_info,
/* Need reset before reusing in a zoned block group */
btrfs_space_info_update_bytes_zone_unusable(space_info, len);
} else if (return_free_space) {
+ spin_unlock(&cache->lock);
btrfs_return_free_space(space_info, len);
}
- spin_unlock(&space_info->lock);
-@@ -3867,6 +3870,10 @@ static int find_free_extent_clustered(struct btrfs_block_group *bg,
+ if (quarantine_back)
+@@ -3897,6 +3900,10 @@ static int find_free_extent_clustered(struct btrfs_block_group *bg,
!block_group_bits(cluster_bg, ffe_ctl->flags) ||
!find_free_extent_check_size_class(ffe_ctl, cluster_bg)))
goto release_cluster;
offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
ffe_ctl->num_bytes, cluster_bg->start,
-@@ -4635,7 +4642,10 @@ static noinline int find_free_extent(struct btrfs_root *root,
+@@ -4380,9 +4387,16 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
+ }
+ spin_unlock(&fs_info->relocation_bg_lock);
+ if (dedicated_now && block_group->space_info) {
+- /* its claimable stripes now belong to relocation alone */
++ /*
++ * its claimable stripes now belong to relocation alone; a held
++ * group's are in bytes_reloc_reserve, not to be subtracted
++ * from everyone else's supply twice. A group that joins the
++ * reserve after its dedication drops out at the next rescan.
++ */
+ spin_lock(&block_group->space_info->lock);
+ block_group->space_info->bytes_stripe_claimable_reloc =
++ test_bit(BLOCK_GROUP_FLAG_RELOC_RESERVE,
++ &block_group->runtime_flags) ? 0 :
+ READ_ONCE(block_group->stripe_claimable);
+ spin_unlock(&block_group->space_info->lock);
+ }
+@@ -4913,7 +4927,10 @@ static noinline int find_free_extent(struct btrfs_root *root,
down_read(&space_info->groups_sem);
if (list_empty(&block_group->list) ||
block_group->ro ||
/*
* someone is removing this block group,
* we can't jump into the have_block_group
-@@ -4678,6 +4688,12 @@ static noinline int find_free_extent(struct btrfs_root *root,
+@@ -4956,6 +4973,12 @@ static noinline int find_free_extent(struct btrfs_root *root,
continue;
}
btrfs_grab_block_group(block_group, ffe_ctl->delalloc);
ffe_ctl->search_start = block_group->start;
-@@ -4882,6 +4898,7 @@ int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
- int ret;
- bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
+@@ -5182,6 +5205,7 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ u64 log_owner = for_treelog ? root->root_key.offset : 0;
+ u64 log_transid = for_treelog ? root->log_transid : 0;
bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
+ bool use_reloc_reserve = false;
+ struct btrfs_inode *steer_inode = NULL;
+ enum btrfs_stripe_run_class steer_class = BTRFS_STRIPE_RUN_COW;
- flags = get_alloc_profile_by_root(root, is_data);
- again:
-@@ -4896,11 +4913,26 @@ int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
- ffe_ctl.hint_byte = hint_byte;
- ffe_ctl.for_treelog = for_treelog;
- ffe_ctl.for_data_reloc = for_data_reloc;
+@@ -5238,11 +5262,26 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ ffe_ctl.steer_inode = steer_inode;
+ ffe_ctl.steer_class = steer_class;
+ ffe_ctl.split_bytes = split_bytes;
+ ffe_ctl.for_reloc = for_data_reloc || btrfs_is_reloc_task(fs_info) ||
+ use_reloc_reserve;
num_bytes = min(num_bytes >> 1, ins->offset);
num_bytes = round_down(num_bytes,
diff --git a/fs/btrfs/extent-tree.h b/fs/btrfs/extent-tree.h
-index ff330d4896d66..70090af81f743 100644
+index 751babb11dedb..b657c77951e27 100644
--- a/fs/btrfs/extent-tree.h
+++ b/fs/btrfs/extent-tree.h
-@@ -49,6 +49,9 @@ struct find_free_extent_ctl {
+@@ -56,6 +56,9 @@ struct find_free_extent_ctl {
/* Allocation is called for data relocation */
bool for_data_reloc;
+ bool for_reloc;
+
/*
- * Set to true if we're retrying the allocation on this block group
- * after waiting for caching progress, this is so that we retry only
+ * Data allocation to steer into a private stripe run (see
+ * stripe_run_owner()), and the run class: NOCOW for nodatacow and
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 2106eec097812..54a33e604c84d 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1567,7 +1567,9 @@ 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)) {
++ /* a held group's stripes are in bytes_reloc_reserve instead */
++ if (bg->start == READ_ONCE(bg->fs_info->data_reloc_bg) &&
++ !test_bit(BLOCK_GROUP_FLAG_RELOC_RESERVE, &bg->runtime_flags)) {
+ if (delta < 0 && sinfo->bytes_stripe_claimable_reloc < (u64)-delta)
+ sinfo->bytes_stripe_claimable_reloc = 0;
+ else
+@@ -2376,6 +2378,8 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
+ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info, trapped);
+ btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
+ claimable);
++ /* A held group's share is its claimable stripes from here on. */
++ btrfs_reloc_reserve_cap(bg, claimable);
+ spin_unlock(&bg->space_info->lock);
+ spin_unlock(&ctl->tree_lock);
+ kvfree(freep);
diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 2dd167c32d612..3b0c9653c8194 100644
+index edb2202d17c4b..6838552fb5c7b 100644
--- a/fs/btrfs/fs.h
+++ b/fs/btrfs/fs.h
-@@ -755,6 +755,12 @@ struct btrfs_fs_info {
- struct btrfs_space_info *data_sinfo;
-
- struct reloc_control *reloc_ctl;
-+ /*
-+ * The task inside btrfs_relocate_block_group(), for its whole run
-+ * (reloc_chunk_start() serializes relocations). Its allocations and
-+ * reservations may use the relocation reserve.
-+ */
-+ struct task_struct *reloc_owner;
-
- /* data_alloc_cluster is only used in ssd_spread mode */
- struct btrfs_free_cluster data_alloc_cluster;
-@@ -1158,6 +1164,12 @@ void __btrfs_clear_fs_compat_ro(struct btrfs_fs_info *fs_info, u64 flag,
+@@ -1442,6 +1442,12 @@ void __btrfs_clear_fs_compat_ro(struct btrfs_fs_info *fs_info, u64 flag,
#define btrfs_test_opt(fs_info, opt) ((fs_info)->mount_opt & \
BTRFS_MOUNT_##opt)
static inline bool btrfs_is_full_ro(const struct btrfs_fs_info *fs_info)
{
if (!sb_rdonly(fs_info->sb))
-diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
-index b2ac5b836b217..179bac3a2dccd 100644
---- a/fs/btrfs/relocation.c
-+++ b/fs/btrfs/relocation.c
-@@ -5494,6 +5494,7 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
- ret = reloc_chunk_start(fs_info);
- if (ret < 0)
- goto out_put_rc;
-+ WRITE_ONCE(fs_info->reloc_owner, current);
-
- ret = btrfs_inc_block_group_ro(rc->block_group, true);
- if (ret)
-@@ -5561,6 +5562,7 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
- if (!btrfs_fs_incompat(fs_info, REMAP_TREE))
- iput(rc->data_inode);
- btrfs_free_path(path);
-+ WRITE_ONCE(fs_info->reloc_owner, NULL);
- reloc_chunk_end(fs_info);
- out_put_rc:
- put_reloc_control(rc);
diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index d5a84fa97462c..18dedf106ae53 100644
+index 22839793ed94f..0b4528a2d3be6 100644
--- a/fs/btrfs/space-info.c
+++ b/fs/btrfs/space-info.c
-@@ -186,11 +186,25 @@ struct reserve_ticket {
- u64 bytes;
- int error;
+@@ -189,6 +189,8 @@ struct reserve_ticket {
bool steal;
-+ /* Made by the relocating task: may use the relocation reserve. */
-+ bool reloc;
- struct list_head list;
- wait_queue_head_t wait;
+ /* Made by the relocation task: may draw on bytes_stripe_reserve. */
+ bool reloc;
++ /* Made by the relocating task: may draw on the relocation reserve. */
++ bool reloc_reserve;
+ /* Made by the mount-time orphan cleanup: may steal regardless. */
+ bool mount_cleanup;
+ /*
+@@ -208,6 +210,18 @@ struct reserve_ticket {
spinlock_t lock;
};
/*
* after adding space to the filesystem, we need to clear the full flags
* on all the space infos.
-@@ -258,6 +272,11 @@ static void init_space_info(struct btrfs_fs_info *info,
+@@ -275,6 +289,11 @@ static void init_space_info(struct btrfs_fs_info *info,
INIT_LIST_HEAD(&space_info->ro_bgs);
INIT_LIST_HEAD(&space_info->tickets);
INIT_LIST_HEAD(&space_info->priority_tickets);
space_info->clamp = 1;
btrfs_update_space_info_chunk_size(space_info, calc_chunk_size(info, flags));
space_info->subgroup_id = BTRFS_SUB_GROUP_PRIMARY;
-@@ -400,6 +419,13 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
+@@ -459,6 +478,13 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
btrfs_space_info_update_bytes_zone_unusable(space_info, block_group->zone_unusable);
if (block_group->length > 0)
space_info->full = false;
btrfs_try_granting_tickets(space_info);
spin_unlock(&space_info->lock);
-@@ -547,7 +573,9 @@ bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
- if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
- return false;
-
-- used = btrfs_space_info_used(space_info, true);
-+ used = reloc_adjusted_used(space_info,
-+ btrfs_space_info_used(space_info, true),
+@@ -704,6 +730,9 @@ bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
+ */
+ if (reloc)
+ used -= min(used, space_info->bytes_stripe_reserve);
++ /* the relocation reserve is the relocating task's alone */
++ used = reloc_adjusted_used(space_info, used, reloc &&
+ btrfs_is_reloc_task(space_info->fs_info));
return check_can_overcommit(space_info, used, bytes, flush);
}
-@@ -597,13 +625,15 @@ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info)
- while (!list_empty(head)) {
- struct reserve_ticket *ticket;
- u64 used_after;
-+ u64 tused;
-
- ticket = list_first_entry(head, struct reserve_ticket, list);
- used_after = used + ticket->bytes;
-+ tused = reloc_adjusted_used(space_info, used, ticket->reloc);
+@@ -878,6 +907,12 @@ static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 byte
+ } else {
+ /* ...and that group is out of reach for everyone else */
+ supply -= min(supply, dedicated);
++ /*
++ * ...and so are the groups held for relocation (the
++ * relocation reserve): whole stripes, but relocation's.
++ */
++ supply -= min(supply,
++ READ_ONCE(space_info->bytes_reloc_reserve));
+ /*
+ * Charge what writeback can claim for the data: whole
+ * stripes of whichever group it lands in. Not the
+@@ -946,6 +981,8 @@ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info)
+ tused = used;
+ if (ticket->reloc)
+ tused -= min(tused, space_info->bytes_stripe_reserve);
++ tused = reloc_adjusted_used(space_info, tused,
++ ticket->reloc_reserve);
- /* 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 (tused + ticket->bytes <= space_info->total_bytes ||
-+ can_overcommit(space_info, tused, ticket->bytes, flush)) {
- btrfs_space_info_update_bytes_may_use(space_info, ticket->bytes);
- remove_ticket(space_info, ticket, 0);
- space_info->tickets_id++;
-@@ -1792,6 +1822,7 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
- u64 used;
- int ret = -ENOSPC;
- bool pending_tickets;
-+ const bool reloc = btrfs_is_reloc_task(fs_info);
+ /*
+ * Check and see if our ticket can be satisfied now. The
+@@ -2233,6 +2270,8 @@ static int __reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
+ flush == BTRFS_RESERVE_NO_FLUSH ||
+ flush == BTRFS_RESERVE_FLUSH_LIMIT ||
+ flush == BTRFS_RESERVE_FLUSH_EMERGENCY;
++ /* Only the relocating task may draw on the relocation reserve. */
++ const bool reloc_task = btrfs_is_reloc_task(fs_info);
ASSERT(orig_bytes, "orig_bytes=%llu", orig_bytes);
/*
-@@ -1813,7 +1844,8 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
+@@ -2255,7 +2294,8 @@ static int __reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
async_work = &fs_info->async_reclaim_work;
spin_lock(&space_info->lock);
- used = btrfs_space_info_used(space_info, true);
+ used = reloc_adjusted_used(space_info,
-+ btrfs_space_info_used(space_info, true), reloc);
++ btrfs_space_info_used(space_info, true), reloc_task);
/*
* We don't want NO_FLUSH allocations to jump everybody, they can
-@@ -1863,6 +1895,7 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
- space_info->reclaim_size += ticket.bytes;
- init_waitqueue_head(&ticket.wait);
+@@ -2313,6 +2353,7 @@ static int __reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
spin_lock_init(&ticket.lock);
-+ ticket.reloc = reloc;
ticket.steal = can_steal(flush);
- if (trace_btrfs_reserve_ticket_enabled())
- start_ns = ktime_get_ns();
-@@ -1994,6 +2027,32 @@ __cold void btrfs_dump_space_info_for_trans_abort(struct btrfs_fs_info *fs_info)
+ ticket.reloc = reloc;
++ ticket.reloc_reserve = reloc_task;
+ ticket.mount_cleanup =
+ READ_ONCE(fs_info->mount_cleanup_task) == current;
+ ticket.hold_stripe = held != NULL;
+@@ -2514,6 +2555,32 @@ __cold void btrfs_dump_space_info_for_trans_abort(struct btrfs_fs_info *fs_info)
dump_global_block_rsv(fs_info);
}
* Account the unused space of all the readonly block group in the space_info.
* takes mirrors into account.
diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 0456b0d2d1b4a..08ee1111085de 100644
+index a38a36362e9bc..eda38ad588b7d 100644
--- a/fs/btrfs/space-info.h
+++ b/fs/btrfs/space-info.h
-@@ -148,6 +148,8 @@ struct btrfs_space_info {
+@@ -156,6 +156,8 @@ struct btrfs_space_info {
u64 bytes_may_use; /* number of bytes that may be used for
delalloc/allocations */
u64 bytes_readonly; /* total bytes that are read only */
+ relocation; used for everyone else */
u64 bytes_zone_unusable; /* total bytes that are unusable until
resetting the device zone */
-
-@@ -163,6 +165,20 @@ struct btrfs_space_info {
+ u64 bytes_stripe_unusable; /* free bytes stripe_alloc and
+@@ -226,6 +228,20 @@ struct btrfs_space_info {
*/
int bg_reclaim_threshold;
int clamp; /* Used to scale our threshold for preemptive
flushing. The value is >> clamp, so turns
out to be a 2^clamp divisor. */
-@@ -290,7 +306,7 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
+@@ -372,7 +388,7 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
return s_info->bytes_used + s_info->bytes_reserved +
s_info->bytes_pinned + s_info->bytes_readonly +
- s_info->bytes_zone_unusable +
+ s_info->bytes_zone_unusable + s_info->bytes_reloc_reserve +
- (may_use_included ? s_info->bytes_may_use : 0);
- }
-
-@@ -307,6 +323,7 @@ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
+ s_info->bytes_stripe_unusable + s_info->bytes_stripe_open +
+ s_info->bytes_stripe_margin +
+ s_info->bytes_stripe_reserve +
+@@ -404,6 +420,7 @@ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
u64 orig_bytes,
enum btrfs_reserve_flush_enum flush);
void btrfs_try_granting_tickets(struct btrfs_space_info *space_info);
+u64 btrfs_account_reloc_reserve_free_space(struct btrfs_space_info *sinfo);
bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
- enum btrfs_reserve_flush_enum flush);
+ enum btrfs_reserve_flush_enum flush, bool reloc);
diff --git a/fs/btrfs/super.c b/fs/btrfs/super.c
-index b424cc836bd4a..829cd78d04dfd 100644
+index bce3a12032b6a..ce98375c49692 100644
--- a/fs/btrfs/super.c
+++ b/fs/btrfs/super.c
-@@ -1729,6 +1729,8 @@ static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
+@@ -1753,6 +1753,8 @@ static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
total_free_data += found->disk_total - found->disk_used;
total_free_data -=
btrfs_account_ro_block_groups_free_space(found);
for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
if (!list_empty(&found->block_groups[i]))
diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 89b0a4ef4063e..4a94ab172a27a 100644
+index 213001078a2ab..f77f709d2cbcd 100644
--- a/fs/btrfs/sysfs.c
+++ b/fs/btrfs/sysfs.c
-@@ -788,6 +788,7 @@ SPACE_INFO_ATTR(bytes_reserved);
- SPACE_INFO_ATTR(bytes_may_use);
- SPACE_INFO_ATTR(bytes_readonly);
- SPACE_INFO_ATTR(bytes_zone_unusable);
+@@ -885,6 +885,7 @@ SPACE_INFO_ATTR(bytes_stripe_open);
+ SPACE_INFO_ATTR(bytes_stripe_margin);
+ SPACE_INFO_ATTR(bytes_stripe_reserve);
+ SPACE_INFO_ATTR(bytes_stripe_quarantine);
+SPACE_INFO_ATTR(bytes_reloc_reserve);
SPACE_INFO_ATTR(disk_used);
SPACE_INFO_ATTR(disk_total);
SPACE_INFO_ATTR(reclaim_count);
-@@ -836,6 +837,50 @@ BTRFS_ATTR_RW(space_info, bg_reclaim_threshold,
+@@ -934,6 +935,50 @@ BTRFS_ATTR_RW(space_info, bg_reclaim_threshold,
btrfs_sinfo_bg_reclaim_threshold_show,
btrfs_sinfo_bg_reclaim_threshold_store);
static ssize_t btrfs_sinfo_dynamic_reclaim_show(struct kobject *kobj,
struct kobj_attribute *a,
char *buf)
-@@ -919,6 +964,9 @@ static struct attribute *space_info_attrs[] = {
+@@ -1024,6 +1069,9 @@ static struct attribute *space_info_attrs[] = {
BTRFS_ATTR_PTR(space_info, disk_used),
BTRFS_ATTR_PTR(space_info, disk_total),
BTRFS_ATTR_PTR(space_info, bg_reclaim_threshold),
BTRFS_ATTR_PTR(space_info, chunk_size),
BTRFS_ATTR_PTR(space_info, size_classes),
diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
-index ce78a9441c64f..f78f83bfe9f47 100644
+index 9f689c4c9d7f8..6a68ecc752d25 100644
--- a/fs/btrfs/volumes.c
+++ b/fs/btrfs/volumes.c
@@ -3723,8 +3723,16 @@ static int btrfs_relocate_chunk_finish(struct btrfs_fs_info *fs_info,
return ret;
}
-@@ -4327,6 +4339,25 @@ static int should_balance_chunk(struct extent_buffer *leaf, struct btrfs_chunk *
+@@ -4351,6 +4363,25 @@ static int should_balance_chunk(struct extent_buffer *leaf, struct btrfs_chunk *
return false;
}
-From 087669d83341b0e044a253146b2f633bc4f63534 Mon Sep 17 00:00:00 2001
+From 206f44fec60d023c07b8ebb664fa68bfbeb45902 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Wed, 21 Oct 2026 12:48:13 -0400
Subject: [PATCH 3/3] btrfs: relocation: flush fully before failing a merge
1 file changed, 10 insertions(+), 1 deletion(-)
diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
-index 179bac3a2dccd..87e22737405b4 100644
+index d9f218e128f6c..74e8adb281215 100644
--- a/fs/btrfs/relocation.c
+++ b/fs/btrfs/relocation.c
-@@ -1675,8 +1675,17 @@ static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
+@@ -1715,8 +1715,17 @@ static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
memset(&next_key, 0, sizeof(next_key));
while (1) {
# Testing: low-space
+Since 2026-10-29 (lsrestack, promoted both lanes) the series is stacked
+on stripe-alloc: the stripe_alloc integration that the rows below call
+"octopus integration" or "fixup" is now part of patch 2, and no octopus
+resolution remains. The restack was tree-identical (misc-next testing
+329cf72e3475 has the same tree as before it), so the results below carry
+over; nothing was rerun for it.
+
+**2026-10-30 (review of 2026-10-29, promoted both lanes):** patch 2
+changed: only the relocating task may use the reserve (stripe_alloc's
+reloc flag no longer admits the transaction machinery's bounded
+reservations to it), only a metadata group with a reserve and live bytes
+may go read-only on the reserve's account (no data exemption), the held
+share is capped at the claimable stripes between rescans and a claimed
+run's remainder leaves it, and held stripes are not counted again as
+the data relocation group's. Rows dated before 2026-10-30 are on the
+earlier patch 2. Runtime round on the candidates
+(`raid56-wh-harness/forensics/review1029-rt-20261029/`):
+reloc-reserve raid1/raid1 and raid5/raid1 PASS on both lanes;
+raid5/raid5 with `RR_STRIPE_ALLOC=1`: misc-next reserve arm PASS (data
+and metadata balance complete, 1035 files verify), control arm ENOSPC
+abort with WARN extent-tree.c:3451 in `find` (files intact; the lane
+shows the same class of WARN); 6.18 reserve arm no verdict (6000 s and
+9000 s caps, delete grind after the fills; the lane baseline also had
+no verdict within 4 h). raid5/raid5 without stripe_alloc: not run.
+
Patch 1 makes a failed background reclaim log its error code ("error
relocating chunk <start>: <errno>" instead of the bare line). Patch 2
keeps, per space_info, a set of block groups held free for relocation
-From a69ecf626addcaa2c0d02bb8fefb6d964ead28a6 Mon Sep 17 00:00:00 2001
+From 34bdaeed875088260f83d6c1ad6212c858199eb1 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:37 -0400
+Date: Fri, 30 Oct 2026 22:32:34 -0400
Subject: [PATCH 0/1] btrfs: limit preallocated extents to 128 MiB
To: linux-btrfs@vger.kernel.org
1 file changed, 1 insertion(+), 1 deletion(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From a69ecf626addcaa2c0d02bb8fefb6d964ead28a6 Mon Sep 17 00:00:00 2001
+From 34bdaeed875088260f83d6c1ad6212c858199eb1 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 21 Dec 2024 10:48:03 -0500
Subject: [PATCH 1/1] btrfs: use BTRFS_MAX_EXTENT_SIZE in prealloc
-From 796097dafc9486af8ee93c8e073d5ca1de5cfc14 Mon Sep 17 00:00:00 2001
+From a4b35a2e9704dbbb331f8931774d6d433c4bffeb Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:37 -0400
+Date: Fri, 30 Oct 2026 22:32:34 -0400
Subject: [PATCH 00/12] btrfs: raid56: rbio lifetime and cache fixes, error reporting
To: linux-btrfs@vger.kernel.org
dead or silently corrupting member. The patches are independent of
each other unless noted.
-Patch 1 logs a message when an extent is dropped because its write
+Patches 1 and 2 are Qu Wenruo's "btrfs: raid56: minor fixes to
+rmw_rbio()", as posted (Reviewed-by: Filipe Manana, Link: tags in the
+patches). They are included because patch 12 applies on top of patch
+2; if they are merged first, "git am --skip" drops them here. Patch 1
+closes a race in which a bio merged into an rbio that failed early was
+never ended. Patch 2 stops an rbio whose write failed from being cached
+for page stealing: a later sub-stripe write to the same full stripe
+would otherwise take those pages instead of reading the disk and compute
+parity over data the failed members never got. It replaces a fix of
+our own for the same bug.
+
+Patch 3 logs a message when an extent is dropped because its write
failed. The error reaches userspace only through fsync or syncfs, and a
process that wrote a file and exited with its data still in dirty pages
is never told. The message carries both the logical address (which
refused the write), since the mapping between them is gone by the time
the error is handled.
-Patch 2 fixes a use-after-free of the rbio in the bio end_io wakeups.
+Patch 4 fixes a use-after-free of the rbio in the bio end_io wakeups.
The submission rounds count in-flight bios with an atomic and wait with
wait_event(); the waiter can see the counter reach zero and free the
rbio while the last end_io is still inside wake_up() on the rbio's
"pvqspinlock: lock ... has corrupted value" warnings; on bare metal it
is silent. The pair becomes a completion.
-Patch 3 propagates a split bio's error when the split that failed is
+Patch 5 propagates a split bio's error when the split that failed is
not the last to complete; the error was dropped when the last split
succeeded. Not raid56-specific. Fixes: d48e1dea3931.
-Patch 4 drops cached rbios when their stripes' extents are freed. A
+Patch 6 drops cached rbios when their stripes' extents are freed. A
cached rbio's pages can be stolen by a later sub-stripe write to the
same full stripe after the space was freed and reallocated, so parity
is generated from the cache's memory of the stripe's previous contents
read and scrub passes, and reconstruction after a device failure
returns garbage. Proven byte-exactly on a raid5 test array.
-Patch 5 verifies reconstructed tree blocks. Data sectors rebuilt from
+Patch 7 verifies reconstructed tree blocks. Data sectors rebuilt from
parity are checked against their csums; metadata was handed back
unverified, and on raid6 the right one of several candidate
reconstructions could not be chosen. The tree block's own header csum
-is checked once every sector of the block has been recovered.
+is checked once every sector of the block has been recovered. Scrub's
+reads are left out: they cover free space too, and scrub verifies the
+sectors that hold extents itself.
-Patches 6 and 7 fix two races around the rbio cache, both seen as
+Patches 8 and 9 fix two races around the rbio cache, both seen as
crashes on a degraded raid5 array under fsstress and made frequent by
-patch 4's trimming, but reachable with the in-tree cache shrink:
+patch 6's trimming, but reachable with the in-tree cache shrink:
lock_stripe_add()'s steal path drops the hash reference before removing
the rbio from the cache, so a concurrent removal frees it under the
-stealing thread (patch 6); and a cache removal can unhash an rbio that
+stealing thread (patch 8); and a cache removal can unhash an rbio that
has rbios plugged on it and hit BUG_ON(!list_empty(&rbio->plug_list))
-(patch 7).
-
-Patch 8 stops a failed write from leaving its pages for the next write.
-rmw_rbio() marks the stripe pages cache-ready before it submits, and
-unlock_stripe() caches the rbio or hands its pages to the next plugged
-rbio whatever the write's status. When the write failed on more members
-than the profile tolerates, a later sub-stripe write to the same full
-stripe takes those pages instead of reading the disk, computes parity
-over data the failed members never got, and is acked; its data then
-fails its csum when rebuilt after a device loss, and scrub silently
-rewrites the bad parity first if it runs. A write that failed within
-the tolerance completes OK and its pages are the correct stripe
-contents, so those stay cached. Fixes: 4ae10b3a133e.
-
-Patch 9 makes a RAID6 RMW rebuild from Q when a sector rebuilt from P
+(patch 9).
+
+Patch 10 makes a RAID6 RMW rebuild from Q when a sector rebuilt from P
fails its csum. The RMW read phase verifies data sectors and rebuilds a
failed one once, from P; P has no csum, so a stale P (left by a write
that failed within tolerance on a data member and the P member) makes
walks P, Q and P+Q; the RMW now retries in the same order.
Fixes: 7a3150723061.
-Patch 10 counts raid56 member I/O errors in the device stats. raid56
+Patch 11 counts raid56 member I/O errors in the device stats. raid56
submits its stripe bios itself and their end_io only marked the rbio's
error bitmap, so a raid56 write or read that failed on a member (within
tolerance, so the operation succeeded) was never counted in
`btrfs device stats`. The device is found by the bio's bdev, so writes
to a replace target are charged to the target. Fixes: 53b381b3abeb.
-Patch 11 makes a sub-stripe write write back the sectors its RMW read
+Patch 12 makes a sub-stripe write write back the sectors its RMW read
repaired. The read phase verifies data sectors against their csums and
-rebuilds bad ones (and, with patch 9, a stale P or Q), but only the new
+rebuilds bad ones (and, with patch 10, a stale P or Q), but only the new
data and parity were written, so the repaired strip stayed stale on
disk until read repair or scrub found it. Csummed data sectors, P/Q
with an error bit, and nodatasum sectors rebuilt from P+Q together with
device never is, and a failed write-back does not count against the
write's tolerance. Fixes: 7a3150723061.
-Patch 12 is a test fixture and NOT for submission: a CONFIG_BTRFS_DEBUG
-sysfs knob for the rbio cache size, used by the dm-stripfault tests to
-reach the RMW read path. Drop it before sending.
+Qu Wenruo (2):
+ btrfs: fix racy bio_list changes for failed RMW rbio
+ btrfs: don't cache rbio if an error is hit
-Zygo Blaxell (12):
+Zygo Blaxell (10):
btrfs: log a message when dropping an extent due to IO error
btrfs: raid56: fix use-after-free of rbio in bio end_io wakeups
btrfs: propagate a split bio's error when the failing split completes
dropped
btrfs: raid56: do not unhash a cached rbio that has rbios plugged on
it
- btrfs: raid56: do not let a failed write leave its pages for the next
- write
btrfs: raid56: rebuild from Q when a sector rebuilt from P fails its
csum
btrfs: raid56: count I/O errors in the device stats
btrfs: raid56: write back the sectors a sub-stripe write repaired
- DO-NOT-UPSTREAM: btrfs: raid56: debug knob for the rbio stripe cache
- size
fs/btrfs/bio.c | 13 +-
fs/btrfs/bio.h | 2 +
fs/btrfs/extent-tree.c | 10 +
- fs/btrfs/fs.h | 4 +
fs/btrfs/inode.c | 16 ++
- fs/btrfs/raid56.c | 633 ++++++++++++++++++++++++++++++++++++++---
- fs/btrfs/raid56.h | 14 +-
- fs/btrfs/sysfs.c | 28 ++
- 8 files changed, 677 insertions(+), 43 deletions(-)
+ fs/btrfs/raid56.c | 626 +++++++++++++++++++++++++++++++++++++----
+ fs/btrfs/raid56.h | 11 +-
+ 6 files changed, 626 insertions(+), 52 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
--- /dev/null
+From 61de2dcc3af6651d7612d23fd7192fa2838c1278 Mon Sep 17 00:00:00 2001
+From: Qu Wenruo <wqu@suse.com>
+Date: Wed, 28 Oct 2026 17:00:46 +1030
+Subject: [PATCH 01/12] btrfs: fix racy bio_list changes for failed RMW rbio
+To: linux-btrfs@vger.kernel.org
+
+If an RMW work failed early, e.g. alloc_rbio_parity_pages() failed, it
+won't get RBIO_RMW_LOCKED_BIT set, and get rbio_orig_end_io() called.
+
+In that case, there can be a race between bio_list_get() on the rbio,
+and new incoming bio merging into the rbio:
+
+ A is the rbio that rbio_orig_end_io() is running on.
+ a is the higher layer bio that generated the rbio A.
+
+ B is the new rbio that will be merged into A.
+ b is the higher layer bio that generated the rbio B.
+
+ rbio_orig_end_io(A) worker | lock_stripe_add(B)
+--------------------------------------+---------------------------------
+rbio_orig_end_io(A) | lock_stripe_add(B)
+|- cur = bio_list_get(A) | |- rbio_can_merge(A, B)
+| |- bio = A->bio_list.head; | | which returned true
+| | which bio a is returned. | |
+| | | |
+| |- A->bio_list.tail = NULL; | |
+| | | |
+| | | |- merge_rbio(A, B)
+| | | | |- bio_list_merge_init()
+| | | | |- if (A->bio_list.tail)
+| | | | | A->bio_list.tail is
+| | | | | still NULL
+| | | | |
+| | | | |- A->bio_list.head = b
+| | | | |- A->bio_list.tail = b
+| |- A->bio_list.head = NULL; | |- return 1;
+| |- return bio; | Caller expect rbio A to
+| which is bio a. | complete bio b.
+|
+|- extra = bio_list_get()
+| Which is NULL
+|
+|- rbio_endio_bio_list(cur);
+ Which only ends bio a.
+
+In above case, the bio_list race can get bio b lost, and never ended.
+Thankfully this race window is very tiny, so not practical in the real
+world.
+
+Fix it by setting RBIO_RMW_LOCKED_BIT for error path before calling
+rbio_orig_end_io().
+And since we're ensuring all RMW rbios have RBIO_RMW_LOCKED_BIT bit set
+before calling rbio_orig_end_io(), add two ASSERT()s for that and remove
+the old comment.
+
+Fixes: 5eb30ee26fa4 ("btrfs: raid56: introduce the main entrance for RMW path")
+Assisted-by: LLM (find and analyze the bug)
+Reviewed-by: Filipe Manana <fdmanana@suse.com>
+Signed-off-by: Qu Wenruo <wqu@suse.com>
+Link: https://lore.kernel.org/r/5a11091a4fb79de6a37bcec6c70b178467641f28.1793168898.git.wqu@suse.com
+---
+ fs/btrfs/raid56.c | 32 ++++++++++++++++++++------------
+ 1 file changed, 20 insertions(+), 12 deletions(-)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 7dd937fa0c262..b24ec362909bb 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -874,7 +874,10 @@ static void rbio_endio_bio_list(struct bio *cur, blk_status_t status)
+ static void rbio_orig_end_io(struct btrfs_raid_bio *rbio, blk_status_t status)
+ {
+ struct bio *cur = bio_list_get(&rbio->bio_list);
+- struct bio *extra;
++
++ /* An RMW rbio must have RBIO_RMW_LOCKED_BIT set. */
++ if (rbio->operation == BTRFS_RBIO_WRITE)
++ ASSERT(test_bit(RBIO_RMW_LOCKED_BIT, &rbio->flags));
+
+ kfree(rbio->csum_buf);
+ bitmap_free(rbio->csum_bitmap);
+@@ -888,21 +891,11 @@ static void rbio_orig_end_io(struct btrfs_raid_bio *rbio, blk_status_t status)
+ */
+ bitmap_clear(&rbio->dbitmap, 0, rbio->stripe_nsectors);
+
+- /*
+- * At this moment, rbio->bio_list is empty, however since rbio does not
+- * always have RBIO_RMW_LOCKED_BIT set and rbio is still linked on the
+- * hash list, rbio may be merged with others so that rbio->bio_list
+- * becomes non-empty.
+- * Once unlock_stripe() is done, rbio->bio_list will not be updated any
+- * more and we can call bio_endio() on all queued bios.
+- */
+ unlock_stripe(rbio);
+- extra = bio_list_get(&rbio->bio_list);
++ ASSERT(bio_list_empty(&rbio->bio_list));
+ free_raid_bio(rbio);
+
+ rbio_endio_bio_list(cur, status);
+- if (extra)
+- rbio_endio_bio_list(extra, status);
+ }
+
+ /*
+@@ -2464,6 +2457,21 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ }
+ }
+ out:
++ /*
++ * If we hit an error early, the rbio won't get
++ * RBIO_RMW_LOCKED_BIT bit set, and can cause unexpected
++ * merge during rbio_orig_end_io().
++ *
++ * So set that flag before calling rbio_orig_end_io(), and
++ * we have to hold the bio_list_lock, to make sure
++ * rbio_can_merge() and merge_rbio() are seeing a stable
++ * flag.
++ */
++ if (ret < 0) {
++ spin_lock(&rbio->bio_list_lock);
++ set_bit(RBIO_RMW_LOCKED_BIT, &rbio->flags);
++ spin_unlock(&rbio->bio_list_lock);
++ }
+ rbio_orig_end_io(rbio, errno_to_blk_status(ret));
+ }
+
+--
+2.47.3
+
+++ /dev/null
-From 2390ec646753c7827a2398c9b50da8a5c5813beb Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 5 Jul 2024 23:08:46 -0400
-Subject: [PATCH 01/12] btrfs: log a message when dropping an extent due to IO
- error
-To: linux-btrfs@vger.kernel.org
-
-When an IO error occurs while writing a datacow file, btrfs will drop the
-extent containing the unwritten blocks. This prevents potential leaks
-of information stored in the unwritten data blocks back to userspace, but
-it is also a data loss event that is not easily visible from userspace.
-
-The existing code does notify userspace of the error via the inode,
-and the notification can be received through fsync (for the inode) or
-syncfs (for any dirty inode on the filesystem) return values; however,
-for the common case of a process that writes to a file and exits with
-its data still in dirty cache pages, there is no process left to notify
-when the ordered writes eventually fail.
-
-In most cases the extent drop is preceded by error messages from the
-write operation, but the IOERR bit can be set for less visible or obvious
-reasons, like running out of memory, bad metadata, or as a result of
-bugs that appear in other parts of btrfs from time to time.
-
-Some of the existing error messages for writes contain only logical
-addresses, while other messages contain only disk bytenrs. For read
-errors, only one address is necessary, as the user can look up the other
-with `btrfs ins log -o` or `btrfs ins sub/ino`, but for write errors, the
-mapping between these addresses is removed when the error is detected in
-btrfs_finish_one_ordered, so we can't derive one address from the other.
-We need both addresses for separate purposes: the logical address to
-identify which files have missing data, and the disk bytenr to identify
-which part of the filesystem address space is failing to accept writes
-(resolvable to device sectors through the chunk tree).
-
-For now, inform the sysadmin that the data has been dropped by logging a
-message when it happens, including both the logical subvol/inode/offset
-triple and the disk bytenr, and the corresponding sizes.
-
-In the future we might want to add some stats counters for this event,
-similar to the dev stats counters, but not tied to any specific device.
-The first step is to detect and report the events at all.
-
-Other notes:
-
-Because the extent is dropped, the lost data cannot be detected by a csum
-mismatch or read failure, i.e. everything will look OK if the file is read
-or the filesystem scrubbed, but an application will notice a truncated
-file or a file with data replaced by zeros. For datasum files, we could
-simply keep the extent as-is, allow future reads or csum verification
-to fail, and report EIO errors that way. That is a larger and riskier
-change to btrfs behavior than simply adding some passive monitoring of
-the status quo. This approach also has problems with csum collisions,
-it doesn't work for nodatasum+datacow files, and it takes much longer
-for the errors to be detected and reported to a sysadmin.
-
-nodatacow files don't have their extents dropped; instead, they will
-simply have garbage in the blocks where the writes failed. In most
-use cases for nodatacow files (e.g. VM disk images or databases), the
-user will be running all writes through fsync(), O_DIRECT, or similar
-mechanisms that can observe the existing EIO return value notification
-path, so there's less need for diagnostic coverage in the kernel log
-for nodatacow files.
-
-Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
----
- fs/btrfs/inode.c | 16 ++++++++++++++++
- 1 file changed, 16 insertions(+)
-
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index b071ed59a583f..8b95be6893f0e 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -3389,6 +3389,22 @@ int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
- clear_reserved_extent &&
- !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
- !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
-+ /*
-+ * Notify the user that some data has been lost due
-+ * to an error, unless we were already expected to
-+ * remove the data because of truncate.
-+ *
-+ * Put both logical and physical addresses here
-+ * because we're about to remove the mapping that
-+ * would have allowed the user to translate from
-+ * one to the other.
-+ */
-+ if (ret && !truncated)
-+ btrfs_err_rl(fs_info,
-+"dropping unwritten extent at root %llu ino %llu offset [%llu,%llu] disk bytenr %llu length %llu",
-+ btrfs_root_id(inode->root), btrfs_ino(inode),
-+ start, end, ordered_extent->disk_bytenr,
-+ ordered_extent->disk_num_bytes);
- /*
- * Discard the range before returning it back to the
- * free space pool
---
-2.47.3
-
--- /dev/null
+From ecf7603159cd81ec718af1efaeb529db1729132b Mon Sep 17 00:00:00 2001
+From: Qu Wenruo <wqu@suse.com>
+Date: Wed, 28 Oct 2026 17:00:47 +1030
+Subject: [PATCH 02/12] btrfs: don't cache rbio if an error is hit
+To: linux-btrfs@vger.kernel.org
+
+If rmw_rbio() hit an error after cache_rbio_pages() call, the rbio still
+have RBIO_CACHE_READY_BIT set, thus can be utilized for future page
+stealing.
+
+But that rbio didn't really reach the disk, thus using the pages for
+future steal can cause data inconsistency between in-memory cache and
+on-disk data.
+
+Fix the problem by clearing the RBIO_CACHE_READY_BIT on the error path
+of rmw_rbio().
+
+Fixes: 5eb30ee26fa4 ("btrfs: raid56: introduce the main entrance for RMW path")
+Assisted-by: LLM (find the bug)
+Reviewed-by: Filipe Manana <fdmanana@suse.com>
+Signed-off-by: Qu Wenruo <wqu@suse.com>
+Link: https://lore.kernel.org/r/b0d3adf5f3cc527b2ffd89c7ed93c99a0cbbdc76.1793168898.git.wqu@suse.com
+---
+ fs/btrfs/raid56.c | 3 +++
+ 1 file changed, 3 insertions(+)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index b24ec362909bb..a8a8004bb14c7 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -2471,6 +2471,9 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ spin_lock(&rbio->bio_list_lock);
+ set_bit(RBIO_RMW_LOCKED_BIT, &rbio->flags);
+ spin_unlock(&rbio->bio_list_lock);
++
++ /* Failed write, don't cache for page stealing. */
++ clear_bit(RBIO_CACHE_READY_BIT, &rbio->flags);
+ }
+ rbio_orig_end_io(rbio, errno_to_blk_status(ret));
+ }
+--
+2.47.3
+
+++ /dev/null
-From 5605ea80dd3424b27a98a7621722b76866c62f64 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 25 Jul 2026 16:06:34 -0400
-Subject: [PATCH 02/12] btrfs: raid56: fix use-after-free of rbio in bio end_io
- wakeups
-To: linux-btrfs@vger.kernel.org
-
-The read/write submission rounds in raid56 count in-flight bios in
-rbio->stripes_pending and wait with a bare
-wait_event(rbio->io_wait, atomic_read(&rbio->stripes_pending) == 0),
-while each bio's end_io does
-"if (atomic_dec_and_test(&stripes_pending)) wake_up(&rbio->io_wait)".
-
-Once the final decrement makes the counter visible as zero, the waiter
-can pass its condition check without consuming the wakeup -- via
-wait_event()'s fast path when all bios complete before the waiter
-arrives, or a condition recheck after an earlier wakeup -- and proceed
-to free the rbio through rbio_orig_end_io(). The end_io context is
-then still inside wake_up() operating on the freed rbio's embedded
-waitqueue lock.
-
-This shows up under sustained raid56 load in KVM guests as recurring
-"pvqspinlock: lock ... has corrupted value 0x0!" warnings from
-__pv_queued_spin_unlock_slowpath with a
-__wake_up <- raid_wait_{read,write}_end_io <- bio_endio call trace:
-paravirt spinlocks detect the unlock of the recycled lock word. KASAN
-reports it as a slab-use-after-free in __wake_up_common or
-do_raw_spin_unlock from the same end_io handlers. On bare metal
-without KASAN the use-after-free is silent and almost always harmless,
-which is how it has survived; it is a plausible match for
-long-standing sporadic crash reports on busy raid5 filesystems.
-
-It reproduces in about 12 seconds in a KVM guest running a KASAN
-kernel, on a degraded raid5 data / raid1 metadata filesystem on four
-2 GiB devices with one missing:
- - 8 parallel O_DIRECT readers of 4K, 16K or 64K at random offsets in
- existing files, so every read of a block on the missing device is a
- reconstruction round;
- - 2 writers rewriting small files with 4K..32K O_DIRECT writes, so
- writes are sub-stripe read-modify-write rounds;
- - the page cache dropped every second.
-With this patch the same load runs for 10 minutes without a warning.
-
-Convert the pair to a completion. wait_for_completion()'s fast path
-takes the completion's own lock, so it cannot return before complete()
-has released it: the completing context is provably finished with the
-rbio before the waiter can free it. A submitter-held bias count keeps
-one completion per submission round even when a round submits zero
-bios or every bio finishes before the submitter starts waiting; the
-scrub path only waits when finish_parity_scrub() actually began a
-round.
-
-Assisted-by: Claude:claude-fable-5
-Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
----
- fs/btrfs/raid56.c | 54 ++++++++++++++++++++++++++++++++++++++---------
- fs/btrfs/raid56.h | 10 ++++++++-
- 2 files changed, 53 insertions(+), 11 deletions(-)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 59aad807f98ab..a0a1bae60c1ae 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -1101,7 +1101,7 @@ static struct btrfs_raid_bio *alloc_rbio(struct btrfs_fs_info *fs_info,
- }
-
- bio_list_init(&rbio->bio_list);
-- init_waitqueue_head(&rbio->io_wait);
-+ init_completion(&rbio->io_done);
- INIT_LIST_HEAD(&rbio->plug_list);
- spin_lock_init(&rbio->bio_list_lock);
- INIT_LIST_HEAD(&rbio->stripe_cache);
-@@ -1689,6 +1689,40 @@ static void verify_bio_data_sectors(struct btrfs_raid_bio *rbio,
- }
- }
-
-+/*
-+ * Begin a submission round of @nr bios whose end_io functions report through
-+ * rbio_dec_io(). stripes_pending gets one extra count on behalf of the
-+ * submitter, dropped by rbio_wait_io(): this guarantees exactly one
-+ * completion per round even when @nr is 0 or every bio finishes before the
-+ * submitter starts waiting.
-+ *
-+ * The completion is what makes the round safe against a use-after-free the
-+ * old bare waitqueue had: once the final bio's decrement made
-+ * stripes_pending visible as zero, the waiter could pass its wait_event()
-+ * condition check and free the rbio while the bio's end_io context was still
-+ * inside wake_up() on the rbio's embedded waitqueue lock. With a
-+ * completion, the waiter cannot return before complete() has released the
-+ * completion's lock, so the completing context is finished with the rbio.
-+ */
-+static void rbio_begin_io(struct btrfs_raid_bio *rbio, unsigned int nr)
-+{
-+ reinit_completion(&rbio->io_done);
-+ atomic_set(&rbio->stripes_pending, nr + 1);
-+}
-+
-+static void rbio_dec_io(struct btrfs_raid_bio *rbio)
-+{
-+ if (atomic_dec_and_test(&rbio->stripes_pending))
-+ complete(&rbio->io_done);
-+}
-+
-+static void rbio_wait_io(struct btrfs_raid_bio *rbio)
-+{
-+ /* Drop the submitter's count from rbio_begin_io(). */
-+ rbio_dec_io(rbio);
-+ wait_for_completion(&rbio->io_done);
-+}
-+
- static void raid_wait_read_end_io(struct bio *bio)
- {
- struct btrfs_raid_bio *rbio = bio->bi_private;
-@@ -1701,8 +1735,7 @@ static void raid_wait_read_end_io(struct bio *bio)
- }
-
- bio_put(bio);
-- if (atomic_dec_and_test(&rbio->stripes_pending))
-- wake_up(&rbio->io_wait);
-+ rbio_dec_io(rbio);
- }
-
- static void submit_read_wait_bio_list(struct btrfs_raid_bio *rbio,
-@@ -1710,7 +1743,7 @@ static void submit_read_wait_bio_list(struct btrfs_raid_bio *rbio,
- {
- struct bio *bio;
-
-- atomic_set(&rbio->stripes_pending, bio_list_size(bio_list));
-+ rbio_begin_io(rbio, bio_list_size(bio_list));
- while ((bio = bio_list_pop(bio_list))) {
- bio->bi_end_io = raid_wait_read_end_io;
-
-@@ -1723,7 +1756,7 @@ static void submit_read_wait_bio_list(struct btrfs_raid_bio *rbio,
- submit_bio(bio);
- }
-
-- wait_event(rbio->io_wait, atomic_read(&rbio->stripes_pending) == 0);
-+ rbio_wait_io(rbio);
- }
-
- static int alloc_rbio_data_pages(struct btrfs_raid_bio *rbio)
-@@ -2416,8 +2449,7 @@ static void raid_wait_write_end_io(struct bio *bio)
- if (bio->bi_status)
- rbio_update_error_bitmap(rbio, bio);
- bio_put(bio);
-- if (atomic_dec_and_test(&rbio->stripes_pending))
-- wake_up(&rbio->io_wait);
-+ rbio_dec_io(rbio);
- }
-
- static void submit_write_bios(struct btrfs_raid_bio *rbio,
-@@ -2425,7 +2457,7 @@ static void submit_write_bios(struct btrfs_raid_bio *rbio,
- {
- struct bio *bio;
-
-- atomic_set(&rbio->stripes_pending, bio_list_size(bio_list));
-+ rbio_begin_io(rbio, bio_list_size(bio_list));
- while ((bio = bio_list_pop(bio_list))) {
- bio->bi_end_io = raid_wait_write_end_io;
-
-@@ -2531,7 +2563,7 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- /* We should have at least one bio assembled. */
- ASSERT(bio_list_size(&bio_list));
- submit_write_bios(rbio, &bio_list);
-- wait_event(rbio->io_wait, atomic_read(&rbio->stripes_pending) == 0);
-+ rbio_wait_io(rbio);
-
- /* We may have more errors than our tolerance during the read. */
- for (sectornr = 0; sectornr < rbio->stripe_nsectors; sectornr++) {
-@@ -2984,7 +3016,9 @@ static void scrub_rbio(struct btrfs_raid_bio *rbio)
- * and writeback the good content.
- */
- ret = finish_parity_scrub(rbio);
-- wait_event(rbio->io_wait, atomic_read(&rbio->stripes_pending) == 0);
-+ /* A submission round only began if finish_parity_scrub() succeeded. */
-+ if (ret == 0)
-+ rbio_wait_io(rbio);
- for (sector_nr = 0; sector_nr < rbio->stripe_nsectors; sector_nr++) {
- int found_errors;
-
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index 8700910b8dc99..b56f9b958d713 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -13,6 +13,7 @@
- #include <linux/bio.h>
- #include <linux/refcount.h>
- #include <linux/workqueue.h>
-+#include <linux/completion.h>
- #include "volumes.h"
-
- struct page;
-@@ -173,9 +174,16 @@ struct btrfs_raid_bio {
-
- refcount_t refs;
-
-+ /*
-+ * In-flight bios of the current submission round, plus one bias
-+ * count held by the submitter and dropped when it starts waiting.
-+ * The final decrement completes io_done; a completion (unlike a
-+ * bare waitqueue) guarantees the completing context is finished
-+ * with the rbio before the waiter can return and free it.
-+ */
- atomic_t stripes_pending;
-
-- wait_queue_head_t io_wait;
-+ struct completion io_done;
-
- /* Bitmap to record which horizontal stripe has data */
- unsigned long dbitmap;
---
-2.47.3
-
--- /dev/null
+From c4a57fb229aadbdacfca2bc6b2bef62557183dfc Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Fri, 5 Jul 2024 23:08:46 -0400
+Subject: [PATCH 03/12] btrfs: log a message when dropping an extent due to IO
+ error
+To: linux-btrfs@vger.kernel.org
+
+When an IO error occurs while writing a datacow file, btrfs will drop the
+extent containing the unwritten blocks. This prevents potential leaks
+of information stored in the unwritten data blocks back to userspace, but
+it is also a data loss event that is not easily visible from userspace.
+
+The existing code does notify userspace of the error via the inode,
+and the notification can be received through fsync (for the inode) or
+syncfs (for any dirty inode on the filesystem) return values; however,
+for the common case of a process that writes to a file and exits with
+its data still in dirty cache pages, there is no process left to notify
+when the ordered writes eventually fail.
+
+In most cases the extent drop is preceded by error messages from the
+write operation, but the IOERR bit can be set for less visible or obvious
+reasons, like running out of memory, bad metadata, or as a result of
+bugs that appear in other parts of btrfs from time to time.
+
+Some of the existing error messages for writes contain only logical
+addresses, while other messages contain only disk bytenrs. For read
+errors, only one address is necessary, as the user can look up the other
+with `btrfs ins log -o` or `btrfs ins sub/ino`, but for write errors, the
+mapping between these addresses is removed when the error is detected in
+btrfs_finish_one_ordered, so we can't derive one address from the other.
+We need both addresses for separate purposes: the logical address to
+identify which files have missing data, and the disk bytenr to identify
+which part of the filesystem address space is failing to accept writes
+(resolvable to device sectors through the chunk tree).
+
+For now, inform the sysadmin that the data has been dropped by logging a
+message when it happens, including both the logical subvol/inode/offset
+triple and the disk bytenr, and the corresponding sizes.
+
+In the future we might want to add some stats counters for this event,
+similar to the dev stats counters, but not tied to any specific device.
+The first step is to detect and report the events at all.
+
+Other notes:
+
+Because the extent is dropped, the lost data cannot be detected by a csum
+mismatch or read failure, i.e. everything will look OK if the file is read
+or the filesystem scrubbed, but an application will notice a truncated
+file or a file with data replaced by zeros. For datasum files, we could
+simply keep the extent as-is, allow future reads or csum verification
+to fail, and report EIO errors that way. That is a larger and riskier
+change to btrfs behavior than simply adding some passive monitoring of
+the status quo. This approach also has problems with csum collisions,
+it doesn't work for nodatasum+datacow files, and it takes much longer
+for the errors to be detected and reported to a sysadmin.
+
+nodatacow files don't have their extents dropped; instead, they will
+simply have garbage in the blocks where the writes failed. In most
+use cases for nodatacow files (e.g. VM disk images or databases), the
+user will be running all writes through fsync(), O_DIRECT, or similar
+mechanisms that can observe the existing EIO return value notification
+path, so there's less need for diagnostic coverage in the kernel log
+for nodatacow files.
+
+Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+---
+ fs/btrfs/inode.c | 16 ++++++++++++++++
+ 1 file changed, 16 insertions(+)
+
+diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
+index b071ed59a583f..8b95be6893f0e 100644
+--- a/fs/btrfs/inode.c
++++ b/fs/btrfs/inode.c
+@@ -3389,6 +3389,22 @@ int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
+ clear_reserved_extent &&
+ !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
+ !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
++ /*
++ * Notify the user that some data has been lost due
++ * to an error, unless we were already expected to
++ * remove the data because of truncate.
++ *
++ * Put both logical and physical addresses here
++ * because we're about to remove the mapping that
++ * would have allowed the user to translate from
++ * one to the other.
++ */
++ if (ret && !truncated)
++ btrfs_err_rl(fs_info,
++"dropping unwritten extent at root %llu ino %llu offset [%llu,%llu] disk bytenr %llu length %llu",
++ btrfs_root_id(inode->root), btrfs_ino(inode),
++ start, end, ordered_extent->disk_bytenr,
++ ordered_extent->disk_num_bytes);
+ /*
+ * Discard the range before returning it back to the
+ * free space pool
+--
+2.47.3
+
+++ /dev/null
-From 9ea7e7a0b451d6f1a49a9aa4c4f43519dd98dcd7 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 1 Aug 2026 01:31:24 -0400
-Subject: [PATCH 03/12] btrfs: propagate a split bio's error when the failing
- split completes last
-To: linux-btrfs@vger.kernel.org
-
-btrfs_bio_end_io() saves the first error of any split bio in the original
-btrfs_bio's ->status, then loads it into ->bio.bi_status when the last
-split completes -- but only if that last completion itself succeeded:
-
- if (atomic_dec_and_test(&bbio->pending_ios)) {
- /* Load split bio's error which might be set above. */
- if (status == BLK_STS_OK)
- bbio->bio.bi_status = READ_ONCE(bbio->status);
-
-The condition assumes that a failing final completion has already stored
-its error in the original bio at the top of the function. That holds only
-when the bio was never split. For a split, "bbio->bio.bi_status = status"
-is applied to the clone, which is then freed and bbio switched to the
-original; the original's bi_status keeps whatever an earlier, successful
-split left in it, and the error never reaches the caller.
-
-The ordering that loses the error is not rare. A read that fails checksum
-verification completes only after read repair has tried every mirror,
-which takes far longer than the healthy splits of the same bio, so the
-failing split completes last essentially every time.
-
-On a degraded raid56 array the result is silent corruption. Reads are
-split per stripe, so for any read of BTRFS_STRIPE_LEN or more, a sector
-whose reconstruction from a torn stripe fails its checksum is returned to
-userspace as zeros with no error -- while btrfs logs the checksum failure
-and increments the device corruption counter. A 4 KiB read of the same
-sector is not split and correctly returns EIO. Profiles that do not split
-at 64 KiB (single, dup, raid1) are unaffected, which is how this has gone
-unnoticed.
-
-Reproducer: on a raid5 filesystem, tear one stripe row's parity (leaving
-the data intact), withhold one data member of that row and mount degraded.
-Reconstructing the missing column then yields wrong bytes for that column
-while every other column still verifies. Reads of 64 KiB or more over the
-affected range return zeros and succeed; 4 KiB reads return EIO.
-
-Load the saved status unconditionally. It is the first error seen by any
-split, including this one, which is the value the caller wants in either
-case.
-
-Fixes: d48e1dea3931 ("btrfs: fix error propagation of split bios")
-CC: stable@vger.kernel.org # 6.6+
-Assisted-by: Claude:claude-opus-5
-Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
----
- fs/btrfs/bio.c | 11 ++++++++---
- 1 file changed, 8 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/bio.c b/fs/btrfs/bio.c
-index 2c6234f6182f8..b589cac044271 100644
---- a/fs/btrfs/bio.c
-+++ b/fs/btrfs/bio.c
-@@ -127,9 +127,14 @@ void btrfs_bio_end_io(struct btrfs_bio *bbio, blk_status_t status)
- cmpxchg(&bbio->status, BLK_STS_OK, status);
-
- if (atomic_dec_and_test(&bbio->pending_ios)) {
-- /* Load split bio's error which might be set above. */
-- if (status == BLK_STS_OK)
-- bbio->bio.bi_status = READ_ONCE(bbio->status);
-+ /*
-+ * Load the first error recorded above. For a split bio the
-+ * assignment at the top of this function landed on the clone,
-+ * which has already been freed, so the original's bi_status is
-+ * only correct if it is loaded here -- including when this
-+ * last completion is itself the failing one.
-+ */
-+ bbio->bio.bi_status = READ_ONCE(bbio->status);
-
- if (bbio_has_ordered_extent(bbio)) {
- struct btrfs_ordered_extent *ordered = bbio->ordered;
---
-2.47.3
-
+++ /dev/null
-From 8b657c64c5b9b11a1552b998c6589de8ff02ea74 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Mon, 3 Aug 2026 03:24:38 -0400
-Subject: [PATCH 04/12] btrfs: raid56: drop cached rbios when their stripes'
- extents are freed
-To: linux-btrfs@vger.kernel.org
-
-A cached rbio keeps an in-memory copy of its full stripe's data
-sectors so that a later sub-stripe write can steal the pages (see
-steal_rbio()) and skip the RMW read. That is only safe while the
-cache and the disk agree. Nothing invalidates cache entries when the
-stripe's extents are freed, so an entry can outlive the data it
-describes: the space is reallocated, a sub-stripe write to the reused
-stripe steals the stale pages, and parity is generated from the
-cache's memory of the stripe's previous life instead of from disk.
-
-If the on-disk content diverged from that memory in the meantime, the
-result is silent, latent damage. The divergence does not require a
-second write: a device error that corrupts a column holding only
-freed data is invisible (no live extent, no csum to fail, nothing for
-scrub to check), but the stale cached copy of that column predates
-the corruption. The poisoned write then produces parity consistent
-with the cache's memory and inconsistent with the actual on-disk
-column. Every read of the live data still passes csum and scrub
-reports nothing, so the loss surfaces only when a device failure
-forces reconstruction -- which XORs the real on-disk garbage against
-parity that remembers different bytes, and hands back trash.
-
-This was found and proven byte-exactly on a raid5 test array: a
-stripe's parity solved uniquely as the XOR of fresh data with the
-PRE-corruption content of a free-space column -- bytes that existed
-nowhere on disk at write time and could only have come from the rbio
-cache. The resulting single-column loss was undetectable by scrub
-and unrecoverable by reconstruction.
-
-Drop cache entries overlapping freed extents at unpin time, when the
-space returns to circulation. The walk is gated on raid56 block
-groups, so filesystems without raid56 never touch it, and the LRU
-list is bounded (RBIO_CACHE_SIZE entries).
-
-The cost of dropping entries was measured on an instrumented stock
-kernel that marks affected entries instead of dropping them, and
-counts a reintroduced RMW full-stripe read whenever a read-skip was
-only possible because of a marked entry. In a worst-case free-heavy
-small-file churn on a 5-device raid5 array with raid5 metadata --
-conditions chosen to flatter the cache, and it delivers, with 87% of
-sub-stripe RMWs skipping their read -- only 1% of those skips (64 of
-6430) were enabled by entries this patch drops, costing 0.04-0.12
-MB/s of extra reads against the workload's own 0.3-0.7 MB/s of
-writes. 93% of the entries the patch drops were evicted without
-ever being stolen again.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/extent-tree.c | 10 ++++++++++
- fs/btrfs/raid56.c | 37 +++++++++++++++++++++++++++++++++++++
- fs/btrfs/raid56.h | 1 +
- 3 files changed, 48 insertions(+)
-
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 9b0a5c6b96f3c..e9248e52d1dce 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -2868,6 +2868,16 @@ static int unpin_extent_range(struct btrfs_fs_info *fs_info,
- if (return_free_space)
- btrfs_add_free_space(cache, start, len);
-
-+ /*
-+ * The rbio stripe cache may still remember this range's
-+ * pre-free contents; a later sub-stripe write into the
-+ * reused stripes would steal those pages and generate
-+ * parity from them. Drop the stale entries now that the
-+ * extents are gone.
-+ */
-+ if (cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK)
-+ btrfs_raid56_uncache_range(fs_info, start, len);
-+
- start += len;
- total_unpinned += len;
- space_info = cache->space_info;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index a0a1bae60c1ae..69ce17bc7f0af 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -539,6 +539,43 @@ static void remove_rbio_from_cache(struct btrfs_raid_bio *rbio)
- spin_unlock(&table->cache_lock);
- }
-
-+/*
-+ * Drop cached rbios whose full stripes overlap [start, start + len).
-+ *
-+ * Called when extents in that range are freed. A cached rbio holds an
-+ * in-memory copy of its stripe's data sectors; once the extents are gone
-+ * the space can be reallocated, and a later sub-stripe write to the same
-+ * stripe would steal the cached pages (see steal_rbio()) and compute
-+ * parity from the cache's memory of the stripe's previous life instead
-+ * of reading the disk. If the on-disk content diverged from that memory
-+ * in the meantime -- for example a device error corrupted a column that
-+ * no longer had live data, so nothing noticed -- the write produces
-+ * parity that disagrees with the on-disk columns, and the stripe is
-+ * latently unreconstructible: every read of the live data passes csum,
-+ * scrub sees nothing wrong, and the loss only surfaces when a device
-+ * failure forces reconstruction. Freed extents' cache entries have no
-+ * value to keep: drop them.
-+ */
-+void btrfs_raid56_uncache_range(struct btrfs_fs_info *info, u64 start, u64 len)
-+{
-+ struct btrfs_stripe_hash_table *table = info->stripe_hash_table;
-+ struct btrfs_raid_bio *rbio;
-+ struct btrfs_raid_bio *tmp;
-+
-+ if (!table)
-+ return;
-+
-+ spin_lock(&table->cache_lock);
-+ list_for_each_entry_safe(rbio, tmp, &table->stripe_cache, stripe_cache) {
-+ const u64 rbio_start = rbio->bioc->full_stripe_logical;
-+ const u64 rbio_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
-+
-+ if (rbio_start < start + len && start < rbio_start + rbio_len)
-+ __remove_rbio_from_cache(rbio);
-+ }
-+ spin_unlock(&table->cache_lock);
-+}
-+
- /*
- * remove everything in the cache
- */
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index b56f9b958d713..be507cceb465d 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -290,5 +290,6 @@ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
-
- int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
-+void btrfs_raid56_uncache_range(struct btrfs_fs_info *info, u64 start, u64 len);
-
- #endif
---
-2.47.3
-
--- /dev/null
+From 3056cb9be26eb4525718fa367091328e9ff9a356 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 25 Jul 2026 16:06:34 -0400
+Subject: [PATCH 04/12] btrfs: raid56: fix use-after-free of rbio in bio end_io
+ wakeups
+To: linux-btrfs@vger.kernel.org
+
+The read/write submission rounds in raid56 count in-flight bios in
+rbio->stripes_pending and wait with a bare
+wait_event(rbio->io_wait, atomic_read(&rbio->stripes_pending) == 0),
+while each bio's end_io does
+"if (atomic_dec_and_test(&stripes_pending)) wake_up(&rbio->io_wait)".
+
+Once the final decrement makes the counter visible as zero, the waiter
+can pass its condition check without consuming the wakeup -- via
+wait_event()'s fast path when all bios complete before the waiter
+arrives, or a condition recheck after an earlier wakeup -- and proceed
+to free the rbio through rbio_orig_end_io(). The end_io context is
+then still inside wake_up() operating on the freed rbio's embedded
+waitqueue lock.
+
+This shows up under sustained raid56 load in KVM guests as recurring
+"pvqspinlock: lock ... has corrupted value 0x0!" warnings from
+__pv_queued_spin_unlock_slowpath with a
+__wake_up <- raid_wait_{read,write}_end_io <- bio_endio call trace:
+paravirt spinlocks detect the unlock of the recycled lock word. KASAN
+reports it as a slab-use-after-free in __wake_up_common or
+do_raw_spin_unlock from the same end_io handlers. On bare metal
+without KASAN the use-after-free is silent and almost always harmless,
+which is how it has survived; it is a plausible match for
+long-standing sporadic crash reports on busy raid5 filesystems.
+
+It reproduces in about 12 seconds in a KVM guest running a KASAN
+kernel, on a degraded raid5 data / raid1 metadata filesystem on four
+2 GiB devices with one missing:
+ - 8 parallel O_DIRECT readers of 4K, 16K or 64K at random offsets in
+ existing files, so every read of a block on the missing device is a
+ reconstruction round;
+ - 2 writers rewriting small files with 4K..32K O_DIRECT writes, so
+ writes are sub-stripe read-modify-write rounds;
+ - the page cache dropped every second.
+With this patch the same load runs for 10 minutes without a warning.
+
+Convert the pair to a completion. wait_for_completion()'s fast path
+takes the completion's own lock, so it cannot return before complete()
+has released it: the completing context is provably finished with the
+rbio before the waiter can free it. A submitter-held bias count keeps
+one completion per submission round even when a round submits zero
+bios or every bio finishes before the submitter starts waiting; the
+scrub path only waits when finish_parity_scrub() actually began a
+round.
+
+Assisted-by: Claude:claude-fable-5
+Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+---
+ fs/btrfs/raid56.c | 54 ++++++++++++++++++++++++++++++++++++++---------
+ fs/btrfs/raid56.h | 10 ++++++++-
+ 2 files changed, 53 insertions(+), 11 deletions(-)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index a8a8004bb14c7..4453a50866b43 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -1019,7 +1019,7 @@ static struct btrfs_raid_bio *alloc_rbio(struct btrfs_fs_info *fs_info,
+ }
+
+ bio_list_init(&rbio->bio_list);
+- init_waitqueue_head(&rbio->io_wait);
++ init_completion(&rbio->io_done);
+ INIT_LIST_HEAD(&rbio->plug_list);
+ spin_lock_init(&rbio->bio_list_lock);
+ INIT_LIST_HEAD(&rbio->stripe_cache);
+@@ -1606,6 +1606,40 @@ static void verify_bio_data_sectors(struct btrfs_raid_bio *rbio,
+ }
+ }
+
++/*
++ * Begin a submission round of @nr bios whose end_io functions report through
++ * rbio_dec_io(). stripes_pending gets one extra count on behalf of the
++ * submitter, dropped by rbio_wait_io(): this guarantees exactly one
++ * completion per round even when @nr is 0 or every bio finishes before the
++ * submitter starts waiting.
++ *
++ * The completion is what makes the round safe against a use-after-free the
++ * old bare waitqueue had: once the final bio's decrement made
++ * stripes_pending visible as zero, the waiter could pass its wait_event()
++ * condition check and free the rbio while the bio's end_io context was still
++ * inside wake_up() on the rbio's embedded waitqueue lock. With a
++ * completion, the waiter cannot return before complete() has released the
++ * completion's lock, so the completing context is finished with the rbio.
++ */
++static void rbio_begin_io(struct btrfs_raid_bio *rbio, unsigned int nr)
++{
++ reinit_completion(&rbio->io_done);
++ atomic_set(&rbio->stripes_pending, nr + 1);
++}
++
++static void rbio_dec_io(struct btrfs_raid_bio *rbio)
++{
++ if (atomic_dec_and_test(&rbio->stripes_pending))
++ complete(&rbio->io_done);
++}
++
++static void rbio_wait_io(struct btrfs_raid_bio *rbio)
++{
++ /* Drop the submitter's count from rbio_begin_io(). */
++ rbio_dec_io(rbio);
++ wait_for_completion(&rbio->io_done);
++}
++
+ static void raid_wait_read_end_io(struct bio *bio)
+ {
+ struct btrfs_raid_bio *rbio = bio->bi_private;
+@@ -1618,8 +1652,7 @@ static void raid_wait_read_end_io(struct bio *bio)
+ }
+
+ bio_put(bio);
+- if (atomic_dec_and_test(&rbio->stripes_pending))
+- wake_up(&rbio->io_wait);
++ rbio_dec_io(rbio);
+ }
+
+ static void submit_read_wait_bio_list(struct btrfs_raid_bio *rbio,
+@@ -1627,7 +1660,7 @@ static void submit_read_wait_bio_list(struct btrfs_raid_bio *rbio,
+ {
+ struct bio *bio;
+
+- atomic_set(&rbio->stripes_pending, bio_list_size(bio_list));
++ rbio_begin_io(rbio, bio_list_size(bio_list));
+ while ((bio = bio_list_pop(bio_list))) {
+ bio->bi_end_io = raid_wait_read_end_io;
+
+@@ -1640,7 +1673,7 @@ static void submit_read_wait_bio_list(struct btrfs_raid_bio *rbio,
+ submit_bio(bio);
+ }
+
+- wait_event(rbio->io_wait, atomic_read(&rbio->stripes_pending) == 0);
++ rbio_wait_io(rbio);
+ }
+
+ static int alloc_rbio_data_pages(struct btrfs_raid_bio *rbio)
+@@ -2328,8 +2361,7 @@ static void raid_wait_write_end_io(struct bio *bio)
+ if (bio->bi_status)
+ rbio_update_error_bitmap(rbio, bio);
+ bio_put(bio);
+- if (atomic_dec_and_test(&rbio->stripes_pending))
+- wake_up(&rbio->io_wait);
++ rbio_dec_io(rbio);
+ }
+
+ static void submit_write_bios(struct btrfs_raid_bio *rbio,
+@@ -2337,7 +2369,7 @@ static void submit_write_bios(struct btrfs_raid_bio *rbio,
+ {
+ struct bio *bio;
+
+- atomic_set(&rbio->stripes_pending, bio_list_size(bio_list));
++ rbio_begin_io(rbio, bio_list_size(bio_list));
+ while ((bio = bio_list_pop(bio_list))) {
+ bio->bi_end_io = raid_wait_write_end_io;
+
+@@ -2444,7 +2476,7 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ /* We should have at least one bio assembled. */
+ ASSERT(bio_list_size(&bio_list));
+ submit_write_bios(rbio, &bio_list);
+- wait_event(rbio->io_wait, atomic_read(&rbio->stripes_pending) == 0);
++ rbio_wait_io(rbio);
+
+ /* We may have more errors than our tolerance during the read. */
+ for (sectornr = 0; sectornr < rbio->stripe_nsectors; sectornr++) {
+@@ -2915,7 +2947,9 @@ static void scrub_rbio(struct btrfs_raid_bio *rbio)
+ * and writeback the good content.
+ */
+ ret = finish_parity_scrub(rbio);
+- wait_event(rbio->io_wait, atomic_read(&rbio->stripes_pending) == 0);
++ /* A submission round only began if finish_parity_scrub() succeeded. */
++ if (ret == 0)
++ rbio_wait_io(rbio);
+ for (sector_nr = 0; sector_nr < rbio->stripe_nsectors; sector_nr++) {
+ int found_errors;
+
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index 8700910b8dc99..b56f9b958d713 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -13,6 +13,7 @@
+ #include <linux/bio.h>
+ #include <linux/refcount.h>
+ #include <linux/workqueue.h>
++#include <linux/completion.h>
+ #include "volumes.h"
+
+ struct page;
+@@ -173,9 +174,16 @@ struct btrfs_raid_bio {
+
+ refcount_t refs;
+
++ /*
++ * In-flight bios of the current submission round, plus one bias
++ * count held by the submitter and dropped when it starts waiting.
++ * The final decrement completes io_done; a completion (unlike a
++ * bare waitqueue) guarantees the completing context is finished
++ * with the rbio before the waiter can return and free it.
++ */
+ atomic_t stripes_pending;
+
+- wait_queue_head_t io_wait;
++ struct completion io_done;
+
+ /* Bitmap to record which horizontal stripe has data */
+ unsigned long dbitmap;
+--
+2.47.3
+
--- /dev/null
+From 279096509d09e88990863f44eea845cc5ef898a8 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 1 Aug 2026 01:31:24 -0400
+Subject: [PATCH 05/12] btrfs: propagate a split bio's error when the failing
+ split completes last
+To: linux-btrfs@vger.kernel.org
+
+btrfs_bio_end_io() saves the first error of any split bio in the original
+btrfs_bio's ->status, then loads it into ->bio.bi_status when the last
+split completes -- but only if that last completion itself succeeded:
+
+ if (atomic_dec_and_test(&bbio->pending_ios)) {
+ /* Load split bio's error which might be set above. */
+ if (status == BLK_STS_OK)
+ bbio->bio.bi_status = READ_ONCE(bbio->status);
+
+The condition assumes that a failing final completion has already stored
+its error in the original bio at the top of the function. That holds only
+when the bio was never split. For a split, "bbio->bio.bi_status = status"
+is applied to the clone, which is then freed and bbio switched to the
+original; the original's bi_status keeps whatever an earlier, successful
+split left in it, and the error never reaches the caller.
+
+The ordering that loses the error is not rare. A read that fails checksum
+verification completes only after read repair has tried every mirror,
+which takes far longer than the healthy splits of the same bio, so the
+failing split completes last essentially every time.
+
+On a degraded raid56 array the result is silent corruption. Reads are
+split per stripe, so for any read of BTRFS_STRIPE_LEN or more, a sector
+whose reconstruction from a torn stripe fails its checksum is returned to
+userspace as zeros with no error -- while btrfs logs the checksum failure
+and increments the device corruption counter. A 4 KiB read of the same
+sector is not split and correctly returns EIO. Profiles that do not split
+at 64 KiB (single, dup, raid1) are unaffected, which is how this has gone
+unnoticed.
+
+Reproducer: on a raid5 filesystem, tear one stripe row's parity (leaving
+the data intact), withhold one data member of that row and mount degraded.
+Reconstructing the missing column then yields wrong bytes for that column
+while every other column still verifies. Reads of 64 KiB or more over the
+affected range return zeros and succeed; 4 KiB reads return EIO.
+
+Load the saved status unconditionally. It is the first error seen by any
+split, including this one, which is the value the caller wants in either
+case.
+
+Fixes: d48e1dea3931 ("btrfs: fix error propagation of split bios")
+CC: stable@vger.kernel.org # 6.6+
+Assisted-by: Claude:claude-opus-5
+Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+---
+ fs/btrfs/bio.c | 11 ++++++++---
+ 1 file changed, 8 insertions(+), 3 deletions(-)
+
+diff --git a/fs/btrfs/bio.c b/fs/btrfs/bio.c
+index 2c6234f6182f8..b589cac044271 100644
+--- a/fs/btrfs/bio.c
++++ b/fs/btrfs/bio.c
+@@ -127,9 +127,14 @@ void btrfs_bio_end_io(struct btrfs_bio *bbio, blk_status_t status)
+ cmpxchg(&bbio->status, BLK_STS_OK, status);
+
+ if (atomic_dec_and_test(&bbio->pending_ios)) {
+- /* Load split bio's error which might be set above. */
+- if (status == BLK_STS_OK)
+- bbio->bio.bi_status = READ_ONCE(bbio->status);
++ /*
++ * Load the first error recorded above. For a split bio the
++ * assignment at the top of this function landed on the clone,
++ * which has already been freed, so the original's bi_status is
++ * only correct if it is loaded here -- including when this
++ * last completion is itself the failing one.
++ */
++ bbio->bio.bi_status = READ_ONCE(bbio->status);
+
+ if (bbio_has_ordered_extent(bbio)) {
+ struct btrfs_ordered_extent *ordered = bbio->ordered;
+--
+2.47.3
+
+++ /dev/null
-From 92f5a085fe10893c3980e9d17734341d85d4efb9 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Wed, 5 Aug 2026 02:59:50 -0400
-Subject: [PATCH 05/12] btrfs: raid56: verify reconstructed tree blocks
-To: linux-btrfs@vger.kernel.org
-
-Data sectors recovered from parity are checked against the csum tree
-before they are trusted: recover_vertical() calls verify_one_sector() for
-each rebuilt sector, and a mismatch fails the read. Metadata gets none of
-that. fill_data_csums() returns early for anything that is not a data
-block group, so csum_bitmap is NULL, and verify_one_sector() then returns
-success without looking at anything:
-
- if (!rbio->csum_bitmap || !rbio->csum_buf)
- return 0;
-
-So a metadata rbio reconstructs a lost column, marks it uptodate having
-verified nothing, and hands it back. A wrong reconstruction is caught
-much later by validate_extent_buffer(), one layer up, after the block has
-already been returned and cached -- and in the raid6 case, where several
-candidate reconstructions exist, raid56 cannot tell which one is right
-because it has no way to check any of them.
-
-A tree block can be verified, just not a sector at a time: its csum lives
-in its own header and covers the whole nodesize block, so the check has to
-wait until every sector of the block has been recovered. Do it after the
-vertical recovery loop rather than inside it. A tree block never straddles
-a column -- nodesize and BTRFS_STRIPE_LEN are both powers of two with
-nodesize <= BTRFS_STRIPE_LEN, and full stripes are stripe-length aligned,
-so each column starts on a nodesize boundary and tree blocks tile it
-exactly.
-
-Only the blocks the caller asked for are checked. Those are known to be
-live tree blocks; the rest of a stripe may be free space, which has no
-header and would fail every test. For the same reason this runs only when
-rebuilding a read: recover_sectors() is also reached from the
-read-modify-write path, where the sectors actually reconstructed are the
-ones read off the surviving columns and any of them may be free space. A
-reconstruction feeding an RMW's parity therefore stays unverified; knowing
-which ranges hold live metadata is not something this layer can do.
-
-Tested with a 3-device raid5 filesystem with raid5 metadata, 3000 files:
-each device in turn missing and corrupted recovers byte-exactly, and with
-two devices corrupted -- where reconstruction necessarily produces a wrong
-block -- raid56 now rejects it itself:
-
- raid56: reconstructed tree block 40796160 has bytenr 8993213254959039756,
- cannot be trusted
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/raid56.c | 174 ++++++++++++++++++++++++++++++++++++++++++++++
- 1 file changed, 174 insertions(+)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 69ce17bc7f0af..13e5a0244fdb3 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -1971,6 +1971,176 @@ static void calculate_block_csum_paddrs(struct btrfs_fs_info *fs_info,
- btrfs_csum_final(&csum, dest);
- }
-
-+/*
-+ * Return the memory holding a recovered sector: the bio's pages when we are
-+ * rebuilding a read, the rbio's own stripe pages otherwise.
-+ */
-+static phys_addr_t *recovered_sector_paddrs(struct btrfs_raid_bio *rbio,
-+ int stripe_nr, int sector_nr)
-+{
-+ if (rbio->operation == BTRFS_RBIO_READ_REBUILD)
-+ return sector_paddrs_in_rbio(rbio, stripe_nr, sector_nr, 0);
-+ return rbio_stripe_paddrs(rbio, stripe_nr, sector_nr);
-+}
-+
-+/*
-+ * Verify one reconstructed tree block.
-+ *
-+ * Data sectors are verified individually against the csum tree, but a tree
-+ * block carries its csum in its own header, covering the whole nodesize
-+ * block. So metadata cannot be checked a sector at a time: the check has to
-+ * wait until every sector of the block has been recovered, which is why this
-+ * runs after the vertical recovery loop rather than inside it.
-+ *
-+ * A tree block never straddles a column. nodesize and the stripe length are
-+ * both powers of two with nodesize <= the stripe length, and a full stripe is
-+ * stripe-length aligned, so each column begins on a nodesize boundary and
-+ * tree blocks tile it exactly.
-+ *
-+ * @sector_nr is the first sector of the block within the column.
-+ */
-+static int verify_one_eb(struct btrfs_raid_bio *rbio, int stripe_nr,
-+ int sector_nr)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ const u32 sectorsize = fs_info->sectorsize;
-+ const u32 sectors_per_tree = fs_info->nodesize >> fs_info->sectorsize_bits;
-+ const u32 step = min(sectorsize, PAGE_SIZE);
-+ const u64 logical = rbio->bioc->full_stripe_logical +
-+ (u64)stripe_nr * rbio->bioc->stripe_len +
-+ (u64)sector_nr * sectorsize;
-+ u8 on_disk_csum[BTRFS_CSUM_SIZE];
-+ u8 calculated_csum[BTRFS_CSUM_SIZE];
-+ struct btrfs_csum_ctx csum;
-+ phys_addr_t *paddrs;
-+ void *kaddr;
-+ u64 found_bytenr;
-+ bool bad_fsid;
-+
-+ /*
-+ * The header lives at the start of the block. Read what we need from
-+ * it before walking the rest: a block whose bytenr or fsid do not
-+ * match was not reconstructed into what it claims to be, and there is
-+ * no point csumming it.
-+ */
-+ paddrs = recovered_sector_paddrs(rbio, stripe_nr, sector_nr);
-+ kaddr = kmap_local_paddr(paddrs[0]);
-+ memcpy(on_disk_csum, ((struct btrfs_header *)kaddr)->csum,
-+ fs_info->csum_size);
-+ found_bytenr = btrfs_stack_header_bytenr((struct btrfs_header *)kaddr);
-+ bad_fsid = memcmp(((struct btrfs_header *)kaddr)->fsid,
-+ fs_info->fs_devices->metadata_uuid,
-+ BTRFS_FSID_SIZE) != 0;
-+ kunmap_local(kaddr);
-+
-+ if (unlikely(found_bytenr != logical)) {
-+ btrfs_warn_rl(fs_info,
-+"raid56: reconstructed tree block %llu has bytenr %llu, cannot be trusted",
-+ logical, found_bytenr);
-+ return -EIO;
-+ }
-+ if (unlikely(bad_fsid)) {
-+ btrfs_warn_rl(fs_info,
-+"raid56: reconstructed tree block %llu has the wrong fsid, cannot be trusted",
-+ logical);
-+ return -EIO;
-+ }
-+
-+ btrfs_csum_init(&csum, fs_info->csum_type);
-+ for (int i = 0; i < sectors_per_tree; i++) {
-+ paddrs = recovered_sector_paddrs(rbio, stripe_nr, sector_nr + i);
-+
-+ for (int j = 0; j < rbio->sector_nsteps; j++) {
-+ kaddr = kmap_local_paddr(paddrs[j]);
-+ /* The csum field itself is not covered by the csum. */
-+ if (i == 0 && j == 0)
-+ btrfs_csum_update(&csum, kaddr + BTRFS_CSUM_SIZE,
-+ step - BTRFS_CSUM_SIZE);
-+ else
-+ btrfs_csum_update(&csum, kaddr, step);
-+ kunmap_local(kaddr);
-+ }
-+ }
-+ btrfs_csum_final(&csum, calculated_csum);
-+
-+ if (unlikely(memcmp(calculated_csum, on_disk_csum, fs_info->csum_size))) {
-+ btrfs_warn_rl(fs_info,
-+"raid56: reconstructed tree block %llu fails its csum, cannot be trusted",
-+ logical);
-+ return -EIO;
-+ }
-+ return 0;
-+}
-+
-+/*
-+ * Verify every tree block this rbio was asked to read, once recovery has
-+ * filled in the missing columns.
-+ *
-+ * Only blocks the caller actually requested are checked: those are known to
-+ * be live tree blocks, whereas the rest of a stripe may be free space, which
-+ * has no header to verify and would fail every test here.
-+ *
-+ * Without this, a metadata rbio reconstructs a column and marks it uptodate
-+ * having checked nothing -- verify_one_sector() returns success immediately
-+ * when there is no csum_bitmap, and metadata never has one (see
-+ * fill_data_csums()). A wrong reconstruction would then be handed back to
-+ * the caller, and cached, for validate_extent_buffer() to reject much later.
-+ */
-+static int verify_recovered_ebs(struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ const u32 sectors_per_tree = fs_info->nodesize >> fs_info->sectorsize_bits;
-+
-+ /*
-+ * Data has its own per-sector verification. A mixed block group has
-+ * neither: its sectors get no csums (fill_data_csums() skips mixed
-+ * groups) and its contents may be file data rather than tree blocks,
-+ * so there is nothing here to check either.
-+ */
-+ if (rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA)
-+ return 0;
-+
-+ /*
-+ * Only when rebuilding a read. recover_sectors() is also reached from
-+ * the read-modify-write path, and there the bio list covers the blocks
-+ * being written -- already-verified memory -- while the sectors that
-+ * were actually reconstructed are the ones read off the other columns.
-+ * Those cannot be checked: any of them may be free space rather than a
-+ * live tree block, and free space has no header to verify. Knowing
-+ * which ranges hold live metadata is exactly what this layer lacks,
-+ * so a reconstruction feeding an RMW's parity stays unverified.
-+ */
-+ if (rbio->operation != BTRFS_RBIO_READ_REBUILD)
-+ return 0;
-+
-+ for (int stripe_nr = 0; stripe_nr < rbio->nr_data; stripe_nr++) {
-+ for (int sector_nr = 0;
-+ sector_nr + sectors_per_tree <= rbio->stripe_nsectors;
-+ sector_nr += sectors_per_tree) {
-+ bool requested = true;
-+ int ret;
-+
-+ for (int i = 0; i < sectors_per_tree; i++) {
-+ const int index = rbio_sector_index(rbio, stripe_nr,
-+ sector_nr + i);
-+
-+ if (rbio->bio_paddrs[index * rbio->sector_nsteps] ==
-+ INVALID_PADDR) {
-+ requested = false;
-+ break;
-+ }
-+ }
-+ if (!requested)
-+ continue;
-+
-+ ret = verify_one_eb(rbio, stripe_nr, sector_nr);
-+ if (ret < 0)
-+ return ret;
-+ }
-+ }
-+ return 0;
-+}
-+
- static int verify_one_sector(struct btrfs_raid_bio *rbio,
- int stripe_nr, int sector_nr)
- {
-@@ -2206,6 +2376,10 @@ static int recover_sectors(struct btrfs_raid_bio *rbio)
- break;
- }
-
-+ /* Metadata is verified per tree block, once every sector is back. */
-+ if (ret == 0)
-+ ret = verify_recovered_ebs(rbio);
-+
- out:
- kfree(pointers);
- kfree(unmap_array);
---
-2.47.3
-
--- /dev/null
+From 01b3569be796c1ca3f9f300c0cbe6c697ff76685 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Mon, 3 Aug 2026 03:24:38 -0400
+Subject: [PATCH 06/12] btrfs: raid56: drop cached rbios when their stripes'
+ extents are freed
+To: linux-btrfs@vger.kernel.org
+
+A cached rbio keeps an in-memory copy of its full stripe's data
+sectors so that a later sub-stripe write can steal the pages (see
+steal_rbio()) and skip the RMW read. That is only safe while the
+cache and the disk agree. Nothing invalidates cache entries when the
+stripe's extents are freed, so an entry can outlive the data it
+describes: the space is reallocated, a sub-stripe write to the reused
+stripe steals the stale pages, and parity is generated from the
+cache's memory of the stripe's previous life instead of from disk.
+
+If the on-disk content diverged from that memory in the meantime, the
+result is silent, latent damage. The divergence does not require a
+second write: a device error that corrupts a column holding only
+freed data is invisible (no live extent, no csum to fail, nothing for
+scrub to check), but the stale cached copy of that column predates
+the corruption. The poisoned write then produces parity consistent
+with the cache's memory and inconsistent with the actual on-disk
+column. Every read of the live data still passes csum and scrub
+reports nothing, so the loss surfaces only when a device failure
+forces reconstruction -- which XORs the real on-disk garbage against
+parity that remembers different bytes, and hands back trash.
+
+This was found and proven byte-exactly on a raid5 test array: a
+stripe's parity solved uniquely as the XOR of fresh data with the
+PRE-corruption content of a free-space column -- bytes that existed
+nowhere on disk at write time and could only have come from the rbio
+cache. The resulting single-column loss was undetectable by scrub
+and unrecoverable by reconstruction.
+
+Drop cache entries overlapping freed extents at unpin time, when the
+space returns to circulation. The walk is gated on raid56 block
+groups, so filesystems without raid56 never touch it, and the LRU
+list is bounded (RBIO_CACHE_SIZE entries).
+
+The cost of dropping entries was measured on an instrumented stock
+kernel that marks affected entries instead of dropping them, and
+counts a reintroduced RMW full-stripe read whenever a read-skip was
+only possible because of a marked entry. In a worst-case free-heavy
+small-file churn on a 5-device raid5 array with raid5 metadata --
+conditions chosen to flatter the cache, and it delivers, with 87% of
+sub-stripe RMWs skipping their read -- only 1% of those skips (64 of
+6430) were enabled by entries this patch drops, costing 0.04-0.12
+MB/s of extra reads against the workload's own 0.3-0.7 MB/s of
+writes. 93% of the entries the patch drops were evicted without
+ever being stolen again.
+
+Assisted-by: Claude:claude-fable-5
+---
+ fs/btrfs/extent-tree.c | 10 ++++++++++
+ fs/btrfs/raid56.c | 37 +++++++++++++++++++++++++++++++++++++
+ fs/btrfs/raid56.h | 1 +
+ 3 files changed, 48 insertions(+)
+
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 9b0a5c6b96f3c..e9248e52d1dce 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -2868,6 +2868,16 @@ static int unpin_extent_range(struct btrfs_fs_info *fs_info,
+ if (return_free_space)
+ btrfs_add_free_space(cache, start, len);
+
++ /*
++ * The rbio stripe cache may still remember this range's
++ * pre-free contents; a later sub-stripe write into the
++ * reused stripes would steal those pages and generate
++ * parity from them. Drop the stale entries now that the
++ * extents are gone.
++ */
++ if (cache->flags & BTRFS_BLOCK_GROUP_RAID56_MASK)
++ btrfs_raid56_uncache_range(fs_info, start, len);
++
+ start += len;
+ total_unpinned += len;
+ space_info = cache->space_info;
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 4453a50866b43..5ec0ec769a0c8 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -464,6 +464,43 @@ static void remove_rbio_from_cache(struct btrfs_raid_bio *rbio)
+ spin_unlock(&table->cache_lock);
+ }
+
++/*
++ * Drop cached rbios whose full stripes overlap [start, start + len).
++ *
++ * Called when extents in that range are freed. A cached rbio holds an
++ * in-memory copy of its stripe's data sectors; once the extents are gone
++ * the space can be reallocated, and a later sub-stripe write to the same
++ * stripe would steal the cached pages (see steal_rbio()) and compute
++ * parity from the cache's memory of the stripe's previous life instead
++ * of reading the disk. If the on-disk content diverged from that memory
++ * in the meantime -- for example a device error corrupted a column that
++ * no longer had live data, so nothing noticed -- the write produces
++ * parity that disagrees with the on-disk columns, and the stripe is
++ * latently unreconstructible: every read of the live data passes csum,
++ * scrub sees nothing wrong, and the loss only surfaces when a device
++ * failure forces reconstruction. Freed extents' cache entries have no
++ * value to keep: drop them.
++ */
++void btrfs_raid56_uncache_range(struct btrfs_fs_info *info, u64 start, u64 len)
++{
++ struct btrfs_stripe_hash_table *table = info->stripe_hash_table;
++ struct btrfs_raid_bio *rbio;
++ struct btrfs_raid_bio *tmp;
++
++ if (!table)
++ return;
++
++ spin_lock(&table->cache_lock);
++ list_for_each_entry_safe(rbio, tmp, &table->stripe_cache, stripe_cache) {
++ const u64 rbio_start = rbio->bioc->full_stripe_logical;
++ const u64 rbio_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
++
++ if (rbio_start < start + len && start < rbio_start + rbio_len)
++ __remove_rbio_from_cache(rbio);
++ }
++ spin_unlock(&table->cache_lock);
++}
++
+ /*
+ * remove everything in the cache
+ */
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index b56f9b958d713..be507cceb465d 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -290,5 +290,6 @@ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
+
+ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
+ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
++void btrfs_raid56_uncache_range(struct btrfs_fs_info *info, u64 start, u64 len);
+
+ #endif
+--
+2.47.3
+
+++ /dev/null
-From 4d6253c5eec47d8b006c6952cad73ea354d2d577 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 4 Sep 2026 22:14:19 -0400
-Subject: [PATCH 06/12] btrfs: raid56: keep a reference on a stolen cached rbio
- until it is dropped
-To: linux-btrfs@vger.kernel.org
-
-lock_stripe_add() steals the pages of a cached rbio for the same full
-stripe, drops the rbio's hash-list reference under the bucket lock, and
-only after releasing that lock calls remove_rbio_from_cache() on it.
-Between those two steps the rbio is held by nothing but the cache
-reference, and anyone who removes it from the cache in that window --
-the cache shrink in cache_rbio(), or btrfs_raid56_uncache_range() when
-the stripe's extents are freed -- frees it. remove_rbio_from_cache()
-then dereferences a freed rbio:
-
- BUG: kernel NULL pointer dereference, address: 0000000000000008
- Workqueue: btrfs-rmw rmw_rbio_work
- RIP: 0010:__remove_rbio_from_cache+0x33/0x180
- remove_rbio_from_cache+0x41/0x60
- lock_stripe_add+0xfc/0x460
- rmw_rbio_work+0x35/0x400
-
-The oops leaves the cache and bucket locks held, and every other RMW
-worker and the transaction thread soft-lock behind them. Seen after
-8h of the device-corruption acceptance suite on 6.18, where freeing of
-extents during read errors made the uncache path frequent; the window
-exists with the plain cache shrink as well.
-
-Keep the hash-list reference across the steal and drop it after the
-cache removal, so a concurrent remover can clear the cache bit and drop
-its own reference but never free the rbio under our feet.
-
-Assisted-by: Claude:claude-opus-4-8
----
- fs/btrfs/raid56.c | 12 ++++++++++--
- 1 file changed, 10 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 13e5a0244fdb3..cb4d6d7afe396 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -831,8 +831,14 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
- list_empty(&cur->plug_list) &&
- test_bit(RBIO_CACHE_BIT, &cur->flags) &&
- !test_bit(RBIO_RMW_LOCKED_BIT, &cur->flags)) {
-+ /*
-+ * Keep the hash-list reference: after the bucket lock
-+ * is released nothing but the cache holds cur, and a
-+ * concurrent cache removal would free it before the
-+ * remove_rbio_from_cache() below runs. The reference
-+ * is dropped there, after the cache is done with it.
-+ */
- list_del_init(&cur->hash_list);
-- refcount_dec(&cur->refs);
-
- steal_rbio(cur, rbio);
- cache_drop = cur;
-@@ -880,8 +886,10 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
- list_add(&rbio->hash_list, &h->hash_list);
- out:
- spin_unlock(&h->lock);
-- if (cache_drop)
-+ if (cache_drop) {
- remove_rbio_from_cache(cache_drop);
-+ free_raid_bio(cache_drop);
-+ }
- if (freeit)
- free_raid_bio(freeit);
- return ret;
---
-2.47.3
-
+++ /dev/null
-From 91863d542ab16d679351dde0560bb5e987459f3d Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 12 Sep 2026 07:17:54 -0400
-Subject: [PATCH 07/12] btrfs: raid56: do not unhash a cached rbio that has
- rbios plugged on it
-To: linux-btrfs@vger.kernel.org
-
-unlock_stripe() caches the finished rbio with cache_rbio() before it
-retakes the bucket and bio_list locks, and RBIO_RMW_LOCKED_BIT is still
-set at that point. A lock_stripe_add() for the same full stripe that
-runs in that window finds a cached rbio it can neither steal (still RMW
-locked) nor merge with (cached) and plugs itself onto it, which is
-correct: unlock_stripe() then sees the plug list and hands the stripe
-lock on to the plugged rbio.
-
-But if the rbio is removed from the cache in that same window --
-btrfs_raid56_uncache_range() from the commit's unpin, or the cache's own
-shrink in cache_rbio() -- __remove_rbio_from_cache() finds an empty
-bio_list, takes the rbio off the hash list, drops the hash reference and
-hits BUG_ON(!list_empty(&rbio->plug_list)). Seen on a degraded raid5
-under fsstress: the transaction kthread died in that BUG_ON with the
-bucket lock held and the rmw workers spun on it until the machine was
-reset.
-
-An rbio with rbios plugged on it is busy, like one with bios: leave it
-on the hash list and let unlock_stripe() hand the lock on; drop only the
-cache's reference here.
-
-Assisted-by: Claude:claude-opus-4-8
----
- fs/btrfs/raid56.c | 14 ++++++++++++--
- 1 file changed, 12 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index cb4d6d7afe396..6ff4eeca37fbc 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -506,11 +506,21 @@ static void __remove_rbio_from_cache(struct btrfs_raid_bio *rbio)
- * the rbio from the hash_table, and drop
- * the corresponding ref
- */
-- if (bio_list_empty(&rbio->bio_list)) {
-+ /*
-+ * An rbio with no bios is idle only if nothing is plugged on
-+ * it either. unlock_stripe() caches the rbio before it retakes
-+ * the locks, with RBIO_RMW_LOCKED_BIT still set, so a
-+ * lock_stripe_add() in that window can neither steal the pages
-+ * nor merge and plugs onto the cached rbio instead. That rbio
-+ * is still the stripe's lock owner and unlock_stripe() hands
-+ * the lock on to the plugged one; only the cache's reference
-+ * goes away here.
-+ */
-+ if (bio_list_empty(&rbio->bio_list) &&
-+ list_empty(&rbio->plug_list)) {
- if (!list_empty(&rbio->hash_list)) {
- list_del_init(&rbio->hash_list);
- refcount_dec(&rbio->refs);
-- ASSERT(list_empty(&rbio->plug_list));
- }
- }
- }
---
-2.47.3
-
--- /dev/null
+From d603a281c880d6a7ab5c8dcd7eb2b3054a6b8f63 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Wed, 5 Aug 2026 02:59:50 -0400
+Subject: [PATCH 07/12] btrfs: raid56: verify reconstructed tree blocks
+To: linux-btrfs@vger.kernel.org
+
+Data sectors recovered from parity are checked against the csum tree
+before they are trusted: recover_vertical() calls verify_one_sector() for
+each rebuilt sector, and a mismatch fails the read. Metadata gets none of
+that. fill_data_csums() returns early for anything that is not a data
+block group, so csum_bitmap is NULL, and verify_one_sector() then returns
+success without looking at anything:
+
+ if (!rbio->csum_bitmap || !rbio->csum_buf)
+ return 0;
+
+So a metadata rbio reconstructs a lost column, marks it uptodate having
+verified nothing, and hands it back. A wrong reconstruction is caught
+much later by validate_extent_buffer(), one layer up, after the block has
+already been returned and cached -- and in the raid6 case, where several
+candidate reconstructions exist, raid56 cannot tell which one is right
+because it has no way to check any of them.
+
+A tree block can be verified, just not a sector at a time: its csum lives
+in its own header and covers the whole nodesize block, so the check has to
+wait until every sector of the block has been recovered. Do it after the
+vertical recovery loop rather than inside it. A tree block never straddles
+a column -- nodesize and BTRFS_STRIPE_LEN are both powers of two with
+nodesize <= BTRFS_STRIPE_LEN, and full stripes are stripe-length aligned,
+so each column starts on a nodesize boundary and tree blocks tile it
+exactly.
+
+Only the blocks the caller asked for are checked. Those are known to be
+live tree blocks; the rest of a stripe may be free space, which has no
+header and would fail every test. For the same reason this runs only when
+rebuilding a read: recover_sectors() is also reached from the
+read-modify-write path, where the sectors actually reconstructed are the
+ones read off the surviving columns and any of them may be free space. A
+reconstruction feeding an RMW's parity therefore stays unverified; knowing
+which ranges hold live metadata is not something this layer can do.
+
+Tested with a 3-device raid5 filesystem with raid5 metadata, 3000 files:
+each device in turn missing and corrupted recovers byte-exactly, and with
+two devices corrupted -- where reconstruction necessarily produces a wrong
+block -- raid56 now rejects it itself:
+
+ raid56: reconstructed tree block 40796160 has bytenr 8993213254959039756,
+ cannot be trusted
+
+Scrub's reads are left out: they cover whole stripes, free space
+included, and scrub verifies the sectors that hold extents itself.
+Checked here, a free slot in a rebuilt stripe failed the whole read,
+which inflated the read error counts, made a replace with -r read the
+source after all, and with nodesize equal to sectorsize left unused
+slots of a replace target unwritten.
+
+Assisted-by: Claude:claude-fable-5
+---
+ fs/btrfs/raid56.c | 185 ++++++++++++++++++++++++++++++++++++++++++++++
+ 1 file changed, 185 insertions(+)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 5ec0ec769a0c8..81d6ec1ab1f13 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -1885,6 +1885,187 @@ static void calculate_block_csum_paddrs(struct btrfs_fs_info *fs_info,
+ btrfs_csum_final(&csum, dest);
+ }
+
++/*
++ * Return the memory holding a recovered sector: the bio's pages when we are
++ * rebuilding a read, the rbio's own stripe pages otherwise.
++ */
++static phys_addr_t *recovered_sector_paddrs(struct btrfs_raid_bio *rbio,
++ int stripe_nr, int sector_nr)
++{
++ if (rbio->operation == BTRFS_RBIO_READ_REBUILD)
++ return sector_paddrs_in_rbio(rbio, stripe_nr, sector_nr, 0);
++ return rbio_stripe_paddrs(rbio, stripe_nr, sector_nr);
++}
++
++/*
++ * Verify one reconstructed tree block.
++ *
++ * Data sectors are verified individually against the csum tree, but a tree
++ * block carries its csum in its own header, covering the whole nodesize
++ * block. So metadata cannot be checked a sector at a time: the check has to
++ * wait until every sector of the block has been recovered, which is why this
++ * runs after the vertical recovery loop rather than inside it.
++ *
++ * A tree block never straddles a column. nodesize and the stripe length are
++ * both powers of two with nodesize <= the stripe length, and a full stripe is
++ * stripe-length aligned, so each column begins on a nodesize boundary and
++ * tree blocks tile it exactly.
++ *
++ * @sector_nr is the first sector of the block within the column.
++ */
++static int verify_one_eb(struct btrfs_raid_bio *rbio, int stripe_nr,
++ int sector_nr)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ const u32 sectorsize = fs_info->sectorsize;
++ const u32 sectors_per_tree = fs_info->nodesize >> fs_info->sectorsize_bits;
++ const u32 step = min(sectorsize, PAGE_SIZE);
++ const u64 logical = rbio->bioc->full_stripe_logical +
++ (u64)stripe_nr * rbio->bioc->stripe_len +
++ (u64)sector_nr * sectorsize;
++ u8 on_disk_csum[BTRFS_CSUM_SIZE];
++ u8 calculated_csum[BTRFS_CSUM_SIZE];
++ struct btrfs_csum_ctx csum;
++ phys_addr_t *paddrs;
++ void *kaddr;
++ u64 found_bytenr;
++ bool bad_fsid;
++
++ /*
++ * The header lives at the start of the block. Read what we need from
++ * it before walking the rest: a block whose bytenr or fsid do not
++ * match was not reconstructed into what it claims to be, and there is
++ * no point csumming it.
++ */
++ paddrs = recovered_sector_paddrs(rbio, stripe_nr, sector_nr);
++ kaddr = kmap_local_paddr(paddrs[0]);
++ memcpy(on_disk_csum, ((struct btrfs_header *)kaddr)->csum,
++ fs_info->csum_size);
++ found_bytenr = btrfs_stack_header_bytenr((struct btrfs_header *)kaddr);
++ bad_fsid = memcmp(((struct btrfs_header *)kaddr)->fsid,
++ fs_info->fs_devices->metadata_uuid,
++ BTRFS_FSID_SIZE) != 0;
++ kunmap_local(kaddr);
++
++ if (unlikely(found_bytenr != logical)) {
++ btrfs_warn_rl(fs_info,
++"raid56: reconstructed tree block %llu has bytenr %llu, cannot be trusted",
++ logical, found_bytenr);
++ return -EIO;
++ }
++ if (unlikely(bad_fsid)) {
++ btrfs_warn_rl(fs_info,
++"raid56: reconstructed tree block %llu has the wrong fsid, cannot be trusted",
++ logical);
++ return -EIO;
++ }
++
++ btrfs_csum_init(&csum, fs_info->csum_type);
++ for (int i = 0; i < sectors_per_tree; i++) {
++ paddrs = recovered_sector_paddrs(rbio, stripe_nr, sector_nr + i);
++
++ for (int j = 0; j < rbio->sector_nsteps; j++) {
++ kaddr = kmap_local_paddr(paddrs[j]);
++ /* The csum field itself is not covered by the csum. */
++ if (i == 0 && j == 0)
++ btrfs_csum_update(&csum, kaddr + BTRFS_CSUM_SIZE,
++ step - BTRFS_CSUM_SIZE);
++ else
++ btrfs_csum_update(&csum, kaddr, step);
++ kunmap_local(kaddr);
++ }
++ }
++ btrfs_csum_final(&csum, calculated_csum);
++
++ if (unlikely(memcmp(calculated_csum, on_disk_csum, fs_info->csum_size))) {
++ btrfs_warn_rl(fs_info,
++"raid56: reconstructed tree block %llu fails its csum, cannot be trusted",
++ logical);
++ return -EIO;
++ }
++ return 0;
++}
++
++/*
++ * Verify every tree block this rbio was asked to read, once recovery has
++ * filled in the missing columns.
++ *
++ * Only blocks the caller actually requested are checked: a filesystem read
++ * asks for live tree blocks, whereas the rest of a stripe may be free space,
++ * which has no header to verify and would fail every test here. Scrub reads
++ * whole stripes, free space included, and verifies the sectors that hold
++ * extents itself, so its reads are not checked here.
++ *
++ * Without this, a metadata rbio reconstructs a column and marks it uptodate
++ * having checked nothing -- verify_one_sector() returns success immediately
++ * when there is no csum_bitmap, and metadata never has one (see
++ * fill_data_csums()). A wrong reconstruction would then be handed back to
++ * the caller, and cached, for validate_extent_buffer() to reject much later.
++ */
++static int verify_recovered_ebs(struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ const u32 sectors_per_tree = fs_info->nodesize >> fs_info->sectorsize_bits;
++
++ /*
++ * Data has its own per-sector verification. A mixed block group has
++ * neither: its sectors get no csums (fill_data_csums() skips mixed
++ * groups) and its contents may be file data rather than tree blocks,
++ * so there is nothing here to check either.
++ */
++ if (rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA)
++ return 0;
++
++ /*
++ * Only when rebuilding a read. recover_sectors() is also reached from
++ * the read-modify-write path, and there the bio list covers the blocks
++ * being written -- already-verified memory -- while the sectors that
++ * were actually reconstructed are the ones read off the other columns.
++ * Those cannot be checked: any of them may be free space rather than a
++ * live tree block, and free space has no header to verify. Knowing
++ * which ranges hold live metadata is exactly what this layer lacks,
++ * so a reconstruction feeding an RMW's parity stays unverified.
++ */
++ if (rbio->operation != BTRFS_RBIO_READ_REBUILD)
++ return 0;
++
++ /*
++ * A scrub read covers free space too, and scrub verifies what it read
++ * itself. A READ_REBUILD rbio is never merged (rbio_can_merge()), so
++ * its one bio says whose read it is.
++ */
++ if (!bio_list_empty(&rbio->bio_list) &&
++ btrfs_bio(bio_list_peek(&rbio->bio_list))->is_scrub)
++ return 0;
++
++ for (int stripe_nr = 0; stripe_nr < rbio->nr_data; stripe_nr++) {
++ for (int sector_nr = 0;
++ sector_nr + sectors_per_tree <= rbio->stripe_nsectors;
++ sector_nr += sectors_per_tree) {
++ bool requested = true;
++ int ret;
++
++ for (int i = 0; i < sectors_per_tree; i++) {
++ const int index = rbio_sector_index(rbio, stripe_nr,
++ sector_nr + i);
++
++ if (rbio->bio_paddrs[index * rbio->sector_nsteps] ==
++ INVALID_PADDR) {
++ requested = false;
++ break;
++ }
++ }
++ if (!requested)
++ continue;
++
++ ret = verify_one_eb(rbio, stripe_nr, sector_nr);
++ if (ret < 0)
++ return ret;
++ }
++ }
++ return 0;
++}
++
+ static int verify_one_sector(struct btrfs_raid_bio *rbio,
+ int stripe_nr, int sector_nr)
+ {
+@@ -2120,6 +2301,10 @@ static int recover_sectors(struct btrfs_raid_bio *rbio)
+ break;
+ }
+
++ /* Metadata is verified per tree block, once every sector is back. */
++ if (ret == 0)
++ ret = verify_recovered_ebs(rbio);
++
+ out:
+ kfree(pointers);
+ kfree(unmap_array);
+--
+2.47.3
+
+++ /dev/null
-From 68a1dc1bf316ba1a62c82b8d4656ccfb932623d8 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 20 Oct 2026 01:19:22 -0400
-Subject: [PATCH 08/12] btrfs: raid56: do not let a failed write leave its
- pages for the next write
-To: linux-btrfs@vger.kernel.org
-
-rmw_rbio() copies the write's bios into the rbio's stripe pages and sets
-RBIO_CACHE_READY_BIT before it submits the writes. rbio_orig_end_io()
-then calls unlock_stripe(), which puts the rbio in the stripe cache, or
-hands its pages to the next rbio plugged on the stripe, whatever the
-status of the write.
-
-When the write failed on more devices than the profile tolerates, its
-bios complete with an error and the ordered extent drops the data, but
-the stripe pages still hold it. A later sub-stripe write to the same
-full stripe steals those pages instead of reading the stripe. It
-computes parity over data the failed devices never got, writes it, and
-completes successfully. The new data is acked, but the stripe's parity
-no longer matches what is on disk. Every read of the new data passes and
-scrub reports no errors (it quietly rewrites the parity, if it runs
-first), but once a device is lost the new data is rebuilt from that
-parity and fails its checksum.
-
-A write that failed within the profile's tolerance completes with
-BLK_STS_OK, and its pages are still what the stripe holds: the failed
-strips rebuild from parity. Keep caching those. Dropping them would make
-the next write read the bad strips from disk, and those are verified only
-when their checksums are already in the csum tree.
-
-Clear RBIO_CACHE_READY_BIT when an rbio completes with an error, before
-unlock_stripe(), so neither the cache nor the plug-list hand-over offers
-its pages.
-
-Test: write-error-cache-test.sh in the raid56-wh-harness. dm-flakey
-error_writes fails one write's writeback on parity+1 members: 224K, so
-its second stripe is a sub-stripe write. Then, with the members healthy
-again, a 160K write fills the rest of that stripe. Before this patch the
-second write stole the failed rbio in all 16 events (raid5 and raid6).
-In every event where a failed member held the first write's sectors (4 of
-8 on raid5, 6 of 8 on raid6), the parity matched the failed write's data
-instead of the disk. The second write's file then failed its checksum
-when rebuilt: 8 of 32 reads with one member missing on raid5, 30 of 120
-reads with two members missing on raid6. The stock allocator shows the
-same steal (3 and 2 events). With this patch the second write reads the
-stripe, its parity matches the disk in every event, and every read
-succeeds. Within the tolerance (one failed member on raid5, one or two on
-raid6) both kernels keep the cache, and every acked file reads back with
-the failed members missing.
-
-Fixes: 4ae10b3a133e ("Btrfs: Add a stripe cache to raid56")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/raid56.c | 12 ++++++++++++
- 1 file changed, 12 insertions(+)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 6ff4eeca37fbc..1d9917330e912 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -1018,6 +1018,18 @@ static void rbio_orig_end_io(struct btrfs_raid_bio *rbio, blk_status_t status)
- */
- bitmap_clear(&rbio->dbitmap, 0, rbio->stripe_nsectors);
-
-+ /*
-+ * A write that failed beyond what the profile tolerates did not put
-+ * the stripe pages on disk, so they must not stand in for the stripe:
-+ * a later sub-stripe write stealing them, from the cache or from the
-+ * hand-over in unlock_stripe(), would compute parity over data that
-+ * the failed devices never got. Make that write read the stripe. A
-+ * write that failed within the tolerance completes OK and its pages
-+ * are still what the stripe holds: keep those.
-+ */
-+ if (status != BLK_STS_OK)
-+ clear_bit(RBIO_CACHE_READY_BIT, &rbio->flags);
-+
- /*
- * At this moment, rbio->bio_list is empty, however since rbio does not
- * always have RBIO_RMW_LOCKED_BIT set and rbio is still linked on the
---
-2.47.3
-
--- /dev/null
+From 4f6c6b2daa562025c2d9e01e76154a4a49a0498c Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Fri, 4 Sep 2026 22:14:19 -0400
+Subject: [PATCH 08/12] btrfs: raid56: keep a reference on a stolen cached rbio
+ until it is dropped
+To: linux-btrfs@vger.kernel.org
+
+lock_stripe_add() steals the pages of a cached rbio for the same full
+stripe, drops the rbio's hash-list reference under the bucket lock, and
+only after releasing that lock calls remove_rbio_from_cache() on it.
+Between those two steps the rbio is held by nothing but the cache
+reference, and anyone who removes it from the cache in that window --
+the cache shrink in cache_rbio(), or btrfs_raid56_uncache_range() when
+the stripe's extents are freed -- frees it. remove_rbio_from_cache()
+then dereferences a freed rbio:
+
+ BUG: kernel NULL pointer dereference, address: 0000000000000008
+ Workqueue: btrfs-rmw rmw_rbio_work
+ RIP: 0010:__remove_rbio_from_cache+0x33/0x180
+ remove_rbio_from_cache+0x41/0x60
+ lock_stripe_add+0xfc/0x460
+ rmw_rbio_work+0x35/0x400
+
+The oops leaves the cache and bucket locks held, and every other RMW
+worker and the transaction thread soft-lock behind them. Seen after
+8h of the device-corruption acceptance suite on 6.18, where freeing of
+extents during read errors made the uncache path frequent; the window
+exists with the plain cache shrink as well.
+
+Keep the hash-list reference across the steal and drop it after the
+cache removal, so a concurrent remover can clear the cache bit and drop
+its own reference but never free the rbio under our feet.
+
+Assisted-by: Claude:claude-opus-4-8
+---
+ fs/btrfs/raid56.c | 12 ++++++++++--
+ 1 file changed, 10 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 81d6ec1ab1f13..44877bc3f51b7 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -756,8 +756,14 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
+ list_empty(&cur->plug_list) &&
+ test_bit(RBIO_CACHE_BIT, &cur->flags) &&
+ !test_bit(RBIO_RMW_LOCKED_BIT, &cur->flags)) {
++ /*
++ * Keep the hash-list reference: after the bucket lock
++ * is released nothing but the cache holds cur, and a
++ * concurrent cache removal would free it before the
++ * remove_rbio_from_cache() below runs. The reference
++ * is dropped there, after the cache is done with it.
++ */
+ list_del_init(&cur->hash_list);
+- refcount_dec(&cur->refs);
+
+ steal_rbio(cur, rbio);
+ cache_drop = cur;
+@@ -805,8 +811,10 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
+ list_add(&rbio->hash_list, &h->hash_list);
+ out:
+ spin_unlock(&h->lock);
+- if (cache_drop)
++ if (cache_drop) {
+ remove_rbio_from_cache(cache_drop);
++ free_raid_bio(cache_drop);
++ }
+ if (freeit)
+ free_raid_bio(freeit);
+ return ret;
+--
+2.47.3
+
--- /dev/null
+From 4e743a3100a732c24ec778a6693ae25400bab9d7 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 12 Sep 2026 07:17:54 -0400
+Subject: [PATCH 09/12] btrfs: raid56: do not unhash a cached rbio that has
+ rbios plugged on it
+To: linux-btrfs@vger.kernel.org
+
+unlock_stripe() caches the finished rbio with cache_rbio() before it
+retakes the bucket and bio_list locks, and RBIO_RMW_LOCKED_BIT is still
+set at that point. A lock_stripe_add() for the same full stripe that
+runs in that window finds a cached rbio it can neither steal (still RMW
+locked) nor merge with (cached) and plugs itself onto it, which is
+correct: unlock_stripe() then sees the plug list and hands the stripe
+lock on to the plugged rbio.
+
+But if the rbio is removed from the cache in that same window --
+btrfs_raid56_uncache_range() from the commit's unpin, or the cache's own
+shrink in cache_rbio() -- __remove_rbio_from_cache() finds an empty
+bio_list, takes the rbio off the hash list, drops the hash reference and
+hits BUG_ON(!list_empty(&rbio->plug_list)). Seen on a degraded raid5
+under fsstress: the transaction kthread died in that BUG_ON with the
+bucket lock held and the rmw workers spun on it until the machine was
+reset.
+
+An rbio with rbios plugged on it is busy, like one with bios: leave it
+on the hash list and let unlock_stripe() hand the lock on; drop only the
+cache's reference here.
+
+Assisted-by: Claude:claude-opus-4-8
+---
+ fs/btrfs/raid56.c | 14 ++++++++++++--
+ 1 file changed, 12 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 44877bc3f51b7..390ad69a64e0a 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -431,11 +431,21 @@ static void __remove_rbio_from_cache(struct btrfs_raid_bio *rbio)
+ * the rbio from the hash_table, and drop
+ * the corresponding ref
+ */
+- if (bio_list_empty(&rbio->bio_list)) {
++ /*
++ * An rbio with no bios is idle only if nothing is plugged on
++ * it either. unlock_stripe() caches the rbio before it retakes
++ * the locks, with RBIO_RMW_LOCKED_BIT still set, so a
++ * lock_stripe_add() in that window can neither steal the pages
++ * nor merge and plugs onto the cached rbio instead. That rbio
++ * is still the stripe's lock owner and unlock_stripe() hands
++ * the lock on to the plugged one; only the cache's reference
++ * goes away here.
++ */
++ if (bio_list_empty(&rbio->bio_list) &&
++ list_empty(&rbio->plug_list)) {
+ if (!list_empty(&rbio->hash_list)) {
+ list_del_init(&rbio->hash_list);
+ refcount_dec(&rbio->refs);
+- ASSERT(list_empty(&rbio->plug_list));
+ }
+ }
+ }
+--
+2.47.3
+
+++ /dev/null
-From f55474d2c5c8a84ee73003e6ea52ada8fd0152be Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 20 Oct 2026 13:04:12 -0400
-Subject: [PATCH 09/12] btrfs: raid56: rebuild from Q when a sector rebuilt
- from P fails its csum
-To: linux-btrfs@vger.kernel.org
-
-A sub-stripe write on RAID6 reads the whole full stripe and verifies its
-data sectors against their csums. A sector that does not match is marked
-failed, and recover_vertical() rebuilds it. With one failed sector in a
-vertical stripe it rebuilds from P, verifies the result, and fails the
-whole write with -EIO if the rebuild does not match either.
-
-P has no csum, so a stale P is not seen as a failure. A write that failed
-on the member holding a data strip and on the member holding P, but
-completed within the profile's tolerance, leaves exactly that: the data
-strip and P stale, and only Q matching what was written. Every later
-sub-stripe write into that full stripe then fails with -EIO. The
-allocator hands the same free space out again, so the next write there
-fails the same way. The same happens on a degraded filesystem when the
-member holding the data strip is missing and P is stale.
-
-Normal reads of the stale data succeed because read repair walks the
-RAID6 mirrors: mirror 2 rebuilds from P, mirror 3 also treats P as failed
-and rebuilds from Q, and each later mirror treats one more data stripe as
-failed (set_rbio_raid6_extra_error()). Scrub repairs it too. The RMW
-path only tries the first of these.
-
-When the one failed data sector of a RAID6 vertical stripe, rebuilt from
-P, does not verify, rebuild it again treating one more stripe as failed,
-in read repair's order: P (a rebuild from Q), then each other data stripe
-(a rebuild from P and Q, which covers a stale data sector that has no
-csum). Use the first rebuild whose data sectors verify. Each try writes
-its rebuild into the extra stripe's sector, so save that sector and put
-it back before the next try.
-
-Only an RMW verifies rebuilt data sectors here (rbio->csum_bitmap is only
-filled there), so read rebuild and parity scrub do not change.
-
-raid6-rmw-stale-parity-test.sh (raid56-wh-harness) makes a data strip
-and P of a full stripe holding csummed data stale, then writes into the
-rest of that stripe. Without this patch the write fails with -EIO; with
-it the write succeeds, the new parity matches the written data, and
-every file reads back, also with members missing. The arms with a stale
-data strip and P where the data member is missing, and with a stale
-csummed data strip plus a stale strip of a nodatasum file, fail the same
-way without the patch and pass with it. The arms with a stale data
-strip and Q, and with two stale csummed data strips, pass either way.
-
-Fixes: 7a3150723061 ("btrfs: raid56: do data csum verification during RMW cycle")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/raid56.c | 115 ++++++++++++++++++++++++++++++++++++++--------
- 1 file changed, 95 insertions(+), 20 deletions(-)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 1d9917330e912..0a84eab7db224 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -2317,6 +2317,94 @@ static void recover_vertical_step(struct btrfs_raid_bio *rbio,
- kunmap_local(unmap_array[stripe_nr]);
- }
-
-+/*
-+ * Rebuild the vertical stripe @sector_nr treating @faila and @failb as the
-+ * failed stripes (@failb < 0 for one), then verify the rebuilt data sectors
-+ * against their csums and mark them uptodate.
-+ */
-+static int recover_vertical_try(struct btrfs_raid_bio *rbio, int sector_nr,
-+ int faila, int failb,
-+ void **pointers, void **unmap_array)
-+{
-+ int ret;
-+
-+ for (int i = 0; i < rbio->sector_nsteps; i++)
-+ recover_vertical_step(rbio, sector_nr, i, faila, failb,
-+ pointers, unmap_array);
-+ ret = verify_one_sector(rbio, faila, sector_nr);
-+ if (ret < 0)
-+ return ret;
-+ if (failb >= 0) {
-+ ret = verify_one_sector(rbio, failb, sector_nr);
-+ if (ret < 0)
-+ return ret;
-+ }
-+
-+ set_bit(rbio_sector_index(rbio, faila, sector_nr),
-+ rbio->stripe_uptodate_bitmap);
-+ if (failb >= 0)
-+ set_bit(rbio_sector_index(rbio, failb, sector_nr),
-+ rbio->stripe_uptodate_bitmap);
-+ return 0;
-+}
-+
-+static void copy_vertical_sector(struct btrfs_raid_bio *rbio, int stripe_nr,
-+ int sector_nr, void *buf, bool to_buf)
-+{
-+ const u32 step = min(rbio->bioc->fs_info->sectorsize, PAGE_SIZE);
-+ phys_addr_t *paddrs = recovered_sector_paddrs(rbio, stripe_nr, sector_nr);
-+
-+ for (int i = 0; i < rbio->sector_nsteps; i++) {
-+ void *kaddr = kmap_local_paddr(paddrs[i]);
-+
-+ if (to_buf)
-+ memcpy(buf + i * step, kaddr, step);
-+ else
-+ memcpy(kaddr, buf + i * step, step);
-+ kunmap_local(kaddr);
-+ }
-+}
-+
-+/*
-+ * A single failed data sector of a RAID6 vertical stripe was rebuilt from P,
-+ * and the result does not match its csum. Nothing verifies P, nor a data
-+ * sector without a csum, so a stale one of those is only found here. Like
-+ * read repair (see set_rbio_raid6_extra_error()), treat one more stripe as
-+ * failed and rebuild again: first P, which rebuilds from Q, then each other
-+ * data stripe, which rebuilds from P and Q.
-+ *
-+ * Each try overwrites the extra stripe's sector with its own rebuild, so put
-+ * the original back before the next one.
-+ */
-+static int recover_vertical_retry(struct btrfs_raid_bio *rbio, int sector_nr,
-+ int faila, void **pointers, void **unmap_array)
-+{
-+ void *saved;
-+ int ret = -EIO;
-+
-+ saved = kmalloc(rbio->bioc->fs_info->sectorsize, GFP_NOFS);
-+ if (!saved)
-+ return -ENOMEM;
-+
-+ for (int extra = rbio->nr_data; extra >= 0; extra--) {
-+ if (extra == faila)
-+ continue;
-+
-+ copy_vertical_sector(rbio, extra, sector_nr, saved, true);
-+ ret = recover_vertical_try(rbio, sector_nr, min(faila, extra),
-+ max(faila, extra), pointers,
-+ unmap_array);
-+ if (ret == 0) {
-+ set_bit(rbio_sector_index(rbio, extra, sector_nr),
-+ rbio->error_bitmap);
-+ break;
-+ }
-+ copy_vertical_sector(rbio, extra, sector_nr, saved, false);
-+ }
-+ kfree(saved);
-+ return ret;
-+}
-+
- /*
- * Recover a vertical stripe specified by @sector_nr.
- * @*pointers are the pre-allocated pointers by the caller, so we don't
-@@ -2328,7 +2416,7 @@ static int recover_vertical(struct btrfs_raid_bio *rbio, int sector_nr,
- int found_errors;
- int faila;
- int failb;
-- int ret = 0;
-+ int ret;
-
- /*
- * Now we just use bitmap to mark the horizontal stripes in
-@@ -2350,25 +2438,12 @@ static int recover_vertical(struct btrfs_raid_bio *rbio, int sector_nr,
- if (unlikely(found_errors > rbio->bioc->max_errors))
- return -EIO;
-
-- for (int i = 0; i < rbio->sector_nsteps; i++)
-- recover_vertical_step(rbio, sector_nr, i, faila, failb,
-- pointers, unmap_array);
-- if (faila >= 0) {
-- ret = verify_one_sector(rbio, faila, sector_nr);
-- if (ret < 0)
-- return ret;
--
-- set_bit(rbio_sector_index(rbio, faila, sector_nr),
-- rbio->stripe_uptodate_bitmap);
-- }
-- if (failb >= 0) {
-- ret = verify_one_sector(rbio, failb, sector_nr);
-- if (ret < 0)
-- return ret;
--
-- set_bit(rbio_sector_index(rbio, failb, sector_nr),
-- rbio->stripe_uptodate_bitmap);
-- }
-+ ret = recover_vertical_try(rbio, sector_nr, faila, failb, pointers,
-+ unmap_array);
-+ if (ret == -EIO && found_errors == 1 &&
-+ (rbio->bioc->map_type & BTRFS_BLOCK_GROUP_RAID6))
-+ ret = recover_vertical_retry(rbio, sector_nr, faila, pointers,
-+ unmap_array);
- return ret;
- }
-
---
-2.47.3
-
+++ /dev/null
-From 200a23a21458376d5d670e46e7a2c8a3a4b34201 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 20 Oct 2026 13:43:10 -0400
-Subject: [PATCH 10/12] btrfs: raid56: count I/O errors in the device stats
-To: linux-btrfs@vger.kernel.org
-
-raid56.c submits the reads and writes of a raid56 stripe itself, with its
-own end_io functions, so they never reach btrfs_log_dev_io_error() in
-bio.c, which counts failed bios in the device stats for every other
-profile (and for raid56 reads that map to a single device). The raid56
-end_io functions only record the failure in the rbio's error bitmap.
-
-So a raid56 write that fails on one device within the tolerance is acked
-and leaves that device's strip stale with no trace in btrfs: write_io_errs
-stays 0 and btrfs logs nothing. Failed read-modify-write, rebuild and
-parity scrub reads are not counted either. It has been like this since
-raid56 was added.
-
-Export btrfs_log_dev_io_error() and call it from both raid56 end_io
-functions, for the device the bio was sent to. The device is found by
-the bio's bdev: a write to the replace target uses the source's pages, so
-the pages do not say which device it went to.
-
-Test (raid56-wh-harness raid56-devstats-test.sh): a write failing on one
-member within tolerance (each member in turn; raid6 also each pair)
-raises write_io_errs on exactly the failing members, and a failed
-read-modify-write read raises read_io_errs on that member only; before,
-nothing was counted. With a member absent (degraded) no counter moves,
-and during a replace onto a target that fails writes only the target is
-charged.
-
-Fixes: 53b381b3abeb ("Btrfs: RAID5 and RAID6")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/bio.c | 2 +-
- fs/btrfs/bio.h | 2 ++
- fs/btrfs/raid56.c | 22 +++++++++++++++++++++-
- 3 files changed, 24 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/bio.c b/fs/btrfs/bio.c
-index b589cac044271..863043cd01117 100644
---- a/fs/btrfs/bio.c
-+++ b/fs/btrfs/bio.c
-@@ -318,7 +318,7 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de
- btrfs_bio_end_io(bbio, bbio->bio.bi_status);
- }
-
--static void btrfs_log_dev_io_error(const struct bio *bio, struct btrfs_device *dev)
-+void btrfs_log_dev_io_error(const struct bio *bio, struct btrfs_device *dev)
- {
- blk_status_t sts = bio->bi_status;
-
-diff --git a/fs/btrfs/bio.h b/fs/btrfs/bio.h
-index bbf362b8668bb..2451d38566d1a 100644
---- a/fs/btrfs/bio.h
-+++ b/fs/btrfs/bio.h
-@@ -13,6 +13,7 @@
- #include "tree-checker.h"
-
- struct btrfs_bio;
-+struct btrfs_device;
- struct btrfs_fs_info;
- struct btrfs_inode;
-
-@@ -121,6 +122,7 @@ void btrfs_bio_end_io(struct btrfs_bio *bbio, blk_status_t status);
- #define REQ_BTRFS_CGROUP_PUNT REQ_FS_PRIVATE
-
- void btrfs_submit_bbio(struct btrfs_bio *bbio, int mirror_num);
-+void btrfs_log_dev_io_error(const struct bio *bio, struct btrfs_device *dev);
- void btrfs_submit_repair_write(struct btrfs_bio *bbio, int mirror_num, bool dev_replace);
- int btrfs_repair_bbio_failure(struct btrfs_bio *bbio, const struct bvec_iter *orig_iter,
- u32 length, int mirror_num);
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 0a84eab7db224..673c579147b15 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -1790,11 +1790,29 @@ static void rbio_wait_io(struct btrfs_raid_bio *rbio)
- wait_for_completion(&rbio->io_done);
- }
-
-+/*
-+ * Count a failed bio in the stats of the device it went to, as bio.c does for
-+ * the other profiles. Look the device up by its bdev: a write to the replace
-+ * target uses the source's pages, so the pages do not tell the device.
-+ */
-+static void rbio_log_dev_io_error(struct btrfs_raid_bio *rbio, struct bio *bio)
-+{
-+ struct btrfs_io_context *bioc = rbio->bioc;
-+
-+ for (int i = 0; i < bioc->num_stripes; i++) {
-+ if (bioc->stripes[i].dev->bdev == bio->bi_bdev) {
-+ btrfs_log_dev_io_error(bio, bioc->stripes[i].dev);
-+ return;
-+ }
-+ }
-+}
-+
- static void raid_wait_read_end_io(struct bio *bio)
- {
- struct btrfs_raid_bio *rbio = bio->bi_private;
-
- if (bio->bi_status) {
-+ rbio_log_dev_io_error(rbio, bio);
- rbio_update_error_bitmap(rbio, bio);
- } else {
- set_bio_pages_uptodate(rbio, bio);
-@@ -2762,8 +2780,10 @@ static void raid_wait_write_end_io(struct bio *bio)
- {
- struct btrfs_raid_bio *rbio = bio->bi_private;
-
-- if (bio->bi_status)
-+ if (bio->bi_status) {
-+ rbio_log_dev_io_error(rbio, bio);
- rbio_update_error_bitmap(rbio, bio);
-+ }
- bio_put(bio);
- rbio_dec_io(rbio);
- }
---
-2.47.3
-
--- /dev/null
+From 13a1771e7dc5195969a132513d35cd9685ee471a Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Tue, 20 Oct 2026 13:04:12 -0400
+Subject: [PATCH 10/12] btrfs: raid56: rebuild from Q when a sector rebuilt
+ from P fails its csum
+To: linux-btrfs@vger.kernel.org
+
+A sub-stripe write on RAID6 reads the whole full stripe and verifies its
+data sectors against their csums. A sector that does not match is marked
+failed, and recover_vertical() rebuilds it. With one failed sector in a
+vertical stripe it rebuilds from P, verifies the result, and fails the
+whole write with -EIO if the rebuild does not match either.
+
+P has no csum, so a stale P is not seen as a failure. A write that failed
+on the member holding a data strip and on the member holding P, but
+completed within the profile's tolerance, leaves exactly that: the data
+strip and P stale, and only Q matching what was written. Every later
+sub-stripe write into that full stripe then fails with -EIO. The
+allocator hands the same free space out again, so the next write there
+fails the same way. The same happens on a degraded filesystem when the
+member holding the data strip is missing and P is stale.
+
+Normal reads of the stale data succeed because read repair walks the
+RAID6 mirrors: mirror 2 rebuilds from P, mirror 3 also treats P as failed
+and rebuilds from Q, and each later mirror treats one more data stripe as
+failed (set_rbio_raid6_extra_error()). Scrub repairs it too. The RMW
+path only tries the first of these.
+
+When the one failed data sector of a RAID6 vertical stripe, rebuilt from
+P, does not verify, rebuild it again treating one more stripe as failed,
+in read repair's order: P (a rebuild from Q), then each other data stripe
+(a rebuild from P and Q, which covers a stale data sector that has no
+csum). Use the first rebuild whose data sectors verify. Each try writes
+its rebuild into the extra stripe's sector, so save that sector and put
+it back before the next try.
+
+Only an RMW verifies rebuilt data sectors here (rbio->csum_bitmap is only
+filled there), so read rebuild and parity scrub do not change.
+
+raid6-rmw-stale-parity-test.sh (raid56-wh-harness) makes a data strip
+and P of a full stripe holding csummed data stale, then writes into the
+rest of that stripe. Without this patch the write fails with -EIO; with
+it the write succeeds, the new parity matches the written data, and
+every file reads back, also with members missing. The arms with a stale
+data strip and P where the data member is missing, and with a stale
+csummed data strip plus a stale strip of a nodatasum file, fail the same
+way without the patch and pass with it. The arms with a stale data
+strip and Q, and with two stale csummed data strips, pass either way.
+
+Fixes: 7a3150723061 ("btrfs: raid56: do data csum verification during RMW cycle")
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/raid56.c | 115 ++++++++++++++++++++++++++++++++++++++--------
+ 1 file changed, 95 insertions(+), 20 deletions(-)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 390ad69a64e0a..a4aeb8c385869 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -2230,6 +2230,94 @@ static void recover_vertical_step(struct btrfs_raid_bio *rbio,
+ kunmap_local(unmap_array[stripe_nr]);
+ }
+
++/*
++ * Rebuild the vertical stripe @sector_nr treating @faila and @failb as the
++ * failed stripes (@failb < 0 for one), then verify the rebuilt data sectors
++ * against their csums and mark them uptodate.
++ */
++static int recover_vertical_try(struct btrfs_raid_bio *rbio, int sector_nr,
++ int faila, int failb,
++ void **pointers, void **unmap_array)
++{
++ int ret;
++
++ for (int i = 0; i < rbio->sector_nsteps; i++)
++ recover_vertical_step(rbio, sector_nr, i, faila, failb,
++ pointers, unmap_array);
++ ret = verify_one_sector(rbio, faila, sector_nr);
++ if (ret < 0)
++ return ret;
++ if (failb >= 0) {
++ ret = verify_one_sector(rbio, failb, sector_nr);
++ if (ret < 0)
++ return ret;
++ }
++
++ set_bit(rbio_sector_index(rbio, faila, sector_nr),
++ rbio->stripe_uptodate_bitmap);
++ if (failb >= 0)
++ set_bit(rbio_sector_index(rbio, failb, sector_nr),
++ rbio->stripe_uptodate_bitmap);
++ return 0;
++}
++
++static void copy_vertical_sector(struct btrfs_raid_bio *rbio, int stripe_nr,
++ int sector_nr, void *buf, bool to_buf)
++{
++ const u32 step = min(rbio->bioc->fs_info->sectorsize, PAGE_SIZE);
++ phys_addr_t *paddrs = recovered_sector_paddrs(rbio, stripe_nr, sector_nr);
++
++ for (int i = 0; i < rbio->sector_nsteps; i++) {
++ void *kaddr = kmap_local_paddr(paddrs[i]);
++
++ if (to_buf)
++ memcpy(buf + i * step, kaddr, step);
++ else
++ memcpy(kaddr, buf + i * step, step);
++ kunmap_local(kaddr);
++ }
++}
++
++/*
++ * A single failed data sector of a RAID6 vertical stripe was rebuilt from P,
++ * and the result does not match its csum. Nothing verifies P, nor a data
++ * sector without a csum, so a stale one of those is only found here. Like
++ * read repair (see set_rbio_raid6_extra_error()), treat one more stripe as
++ * failed and rebuild again: first P, which rebuilds from Q, then each other
++ * data stripe, which rebuilds from P and Q.
++ *
++ * Each try overwrites the extra stripe's sector with its own rebuild, so put
++ * the original back before the next one.
++ */
++static int recover_vertical_retry(struct btrfs_raid_bio *rbio, int sector_nr,
++ int faila, void **pointers, void **unmap_array)
++{
++ void *saved;
++ int ret = -EIO;
++
++ saved = kmalloc(rbio->bioc->fs_info->sectorsize, GFP_NOFS);
++ if (!saved)
++ return -ENOMEM;
++
++ for (int extra = rbio->nr_data; extra >= 0; extra--) {
++ if (extra == faila)
++ continue;
++
++ copy_vertical_sector(rbio, extra, sector_nr, saved, true);
++ ret = recover_vertical_try(rbio, sector_nr, min(faila, extra),
++ max(faila, extra), pointers,
++ unmap_array);
++ if (ret == 0) {
++ set_bit(rbio_sector_index(rbio, extra, sector_nr),
++ rbio->error_bitmap);
++ break;
++ }
++ copy_vertical_sector(rbio, extra, sector_nr, saved, false);
++ }
++ kfree(saved);
++ return ret;
++}
++
+ /*
+ * Recover a vertical stripe specified by @sector_nr.
+ * @*pointers are the pre-allocated pointers by the caller, so we don't
+@@ -2241,7 +2329,7 @@ static int recover_vertical(struct btrfs_raid_bio *rbio, int sector_nr,
+ int found_errors;
+ int faila;
+ int failb;
+- int ret = 0;
++ int ret;
+
+ /*
+ * Now we just use bitmap to mark the horizontal stripes in
+@@ -2263,25 +2351,12 @@ static int recover_vertical(struct btrfs_raid_bio *rbio, int sector_nr,
+ if (unlikely(found_errors > rbio->bioc->max_errors))
+ return -EIO;
+
+- for (int i = 0; i < rbio->sector_nsteps; i++)
+- recover_vertical_step(rbio, sector_nr, i, faila, failb,
+- pointers, unmap_array);
+- if (faila >= 0) {
+- ret = verify_one_sector(rbio, faila, sector_nr);
+- if (ret < 0)
+- return ret;
+-
+- set_bit(rbio_sector_index(rbio, faila, sector_nr),
+- rbio->stripe_uptodate_bitmap);
+- }
+- if (failb >= 0) {
+- ret = verify_one_sector(rbio, failb, sector_nr);
+- if (ret < 0)
+- return ret;
+-
+- set_bit(rbio_sector_index(rbio, failb, sector_nr),
+- rbio->stripe_uptodate_bitmap);
+- }
++ ret = recover_vertical_try(rbio, sector_nr, faila, failb, pointers,
++ unmap_array);
++ if (ret == -EIO && found_errors == 1 &&
++ (rbio->bioc->map_type & BTRFS_BLOCK_GROUP_RAID6))
++ ret = recover_vertical_retry(rbio, sector_nr, faila, pointers,
++ unmap_array);
+ return ret;
+ }
+
+--
+2.47.3
+
--- /dev/null
+From bc422dc6bdb326f04e6fe719aa9cb4f09042e60b Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Tue, 20 Oct 2026 13:43:10 -0400
+Subject: [PATCH 11/12] btrfs: raid56: count I/O errors in the device stats
+To: linux-btrfs@vger.kernel.org
+
+raid56.c submits the reads and writes of a raid56 stripe itself, with its
+own end_io functions, so they never reach btrfs_log_dev_io_error() in
+bio.c, which counts failed bios in the device stats for every other
+profile (and for raid56 reads that map to a single device). The raid56
+end_io functions only record the failure in the rbio's error bitmap.
+
+So a raid56 write that fails on one device within the tolerance is acked
+and leaves that device's strip stale with no trace in btrfs: write_io_errs
+stays 0 and btrfs logs nothing. Failed read-modify-write, rebuild and
+parity scrub reads are not counted either. It has been like this since
+raid56 was added.
+
+Export btrfs_log_dev_io_error() and call it from both raid56 end_io
+functions, for the device the bio was sent to. The device is found by
+the bio's bdev: a write to the replace target uses the source's pages, so
+the pages do not say which device it went to.
+
+Test (raid56-wh-harness raid56-devstats-test.sh): a write failing on one
+member within tolerance (each member in turn; raid6 also each pair)
+raises write_io_errs on exactly the failing members, and a failed
+read-modify-write read raises read_io_errs on that member only; before,
+nothing was counted. With a member absent (degraded) no counter moves,
+and during a replace onto a target that fails writes only the target is
+charged.
+
+Fixes: 53b381b3abeb ("Btrfs: RAID5 and RAID6")
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/bio.c | 2 +-
+ fs/btrfs/bio.h | 2 ++
+ fs/btrfs/raid56.c | 22 +++++++++++++++++++++-
+ 3 files changed, 24 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/bio.c b/fs/btrfs/bio.c
+index b589cac044271..863043cd01117 100644
+--- a/fs/btrfs/bio.c
++++ b/fs/btrfs/bio.c
+@@ -318,7 +318,7 @@ static void btrfs_check_read_bio(struct btrfs_bio *bbio, struct btrfs_device *de
+ btrfs_bio_end_io(bbio, bbio->bio.bi_status);
+ }
+
+-static void btrfs_log_dev_io_error(const struct bio *bio, struct btrfs_device *dev)
++void btrfs_log_dev_io_error(const struct bio *bio, struct btrfs_device *dev)
+ {
+ blk_status_t sts = bio->bi_status;
+
+diff --git a/fs/btrfs/bio.h b/fs/btrfs/bio.h
+index bbf362b8668bb..2451d38566d1a 100644
+--- a/fs/btrfs/bio.h
++++ b/fs/btrfs/bio.h
+@@ -13,6 +13,7 @@
+ #include "tree-checker.h"
+
+ struct btrfs_bio;
++struct btrfs_device;
+ struct btrfs_fs_info;
+ struct btrfs_inode;
+
+@@ -121,6 +122,7 @@ void btrfs_bio_end_io(struct btrfs_bio *bbio, blk_status_t status);
+ #define REQ_BTRFS_CGROUP_PUNT REQ_FS_PRIVATE
+
+ void btrfs_submit_bbio(struct btrfs_bio *bbio, int mirror_num);
++void btrfs_log_dev_io_error(const struct bio *bio, struct btrfs_device *dev);
+ void btrfs_submit_repair_write(struct btrfs_bio *bbio, int mirror_num, bool dev_replace);
+ int btrfs_repair_bbio_failure(struct btrfs_bio *bbio, const struct bvec_iter *orig_iter,
+ u32 length, int mirror_num);
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index a4aeb8c385869..e45e6a6ba2566 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -1695,11 +1695,29 @@ static void rbio_wait_io(struct btrfs_raid_bio *rbio)
+ wait_for_completion(&rbio->io_done);
+ }
+
++/*
++ * Count a failed bio in the stats of the device it went to, as bio.c does for
++ * the other profiles. Look the device up by its bdev: a write to the replace
++ * target uses the source's pages, so the pages do not tell the device.
++ */
++static void rbio_log_dev_io_error(struct btrfs_raid_bio *rbio, struct bio *bio)
++{
++ struct btrfs_io_context *bioc = rbio->bioc;
++
++ for (int i = 0; i < bioc->num_stripes; i++) {
++ if (bioc->stripes[i].dev->bdev == bio->bi_bdev) {
++ btrfs_log_dev_io_error(bio, bioc->stripes[i].dev);
++ return;
++ }
++ }
++}
++
+ static void raid_wait_read_end_io(struct bio *bio)
+ {
+ struct btrfs_raid_bio *rbio = bio->bi_private;
+
+ if (bio->bi_status) {
++ rbio_log_dev_io_error(rbio, bio);
+ rbio_update_error_bitmap(rbio, bio);
+ } else {
+ set_bio_pages_uptodate(rbio, bio);
+@@ -2673,8 +2691,10 @@ static void raid_wait_write_end_io(struct bio *bio)
+ {
+ struct btrfs_raid_bio *rbio = bio->bi_private;
+
+- if (bio->bi_status)
++ if (bio->bi_status) {
++ rbio_log_dev_io_error(rbio, bio);
+ rbio_update_error_bitmap(rbio, bio);
++ }
+ bio_put(bio);
+ rbio_dec_io(rbio);
+ }
+--
+2.47.3
+
+++ /dev/null
-From 4f9f89c3d420ce96b9e541f22aebbeaa469a2ceb Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 20 Oct 2026 15:52:51 -0400
-Subject: [PATCH 11/12] btrfs: raid56: write back the sectors a sub-stripe
- write repaired
-To: linux-btrfs@vger.kernel.org
-
-A sub-stripe write reads the rest of its full stripe and verifies the data
-sectors that have csums. It rebuilds the sectors that failed their csum or
-their read, and the sectors of a missing device, and computes the new P and
-Q from the result. On RAID6 it also finds a stale P, or a stale data
-sector without a csum, by rebuilding again with one more stripe treated as
-failed. The write phase then writes only the new data, and P and Q of the
-vertical stripes the new data covers.
-
-The repaired sectors stay stale on disk until a read repair or a scrub
-finds them, even though the new parity was computed from their rebuilt
-contents. Until then the full stripe has one healthy member fewer than it
-seems, and one more lost device loses data that was recoverable.
-
-Write the repaired sectors back in the same write phase:
-
-- a data sector whose rebuild is verified. It has a csum, or it has none
- but was rebuilt from P and Q together with a data sector of the same
- vertical stripe that has one. The RAID6 retry finds a stale data sector
- without a csum that way. A lone rebuild of a sector without a csum comes
- from parity that nothing checked, and the copy on disk may be the right
- one, so it is left alone;
-- P or Q that failed its read or was found stale, in the vertical stripes
- the write does not cover (the others get new P and Q anyway);
-- nothing on a missing device. The replace target gets the same sectors as
- its source, as with the other writes.
-
-The write-backs go out with the rest of the write. A write-back that fails
-leaves its sector as stale as it was before the write, so it does not count
-against the write's tolerance, and the write completes as it did before.
-
-The rbio repairs before it writes anything, so a write-back never retries a
-write that the same rbio just failed. A write that failed on a member
-within the tolerance leaves its pages in the stripe cache, and the next
-sub-stripe write into that full stripe takes them without reading, so it
-has nothing to repair either. A write-back can still go to a sector whose
-write by an earlier rbio failed, when that rbio's pages were not cached (a
-full stripe write) or were evicted: then it fails again, or heals the
-sector. A btrfs_debug line counts the write-backs and the failed ones.
-
-rmw-writeback-test.sh (raid56-wh-harness) puts strips of one full stripe
-back to stale contents, writes into the rest of the stripe, once with
-fsync and once with a plain write(), and reads the members back offline
-before anything else touches them. The stale strips are, on RAID5, a data
-strip with a csum, alone or also failing its reads; on RAID6, a data strip
-with P, with Q, with a second data strip with a csum, or with a strip of a
-nodatasum file, with the write covering all rows or only some of them.
-Without this patch every repaired strip, and P outside the written rows,
-is still stale after the write in all 18 runs; with it none is, and P and
-Q match the data in every row. With the stale member failing writes, the
-write-back fails, the write still completes and its data reads back,
-also on RAID5 when the write to P fails as well (counting the failed
-write-back against the tolerance fails that write with -EIO). A
-nodatasum strip rebuilt from P alone after a read error is not written
-back.
-
-Fixes: 7a3150723061 ("btrfs: raid56: do data csum verification during RMW cycle")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/raid56.c | 152 ++++++++++++++++++++++++++++++++++++++++++++++
- 1 file changed, 152 insertions(+)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 673c579147b15..0b10204b70a50 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -2830,10 +2830,153 @@ static bool need_read_stripe_sectors(struct btrfs_raid_bio *rbio)
- return false;
- }
-
-+/*
-+ * Return true if the rebuild of data sector @sector_nr of @stripe_nr can be
-+ * trusted enough to write it back. It can when the sector has a csum: the
-+ * rebuild was verified. Without a csum, it can only when another data sector
-+ * of the same vertical stripe also failed and has a csum: the two were
-+ * rebuilt together from P and Q (on RAID6 that is also how a stale sector
-+ * without a csum is found, see recover_vertical_retry()), and the csum that
-+ * verified one verifies the other. A lone rebuild without a csum came from
-+ * parity that nothing checked, and the copy on the disk may still be right.
-+ */
-+static bool rmw_repair_verified(struct btrfs_raid_bio *rbio, int stripe_nr,
-+ int sector_nr)
-+{
-+ if (!rbio->csum_bitmap)
-+ return false;
-+
-+ for (int i = 0; i < rbio->nr_data; i++) {
-+ const int index = rbio_sector_index(rbio, i, sector_nr);
-+
-+ if (!test_bit(index, rbio->csum_bitmap))
-+ continue;
-+ if (i == stripe_nr || test_bit(index, rbio->error_bitmap))
-+ return true;
-+ }
-+ return false;
-+}
-+
-+/*
-+ * After the read phase of a sub-stripe write, return the sectors it repaired
-+ * that the write phase should also write back, or NULL if there are none.
-+ *
-+ * recover_sectors() leaves the error bit set on every sector it rebuilt: a
-+ * data sector that failed its csum or its read, every sector of a missing
-+ * device, and the extra stripe that recover_vertical_retry() found stale.
-+ * The rebuilt sectors are in the stripe pages and the new P and Q are
-+ * generated from them, so without a write-back the disk copies stay stale
-+ * until read repair or scrub finds them.
-+ *
-+ * Nothing is written to a missing device. A data sector is written back only
-+ * if its rebuild is verified (rmw_repair_verified()). P and Q are generated
-+ * from the data either way, so a failed or stale one is always written back.
-+ *
-+ * This rbio has not written anything yet, so none of these is a retry of a
-+ * write that just failed here.
-+ */
-+static unsigned long *rmw_repaired_sectors(struct btrfs_raid_bio *rbio)
-+{
-+ unsigned long *repaired = NULL;
-+ int total_sector_nr;
-+
-+ for_each_set_bit(total_sector_nr, rbio->error_bitmap, rbio->nr_sectors) {
-+ const int stripe = total_sector_nr / rbio->stripe_nsectors;
-+ const int sectornr = total_sector_nr % rbio->stripe_nsectors;
-+
-+ if (!rbio->bioc->stripes[stripe].dev->bdev)
-+ continue;
-+ if (stripe < rbio->nr_data &&
-+ !rmw_repair_verified(rbio, stripe, sectornr))
-+ continue;
-+
-+ if (!repaired) {
-+ /* Without memory the sectors just stay stale on disk. */
-+ repaired = bitmap_zalloc(rbio->nr_sectors, GFP_NOFS);
-+ if (!repaired)
-+ return NULL;
-+ }
-+ set_bit(total_sector_nr, repaired);
-+ }
-+ return repaired;
-+}
-+
-+/*
-+ * Add write bios for the repaired sectors that the write phase does not write
-+ * anyway: data sectors no bio of this rbio covers, and P/Q outside the
-+ * vertical stripes being written. The others are dropped from @repaired.
-+ * The replace target gets the same sectors as its source.
-+ */
-+static int rmw_assemble_repair_bios(struct btrfs_raid_bio *rbio,
-+ struct bio_list *bio_list,
-+ unsigned long *repaired)
-+{
-+ int total_sector_nr;
-+ int ret;
-+
-+ for_each_set_bit(total_sector_nr, repaired, rbio->nr_sectors) {
-+ const int stripe = total_sector_nr / rbio->stripe_nsectors;
-+ const int sectornr = total_sector_nr % rbio->stripe_nsectors;
-+ phys_addr_t *paddrs;
-+ bool written;
-+
-+ if (stripe < rbio->nr_data)
-+ written = sector_paddrs_in_rbio(rbio, stripe, sectornr, 1);
-+ else
-+ written = test_bit(sectornr, &rbio->dbitmap);
-+ if (written) {
-+ clear_bit(total_sector_nr, repaired);
-+ continue;
-+ }
-+
-+ paddrs = rbio_stripe_paddrs(rbio, stripe, sectornr);
-+ ret = rbio_add_io_paddrs(rbio, bio_list, paddrs, stripe,
-+ sectornr, REQ_OP_WRITE);
-+ if (ret)
-+ goto error;
-+
-+ if (likely(!rbio->bioc->replace_nr_stripes) ||
-+ stripe != rbio->bioc->replace_stripe_src)
-+ continue;
-+ ret = rbio_add_io_paddrs(rbio, bio_list, paddrs,
-+ rbio->real_stripes, sectornr,
-+ REQ_OP_WRITE);
-+ if (ret)
-+ goto error;
-+ }
-+ return 0;
-+error:
-+ bio_list_put(bio_list);
-+ return -EIO;
-+}
-+
-+/*
-+ * A write-back that fails leaves the sector as stale as it was before this
-+ * write, so it does not count against the tolerance of the write itself.
-+ */
-+static void rmw_finish_repair_bios(struct btrfs_raid_bio *rbio,
-+ unsigned long *repaired)
-+{
-+ int written = 0;
-+ int failed = 0;
-+ int total_sector_nr;
-+
-+ for_each_set_bit(total_sector_nr, repaired, rbio->nr_sectors) {
-+ written++;
-+ if (test_and_clear_bit(total_sector_nr, rbio->error_bitmap))
-+ failed++;
-+ }
-+ if (written)
-+ btrfs_debug_rl(rbio->bioc->fs_info,
-+ "sub-stripe write for full stripe %llu wrote back %d repaired sectors, %d failed",
-+ rbio->bioc->full_stripe_logical, written, failed);
-+}
-+
- static void rmw_rbio(struct btrfs_raid_bio *rbio)
- {
- struct bio_list bio_list;
- int sectornr;
-+ unsigned long *repaired = NULL;
- int ret = 0;
-
- /*
-@@ -2862,6 +3005,7 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- ret = rmw_read_wait_recover(rbio);
- if (ret < 0)
- goto out;
-+ repaired = rmw_repaired_sectors(rbio);
- }
-
- /*
-@@ -2895,11 +3039,18 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- ret = rmw_assemble_write_bios(rbio, &bio_list);
- if (ret < 0)
- goto out;
-+ if (repaired) {
-+ ret = rmw_assemble_repair_bios(rbio, &bio_list, repaired);
-+ if (ret < 0)
-+ goto out;
-+ }
-
- /* We should have at least one bio assembled. */
- ASSERT(bio_list_size(&bio_list));
- submit_write_bios(rbio, &bio_list);
- rbio_wait_io(rbio);
-+ if (repaired)
-+ rmw_finish_repair_bios(rbio, repaired);
-
- /* We may have more errors than our tolerance during the read. */
- for (sectornr = 0; sectornr < rbio->stripe_nsectors; sectornr++) {
-@@ -2912,6 +3063,7 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- }
- }
- out:
-+ bitmap_free(repaired);
- rbio_orig_end_io(rbio, errno_to_blk_status(ret));
- }
-
---
-2.47.3
-
+++ /dev/null
-From 796097dafc9486af8ee93c8e073d5ca1de5cfc14 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 1 Oct 2026 03:54:55 -0400
-Subject: [PATCH 12/12] DO-NOT-UPSTREAM: btrfs: raid56: debug knob for the rbio
- stripe cache size
-To: linux-btrfs@vger.kernel.org
-
-Test fixture, not for submission. A read-modify-write whose stripe is
-still in the rbio stripe cache takes the other strips from memory instead
-of reading them, so a test that injects faults into reads (dm-stripfault)
-cannot reach the RMW read path for recently written stripes.
-
-With CONFIG_BTRFS_DEBUG, /sys/fs/btrfs/<uuid>/debug/rbio_cache_size
-replaces the RBIO_CACHE_SIZE limit (default unchanged, 1024); 0 disables
-the cache. Lowering it empties the cache, and the prune in cache_rbio()
-now loops so a lowered limit holds.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/fs.h | 4 ++++
- fs/btrfs/raid56.c | 41 ++++++++++++++++++++++++++++++++++++++---
- fs/btrfs/raid56.h | 3 +++
- fs/btrfs/sysfs.c | 28 ++++++++++++++++++++++++++++
- 4 files changed, 73 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 2dd167c32d612..326a54601289c 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -635,6 +635,10 @@ struct btrfs_fs_info {
- * trying to mod the same stripe at the same time.
- */
- struct btrfs_stripe_hash_table *stripe_hash_table;
-+#ifdef CONFIG_BTRFS_DEBUG
-+ /* Size limit of the rbio stripe cache (debug/rbio_cache_size). */
-+ unsigned int rbio_cache_size;
-+#endif
-
- /*
- * This protects the ordered operations list only while we are
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 0b10204b70a50..5ea3efebfa6c8 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -198,6 +198,9 @@ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info)
- struct btrfs_stripe_hash *h;
- unsigned int num_entries = 1U << BTRFS_STRIPE_HASH_TABLE_BITS;
-
-+#ifdef CONFIG_BTRFS_DEBUG
-+ WRITE_ONCE(info->rbio_cache_size, RBIO_CACHE_SIZE);
-+#endif
- if (info->stripe_hash_table)
- return 0;
-
-@@ -605,6 +608,23 @@ static void btrfs_clear_rbio_cache(struct btrfs_fs_info *info)
- spin_unlock(&table->cache_lock);
- }
-
-+#ifdef CONFIG_BTRFS_DEBUG
-+/*
-+ * Test knob (debug/rbio_cache_size): with a small or zero limit, a
-+ * read-modify-write cannot take its stripe from the cache and must read it,
-+ * which is what a fault-injecting test needs to see. Lowering it empties the
-+ * cache, so the new limit holds from the next rbio on.
-+ */
-+void btrfs_set_rbio_cache_size(struct btrfs_fs_info *info, unsigned int size)
-+{
-+ unsigned int old = READ_ONCE(info->rbio_cache_size);
-+
-+ WRITE_ONCE(info->rbio_cache_size, size);
-+ if (size < old && info->stripe_hash_table)
-+ btrfs_clear_rbio_cache(info);
-+}
-+#endif
-+
- /*
- * remove all cached entries and free the hash table
- * used by unmount
-@@ -629,12 +649,25 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info)
- * If the size of the rbio cache is too big, we
- * prune an item.
- */
-+/* How many rbios the stripe cache keeps (0: none). */
-+static unsigned int rbio_cache_limit(const struct btrfs_fs_info *fs_info)
-+{
-+#ifdef CONFIG_BTRFS_DEBUG
-+ return READ_ONCE(fs_info->rbio_cache_size);
-+#else
-+ return RBIO_CACHE_SIZE;
-+#endif
-+}
-+
- static void cache_rbio(struct btrfs_raid_bio *rbio)
- {
- struct btrfs_stripe_hash_table *table;
-+ const unsigned int limit = rbio_cache_limit(rbio->bioc->fs_info);
-
- if (!test_bit(RBIO_CACHE_READY_BIT, &rbio->flags))
- return;
-+ if (!limit)
-+ return;
-
- table = rbio->bioc->fs_info->stripe_hash_table;
-
-@@ -654,15 +687,17 @@ static void cache_rbio(struct btrfs_raid_bio *rbio)
-
- spin_unlock(&rbio->bio_list_lock);
-
-- if (table->cache_size > RBIO_CACHE_SIZE) {
-+ /* A loop, not one eviction: the limit can have been lowered. */
-+ while (table->cache_size > limit) {
- struct btrfs_raid_bio *found;
-
- found = list_last_entry(&table->stripe_cache,
- struct btrfs_raid_bio,
- stripe_cache);
-
-- if (found != rbio)
-- __remove_rbio_from_cache(found);
-+ if (found == rbio)
-+ break;
-+ __remove_rbio_from_cache(found);
- }
-
- spin_unlock(&table->cache_lock);
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index be507cceb465d..0a25e41a00132 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -290,6 +290,9 @@ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
-
- int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
-+#ifdef CONFIG_BTRFS_DEBUG
-+void btrfs_set_rbio_cache_size(struct btrfs_fs_info *info, unsigned int size);
-+#endif
- void btrfs_raid56_uncache_range(struct btrfs_fs_info *info, u64 start, u64 len);
-
- #endif
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 89b0a4ef4063e..c208300634ebc 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -25,6 +25,7 @@
- #include "misc.h"
- #include "fs.h"
- #include "accessors.h"
-+#include "raid56.h"
-
- /*
- * Structure name Path
-@@ -520,12 +521,39 @@ static const struct attribute *discard_attrs[] = {
-
- #ifdef CONFIG_BTRFS_DEBUG
-
-+/* The raid56 stripe cache limit (raid56.c), 0 to disable the cache. */
-+static ssize_t btrfs_rbio_cache_size_show(struct kobject *kobj,
-+ struct kobj_attribute *a, char *buf)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
-+
-+ return sysfs_emit(buf, "%u\n", READ_ONCE(fs_info->rbio_cache_size));
-+}
-+
-+static ssize_t btrfs_rbio_cache_size_store(struct kobject *kobj,
-+ struct kobj_attribute *a,
-+ const char *buf, size_t len)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
-+ unsigned int val;
-+ int ret;
-+
-+ ret = kstrtouint(buf, 10, &val);
-+ if (ret)
-+ return ret;
-+ btrfs_set_rbio_cache_size(fs_info, val);
-+ return len;
-+}
-+BTRFS_ATTR_RW(debug_mount, rbio_cache_size, btrfs_rbio_cache_size_show,
-+ btrfs_rbio_cache_size_store);
-+
- /*
- * Per-filesystem runtime debugging exported via sysfs.
- *
- * Path: /sys/fs/btrfs/UUID/debug/
- */
- static const struct attribute *btrfs_debug_mount_attrs[] = {
-+ BTRFS_ATTR_PTR(debug_mount, rbio_cache_size),
- NULL,
- };
-
---
-2.47.3
-
--- /dev/null
+From a4b35a2e9704dbbb331f8931774d6d433c4bffeb Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Tue, 20 Oct 2026 15:52:51 -0400
+Subject: [PATCH 12/12] btrfs: raid56: write back the sectors a sub-stripe
+ write repaired
+To: linux-btrfs@vger.kernel.org
+
+A sub-stripe write reads the rest of its full stripe and verifies the data
+sectors that have csums. It rebuilds the sectors that failed their csum or
+their read, and the sectors of a missing device, and computes the new P and
+Q from the result. On RAID6 it also finds a stale P, or a stale data
+sector without a csum, by rebuilding again with one more stripe treated as
+failed. The write phase then writes only the new data, and P and Q of the
+vertical stripes the new data covers.
+
+The repaired sectors stay stale on disk until a read repair or a scrub
+finds them, even though the new parity was computed from their rebuilt
+contents. Until then the full stripe has one healthy member fewer than it
+seems, and one more lost device loses data that was recoverable.
+
+Write the repaired sectors back in the same write phase:
+
+- a data sector whose rebuild is verified. It has a csum, or it has none
+ but was rebuilt from P and Q together with a data sector of the same
+ vertical stripe that has one. The RAID6 retry finds a stale data sector
+ without a csum that way. A lone rebuild of a sector without a csum comes
+ from parity that nothing checked, and the copy on disk may be the right
+ one, so it is left alone;
+- P or Q that failed its read or was found stale, in the vertical stripes
+ the write does not cover (the others get new P and Q anyway);
+- nothing on a missing device. The replace target gets the same sectors as
+ its source, as with the other writes.
+
+The write-backs go out with the rest of the write. A write-back that fails
+leaves its sector as stale as it was before the write, so it does not count
+against the write's tolerance, and the write completes as it did before.
+
+The rbio repairs before it writes anything, so a write-back never retries a
+write that the same rbio just failed. A write that failed on a member
+within the tolerance leaves its pages in the stripe cache, and the next
+sub-stripe write into that full stripe takes them without reading, so it
+has nothing to repair either. A write-back can still go to a sector whose
+write by an earlier rbio failed, when that rbio's pages were not cached (a
+full stripe write) or were evicted: then it fails again, or heals the
+sector. A btrfs_debug line counts the write-backs and the failed ones.
+
+rmw-writeback-test.sh (raid56-wh-harness) puts strips of one full stripe
+back to stale contents, writes into the rest of the stripe, once with
+fsync and once with a plain write(), and reads the members back offline
+before anything else touches them. The stale strips are, on RAID5, a data
+strip with a csum, alone or also failing its reads; on RAID6, a data strip
+with P, with Q, with a second data strip with a csum, or with a strip of a
+nodatasum file, with the write covering all rows or only some of them.
+Without this patch every repaired strip, and P outside the written rows,
+is still stale after the write in all 18 runs; with it none is, and P and
+Q match the data in every row. With the stale member failing writes, the
+write-back fails, the write still completes and its data reads back,
+also on RAID5 when the write to P fails as well (counting the failed
+write-back against the tolerance fails that write with -EIO). A
+nodatasum strip rebuilt from P alone after a read error is not written
+back.
+
+Fixes: 7a3150723061 ("btrfs: raid56: do data csum verification during RMW cycle")
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/raid56.c | 152 ++++++++++++++++++++++++++++++++++++++++++++++
+ 1 file changed, 152 insertions(+)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index e45e6a6ba2566..1706ec66b05fb 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -2742,10 +2742,153 @@ static bool need_read_stripe_sectors(struct btrfs_raid_bio *rbio)
+ return false;
+ }
+
++/*
++ * Return true if the rebuild of data sector @sector_nr of @stripe_nr can be
++ * trusted enough to write it back. It can when the sector has a csum: the
++ * rebuild was verified. Without a csum, it can only when another data sector
++ * of the same vertical stripe also failed and has a csum: the two were
++ * rebuilt together from P and Q (on RAID6 that is also how a stale sector
++ * without a csum is found, see recover_vertical_retry()), and the csum that
++ * verified one verifies the other. A lone rebuild without a csum came from
++ * parity that nothing checked, and the copy on the disk may still be right.
++ */
++static bool rmw_repair_verified(struct btrfs_raid_bio *rbio, int stripe_nr,
++ int sector_nr)
++{
++ if (!rbio->csum_bitmap)
++ return false;
++
++ for (int i = 0; i < rbio->nr_data; i++) {
++ const int index = rbio_sector_index(rbio, i, sector_nr);
++
++ if (!test_bit(index, rbio->csum_bitmap))
++ continue;
++ if (i == stripe_nr || test_bit(index, rbio->error_bitmap))
++ return true;
++ }
++ return false;
++}
++
++/*
++ * After the read phase of a sub-stripe write, return the sectors it repaired
++ * that the write phase should also write back, or NULL if there are none.
++ *
++ * recover_sectors() leaves the error bit set on every sector it rebuilt: a
++ * data sector that failed its csum or its read, every sector of a missing
++ * device, and the extra stripe that recover_vertical_retry() found stale.
++ * The rebuilt sectors are in the stripe pages and the new P and Q are
++ * generated from them, so without a write-back the disk copies stay stale
++ * until read repair or scrub finds them.
++ *
++ * Nothing is written to a missing device. A data sector is written back only
++ * if its rebuild is verified (rmw_repair_verified()). P and Q are generated
++ * from the data either way, so a failed or stale one is always written back.
++ *
++ * This rbio has not written anything yet, so none of these is a retry of a
++ * write that just failed here.
++ */
++static unsigned long *rmw_repaired_sectors(struct btrfs_raid_bio *rbio)
++{
++ unsigned long *repaired = NULL;
++ int total_sector_nr;
++
++ for_each_set_bit(total_sector_nr, rbio->error_bitmap, rbio->nr_sectors) {
++ const int stripe = total_sector_nr / rbio->stripe_nsectors;
++ const int sectornr = total_sector_nr % rbio->stripe_nsectors;
++
++ if (!rbio->bioc->stripes[stripe].dev->bdev)
++ continue;
++ if (stripe < rbio->nr_data &&
++ !rmw_repair_verified(rbio, stripe, sectornr))
++ continue;
++
++ if (!repaired) {
++ /* Without memory the sectors just stay stale on disk. */
++ repaired = bitmap_zalloc(rbio->nr_sectors, GFP_NOFS);
++ if (!repaired)
++ return NULL;
++ }
++ set_bit(total_sector_nr, repaired);
++ }
++ return repaired;
++}
++
++/*
++ * Add write bios for the repaired sectors that the write phase does not write
++ * anyway: data sectors no bio of this rbio covers, and P/Q outside the
++ * vertical stripes being written. The others are dropped from @repaired.
++ * The replace target gets the same sectors as its source.
++ */
++static int rmw_assemble_repair_bios(struct btrfs_raid_bio *rbio,
++ struct bio_list *bio_list,
++ unsigned long *repaired)
++{
++ int total_sector_nr;
++ int ret;
++
++ for_each_set_bit(total_sector_nr, repaired, rbio->nr_sectors) {
++ const int stripe = total_sector_nr / rbio->stripe_nsectors;
++ const int sectornr = total_sector_nr % rbio->stripe_nsectors;
++ phys_addr_t *paddrs;
++ bool written;
++
++ if (stripe < rbio->nr_data)
++ written = sector_paddrs_in_rbio(rbio, stripe, sectornr, 1);
++ else
++ written = test_bit(sectornr, &rbio->dbitmap);
++ if (written) {
++ clear_bit(total_sector_nr, repaired);
++ continue;
++ }
++
++ paddrs = rbio_stripe_paddrs(rbio, stripe, sectornr);
++ ret = rbio_add_io_paddrs(rbio, bio_list, paddrs, stripe,
++ sectornr, REQ_OP_WRITE);
++ if (ret)
++ goto error;
++
++ if (likely(!rbio->bioc->replace_nr_stripes) ||
++ stripe != rbio->bioc->replace_stripe_src)
++ continue;
++ ret = rbio_add_io_paddrs(rbio, bio_list, paddrs,
++ rbio->real_stripes, sectornr,
++ REQ_OP_WRITE);
++ if (ret)
++ goto error;
++ }
++ return 0;
++error:
++ bio_list_put(bio_list);
++ return -EIO;
++}
++
++/*
++ * A write-back that fails leaves the sector as stale as it was before this
++ * write, so it does not count against the tolerance of the write itself.
++ */
++static void rmw_finish_repair_bios(struct btrfs_raid_bio *rbio,
++ unsigned long *repaired)
++{
++ int written = 0;
++ int failed = 0;
++ int total_sector_nr;
++
++ for_each_set_bit(total_sector_nr, repaired, rbio->nr_sectors) {
++ written++;
++ if (test_and_clear_bit(total_sector_nr, rbio->error_bitmap))
++ failed++;
++ }
++ if (written)
++ btrfs_debug_rl(rbio->bioc->fs_info,
++ "sub-stripe write for full stripe %llu wrote back %d repaired sectors, %d failed",
++ rbio->bioc->full_stripe_logical, written, failed);
++}
++
+ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ {
+ struct bio_list bio_list;
+ int sectornr;
++ unsigned long *repaired = NULL;
+ int ret = 0;
+
+ /*
+@@ -2774,6 +2917,7 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ ret = rmw_read_wait_recover(rbio);
+ if (ret < 0)
+ goto out;
++ repaired = rmw_repaired_sectors(rbio);
+ }
+
+ /*
+@@ -2807,11 +2951,18 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ ret = rmw_assemble_write_bios(rbio, &bio_list);
+ if (ret < 0)
+ goto out;
++ if (repaired) {
++ ret = rmw_assemble_repair_bios(rbio, &bio_list, repaired);
++ if (ret < 0)
++ goto out;
++ }
+
+ /* We should have at least one bio assembled. */
+ ASSERT(bio_list_size(&bio_list));
+ submit_write_bios(rbio, &bio_list);
+ rbio_wait_io(rbio);
++ if (repaired)
++ rmw_finish_repair_bios(rbio, repaired);
+
+ /* We may have more errors than our tolerance during the read. */
+ for (sectornr = 0; sectornr < rbio->stripe_nsectors; sectornr++) {
+@@ -2842,6 +2993,7 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ /* Failed write, don't cache for page stealing. */
+ clear_bit(RBIO_CACHE_READY_BIT, &rbio->flags);
+ }
++ bitmap_free(repaired);
+ rbio_orig_end_io(rbio, errno_to_blk_status(ret));
+ }
+
+--
+2.47.3
+
# Testing: raid56-fixes
+## Patch numbers (series as of 2026-10-29)
+
+The rows below were written against the 2026-10-20 numbering and name the
+candidates by letter. In the exported series (12 patches):
+
+| series | below | patch |
+|---|---|---|
+| 1 | - | Qu Wenruo: fix racy bio_list changes for failed RMW rbio |
+| 2 | (replaces 9) | Qu Wenruo: don't cache rbio if an error is hit |
+| 3-9 | 1-7 | log message, end_io UAF, split bio, uncache, verify tree blocks, stolen rbio ref, plugged unhash |
+| 10 | Q | rebuild from Q |
+| 11 | S | device stats |
+| 12 | WB | write-back of repaired sectors |
+| dropped | 8 | DO-NOT-UPSTREAM rbio cache size knob (not exported; the tests that use it run on lane kernels) |
+| dropped | 9 | our failed-write fix, replaced by Qu's patch 2 (Zygo 2026-10-28) |
+
+Qu's two patches (qu2, promoted 2026-10-29), tested on misc-next zb64
+eaa8a251984e (dhive `7.3.0-rc7+ #55`, KASAN + lockdep + BTRFS_ASSERT) with
+our patch 9 dropped: the rb1028 regression runner PASS (write-error-cache
+7/7 arms on Qu's patch 2 alone, rmw-writeback, scrub and replace tests,
+enospc-dataloss both modes; retire-wait-abort SKIP rc=77 as on every
+baseline), no KASAN/WARN/BUG/ASSERT. Patch 1's race, with a test-only
+DO-NOT-UPSTREAM delay knob (refs/cand/qu2/mn/zb64-p1knob 56f315505c82,
+dhive #56; never in a topic): qu-p1-merge-race-test.sh raid5 and raid6 5/5
+designed events PASS, every writer completed. 6.18 (bhive #305): the same.
+Evidence: `raid56-wh-harness/forensics/rb1028-20261028/` (qu2-mn, qu2k-mn,
+qu2k-618, README).
+
+## As written 2026-10-20
+
Independent raid56 fixes and one generic one. Patch 1 logs a message when
a datacow extent is dropped because its write failed. Patch 2 fixes a
use-after-free of the rbio between the last bio's end_io wakeup and the
-From b7b4005cacc44b50375cbb55d550f35eed1662f6 Mon Sep 17 00:00:00 2001
+From 7ec955fbc4dd0c0ae0a87ad4f7d26a03277e9f5d Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:39 -0400
+Date: Fri, 30 Oct 2026 22:32:35 -0400
Subject: [PATCH 00/12] btrfs: raid56 scrub and device replace with unrepairable data
To: linux-btrfs@vger.kernel.org
error return value when scrubbing raid56 parity stripe" (ec0795c045c3
in for-next), which this base contains.
+It also applies on top of the series "btrfs: read repair and scrub
+after a transaction abort" (4 patches; the prerequisite-patch-id lines below are
+for it). Its patch 4 ("btrfs: scrub: do not write back repairs after a
+transaction abort") adds the btrfs_can_submit_repair_write() gate that
+patches 9, 10 and 12 here extend to what they add: nothing that a scrub
+writes or counts as corrected bypasses it after an abort.
+
Patch 1 checks P/Q per row. When a data stripe has unrepaired sectors,
scrub_raid56_parity_stripe() skipped the parity check for the whole full
stripe, so P/Q of the other rows was never verified, and on dev-replace
the replaced device's P/Q strip was never written to the target. Now
-only the rows with unrepaired sectors are left out. A full stripe with
+only the rows with unrepaired sectors are left out, and the rows with a
+sector without an extent that could be neither read nor rebuilt. A full stripe with
unrepaired data still fails the scrub with -EIO at this point.
Patch 2 copies the original P/Q of the unrepairable rows to the replace
byte), scrub rebuilds that strip from P and Q and writes it back
instead of rewriting parity from the stale data, which destroyed the
only good copy of nodatasum data left stale by a write that failed
-within tolerance. Only the scrub of P rebuilds, so the parallel scrub
+within tolerance. A data sector that scrub verified (csum or tree
+block) is never rebuilt: when P and Q both point at it, they are what
+is stale, and each is rewritten. Only the scrub of P rebuilds, so the parallel scrub
of Q does not repeat it. RAID5 has no such redundancy and keeps
-today's behaviour. Fixes: 5a6ac9eacb49.
+today's behaviour. After an abort the rebuilt data is not written
+either; a running dev-replace still copies parity to its target.
+Fixes: 5a6ac9eacb49.
Patch 10 counts parity mismatches found by raid56 parity scrub as
corruption errors: in the device stats of the data member patch 9
rebuilt, otherwise of the scrubbed parity member, and in the scrub's
-corrected count. They were rewritten silently before. On RAID5, and
+corrected count (not in a read-only scrub or after an abort, when
+nothing is corrected). A row whose only read error is in the other
+parity is still checked and counted. They
+were rewritten silently before. On RAID5, and
on a RAID6 row patch 9 cannot locate, a mismatch may equally be
undetectable corruption in a data strip without csums; it is charged to
the parity member because there is no better information.
scrub of a failing member counted 23% of its damaged sectors, and none
when that member was scrubbed last. Repairs are now counted once, by
the parity scrub only when the data device is not being scrubbed at the
-same time, and not at all in a read-only scrub. Fixes: 1009254bf22a.
+same time, and not at all in a read-only scrub or after an abort.
+Fixes: 1009254bf22a.
Testing: a raid5 filesystem filled with block-location-identifying
data in partially filled stripes, two devices corrupted in chosen rows,
btrfs: scrub: name the device a raid56 data sector was read from
btrfs: scrub: count the raid56 data repairs made by a parity scrub
- fs/btrfs/raid56.c | 234 +++++++++++++++++++++++--
- fs/btrfs/raid56.h | 9 +-
- fs/btrfs/scrub.c | 434 +++++++++++++++++++++++++++++++++++++++++-----
- 3 files changed, 618 insertions(+), 59 deletions(-)
+ fs/btrfs/raid56.c | 280 +++++++++++++++++++++++++---
+ fs/btrfs/raid56.h | 17 +-
+ fs/btrfs/scrub.c | 463 ++++++++++++++++++++++++++++++++++++++++++----
+ 3 files changed, 700 insertions(+), 60 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
+prerequisite-patch-id: b8b4a66a0e1de9b1976b16c26f8c5972ce30b1b8
+prerequisite-patch-id: 173b1a1df563e2792318f2be7d1f8ae885566355
+prerequisite-patch-id: b96f5525980fd5dc9349f7854e7fafc21d6b260a
+prerequisite-patch-id: 2323b7694c1b11ef421487dc4385eb8236c83489
--
2.47.3
-From 3a63fbd085fcf4b7844e7c4bb8f6c12bfabc35cc Mon Sep 17 00:00:00 2001
+From 611f3c63bf6e68e1dff48605c738cbcfeaaf29ea Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 02:32:16 -0400
Subject: [PATCH 01/12] btrfs: scrub: check raid56 parity of the rows without
device with -EIO, now after its good rows have been checked. Whether
the scrub should fail at all is left to a later change.
+A sector without an extent that could be neither read nor rebuilt makes
+its row bad as well: there is nothing to compute the row's parity from.
+
Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/scrub.c | 33 ++++++++++++++++++++++++++-------
- 1 file changed, 26 insertions(+), 7 deletions(-)
+ fs/btrfs/scrub.c | 43 ++++++++++++++++++++++++++++++++++++-------
+ 1 file changed, 36 insertions(+), 7 deletions(-)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 98362c91bce43..73d200304271d 100644
+index 4770fd5e8039c..5eca3ad5f9167 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -2156,6 +2156,8 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
+@@ -2160,6 +2160,8 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
const u32 stripe_len = map->stripe_len;
const int data_stripes = nr_data_stripes(map);
unsigned long extent_bitmap = 0;
int ret;
ASSERT(sctx->raid56_data_stripes);
-@@ -2243,9 +2245,9 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
+@@ -2247,21 +2249,31 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
ASSERT(!btrfs_is_zoned(sctx->fs_info));
/*
*
* During the loop, also populate extent_bitmap.
*/
-@@ -2268,15 +2270,32 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
+ for (int i = 0; i < data_stripes; i++) {
+ unsigned long error;
+ unsigned long has_extent;
++ unsigned long unread;
+
+ stripe = &sctx->raid56_data_stripes[i];
+
+ error = scrub_bitmap_read_error(stripe);
+ has_extent = scrub_bitmap_read_has_extent(stripe);
+
++ /*
++ * A sector without an extent that could be neither read nor
++ * rebuilt leaves nothing to compute its row's parity from:
++ * treat that row like one with unrepaired data.
++ */
++ unread = scrub_bitmap_read_io_error(stripe);
++ bitmap_andnot(&unread, &unread, &has_extent, stripe->nr_sectors);
++ bitmap_or(&bad_rows, &bad_rows, &unread, stripe->nr_sectors);
++
+ /*
+ * We should only check the errors where there is an extent.
+ * As we may hit an empty data stripe while it's missing.
+@@ -2272,15 +2284,32 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
"scrub: unrepaired sectors detected, full stripe %llu data stripe %u errors %*pbl",
full_stripe_start, i, stripe->nr_sectors,
&error);
-From dbd38ff999b5f6be70fee9c3b537c4f16219e03a Mon Sep 17 00:00:00 2001
+From 31e50e6cc975d985369dd5583acde2591b449a5b Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 02:32:16 -0400
Subject: [PATCH 02/12] btrfs: scrub: copy raid56 parity of unrepairable rows
1 file changed, 65 insertions(+), 3 deletions(-)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 73d200304271d..8e4febe466dbc 100644
+index 5eca3ad5f9167..97b1d8adaaa5c 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -2142,6 +2142,65 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
+@@ -2146,6 +2146,65 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
return ret;
}
static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
struct btrfs_device *scrub_dev,
struct btrfs_block_group *bg,
-@@ -2277,11 +2336,14 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
+@@ -2291,11 +2350,14 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
stripe->nr_sectors);
}
-From e00230459d26e6365c353de0083231d53a82b7da Mon Sep 17 00:00:00 2001
+From 78d758e1da37e1d8a5ed6c1365f2469f0b90a0a4 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 02:32:17 -0400
Subject: [PATCH 03/12] btrfs: scrub: copy unrepaired raid56 data sectors to
1 file changed, 50 insertions(+)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 8e4febe466dbc..4e815980c08b5 100644
+index 97b1d8adaaa5c..c99b7ae338c68 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -1938,6 +1938,54 @@ static void submit_initial_group_read(struct scrub_ctx *sctx,
+@@ -1942,6 +1942,54 @@ static void submit_initial_group_read(struct scrub_ctx *sctx,
blk_finish_plug(&plug);
}
static int flush_scrub_stripes(struct scrub_ctx *sctx)
{
struct btrfs_fs_info *fs_info = sctx->fs_info;
-@@ -1989,6 +2037,8 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
+@@ -1993,6 +2041,8 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
error = scrub_bitmap_read_error(stripe);
bitmap_andnot(&good, &has_extent, &error, stripe->nr_sectors);
scrub_write_sectors(sctx, stripe, good, true);
-From dcef108c87c970b53ef041811305692649deaac6 Mon Sep 17 00:00:00 2001
+From 676b778f2899780d1d45897344ab401971975679 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 20:33:38 -0400
Subject: [PATCH 04/12] btrfs: scrub: copy every sector of raid56 data stripes
1 file changed, 85 insertions(+), 2 deletions(-)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 4e815980c08b5..f064acbd7a8ef 100644
+index c99b7ae338c68..42ca7d968873d 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -1325,8 +1325,13 @@ static void scrub_write_sectors(struct scrub_ctx *sctx, struct scrub_stripe *str
+@@ -1329,8 +1329,13 @@ static void scrub_write_sectors(struct scrub_ctx *sctx, struct scrub_stripe *str
int sector_nr;
for_each_set_bit(sector_nr, &write_bitmap, stripe->nr_sectors) {
/* Cannot merge with previous sector, submit the current one. */
if (bbio && sector_nr && !test_bit(sector_nr - 1, &write_bitmap)) {
-@@ -1986,6 +1991,30 @@ static void scrub_raid56_copy_bad_sectors(struct scrub_ctx *sctx,
+@@ -1990,6 +1995,30 @@ static void scrub_raid56_copy_bad_sectors(struct scrub_ctx *sctx,
kfree(buf);
}
static int flush_scrub_stripes(struct scrub_ctx *sctx)
{
struct btrfs_fs_info *fs_info = sctx->fs_info;
-@@ -2036,6 +2065,8 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
+@@ -2040,6 +2069,8 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
has_extent = scrub_bitmap_read_has_extent(stripe);
error = scrub_bitmap_read_error(stripe);
bitmap_andnot(&good, &has_extent, &error, stripe->nr_sectors);
scrub_write_sectors(sctx, stripe, good, true);
scrub_raid56_copy_bad_sectors(sctx, stripe,
error & has_extent);
-@@ -2062,6 +2093,54 @@ static void raid56_scrub_wait_endio(struct bio *bio)
+@@ -2066,6 +2097,54 @@ static void raid56_scrub_wait_endio(struct bio *bio)
complete(bio->bi_private);
}
static int queue_scrub_stripe(struct scrub_ctx *sctx, struct btrfs_block_group *bg,
struct btrfs_device *dev, int mirror_num,
u64 logical, u32 length, u64 physical,
-@@ -2084,6 +2163,10 @@ static int queue_scrub_stripe(struct scrub_ctx *sctx, struct btrfs_block_group *
+@@ -2088,6 +2167,10 @@ static int queue_scrub_stripe(struct scrub_ctx *sctx, struct btrfs_block_group *
ret = scrub_find_fill_first_stripe(bg, &sctx->extent_path,
&sctx->csum_path, dev, physical,
mirror_num, logical, length, stripe);
-From c9a6389239a4e644ea9e2eda4be889f9050196f2 Mon Sep 17 00:00:00 2001
+From 79f1ea957a49d17a2b0df67f16edc724db80aaa8 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 20:33:38 -0400
Subject: [PATCH 05/12] btrfs: scrub: only avoid the replace source device for
1 file changed, 13 insertions(+), 4 deletions(-)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index f064acbd7a8ef..c547379692ac5 100644
+index 42ca7d968873d..a47cfd303ca88 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -1886,12 +1886,21 @@ static void scrub_submit_initial_read(struct scrub_ctx *sctx,
+@@ -1890,12 +1890,21 @@ static void scrub_submit_initial_read(struct scrub_ctx *sctx,
atomic_inc(&stripe->pending_io);
/*
-From 7105ab505bd11a8cd4f75957efee33652ea27cc7 Mon Sep 17 00:00:00 2001
+From 1c237ec66b90d58a38df79c78cba01e59e401267 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 21:06:45 -0400
Subject: [PATCH 06/12] btrfs: scrub: read raid56 sectors without an extent
1 file changed, 49 insertions(+), 1 deletion(-)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index c547379692ac5..9fe5c83c8273a 100644
+index a47cfd303ca88..bdfb70eac7f4e 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -2024,6 +2024,49 @@ static unsigned long scrub_raid56_unused_sectors(struct scrub_stripe *stripe)
+@@ -2028,6 +2028,49 @@ static unsigned long scrub_raid56_unused_sectors(struct scrub_stripe *stripe)
return unused;
}
static int flush_scrub_stripes(struct scrub_ctx *sctx)
{
struct btrfs_fs_info *fs_info = sctx->fs_info;
-@@ -2074,8 +2117,13 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
+@@ -2078,8 +2121,13 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
has_extent = scrub_bitmap_read_has_extent(stripe);
error = scrub_bitmap_read_error(stripe);
bitmap_andnot(&good, &has_extent, &error, stripe->nr_sectors);
-From 9ed90b2065e4fbdc968ccb96244178ef22c461b8 Mon Sep 17 00:00:00 2001
+From cf3a5686fa15382a4f3c661ca473ca51d80f9623 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Wed, 3 Jul 2024 21:00:18 -0400
Subject: [PATCH 07/12] btrfs: don't abort raid56 data scrub on first
1 file changed, 5 insertions(+), 11 deletions(-)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 9fe5c83c8273a..89067b08106d2 100644
+index bdfb70eac7f4e..8a2897a80de0b 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -2536,18 +2536,12 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
+@@ -2550,18 +2550,12 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
* check and regenerate the rest.
*/
bitmap_andnot(&extent_bitmap, &extent_bitmap, &bad_rows, nr_sectors);
-From 86ab0366dc0e9d21fe74fde137cd51d87ddc0e4a Mon Sep 17 00:00:00 2001
+From 3b9f88ff5f4f9171f022f53417905aaf9e11b978 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Wed, 21 Oct 2026 03:59:11 -0400
Subject: [PATCH 08/12] btrfs: scrub: do not write raid56 parity in a read-only
3 files changed, 14 insertions(+), 3 deletions(-)
diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 59aad807f98ab..58f4e05561e6f 100644
+index b02c0d533342c..216012c88ad7f 100644
--- a/fs/btrfs/raid56.c
+++ b/fs/btrfs/raid56.c
-@@ -2574,7 +2574,8 @@ static void rmw_rbio_work_locked(struct work_struct *work)
+@@ -2494,7 +2494,8 @@ static void rmw_rbio_work_locked(struct work_struct *work)
struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
struct btrfs_io_context *bioc,
struct btrfs_device *scrub_dev,
{
struct btrfs_fs_info *fs_info = bioc->fs_info;
struct btrfs_raid_bio *rbio;
-@@ -2605,6 +2606,7 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
+@@ -2525,6 +2526,7 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
ASSERT_RBIO_STRIPE(i < rbio->real_stripes, rbio, i);
bitmap_copy(&rbio->dbitmap, dbitmap, stripe_nsectors);
return rbio;
}
-@@ -2780,6 +2782,10 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
+@@ -2700,6 +2702,10 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
q_paddr = INVALID_PADDR;
}
+ goto submit_write;
+
/*
- * time to start writing. Make bios for everything from the
- * higher layers (the bio_list in our rbio) and our p/q. Ignore
+ * After a transaction abort or another filesystem error, write
+ * nothing back to the scrubbed device. A running dev-replace still
diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
index 8700910b8dc99..d213ddcb102dc 100644
--- a/fs/btrfs/raid56.h
void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 89067b08106d2..e1544cf597957 100644
+index 8a2897a80de0b..dccdf44aeb3c6 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -2310,7 +2310,8 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
+@@ -2314,7 +2314,8 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
/* For RAID56 write there must be an @bioc allocated. */
ASSERT(bioc);
rbio = raid56_parity_alloc_scrub_rbio(&bio, bioc, scrub_dev, extent_bitmap,
-From dc2880d0871aa4c790df4a326b0cd904dd039168 Mon Sep 17 00:00:00 2001
+From b659dc5350db5bd2dcd0597bcb64b0182422278e Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Tue, 20 Oct 2026 13:43:04 -0400
Subject: [PATCH 09/12] btrfs: scrub: rebuild a raid6 data stripe that both P
stale strips per row (two members failing) cannot be located and still
get their parity rewritten, as before.
+A data sector that scrub verified, by its csum or as a tree block, is
+never rebuilt: it is right as read. When P and Q both point at it, they
+are what is stale (both can miss the same write, e.g. a sub-stripe write
+made while the P and Q devices were missing), so the scrub of P and the
+scrub of Q each rewrite theirs.
+
+After a transaction abort or another filesystem error, the rebuilt data
+is not written either: the btrfs_can_submit_repair_write() check that
+"btrfs: scrub: do not write back repairs after a transaction abort" put
+before the parity write moves ahead of the rebuilt-data writes, and a
+running dev-replace still gets the parity copy.
+
Fixes: 5a6ac9eacb49 ("Btrfs, raid56: support parity scrub on raid56")
Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/raid56.c | 195 +++++++++++++++++++++++++++++++++++++++++-----
- 1 file changed, 177 insertions(+), 18 deletions(-)
+ fs/btrfs/raid56.c | 229 ++++++++++++++++++++++++++++++++++++++++++----
+ fs/btrfs/raid56.h | 8 ++
+ fs/btrfs/scrub.c | 21 +++++
+ 3 files changed, 238 insertions(+), 20 deletions(-)
diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 58f4e05561e6f..730fbd5225c1e 100644
+index 216012c88ad7f..13f70a4165297 100644
--- a/fs/btrfs/raid56.c
+++ b/fs/btrfs/raid56.c
@@ -9,6 +9,7 @@
#include <linux/hash.h>
#include <linux/list_sort.h>
#include <linux/raid/xor.h>
-@@ -2653,16 +2654,13 @@ static int alloc_rbio_essential_pages(struct btrfs_raid_bio *rbio)
+@@ -150,6 +151,7 @@ static void scrub_rbio_work_locked(struct work_struct *work);
+ static void free_raid_bio_pointers(struct btrfs_raid_bio *rbio)
+ {
+ bitmap_free(rbio->error_bitmap);
++ bitmap_free(rbio->scrub_verified);
+ bitmap_free(rbio->stripe_uptodate_bitmap);
+ kfree(rbio->stripe_pages);
+ kfree(rbio->bio_paddrs);
+@@ -2504,6 +2506,11 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
+ rbio = alloc_rbio(fs_info, bioc);
+ if (IS_ERR(rbio))
+ return NULL;
++ rbio->scrub_verified = bitmap_zalloc(rbio->nr_sectors, GFP_NOFS);
++ if (!rbio->scrub_verified) {
++ free_raid_bio(rbio);
++ return NULL;
++ }
+ bio_list_add(&rbio->bio_list, bio);
+ /*
+ * This is a special bio which is used to hold the completion handler
+@@ -2573,16 +2580,13 @@ static int alloc_rbio_essential_pages(struct btrfs_raid_bio *rbio)
return 0;
}
ASSERT(step_nr < rbio->sector_nsteps);
-@@ -2682,36 +2680,159 @@ static bool verify_one_parity_step(struct btrfs_raid_bio *rbio,
+@@ -2602,36 +2606,166 @@ static bool verify_one_parity_step(struct btrfs_raid_bio *rbio,
xor_gen(pointers[nr_data], pointers + 1, nr_data - 1, step);
}
+ * stale, e.g. after a write that failed on its device but succeeded on
+ * the others. On RAID6, P and Q together tell which one, so rebuild
+ * that data stripe instead of rewriting the parity from it.
++ *
++ * Never rebuild a sector scrub verified (by its csum, or as a tree
++ * block): it is right as read. If P and Q both point at it, they are
++ * what is stale (both missed the same write), and the scrub of P and
++ * the scrub of Q each rewrite theirs below.
+ */
+ if (has_qstripe && can_locate) {
+ const int bad = raid6_locate_bad_data(rbio, pointers, sector_nr);
+
-+ if (bad >= 0) {
++ if (bad >= 0 &&
++ !test_bit(bad * rbio->stripe_nsectors + sector_nr,
++ rbio->scrub_verified)) {
+ /*
+ * P and Q are scrubbed in parallel, each with its own
+ * read of the data: leave the rebuild to the scrub of P,
}
static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
-@@ -2727,6 +2848,9 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
+@@ -2647,6 +2781,9 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
phys_addr_t q_paddr = INVALID_PADDR;
struct bio_list bio_list;
bool is_replace = false;
int ret;
bio_list_init(&bio_list);
-@@ -2767,12 +2891,27 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
+@@ -2687,12 +2824,27 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
pointers[rbio->real_stripes - 1] = kmap_local_paddr(q_paddr);
}
kunmap_local(pointers[nr_data]);
__free_page(phys_to_page(p_paddr));
-@@ -2786,6 +2925,26 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
- if (rbio->scrub_readonly)
- goto submit_write;
+@@ -2708,12 +2860,32 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
+
+ /*
+ * After a transaction abort or another filesystem error, write
+- * nothing back to the scrubbed device. A running dev-replace still
+- * copies to its target.
++ * nothing back to the scrubbed devices, rebuilt data included. A
++ * running dev-replace still copies parity to its target.
+ */
+ if (!btrfs_can_submit_repair_write(rbio->bioc->fs_info))
+ goto replace;
+ /* Write the data sectors rebuilt from P and Q. */
+ for_each_set_bit(sectornr, &rebuilt, rbio->stripe_nsectors) {
/*
* time to start writing. Make bios for everything from the
* higher layers (the bio_list in our rbio) and our p/q. Ignore
+@@ -2944,6 +3116,23 @@ void raid56_parity_submit_scrub_rbio(struct btrfs_raid_bio *rbio)
+ start_async_work(rbio, scrub_rbio_work_locked);
+ }
+
++/*
++ * Parity scrub: @verified has a bit for each sector of data stripe @stripe_nr
++ * that scrub verified, by its csum or as a tree block. The parity check never
++ * rebuilds those.
++ */
++void raid56_parity_set_verified(struct btrfs_raid_bio *rbio, int stripe_nr,
++ unsigned long verified)
++{
++ unsigned int sector_nr;
++
++ ASSERT(rbio->operation == BTRFS_RBIO_PARITY_SCRUB);
++ ASSERT(stripe_nr < rbio->nr_data);
++ for_each_set_bit(sector_nr, &verified, rbio->stripe_nsectors)
++ __set_bit(stripe_nr * rbio->stripe_nsectors + sector_nr,
++ rbio->scrub_verified);
++}
++
+ /*
+ * This is for scrub call sites where we already have correct data contents.
+ * This allows us to avoid reading data stripes again.
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index d213ddcb102dc..c88e5ca548f70 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -168,6 +168,12 @@ struct btrfs_raid_bio {
+ /* Parity scrub of a read-only scrub: check, but write nothing. */
+ bool scrub_readonly;
+
++ /*
++ * Parity scrub: the data sectors scrub verified, indexed like
++ * error_bitmap (see raid56_parity_set_verified()).
++ */
++ unsigned long *scrub_verified;
++
+ /*
+ * Size of all the bios in the bio_list. This helps us decide if the
+ * rbio maps to a full stripe or not.
+@@ -281,6 +287,8 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
+ bool readonly);
+ void raid56_parity_submit_scrub_rbio(struct btrfs_raid_bio *rbio);
+
++void raid56_parity_set_verified(struct btrfs_raid_bio *rbio, int stripe_nr,
++ unsigned long verified);
+ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
+ void *vaddr, u64 data_logical);
+
+diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
+index dccdf44aeb3c6..be0031f5187c5 100644
+--- a/fs/btrfs/scrub.c
++++ b/fs/btrfs/scrub.c
+@@ -2286,6 +2286,26 @@ static int should_cancel_scrub(const struct scrub_ctx *sctx)
+ return 0;
+ }
+
++/*
++ * The sectors of @stripe that scrub verified: sectors of an extent that have
++ * no error left and either a csum or a tree block. Data without a csum is
++ * taken as it reads.
++ */
++static unsigned long scrub_stripe_verified(struct scrub_stripe *stripe)
++{
++ const unsigned long has_extent = scrub_bitmap_read_has_extent(stripe);
++ const unsigned long error = scrub_bitmap_read_error(stripe);
++ unsigned long verified = 0;
++ int sector_nr;
++
++ for_each_set_bit(sector_nr, &has_extent, stripe->nr_sectors)
++ if (!test_bit(sector_nr, &error) &&
++ (scrub_bitmap_test_bit_is_metadata(stripe, sector_nr) ||
++ stripe->sectors[sector_nr].csum))
++ __set_bit(sector_nr, &verified);
++ return verified;
++}
++
+ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
+ struct btrfs_device *scrub_dev,
+ struct btrfs_chunk_map *map,
+@@ -2327,6 +2347,7 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
+
+ raid56_parity_cache_data_folios(rbio, stripe->buffer,
+ full_stripe_start + (i << map->stripe_shift));
++ raid56_parity_set_verified(rbio, i, scrub_stripe_verified(stripe));
+ }
+ raid56_parity_submit_scrub_rbio(rbio);
+ wait_for_completion_io(&io_done);
--
2.47.3
-From 0c60a08b66859c207b4c5bca366910ef8334e3bb Mon Sep 17 00:00:00 2001
+From 31742d9026ead87e06df4ed3028d6f209af68b8b Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Tue, 20 Oct 2026 16:15:58 -0400
Subject: [PATCH 10/12] btrfs: scrub: count raid56 parity mismatches as
nodatasum-scrub-repair-test.sh, raid6 with one stale member per row:
every stale sector is charged once, to the member that held it.
+A row whose only read error is in the other parity is counted: the check
+of this parity does not use it. A read-only scrub adds nothing to
+corrected_errors, and neither does a scrub after a transaction abort or
+another filesystem error, which writes nothing back
+(btrfs_can_submit_repair_write()).
+
Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/raid56.c | 33 ++++++++++++++++++++++++++++++++-
+ fs/btrfs/raid56.c | 51 +++++++++++++++++++++++++++++++++++++++++++----
fs/btrfs/raid56.h | 5 ++++-
fs/btrfs/scrub.c | 8 +++++++-
- 3 files changed, 43 insertions(+), 3 deletions(-)
+ 3 files changed, 58 insertions(+), 6 deletions(-)
diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 730fbd5225c1e..37a077b64f99b 100644
+index 13f70a4165297..27b189a7fbeb4 100644
--- a/fs/btrfs/raid56.c
+++ b/fs/btrfs/raid56.c
-@@ -2576,7 +2576,7 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
+@@ -2497,7 +2497,7 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
struct btrfs_io_context *bioc,
struct btrfs_device *scrub_dev,
unsigned long *dbitmap, int stripe_nsectors,
{
struct btrfs_fs_info *fs_info = bioc->fs_info;
struct btrfs_raid_bio *rbio;
-@@ -2608,6 +2608,7 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
+@@ -2534,6 +2534,7 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
bitmap_copy(&rbio->dbitmap, dbitmap, stripe_nsectors);
rbio->scrub_readonly = readonly;
return rbio;
}
-@@ -2835,6 +2836,35 @@ static int verify_one_parity_sector(struct btrfs_raid_bio *rbio,
+@@ -2768,6 +2769,37 @@ static int verify_one_parity_sector(struct btrfs_raid_bio *rbio,
return -1;
}
+ * Rows with a read error are not counted here: the read error was.
+ */
+static void count_parity_scrub_errors(struct btrfs_raid_bio *rbio,
-+ unsigned long read_errors,
++ unsigned long uncounted,
+ unsigned long rebuilt,
+ const u8 *rebuilt_stripe)
+{
+ unsigned long parity_bad;
+ unsigned int sectornr;
+
-+ bitmap_andnot(&parity_bad, &rbio->dbitmap, &read_errors, rbio->stripe_nsectors);
++ bitmap_andnot(&parity_bad, &rbio->dbitmap, &uncounted, rbio->stripe_nsectors);
+ for_each_set_bit(sectornr, &rebuilt, rbio->stripe_nsectors)
+ btrfs_dev_stat_inc_and_print(bioc->stripes[rebuilt_stripe[sectornr]].dev,
+ BTRFS_DEV_STAT_CORRUPTION_ERRS);
+ for_each_set_bit(sectornr, &parity_bad, rbio->stripe_nsectors)
+ btrfs_dev_stat_inc_and_print(bioc->stripes[rbio->scrubp].dev,
+ BTRFS_DEV_STAT_CORRUPTION_ERRS);
-+ if (rbio->scrub_corrected)
++ /* A read-only scrub corrects nothing, nor does one after an abort. */
++ if (rbio->scrub_corrected && !rbio->scrub_readonly &&
++ btrfs_can_submit_repair_write(bioc->fs_info))
+ *rbio->scrub_corrected += bitmap_weight(&rebuilt, rbio->stripe_nsectors) +
+ bitmap_weight(&parity_bad, rbio->stripe_nsectors);
+}
static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
{
struct btrfs_io_context *bioc = rbio->bioc;
-@@ -2912,6 +2942,7 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
+@@ -2782,6 +2814,7 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
+ struct bio_list bio_list;
+ bool is_replace = false;
+ unsigned long read_errors = 0;
++ unsigned long uncounted = 0;
+ unsigned long rebuilt = 0;
+ u8 rebuilt_stripe[BITS_PER_LONG];
+ int ret;
+@@ -2826,11 +2859,20 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
+
+ /*
+ * Rows with a read error were rebuilt by recover_scrub_rbio(): do not
+- * look for a bad data stripe there.
++ * look for a bad data stripe there, and do not count their mismatches
++ * unless the only error is in the other parity, which the check of
++ * this one does not use.
+ */
+- for_each_set_bit(sectornr, &rbio->dbitmap, rbio->stripe_nsectors)
+- if (get_rbio_vertical_errors(rbio, sectornr, NULL, NULL))
++ for_each_set_bit(sectornr, &rbio->dbitmap, rbio->stripe_nsectors) {
++ for (int s = 0; s < rbio->real_stripes; s++) {
++ if (!test_bit(s * rbio->stripe_nsectors + sectornr,
++ rbio->error_bitmap))
++ continue;
+ __set_bit(sectornr, &read_errors);
++ if (s < nr_data || s == rbio->scrubp)
++ __set_bit(sectornr, &uncounted);
++ }
++ }
+
+ bitmap_clear(rbio->error_bitmap, 0, rbio->nr_sectors);
+
+@@ -2845,6 +2887,7 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
rebuilt_stripe[sectornr] = stripe;
}
}
-+ count_parity_scrub_errors(rbio, read_errors, rebuilt, rebuilt_stripe);
++ count_parity_scrub_errors(rbio, uncounted, rebuilt, rebuilt_stripe);
kunmap_local(pointers[nr_data]);
__free_page(phys_to_page(p_paddr));
diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index d213ddcb102dc..2f5c05d5a00a4 100644
+index c88e5ca548f70..e823b25a51845 100644
--- a/fs/btrfs/raid56.h
+++ b/fs/btrfs/raid56.h
@@ -165,6 +165,9 @@ struct btrfs_raid_bio {
/* Parity scrub of a read-only scrub: check, but write nothing. */
bool scrub_readonly;
-@@ -278,7 +281,7 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
+@@ -284,7 +287,7 @@ struct btrfs_raid_bio *raid56_parity_alloc_scrub_rbio(struct bio *bio,
struct btrfs_io_context *bioc,
struct btrfs_device *scrub_dev,
unsigned long *dbitmap, int stripe_nsectors,
+ bool readonly, u32 *corrected);
void raid56_parity_submit_scrub_rbio(struct btrfs_raid_bio *rbio);
- void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
+ void raid56_parity_set_verified(struct btrfs_raid_bio *rbio, int stripe_nr,
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index e1544cf597957..799e78a892d10 100644
+index be0031f5187c5..f3251ec7654a7 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -2295,6 +2295,7 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
+@@ -2319,6 +2319,7 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
struct bio bio;
const int data_stripes = nr_data_stripes(map);
u64 length = btrfs_stripe_nr_to_offset(data_stripes, map->stripe_len);
int ret;
bio_init(&bio, NULL, NULL, 0, REQ_OP_READ);
-@@ -2311,7 +2312,7 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
+@@ -2335,7 +2336,7 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
ASSERT(bioc);
rbio = raid56_parity_alloc_scrub_rbio(&bio, bioc, scrub_dev, extent_bitmap,
map->stripe_len >> fs_info->sectorsize_bits,
btrfs_put_bioc(bioc);
if (!rbio) {
ret = -ENOMEM;
-@@ -2327,6 +2328,11 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
+@@ -2352,6 +2353,11 @@ static int scrub_raid56_cached_parity(struct scrub_ctx *sctx,
raid56_parity_submit_scrub_rbio(rbio);
wait_for_completion_io(&io_done);
ret = blk_status_to_errno(bio.bi_status);
-From 5a37421678943cb3293ea13905617134297aa7b3 Mon Sep 17 00:00:00 2001
+From 17bd70d878da91e41a87a12f8802f01e010aa203 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Tue, 20 Oct 2026 22:15:15 -0400
Subject: [PATCH 11/12] btrfs: scrub: name the device a raid56 data sector was
1 file changed, 7 insertions(+), 24 deletions(-)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 799e78a892d10..a776b519acb8f 100644
+index f3251ec7654a7..89f2a1d27c430 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
@@ -1004,34 +1004,17 @@ static void scrub_stripe_report_errors(struct scrub_ctx *sctx,
-From b7b4005cacc44b50375cbb55d550f35eed1662f6 Mon Sep 17 00:00:00 2001
+From 7ec955fbc4dd0c0ae0a87ad4f7d26a03277e9f5d Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Tue, 20 Oct 2026 22:15:16 -0400
Subject: [PATCH 12/12] btrfs: scrub: count the raid56 data repairs made by a
failing under load: raid5 36128 of 36128, raid6 30231 of 30231 damaged
sectors counted; before, 26519 of 40556 and 11049 of 30723.
+After a transaction abort or another filesystem error nothing is written
+back (btrfs_can_submit_repair_write()), so the parity scrub's repairs are
+neither reported nor counted then, and the read repair worker's write-back
+keeps that check next to the own-scrub test.
+
Fixes: 1009254bf22a ("btrfs: scrub: use scrub_stripe to implement RAID56 P/Q scrub")
Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/scrub.c | 109 +++++++++++++++++++++++++++++++++++++++++++++--
- 1 file changed, 105 insertions(+), 4 deletions(-)
+ fs/btrfs/scrub.c | 107 +++++++++++++++++++++++++++++++++++++++++++++--
+ 1 file changed, 104 insertions(+), 3 deletions(-)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index a776b519acb8f..86c9801ca3155 100644
+index 89f2a1d27c430..6f518aeb55240 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
@@ -85,10 +85,17 @@ enum scrub_stripe_flags {
+ int sector_nr;
+
+ if (sctx->readonly || test_bit(SCRUB_STRIPE_FLAG_OWN_SCRUB, &stripe->state) ||
-+ !stripe->dev->bdev)
++ !stripe->dev->bdev || !btrfs_can_submit_repair_write(fs_info))
+ return;
+ bitmap_andnot(&repaired, &errors->init_error_bitmap, &error_bitmap, nr_sectors);
+ if (bitmap_empty(&repaired, nr_sectors))
if (bitmap_empty(&errors.init_error_bitmap, stripe->nr_sectors))
goto out;
-@@ -1207,7 +1293,8 @@ static void scrub_stripe_read_repair_worker(struct work_struct *work)
- */
+@@ -1211,6 +1297,7 @@ static void scrub_stripe_read_repair_worker(struct work_struct *work)
bitmap_andnot(&repaired, &errors.init_error_bitmap, &error,
stripe->nr_sectors);
-- if (!sctx->readonly && !bitmap_empty(&repaired, stripe->nr_sectors)) {
-+ if (!sctx->readonly && !bitmap_empty(&repaired, stripe->nr_sectors) &&
-+ !test_bit(SCRUB_STRIPE_FLAG_OWN_SCRUB, &stripe->state)) {
+ if (!sctx->readonly && !bitmap_empty(&repaired, stripe->nr_sectors) &&
++ !test_bit(SCRUB_STRIPE_FLAG_OWN_SCRUB, &stripe->state) &&
+ btrfs_can_submit_repair_write(fs_info)) {
if (btrfs_is_zoned(fs_info)) {
btrfs_repair_one_zone(fs_info, sctx->stripes[0].bg->start);
- } else {
-@@ -2381,6 +2468,18 @@ static void scrub_raid56_copy_parity_rows(struct scrub_ctx *sctx,
+@@ -2406,6 +2493,18 @@ static void scrub_raid56_copy_parity_rows(struct scrub_ctx *sctx,
kfree(buf);
}
static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
struct btrfs_device *scrub_dev,
struct btrfs_block_group *bg,
-@@ -2439,6 +2538,8 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
+@@ -2464,6 +2563,8 @@ static int scrub_raid56_parity_stripe(struct scrub_ctx *sctx,
scrub_reset_stripe(stripe);
set_bit(SCRUB_STRIPE_FLAG_NO_REPORT, &stripe->state);
# Testing: raid56-scrub-replace
+> **Stacked (2026-10-30):** the series now applies on top of
+> read-repair-fixes. The abort-gate code that the lane's integration
+> branch used to add when merging the two (patches 9, 10 and 12 here:
+> no rebuilt-data write, corrected count or parity-scrub repair count
+> after an abort) moved into those three patches and their messages; the
+> integrated tree did not change, so the results below, run on
+> integrated kernels, still apply.
+>
> **Numbering (2026-10-25):** the lane was rebased onto btrfs/for-next
> `0713fa6a4356`, which contains Filipe Manana's -EIO fix (`ec0795c045c3`),
> so the series is now 0/12. The patch numbers below are from the earlier
-From ccf8a6c6d49bbbf18675148d9af1a74d7512f6aa Mon Sep 17 00:00:00 2001
+From 76eb4edbade0c6ba280af99ef5e91f204e04d6d4 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:47 -0400
+Date: Fri, 30 Oct 2026 22:32:40 -0400
Subject: [PATCH 0/9] btrfs: read policies and per-device read stats (Kai Krakow's series, as carried on misc-next)
To: linux-btrfs@vger.kernel.org
6 files changed, 510 insertions(+), 32 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From ec0c9ea075a4fa3b568c350fb6b77326ee73178f Mon Sep 17 00:00:00 2001
+From d71e118b9173507fe36a00a13a74f7b06119d206 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Sat, 11 Jul 2026 00:44:51 +0200
Subject: [PATCH 1/9] btrfs: add io read stats per device to devinfo
-From 06930d250a45b0deb76222acf79694e5a40b5992 Mon Sep 17 00:00:00 2001
+From 59bb2938019d6749f1eb2244d592bacb2d5ca6ca Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Sat, 13 Dec 2025 18:34:36 +0100
Subject: [PATCH 2/9] btrfs: move read policies out of experimental
-From 9f84f0ee680adf55ff17a0c10277b21216eb100d Mon Sep 17 00:00:00 2001
+From 336671af9065554471666f16177c5bb3ab8c94c0 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Fri, 25 Apr 2025 21:46:52 +0200
Subject: [PATCH 3/9] btrfs: add in-flight queue read policy
-From 244eddf9e713458014856e0cc62ab0c5be764871 Mon Sep 17 00:00:00 2001
+From e2cbe223f5f6d86fd739745b8ba86f84b582883e Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Thu, 9 Jul 2026 12:35:14 +0200
Subject: [PATCH 4/9] btrfs: move age io stat out of
-From 776a329bca41446491777ce2bdd5a02518111a19 Mon Sep 17 00:00:00 2001
+From 63b6f0773c9843cb6af29e4fb0cfa240b9fd58fd Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Thu, 9 Jul 2026 12:27:18 +0200
Subject: [PATCH 5/9] btrfs: break queue read ties by mirror age
-From 9e1ef3d3ea2434fb152e0bfcb8e1695989a00889 Mon Sep 17 00:00:00 2001
+From c5a0115e99bd21233fd97e891cb651f5e03d077e Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Thu, 9 Jul 2026 13:10:10 +0200
Subject: [PATCH 6/9] btrfs: add read latency health stats to per-device io
-From 498e825a967d96cc549d310fbad098402fc60224 Mon Sep 17 00:00:00 2001
+From 115e32a72555b6abce8a4ee8715fb71ce28976aa Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Wed, 8 Jul 2026 16:38:51 +0200
Subject: [PATCH 7/9] btrfs: add queue-adaptive read policy
-From 5fa641efa7da094fc3322d307f9077f0f355e2dd Mon Sep 17 00:00:00 2001
+From 03489adc8d7f8a8fba8c8c48b642acdef4573c64 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Sun, 12 Jul 2026 14:15:19 +0200
Subject: [PATCH 8/9] btrfs: scale adaptive queue guard with latency
-From ccf8a6c6d49bbbf18675148d9af1a74d7512f6aa Mon Sep 17 00:00:00 2001
+From 76eb4edbade0c6ba280af99ef5e91f204e04d6d4 Mon Sep 17 00:00:00 2001
From: Kai Krakow <kai@kaishome.de>
Date: Sat, 18 Jul 2026 18:15:38 +0200
Subject: [PATCH 9/9] btrfs: count unstable read health snapshots
-From df4629dcf9ad9994c9d40ed0705d072cf58c05d5 Mon Sep 17 00:00:00 2001
+From 72e09512671c6dbee47d35aad0fa6f98073fcb4e Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:48 -0400
+Date: Fri, 30 Oct 2026 22:32:35 -0400
Subject: [PATCH 0/4] btrfs: read repair and scrub after a transaction abort
To: linux-btrfs@vger.kernel.org
Patch 4 does the same for scrub's read-repair write-back, which never
checked the filesystem state: after an abort that is not a commit, a
running scrub went on repairing through every remaining block group.
-raid56 parity scrub, the raid56 RMW write-back and the dev-replace target
-copy are unchanged.
+The raid56 parity scrub's parity write-back is skipped the same way; the
+copy to a dev-replace target still goes out.
The rule for writes after an abort is being revised upstream, so patches
3 and 4 carry no stable tag; patches 1 and 2 do.
btrfs: do not write back a read repair after a transaction abort
btrfs: scrub: do not write back repairs after a transaction abort
- fs/btrfs/bio.c | 31 +++++++++++++++++++++++++++++--
- fs/btrfs/fs.h | 13 +++++++++++++
- fs/btrfs/scrub.c | 6 +++++-
- 3 files changed, 47 insertions(+), 3 deletions(-)
+ fs/btrfs/bio.c | 31 +++++++++++++++++++++++++++++--
+ fs/btrfs/fs.h | 13 +++++++++++++
+ fs/btrfs/raid56.c | 9 +++++++++
+ fs/btrfs/scrub.c | 6 +++++-
+ 4 files changed, 56 insertions(+), 3 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From 020df2f9856ef39d4216e12bbded5107c556506b Mon Sep 17 00:00:00 2001
+From 13a9bbefab5769fb053c1cc67534ee62761840a5 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Thu, 22 Oct 2026 02:16:13 -0400
Subject: [PATCH 1/4] btrfs: give the read repair bio an end_io for submit
-From f05da064ee63244a7a89d77b6020e44433f2b5f2 Mon Sep 17 00:00:00 2001
+From a4071d1bdf4f3024c37b6c213fc462bf8383c4c0 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Thu, 22 Oct 2026 14:31:46 -0400
Subject: [PATCH 2/4] btrfs: look up a repair read's csums in the same root as
-From 7bc1870e25ad7e6ad2171059bafa41f656acdb9f Mon Sep 17 00:00:00 2001
+From e3d9b5c617267b110c72f9294b3d5462697bdf0f Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Thu, 22 Oct 2026 14:31:48 -0400
Subject: [PATCH 3/4] btrfs: do not write back a read repair after a
-From df4629dcf9ad9994c9d40ed0705d072cf58c05d5 Mon Sep 17 00:00:00 2001
+From 72e09512671c6dbee47d35aad0fa6f98073fcb4e Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Thu, 22 Oct 2026 14:31:49 -0400
Subject: [PATCH 4/4] btrfs: scrub: do not write back repairs after a
sector back after the abort; with it nothing is written to either
device after the abort and the bad copy stays as it was.
+The parity scrub of raid56 checks the same: its parity write-back is
+skipped too, and its copy to a dev-replace target still goes out.
+
Fixes: 54765392a1b9 ("btrfs: scrub: introduce helper to queue a stripe for scrub")
Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/scrub.c | 6 +++++-
- 1 file changed, 5 insertions(+), 1 deletion(-)
+ fs/btrfs/raid56.c | 9 +++++++++
+ fs/btrfs/scrub.c | 6 +++++-
+ 2 files changed, 14 insertions(+), 1 deletion(-)
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 7dd937fa0c262..b02c0d533342c 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -2700,6 +2700,14 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
+ q_paddr = INVALID_PADDR;
+ }
+
++ /*
++ * After a transaction abort or another filesystem error, write
++ * nothing back to the scrubbed device. A running dev-replace still
++ * copies to its target.
++ */
++ if (!btrfs_can_submit_repair_write(rbio->bioc->fs_info))
++ goto replace;
++
+ /*
+ * time to start writing. Make bios for everything from the
+ * higher layers (the bio_list in our rbio) and our p/q. Ignore
+@@ -2715,6 +2723,7 @@ static int finish_parity_scrub(struct btrfs_raid_bio *rbio)
+ goto cleanup;
+ }
+
++replace:
+ if (!is_replace)
+ goto submit_write;
+
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
index 98362c91bce43..4770fd5e8039c 100644
--- a/fs/btrfs/scrub.c
-From 9a8bd47b0b9960efa030c57f1023211634ee9fea Mon Sep 17 00:00:00 2001
+From 002da63fa0320576de844ad398efc2d2586a69df Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Wed, 28 Oct 2026 03:31:36 -0400
-Subject: [PATCH 0/4] btrfs: block group reclaim fixes for a full filesystem
+Date: Fri, 30 Oct 2026 22:32:35 -0400
+Subject: [PATCH 0/3] btrfs: block group reclaim fixes for a full filesystem
To: linux-btrfs@vger.kernel.org
-Four small fixes to the background block group reclaim worker
+Three small fixes to the background block group reclaim worker
(btrfs_reclaim_bgs_work()). None depends on a particular allocator; they
were found while running stripe-exclusive raid56 allocation, whose trapped
space keeps the reclaim list full at the fill edge, but each applies to
Patch 3 backs off after three -ENOSPC reclaims in a row in a space_info,
until ten minutes pass, a chunk is added or removed, or free space grows
by what the last failed group held. Without it, a full filesystem
-retries forever while holding the balance exclusive operation.
-
-Patch 4 releases the balance exclusive operation between groups and
-leaves a 12 s gap while groups remain queued, so a resize, replace or
-balance queued with btrfs-progs --enqueue gets in at the next hand-off
-instead of waiting out the whole list. The gap length follows from
-btrfs-progs' randomized re-check after the sysfs notification; the commit
-message has the numbers.
-
-Patches 3 and 4 add sysfs counters and debug lines only; nothing changes
-on a filesystem where reclaim succeeds and nobody waits for the exclusive
-operation.
-
-Zygo Blaxell (4):
+retries forever while holding the balance exclusive operation. It adds
+one sysfs counter, allocation/<type>/reclaim_backoffs; nothing changes on
+a filesystem where reclaim succeeds.
+
+A related problem is left to the list: while the worker has a long list
+queued it holds the balance exclusive operation from one group to the
+next, so a resize, replace or balance queued with btrfs-progs --enqueue
+can wait for the whole list (up to about 655 s in our tests). We carry
+a workaround that releases the operation between groups with a gap long
+enough for btrfs-progs' re-check, but do not propose it.
+
+Zygo Blaxell (3):
btrfs: do not reclaim block groups on an errored filesystem
btrfs: log block group reclaim at debug level
btrfs: back off block group reclaim after repeated ENOSPC
- btrfs: let queued exclusive operations in between block group reclaims
- fs/btrfs/block-group.c | 148 +++++++++++++++++++++++++++++++++++++++--
+ fs/btrfs/block-group.c | 107 +++++++++++++++++++++++++++++++++++++++--
fs/btrfs/block-group.h | 1 +
- fs/btrfs/fs.c | 29 ++++++++
- fs/btrfs/fs.h | 16 +++++
- fs/btrfs/space-info.h | 17 +++++
+ fs/btrfs/space-info.h | 17 +++++++
fs/btrfs/sysfs.c | 2 +
- 6 files changed, 208 insertions(+), 5 deletions(-)
+ 4 files changed, 124 insertions(+), 3 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From 37196f862f108ba73c95aefe58d9c85ba69f6575 Mon Sep 17 00:00:00 2001
+From 56bbc2412451d2750d4432b24c03f191e8ee6b79 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Thu, 24 Sep 2026 02:21:12 -0400
-Subject: [PATCH 1/4] btrfs: do not reclaim block groups on an errored
+Subject: [PATCH 1/3] btrfs: do not reclaim block groups on an errored
filesystem
To: linux-btrfs@vger.kernel.org
-From eab2d01495ad8fbc02b954412b3ef4d26f9476df Mon Sep 17 00:00:00 2001
+From 9e8e0abcbcb4feb8eea8cc1ae090a218739b6bc7 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Tue, 20 Oct 2026 13:04:19 -0400
-Subject: [PATCH 2/4] btrfs: log block group reclaim at debug level
+Subject: [PATCH 2/3] btrfs: log block group reclaim at debug level
To: linux-btrfs@vger.kernel.org
The reclaim worker relocates block groups without a word in the kernel
-From 1c974bb6d78b206f0fc49d88ae455f6b75262340 Mon Sep 17 00:00:00 2001
+From 002da63fa0320576de844ad398efc2d2586a69df Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Thu, 22 Oct 2026 04:02:52 -0400
-Subject: [PATCH 3/4] btrfs: back off block group reclaim after repeated ENOSPC
+Subject: [PATCH 3/3] btrfs: back off block group reclaim after repeated ENOSPC
To: linux-btrfs@vger.kernel.org
Near a full filesystem every reclaim of a block group can fail with
+++ /dev/null
-From 13013fcff5058f98d5ac355cfe1aab2a3ea6c29d Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 22 Oct 2026 04:02:53 -0400
-Subject: [PATCH 4/4] btrfs: let queued exclusive operations in between block
- group reclaims
-To: linux-btrfs@vger.kernel.org
-
-The block group reclaim worker runs under the balance exclusive operation.
-At the fill edge, with writers active, each relocation takes tens of
-seconds (2 to 61 s measured) and the list keeps refilling, so the
-worker held the operation for most of the time writers ran: 84-90% of a
-600 s churn in reclaim-futile-test.sh, and for an hour of fsstress in the
-octopus P1 pass, where a resize and a replace could not start.
-
-btrfs-progs makes this worse than a plain refusal: before it calls the
-ioctl it reads sysfs exclusive_operation. Without --enqueue it gives up
-there; with --enqueue it waits for the notification that
-btrfs_exclop_finish() sends and then calls the ioctl. Either way the
-kernel never sees a refusal, and the worker retakes the operation right
-after each group, before a waiter can get in: on the lane a queued resize
-waited the whole churn (0 of 40 one-shot resizes succeeded, the longest
-refusal 601 s).
-
-Between groups, release the operation (btrfs_exclop_finish() sends the
-sysfs notification) and, if more groups are queued, leave it free for
-BTRFS_RECLAIM_GAP (12 s) before taking it back; if someone took it
-meanwhile, leave the rest of the list for a later run. 12 s comes from
-btrfs-progs: after the notification, check_running_fs_exclop() reopens
-the file and sleeps in a second select() for (remaining % 10) + 1 s "to
-randomize the order" before it re-reads the operation, so a waiter can
-take up to 10 s, plus wakeup latency under load, to get to the ioctl;
-with a 5 s gap about half the queued waiters woke after the worker had
-retaken the operation and waited another group. A progs change that
-re-reads right after the notification (and randomizes only when it loses
-a race) would allow a much shorter gap. With nobody waiting the gap
-costs only reclaim throughput: reclaim resumes after it.
-
-A caller that does reach btrfs_exclop_start() while the worker holds
-the operation (an ioctl user that does not pre-check sysfs) opens a
-BTRFS_RECLAIM_YIELD_WINDOW (60 s, longer than such a caller's retry
-interval and short next to the five-minute reclaim hysteresis) in which
-the worker neither starts nor takes another group. Both are backoffs
-only: no drain or accounting wait is bounded by them.
-
-A group in progress is not interrupted, so a queued operation waits for
-the rest of the current group plus at most one gap. Measured on a
-stripe_alloc filesystem, whose trapped space keeps the reclaim list full
-at the fill edge, with
-reclaim-futile-test.sh (6 x 1 GiB raid5 at the fill edge, 128 MiB per
-member added, "all" written to stripe_reclaim_now, 600 s of fsstress, a
-no-op `btrfs filesystem resize` every 15 s and a `--enqueue` one every
-60 s), three traced runs per kernel:
-
- without this patch: the worker held the operation for a whole sweep
- (184, 176 and 616 s); the first queued resize waited 184, 176 and about
- 655 s, i.e. for every queued group; one-shot resizes 27/40, 28/40, 0/40.
-
- with it: every queued resize got in at the first hand-off after it
- arrived (one sat through three short groups, 23 s), 0.3-9.4 s after the
- worker's finish; longest queued waits 82, 11 and 23 s (the 82 s one sat
- behind a single 127 s group); one-shot resizes 12/40, 31/40, 27/40.
-
-Reclaim kept its pace: 10, 10 and 14 groups per 10 minutes without the
-patch, 13, 11 and 10 with it.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 41 +++++++++++++++++++++++++++++++++++++++--
- fs/btrfs/fs.c | 29 +++++++++++++++++++++++++++++
- fs/btrfs/fs.h | 16 ++++++++++++++++
- 3 files changed, 84 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 0c8ce98021a41..1885e1527e038 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2165,6 +2165,14 @@ static void reclaim_note_result(struct btrfs_block_group *bg, bool enospc, u64 n
- streak, bg->start, space_info->flags);
- }
-
-+/* A refused operation's retry window is open: see btrfs_exclop_start(). */
-+static bool reclaim_yielding(const struct btrfs_fs_info *fs_info)
-+{
-+ const unsigned long until = READ_ONCE(fs_info->reclaim_yield_until);
-+
-+ return until && time_before(jiffies, until);
-+}
-+
- void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limit)
- {
- struct btrfs_block_group *bg;
-@@ -2179,9 +2187,12 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- if (!btrfs_should_reclaim(fs_info))
- return;
-
-+ if (reclaim_yielding(fs_info))
-+ return;
-+
- guard(super_write)(fs_info->sb);
-
-- if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
-+ if (!btrfs_exclop_start_reclaim(fs_info))
- return;
-
- /*
-@@ -2235,11 +2246,36 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- btrfs_put_block_group(bg);
-
- mutex_unlock(&fs_info->reclaim_bgs_lock);
-+ /*
-+ * Between groups, let a balance, replace or resize that is
-+ * waiting for the exclusive operation have it: a long reclaim
-+ * list must not lock them out for its whole run.
-+ */
-+ btrfs_exclop_finish(fs_info);
- /*
- * Reclaiming all the block groups in the list can take really
- * long. Prioritize cleaning up unused block groups.
- */
- btrfs_delete_unused_bgs(fs_info);
-+ /*
-+ * Leave the exclusive operation free for a moment before the
-+ * next group. btrfs-progs reads sysfs exclusive_operation
-+ * before it calls the ioctl: without --enqueue it gives up
-+ * there, and with it it waits for the notification that
-+ * btrfs_exclop_finish() just sent. Either way the refusal
-+ * never reaches btrfs_exclop_start(), so only a gap lets a
-+ * balance, replace or resize in while the list is long.
-+ */
-+ if (!list_empty_careful(&fs_info->reclaim_bgs))
-+ schedule_timeout_idle(BTRFS_RECLAIM_GAP);
-+ /*
-+ * Someone was refused the exclusive operation while we held
-+ * it: leave the rest of the list to a run after their retry.
-+ */
-+ if (reclaim_yielding(fs_info))
-+ goto out;
-+ if (!btrfs_exclop_start_reclaim(fs_info))
-+ goto out;
- /*
- * If we are interrupted by a balance, we can just bail out. The
- * cleaner thread restart again if necessary.
-@@ -2253,10 +2289,11 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- spin_unlock(&fs_info->unused_bgs_lock);
- mutex_unlock(&fs_info->reclaim_bgs_lock);
- end:
-+ btrfs_exclop_finish(fs_info);
-+out:
- spin_lock(&fs_info->unused_bgs_lock);
- list_splice_tail(&retry_list, &fs_info->reclaim_bgs);
- spin_unlock(&fs_info->unused_bgs_lock);
-- btrfs_exclop_finish(fs_info);
- }
-
- void btrfs_reclaim_bgs_work(struct work_struct *work)
-diff --git a/fs/btrfs/fs.c b/fs/btrfs/fs.c
-index 75a1217727a7b..9a36fbd24e318 100644
---- a/fs/btrfs/fs.c
-+++ b/fs/btrfs/fs.c
-@@ -183,6 +183,34 @@ bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
- if (fs_info->exclusive_operation == BTRFS_EXCLOP_NONE) {
- fs_info->exclusive_operation = type;
- ret = true;
-+ } else if (test_bit(BTRFS_FS_RECLAIM_EXCLOP, &fs_info->flags)) {
-+ /*
-+ * The block group reclaim worker holds it. It is background
-+ * work: have it stand aside after its current group, long
-+ * enough for the caller to retry.
-+ */
-+ WRITE_ONCE(fs_info->reclaim_yield_until,
-+ (jiffies + BTRFS_RECLAIM_YIELD_WINDOW) ?: 1);
-+ }
-+ spin_unlock(&fs_info->super_lock);
-+
-+ return ret;
-+}
-+
-+/*
-+ * The block group reclaim worker's balance exclusive operation: marked as
-+ * the worker's, so that an operation it refuses makes it yield (see
-+ * btrfs_exclop_start()).
-+ */
-+bool btrfs_exclop_start_reclaim(struct btrfs_fs_info *fs_info)
-+{
-+ bool ret = false;
-+
-+ spin_lock(&fs_info->super_lock);
-+ if (fs_info->exclusive_operation == BTRFS_EXCLOP_NONE) {
-+ fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
-+ set_bit(BTRFS_FS_RECLAIM_EXCLOP, &fs_info->flags);
-+ ret = true;
- }
- spin_unlock(&fs_info->super_lock);
-
-@@ -222,6 +250,7 @@ void btrfs_exclop_finish(struct btrfs_fs_info *fs_info)
- {
- spin_lock(&fs_info->super_lock);
- WRITE_ONCE(fs_info->exclusive_operation, BTRFS_EXCLOP_NONE);
-+ clear_bit(BTRFS_FS_RECLAIM_EXCLOP, &fs_info->flags);
- spin_unlock(&fs_info->super_lock);
- sysfs_notify(&fs_info->fs_devices->fsid_kobj, NULL, "exclusive_operation");
- }
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 2dd167c32d612..686514187327f 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -234,6 +234,9 @@ enum {
- */
- BTRFS_FS_UNALIGNED_TREE_BLOCK,
-
-+ /* The block group reclaim worker holds the exclusive operation. */
-+ BTRFS_FS_RECLAIM_EXCLOP,
-+
- #if BITS_PER_LONG == 32
- /* Indicate if we have error/warn message printed on 32bit systems */
- BTRFS_FS_32BIT_ERROR,
-@@ -869,6 +872,13 @@ struct btrfs_fs_info {
-
- /* Reclaim partially filled block groups in the background */
- struct work_struct reclaim_bgs_work;
-+ /*
-+ * A balance, replace, resize or device add/remove was refused while
-+ * the reclaim worker held the exclusive operation: until this jiffies
-+ * value the worker neither starts nor takes another group, so that the
-+ * caller's retry gets the operation.
-+ */
-+ unsigned long reclaim_yield_until;
- /* Protected by unused_bgs_lock. */
- struct list_head reclaim_bgs;
- int bg_reclaim_threshold;
-@@ -1084,6 +1094,12 @@ static inline unsigned int btrfs_blocks_per_folio(const struct btrfs_fs_info *fs
- }
-
- bool __attribute_const__ btrfs_supported_blocksize(u32 blocksize);
-+/* How long the reclaim worker stands aside after a refused operation. */
-+#define BTRFS_RECLAIM_YIELD_WINDOW (60 * HZ)
-+/* How long it leaves the exclusive operation free between two groups. */
-+#define BTRFS_RECLAIM_GAP (12 * HZ)
-+
-+bool btrfs_exclop_start_reclaim(struct btrfs_fs_info *fs_info);
- bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
- enum btrfs_exclusive_operation type);
- bool btrfs_exclop_start_try_lock(struct btrfs_fs_info *fs_info,
---
-2.47.3
-
# Testing: reclaim-fixes
-CANDIDATE (2026-10-28), not promoted. Split out of topics/stripe-alloc by
+PROMOTED 2026-10-28 with the sa-fold (misc-next/topics/reclaim-fixes;
+topics/stripe-alloc is stacked on it). Patch 4 is DO-NOT-UPSTREAM (Zygo
+2026-10-29: "mark the feature do-not-upstream. I'll defer to upstream on
+what they want to do about reclaim starvation"); since 2026-10-30 it is
+in topics/test-knobs (on top of stripe-alloc), which the export leaves
+out, so the series is patches 1-3. The rows for "patch 4" below stay
+for the lanes.
+
+Originally a candidate (2026-10-28). Split out of topics/stripe-alloc by
the sa-fold rework (Zygo 2026-10-27: "Split generic reclaim into a separate
topic where reasonable"): the generic parts of four stripe-alloc commits.
Candidate refs: refs/cand/sa-fold/{mn,618}/reclaim (the first four commits
-From be33f3b2272b357904ead23cff12a8e7007d612b Mon Sep 17 00:00:00 2001
+From 4d9e701c741188892031ed8989b6824e2ee59411 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Mon, 26 Oct 2026 17:33:57 -0400
+Date: Fri, 30 Oct 2026 22:32:41 -0400
Subject: [PATCH 0/2] btrfs: reflink: two fixes for copying inline extents into the page cache
To: linux-btrfs@vger.kernel.org
1 file changed, 18 insertions(+), 2 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From f36cf85b9ec74df310e9a8f24e53d5142b6cad93 Mon Sep 17 00:00:00 2001
+From cc69842d79ecb04b150b2b84c9983390b568a6f7 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Mon, 26 Oct 2026 15:26:35 -0400
Subject: [PATCH 1/2] btrfs: reflink: zero the right part of the folio after
-From be33f3b2272b357904ead23cff12a8e7007d612b Mon Sep 17 00:00:00 2001
+From 4d9e701c741188892031ed8989b6824e2ee59411 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Mon, 26 Oct 2026 15:26:36 -0400
Subject: [PATCH 2/2] btrfs: reflink: undo delalloc if inline extent
-From 1c26761301041e16e2d84460c570ba92f4f66c58 Mon Sep 17 00:00:00 2001
+From 1a00c361d1af739637dd7663f72bd20a7a66dcc7 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:47 -0400
-Subject: [PATCH 0/7] btrfs: dev-replace error accounting, cancel state, and an abort option
+Date: Fri, 30 Oct 2026 22:32:40 -0400
+Subject: [PATCH 00/10] btrfs: dev-replace error accounting, resume and failure handling, and an abort option
To: linux-btrfs@vger.kernel.org
-Device replace reports and acts on errors that it no longer counts.
-This series restores the counters, fixes what a failed replace leaves
+Device replace reports and acts on errors that it no longer counts, can
+lose data when it is resumed after an unmount, cannot be resumed at all
+on a single device filesystem, and goes on reading the source device
+after the filesystem has had an error. This series restores the
+counters, fixes those three failures and what a failed replace leaves
behind, and adds an option to abort a replace on uncorrectable data.
Patch 1 commits the CANCELED state when a replace fails or is canceled.
failing target does not silently become the new device, but nothing has
incremented it since the move to scrub_stripe. Fixes: e02ee89baa66c.
-Patch 6 reports how far a canceled replace got, instead of "at 0.0%".
+Patch 6 fixes a data loss. When the copy of a chunk stops part way,
+scrub_enumerate_chunks() still moves cursor_left to the end of the
+chunk; if the replace is being suspended by an unmount and a transaction
+is still running then (e.g. the cleaner dropping a subvolume), the
+final commit writes that cursor, and the resumed replace never copies
+the rest of the chunk. The replace finishes without an error. On a
+single-profile filesystem with 1 GiB data chunks, 530 MiB of file data
+read back as -EIO after the source was removed; on raid1, scrub found
+the same blocks with csum errors on the new device. Reproduced on
+misc-next and on stock 6.12. Since v6.11 an idle unmount commits
+nothing there and hides it; before that, every unmount during a replace
+was exposed. Fixes: 1a1a8b732c7e9.
-Patch 7 adds BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE, a flag in
+Patch 7 reports how far a canceled replace got, instead of "at 0.0%".
+
+Patch 8 adds BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE, a flag in
the high 32 bits of cont_reading_from_srcdev_mode. By default a
replace counts unreadable sectors and goes on, which is what rescuing a
failing device needs. Replacing a healthy device (e.g. with a larger
the option fails closed; unknown flags get -EOPNOTSUPP. A btrfs-progs
patch adds "btrfs replace start --abort-on-uncorrectable".
+Patch 9 lets a single device filesystem with a replace in progress
+mount again. Since v6.7 a scan does not register a device whose
+superblock says num_devices == 1, and a second device with the same
+fsid is taken for a clone and given a temp-fsid; the replace target
+(devid 0, not counted in num_devices) hits both, and the mount fails
+with "failed to init dev_replace: -EIO" however often 'btrfs device
+scan' is run. Fixes: bc27d6f0aa0e4, a5b8a5f9f8355.
+
+Patch 10 stops a scrub or a replace at the next extent once the
+filesystem has an error. Since 1acd6831d9877 removed the cancel from
+the error handler, a scrub or replace after e.g. a log sync abort reads
+on to the end of the device on the read-only filesystem, and a replace
+then stays started anyway. The scrub ioctl now returns -EROFS with the
+progress so far; a replace keeps its cursor at the start of the block
+group (patch 6) and resumes at the next writable mount.
+
Testing: raid1, raid5 and raid6 replaces with planted uncorrectable
sectors, with and without the flag and -r, across unmount/suspend,
crash-image resume and target write errors; target contents checked
sector by sector against a device-identifying prefill; KASAN, misc-next
-and 6.18.
+and 6.18. Patches 6, 9 and 10: an unmount mid-chunk with a subvolume
+drop running (single, raid1, and a single device filesystem), with
+idle-unmount and no-unmount controls, and a scrub and a replace after a
+forced abort (unfixed: the scrub went through 5 more block groups,
+1235 MiB in 76 s, and reported success; fixed: -EROFS within a second),
+on both lanes.
+
-Zygo Blaxell (7):
+Zygo Blaxell (10):
btrfs: commit the canceled state when a device replace fails or is
canceled
btrfs: scrub: do not count write errors twice, or on the wrong device
btrfs: dev-replace: count uncorrectable read errors
btrfs: dev-replace: do not warn when a resumed replace fails
btrfs: dev-replace: count write errors to the target again
+ btrfs: dev-replace: do not skip the rest of a chunk when resuming a
+ replace
btrfs: dev-replace: report the progress of a canceled replace
btrfs: dev-replace: optionally abort on uncorrectable read errors
+ btrfs: mount a single device filesystem with a device replace in
+ progress
+ btrfs: scrub: stop scrub and device replace when the filesystem has an
+ error
- fs/btrfs/dev-replace.c | 61 +++++++++++++++++++++++++++------
- fs/btrfs/fs.h | 4 +++
- fs/btrfs/scrub.c | 36 +++++++++++++++++--
- include/uapi/linux/btrfs.h | 13 +++++++
- include/uapi/linux/btrfs_tree.h | 7 ++++
- 5 files changed, 107 insertions(+), 14 deletions(-)
+ fs/btrfs/dev-replace.c | 61 ++++++++++++++++++----
+ fs/btrfs/fs.h | 4 ++
+ fs/btrfs/messages.c | 13 ++---
+ fs/btrfs/scrub.c | 89 +++++++++++++++++++++++++++++----
+ fs/btrfs/volumes.c | 32 +++++++++++-
+ include/uapi/linux/btrfs.h | 13 +++++
+ include/uapi/linux/btrfs_tree.h | 7 +++
+ 7 files changed, 190 insertions(+), 29 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From c4c21d9a929883dd69fcdfeae2a9e34ed627477c Mon Sep 17 00:00:00 2001
+From b6aab469cf1d43ba27bdedec68ac943f6e2aa84d Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 01:19:17 -0400
-Subject: [PATCH 1/7] btrfs: commit the canceled state when a device replace
+Subject: [PATCH 01/10] btrfs: commit the canceled state when a device replace
fails or is canceled
To: linux-btrfs@vger.kernel.org
-From 2b3a5ba66685a3924a2db09393c2c506dd772d8e Mon Sep 17 00:00:00 2001
+From 96b87030db6ae7e4eedbe275dd02be2d651c7a35 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 04:07:33 -0400
-Subject: [PATCH 2/7] btrfs: scrub: do not count write errors twice, or on the
- wrong device
+Subject: [PATCH 02/10] btrfs: scrub: do not count write errors twice, or on
+ the wrong device
To: linux-btrfs@vger.kernel.org
scrub_write_endio() increments the write error counter of stripe->dev
-From f217a9f8ee76116618ddf8ef59358c69318ba8c5 Mon Sep 17 00:00:00 2001
+From b5b7853cd89b39ce2145822b01402ef1ce852c81 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 04:07:34 -0400
-Subject: [PATCH 3/7] btrfs: dev-replace: count uncorrectable read errors
+Subject: [PATCH 03/10] btrfs: dev-replace: count uncorrectable read errors
To: linux-btrfs@vger.kernel.org
btrfs_dev_replace::num_uncorrectable_read_errors is reported by the
read or repaired from any copy. This covers every uncorrectable sector
the replace skips, checksummed or not.
+The count is taken before the check for a metadata error, which aborts
+the replace, so that the sectors of the batch that aborts it are counted
+as well.
+
Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/scrub.c | 4 ++++
- 1 file changed, 4 insertions(+)
+ fs/btrfs/scrub.c | 21 +++++++++++++++++----
+ 1 file changed, 17 insertions(+), 4 deletions(-)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 5128e2989016b..88b1f5d43ce89 100644
+index 5128e2989016b..0a84f309c1f7a 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -1984,6 +1984,10 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
-
- has_extent = scrub_bitmap_read_has_extent(stripe);
- error = scrub_bitmap_read_error(stripe);
+@@ -1965,14 +1965,26 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
+ if (sctx->is_dev_replace) {
+ /*
+ * For dev-replace, if we know there is something wrong with
+- * metadata, we should immediately abort.
++ * metadata, we should immediately abort. Count every
++ * uncorrectable sector of the batch first, those of an
++ * aborting batch included.
+ */
+ for (int i = 0; i < nr_stripes; i++) {
+- if (unlikely(stripe_has_metadata_error(&sctx->stripes[i]))) {
++ unsigned long has_extent;
++ unsigned long error;
++
++ stripe = &sctx->stripes[i];
++ has_extent = scrub_bitmap_read_has_extent(stripe);
++ error = scrub_bitmap_read_error(stripe);
+ bitmap_and(&error, &error, &has_extent, stripe->nr_sectors);
+ if (!bitmap_empty(&error, stripe->nr_sectors))
+ atomic64_add(bitmap_weight(&error, stripe->nr_sectors),
+ &fs_info->dev_replace.num_uncorrectable_read_errors);
++ if (unlikely(stripe_has_metadata_error(stripe)))
+ ret = -EIO;
+- goto out;
+- }
+ }
++ if (ret)
++ goto out;
+ for (int i = 0; i < nr_stripes; i++) {
+ unsigned long good;
+ unsigned long has_extent;
+@@ -1984,6 +1996,7 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
+
+ has_extent = scrub_bitmap_read_has_extent(stripe);
+ error = scrub_bitmap_read_error(stripe);
++ bitmap_and(&error, &error, &has_extent, stripe->nr_sectors);
bitmap_andnot(&good, &has_extent, &error, stripe->nr_sectors);
scrub_write_sectors(sctx, stripe, good, true);
}
-From 9488e7f09b4faec770edaf9eda837801d15109f5 Mon Sep 17 00:00:00 2001
+From ef9040540b2392e1d3e3f7d563302ead2a54f901 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 13:58:22 -0400
-Subject: [PATCH 4/7] btrfs: dev-replace: do not warn when a resumed replace
+Subject: [PATCH 04/10] btrfs: dev-replace: do not warn when a resumed replace
fails
To: linux-btrfs@vger.kernel.org
-From 92f953d555b6e195808b2a299709c2462a0e1aa9 Mon Sep 17 00:00:00 2001
+From adbf4100993da32d4dd535d34d0825e474368bb0 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Fri, 16 Oct 2026 04:07:34 -0400
-Subject: [PATCH 5/7] btrfs: dev-replace: count write errors to the target
+Subject: [PATCH 05/10] btrfs: dev-replace: count write errors to the target
again
To: linux-btrfs@vger.kernel.org
1 file changed, 19 insertions(+)
diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 88b1f5d43ce89..1a2bde86c305a 100644
+index 0a84f309c1f7a..5d3fa99743f47 100644
--- a/fs/btrfs/scrub.c
+++ b/fs/btrfs/scrub.c
-@@ -1982,6 +1982,14 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
+@@ -1994,6 +1994,14 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
ASSERT(stripe->dev == fs_info->dev_replace.srcdev);
has_extent = scrub_bitmap_read_has_extent(stripe);
error = scrub_bitmap_read_error(stripe);
bitmap_and(&error, &error, &has_extent, stripe->nr_sectors);
-@@ -1998,6 +2006,17 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
+@@ -2007,6 +2015,17 @@ static int flush_scrub_stripes(struct scrub_ctx *sctx)
stripe = &sctx->stripes[i];
wait_scrub_stripe_io(stripe);
--- /dev/null
+From 26025d2bbc6648b956e2a0cab9b3676adac28cf5 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 29 Oct 2026 12:17:20 -0400
+Subject: [PATCH 06/10] btrfs: dev-replace: do not skip the rest of a chunk
+ when resuming a replace
+To: linux-btrfs@vger.kernel.org
+
+When the copy of a chunk stops part way through, scrub_enumerate_chunks()
+still moves cursor_left to the end of the chunk and marks the
+dev_replace item for writeback. If the replace is being suspended, the
+next transaction commit writes that cursor to disk, and the replace
+resumed at the next mount starts after the chunk. The part of the chunk
+that the scrub had not reached yet is never copied to the target:
+handle_ops_on_dev_replace() duplicates only new writes, and nothing else
+copies existing extents. The replace finishes without reporting any
+error, and when the source device goes away, the data that was only on
+it is lost.
+
+This happens on unmount: close_ctree() suspends a running replace with
+btrfs_dev_replace_suspend_for_unmount() and cancels its scrub, and
+btrfs_commit_super() then commits the running transaction, if there is
+one, with the advanced cursor. Since commit cab0d8623fb4 ("btrfs: avoid
+create and commit empty transaction when committing super") an idle
+unmount commits nothing there, and the cursor on disk stays at the
+start of the chunk, but any transaction still running at that point
+exposes the bug, e.g. one left by the cleaner dropping a deleted
+subvolume. Before that commit, every unmount during a replace was
+affected.
+
+With 1 GiB data chunks, a filesystem with data profile single was
+unmounted while a replace was copying a chunk and a subvolume was being
+dropped. After the resumed replace finished and the source device was
+removed, 530 MiB of file data from that chunk read back as -EIO. With
+data profile raid1, scrub found the same blocks with csum errors on the
+new device.
+
+Move cursor_left to the end of the chunk only when scrub_chunk() returns
+0. When it fails or is canceled, cursor_left stays at the start of the
+chunk, where it was set before the copy started, and a resumed replace
+copies the whole chunk again. A replace that fails is canceled, not
+resumed, so for it the cursor only changes the reported progress.
+
+Commit 1a1a8b732c7e ("Btrfs: fix race setting block group back to RW
+mode during device replace") moved the cursor update before the error
+checks so that it would happen before the block group goes back to RW,
+because at the time writes were duplicated to the target only below
+cursor_left. Commit 22ab04e814f4 ("Btrfs: fix race between device
+replace and chunk allocation") made the duplication of writes
+unconditional, and since then the cursor is only used to report
+progress and to resume the replace. The update stays before
+btrfs_dec_block_group_ro() anyway.
+
+Fixes: 1a1a8b732c7e9 ("Btrfs: fix race setting block group back to RW mode during device replace")
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/scrub.c | 18 ++++++++++++++----
+ 1 file changed, 14 insertions(+), 4 deletions(-)
+
+diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
+index 5d3fa99743f47..3f888366c1442 100644
+--- a/fs/btrfs/scrub.c
++++ b/fs/btrfs/scrub.c
+@@ -2929,10 +2929,20 @@ int scrub_enumerate_chunks(struct scrub_ctx *sctx,
+ cache, found_key.offset))
+ ro_set = 0;
+
+- down_write(&dev_replace->rwsem);
+- dev_replace->cursor_left = dev_replace->cursor_right;
+- dev_replace->item_needs_writeback = 1;
+- up_write(&dev_replace->rwsem);
++ /*
++ * Move the cursor past this chunk only when all of it has been
++ * copied. If the copy was canceled or failed part way through,
++ * the cursor stays at the start of the chunk, so that a replace
++ * suspended by unmount copies the whole chunk again when it is
++ * resumed. Nothing else copies the extents the scrub did not
++ * reach: only new writes are duplicated to the target.
++ */
++ if (ret == 0) {
++ down_write(&dev_replace->rwsem);
++ dev_replace->cursor_left = dev_replace->cursor_right;
++ dev_replace->item_needs_writeback = 1;
++ up_write(&dev_replace->rwsem);
++ }
+
+ if (ro_set)
+ btrfs_dec_block_group_ro(cache);
+--
+2.47.3
+
+++ /dev/null
-From c010dc2e430ea26fa70d328e45b59da13f217301 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 16 Oct 2026 04:07:34 -0400
-Subject: [PATCH 6/7] btrfs: dev-replace: report the progress of a canceled
- replace
-To: linux-btrfs@vger.kernel.org
-
-btrfs_dev_replace_progress() returns 0 for a canceled replace, so
-"btrfs replace status" says it was canceled "at 0.0%" however far it
-got. The progress cannot be computed after the fact: it is derived from
-cursor_left and the size of the source device, and the source device is
-forgotten when the replace stops.
-
-Remember the progress when a running replace fails or is canceled
-(btrfs_dev_replace_finishing()) and when a suspended replace is canceled
-(btrfs_dev_replace_cancel()), and report it for the CANCELED state. The
-value is kept in memory only; a canceled replace loaded from disk after a
-remount still reports 0. It is as coarse as the progress of a running
-replace: scrub_enumerate_chunks() moves cursor_left to the end of a chunk
-when the copy of that chunk returns, also when it returns an error, so a
-replace that stops part way through a chunk is reported as if that chunk
-had been copied.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/dev-replace.c | 10 +++++++++-
- fs/btrfs/fs.h | 2 ++
- 2 files changed, 11 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/dev-replace.c b/fs/btrfs/dev-replace.c
-index ee16b80d7de9b..a48c5daae2302 100644
---- a/fs/btrfs/dev-replace.c
-+++ b/fs/btrfs/dev-replace.c
-@@ -65,6 +65,7 @@
-
- static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
- int scrub_ret);
-+static u64 btrfs_dev_replace_progress(struct btrfs_fs_info *fs_info);
- static int btrfs_dev_replace_kthread(void *data);
-
- int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
-@@ -941,6 +942,9 @@ static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
- }
-
- down_write(&dev_replace->rwsem);
-+ if (scrub_ret)
-+ dev_replace->canceled_progress_1000 =
-+ btrfs_dev_replace_progress(fs_info);
- dev_replace->replace_state =
- scrub_ret ? BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED
- : BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED;
-@@ -1084,9 +1088,11 @@ static u64 btrfs_dev_replace_progress(struct btrfs_fs_info *fs_info)
-
- switch (dev_replace->replace_state) {
- case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
-- case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
- ret = 0;
- break;
-+ case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
-+ ret = dev_replace->canceled_progress_1000;
-+ break;
- case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
- ret = 1000;
- break;
-@@ -1170,6 +1176,8 @@ int btrfs_dev_replace_cancel(struct btrfs_fs_info *fs_info)
- result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
- tgt_device = dev_replace->tgtdev;
- src_device = dev_replace->srcdev;
-+ dev_replace->canceled_progress_1000 =
-+ btrfs_dev_replace_progress(fs_info);
- dev_replace->tgtdev = NULL;
- dev_replace->srcdev = NULL;
- dev_replace->replace_state =
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 2dd167c32d612..a3b0edf4025ce 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -374,6 +374,8 @@ struct btrfs_dev_replace {
- u64 committed_cursor_left;
- u64 cursor_left_last_write_of_item;
- u64 cursor_right;
-+ /* Progress (0..1000) when the replace was canceled, in memory only */
-+ u64 canceled_progress_1000;
-
- /* See #define above */
- u64 cont_reading_from_srcdev_mode;
---
-2.47.3
-
+++ /dev/null
-From 1c26761301041e16e2d84460c570ba92f4f66c58 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 16 Oct 2026 13:02:21 -0400
-Subject: [PATCH 7/7] btrfs: dev-replace: optionally abort on uncorrectable
- read errors
-To: linux-btrfs@vger.kernel.org
-
-When a sector that is in use cannot be read from any copy, device
-replace counts it and goes on, leaving the sector unwritten on the
-target. That is what a user rescuing data from a failing device wants:
-copy everything that can still be read, as fast as possible, and find
-the damage afterwards with the checksums.
-
-A user replacing a healthy device, e.g. with a larger one, wants the
-opposite. An uncorrectable sector means the array has already lost data
-it was expected to keep, and the user wants to stop and find out why
-before the source device is removed for good.
-Today such a user has to add the new device and remove the old one
-instead, because relocation stops at the first unreadable block, at the
-cost of a much slower relocation.
-
-Add BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE. When it is set,
-replace fails with -EIO and is canceled, like it is on write errors to
-the target, at the end of the block group where the first uncorrectable
-read error was counted. The source device stays in the filesystem.
-
-The flag goes in the high 32 bits of cont_reading_from_srcdev_mode,
-which has only ever held 0 or 1. Kernels without this patch reject any
-other value with -EINVAL, so a user asking to abort cannot get a replace
-that silently does not. Unknown flags now get -EOPNOTSUPP. The same
-bit is stored in the dev_replace item next to the mode, so a replace
-resumed after a remount still aborts. An older kernel resuming such a
-replace ignores the flag, and since the mode then no longer compares
-equal to BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID, it
-also reads from the source device again, as if -r was not given.
-
-This depends on the counting of uncorrectable read errors added by
-"btrfs: dev-replace: count uncorrectable read errors".
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/dev-replace.c | 32 ++++++++++++++++++++++++--------
- fs/btrfs/fs.h | 2 ++
- fs/btrfs/scrub.c | 10 ++++++++++
- include/uapi/linux/btrfs.h | 13 +++++++++++++
- include/uapi/linux/btrfs_tree.h | 7 +++++++
- 5 files changed, 56 insertions(+), 8 deletions(-)
-
-diff --git a/fs/btrfs/dev-replace.c b/fs/btrfs/dev-replace.c
-index a48c5daae2302..50c2e53c148a4 100644
---- a/fs/btrfs/dev-replace.c
-+++ b/fs/btrfs/dev-replace.c
-@@ -81,6 +81,7 @@ int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
- int item_size;
- struct btrfs_dev_replace_item *ptr;
- u64 src_devid;
-+ u64 mode;
-
- if (!dev_root)
- return 0;
-@@ -108,6 +109,7 @@ int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
- BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED;
- dev_replace->cont_reading_from_srcdev_mode =
- BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS;
-+ dev_replace->flags = 0;
- dev_replace->time_started = 0;
- dev_replace->time_stopped = 0;
- atomic64_set(&dev_replace->num_write_errors, 0);
-@@ -134,8 +136,10 @@ int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
- }
-
- src_devid = btrfs_dev_replace_src_devid(eb, ptr);
-+ mode = btrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr);
- dev_replace->cont_reading_from_srcdev_mode =
-- btrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr);
-+ mode & BTRFS_DEV_REPLACE_ITEM_MODE_MASK;
-+ dev_replace->flags = mode & BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE;
- dev_replace->replace_state = btrfs_dev_replace_replace_state(eb, ptr);
- dev_replace->time_started = btrfs_dev_replace_time_started(eb, ptr);
- dev_replace->time_stopped =
-@@ -422,7 +426,7 @@ int btrfs_run_dev_replace(struct btrfs_trans_handle *trans)
- else
- btrfs_set_dev_replace_src_devid(eb, ptr, (u64)-1);
- btrfs_set_dev_replace_cont_reading_from_srcdev_mode(eb, ptr,
-- dev_replace->cont_reading_from_srcdev_mode);
-+ dev_replace->cont_reading_from_srcdev_mode | dev_replace->flags);
- btrfs_set_dev_replace_replace_state(eb, ptr,
- dev_replace->replace_state);
- btrfs_set_dev_replace_time_started(eb, ptr, dev_replace->time_started);
-@@ -592,7 +596,7 @@ bool btrfs_finish_block_group_to_copy(struct btrfs_device *srcdev,
-
- static int btrfs_dev_replace_start(struct btrfs_fs_info *fs_info,
- const char *tgtdev_name, u64 srcdevid, const char *srcdev_name,
-- int read_src)
-+ int read_src, u64 flags)
- {
- struct btrfs_root *root = fs_info->dev_root;
- struct btrfs_trans_handle *trans;
-@@ -660,14 +664,17 @@ static int btrfs_dev_replace_start(struct btrfs_fs_info *fs_info,
- }
-
- dev_replace->cont_reading_from_srcdev_mode = read_src;
-+ dev_replace->flags = flags;
- dev_replace->srcdev = src_device;
- dev_replace->tgtdev = tgt_device;
-
- btrfs_info(fs_info,
-- "dev_replace from %s (devid %llu) to %s started",
-+ "dev_replace from %s (devid %llu) to %s started%s",
- btrfs_dev_name(src_device),
- src_device->devid,
-- btrfs_dev_name(tgt_device));
-+ btrfs_dev_name(tgt_device),
-+ (flags & BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE) ?
-+ ", aborting on uncorrectable read errors" : "");
-
- /*
- * from now on, the writes to the srcdev are all duplicated to
-@@ -750,9 +757,19 @@ static int btrfs_check_replace_dev_names(struct btrfs_ioctl_dev_replace_args *ar
- int btrfs_dev_replace_by_ioctl(struct btrfs_fs_info *fs_info,
- struct btrfs_ioctl_dev_replace_args *args)
- {
-+ const u64 mode = args->start.cont_reading_from_srcdev_mode &
-+ BTRFS_IOCTL_DEV_REPLACE_MODE_MASK;
-+ const u64 flags = args->start.cont_reading_from_srcdev_mode &
-+ ~BTRFS_IOCTL_DEV_REPLACE_MODE_MASK;
- int ret;
-
-- switch (args->start.cont_reading_from_srcdev_mode) {
-+ static_assert(BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE ==
-+ BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE);
-+
-+ if (flags & ~BTRFS_IOCTL_DEV_REPLACE_SUPPORTED_FLAGS)
-+ return -EOPNOTSUPP;
-+
-+ switch (mode) {
- case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS:
- case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID:
- break;
-@@ -765,8 +782,7 @@ int btrfs_dev_replace_by_ioctl(struct btrfs_fs_info *fs_info,
-
- ret = btrfs_dev_replace_start(fs_info, args->start.tgtdev_name,
- args->start.srcdevid,
-- args->start.srcdev_name,
-- args->start.cont_reading_from_srcdev_mode);
-+ args->start.srcdev_name, mode, flags);
- args->result = ret;
- /* don't warn if EINPROGRESS, someone else might be running scrub */
- if (ret == BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS ||
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index a3b0edf4025ce..4cf6672459e3a 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -379,6 +379,8 @@ struct btrfs_dev_replace {
-
- /* See #define above */
- u64 cont_reading_from_srcdev_mode;
-+ /* BTRFS_DEV_REPLACE_ITEM_* flags, stored with the mode in the item */
-+ u64 flags;
-
- int is_valid;
- int item_needs_writeback;
-diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
-index 1a2bde86c305a..b443c80d8e72f 100644
---- a/fs/btrfs/scrub.c
-+++ b/fs/btrfs/scrub.c
-@@ -2957,6 +2957,16 @@ int scrub_enumerate_chunks(struct scrub_ctx *sctx,
- ret = -EIO;
- break;
- }
-+ if (unlikely(sctx->is_dev_replace &&
-+ (dev_replace->flags &
-+ BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE) &&
-+ atomic64_read(&dev_replace->num_uncorrectable_read_errors) > 0)) {
-+ btrfs_err(fs_info,
-+ "dev_replace: %lld uncorrectable read errors, aborting as requested",
-+ atomic64_read(&dev_replace->num_uncorrectable_read_errors));
-+ ret = -EIO;
-+ break;
-+ }
- if (sctx->stat.malloc_errors > 0) {
- ret = -ENOMEM;
- break;
-diff --git a/include/uapi/linux/btrfs.h b/include/uapi/linux/btrfs.h
-index b6f196bfa600a..e53650a60d8a4 100644
---- a/include/uapi/linux/btrfs.h
-+++ b/include/uapi/linux/btrfs.h
-@@ -201,6 +201,19 @@ struct btrfs_ioctl_scrub_args {
-
- #define BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS 0
- #define BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID 1
-+/*
-+ * The low 32 bits of cont_reading_from_srcdev_mode hold one of the modes
-+ * above, the high 32 bits hold flags. Kernels that do not know a flag
-+ * fail the start with -EINVAL (before this flag existed) or -EOPNOTSUPP.
-+ */
-+#define BTRFS_IOCTL_DEV_REPLACE_MODE_MASK 0xffffffffULL
-+/*
-+ * Cancel the replace, with -EIO, when a sector that is in use cannot be
-+ * read from any copy. Without it such sectors are counted and skipped.
-+ */
-+#define BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE (1ULL << 32)
-+#define BTRFS_IOCTL_DEV_REPLACE_SUPPORTED_FLAGS \
-+ (BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE)
- struct btrfs_ioctl_dev_replace_start_params {
- __u64 srcdevid; /* in, if 0, use srcdev_name instead */
- __u64 cont_reading_from_srcdev_mode; /* in, see #define
-diff --git a/include/uapi/linux/btrfs_tree.h b/include/uapi/linux/btrfs_tree.h
-index 47ee52859b458..6eb00d5c00b77 100644
---- a/include/uapi/linux/btrfs_tree.h
-+++ b/include/uapi/linux/btrfs_tree.h
-@@ -1141,6 +1141,13 @@ struct btrfs_dev_stats_item {
-
- #define BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS 0
- #define BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID 1
-+/*
-+ * Flags in the high 32 bits of cont_reading_from_srcdev_mode, same values as
-+ * the BTRFS_IOCTL_DEV_REPLACE_* flags. Older kernels ignore them and read
-+ * the mode as BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS.
-+ */
-+#define BTRFS_DEV_REPLACE_ITEM_MODE_MASK 0xffffffffULL
-+#define BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE (1ULL << 32)
-
- struct btrfs_dev_replace_item {
- /*
---
-2.47.3
-
--- /dev/null
+From 5cd2203a007a4dd165929ee550000955aead9279 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Fri, 16 Oct 2026 04:07:34 -0400
+Subject: [PATCH 07/10] btrfs: dev-replace: report the progress of a canceled
+ replace
+To: linux-btrfs@vger.kernel.org
+
+btrfs_dev_replace_progress() returns 0 for a canceled replace, so
+"btrfs replace status" says it was canceled "at 0.0%" however far it
+got. The progress cannot be computed after the fact: it is derived from
+cursor_left and the size of the source device, and the source device is
+forgotten when the replace stops.
+
+Remember the progress when a running replace fails or is canceled
+(btrfs_dev_replace_finishing()) and when a suspended replace is canceled
+(btrfs_dev_replace_cancel()), and report it for the CANCELED state. The
+value is kept in memory only; a canceled replace loaded from disk after a
+remount still reports 0. It is as coarse as the progress of a running
+replace: scrub_enumerate_chunks() moves cursor_left to the end of a chunk
+only when the copy of that chunk is complete, so a replace that stops
+part way through a chunk is reported at the start of that chunk.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/dev-replace.c | 10 +++++++++-
+ fs/btrfs/fs.h | 2 ++
+ 2 files changed, 11 insertions(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/dev-replace.c b/fs/btrfs/dev-replace.c
+index ee16b80d7de9b..a48c5daae2302 100644
+--- a/fs/btrfs/dev-replace.c
++++ b/fs/btrfs/dev-replace.c
+@@ -65,6 +65,7 @@
+
+ static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
+ int scrub_ret);
++static u64 btrfs_dev_replace_progress(struct btrfs_fs_info *fs_info);
+ static int btrfs_dev_replace_kthread(void *data);
+
+ int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
+@@ -941,6 +942,9 @@ static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
+ }
+
+ down_write(&dev_replace->rwsem);
++ if (scrub_ret)
++ dev_replace->canceled_progress_1000 =
++ btrfs_dev_replace_progress(fs_info);
+ dev_replace->replace_state =
+ scrub_ret ? BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED
+ : BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED;
+@@ -1084,9 +1088,11 @@ static u64 btrfs_dev_replace_progress(struct btrfs_fs_info *fs_info)
+
+ switch (dev_replace->replace_state) {
+ case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
+- case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
+ ret = 0;
+ break;
++ case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
++ ret = dev_replace->canceled_progress_1000;
++ break;
+ case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
+ ret = 1000;
+ break;
+@@ -1170,6 +1176,8 @@ int btrfs_dev_replace_cancel(struct btrfs_fs_info *fs_info)
+ result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
+ tgt_device = dev_replace->tgtdev;
+ src_device = dev_replace->srcdev;
++ dev_replace->canceled_progress_1000 =
++ btrfs_dev_replace_progress(fs_info);
+ dev_replace->tgtdev = NULL;
+ dev_replace->srcdev = NULL;
+ dev_replace->replace_state =
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 2dd167c32d612..a3b0edf4025ce 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -374,6 +374,8 @@ struct btrfs_dev_replace {
+ u64 committed_cursor_left;
+ u64 cursor_left_last_write_of_item;
+ u64 cursor_right;
++ /* Progress (0..1000) when the replace was canceled, in memory only */
++ u64 canceled_progress_1000;
+
+ /* See #define above */
+ u64 cont_reading_from_srcdev_mode;
+--
+2.47.3
+
--- /dev/null
+From 3df39f4186e993b659a4eff8853d24557404acc0 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Fri, 16 Oct 2026 13:02:21 -0400
+Subject: [PATCH 08/10] btrfs: dev-replace: optionally abort on uncorrectable
+ read errors
+To: linux-btrfs@vger.kernel.org
+
+When a sector that is in use cannot be read from any copy, device
+replace counts it and goes on, leaving the sector unwritten on the
+target. That is what a user rescuing data from a failing device wants:
+copy everything that can still be read, as fast as possible, and find
+the damage afterwards with the checksums.
+
+A user replacing a healthy device, e.g. with a larger one, wants the
+opposite. An uncorrectable sector means the array has already lost data
+it was expected to keep, and the user wants to stop and find out why
+before the source device is removed for good.
+Today such a user has to add the new device and remove the old one
+instead, because relocation stops at the first unreadable block, at the
+cost of a much slower relocation.
+
+Add BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE. When it is set,
+replace fails with -EIO and is canceled, like it is on write errors to
+the target, at the end of the block group where the first uncorrectable
+read error was counted. The source device stays in the filesystem.
+
+The flag goes in the high 32 bits of cont_reading_from_srcdev_mode,
+which has only ever held 0 or 1. Kernels without this patch reject any
+other value with -EINVAL, so a user asking to abort cannot get a replace
+that silently does not. Unknown flags now get -EOPNOTSUPP. The same
+bit is stored in the dev_replace item next to the mode, so a replace
+resumed after a remount still aborts. An older kernel resuming such a
+replace ignores the flag, and since the mode then no longer compares
+equal to BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID, it
+also reads from the source device again, as if -r was not given.
+
+This depends on the counting of uncorrectable read errors added by
+"btrfs: dev-replace: count uncorrectable read errors".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/dev-replace.c | 32 ++++++++++++++++++++++++--------
+ fs/btrfs/fs.h | 2 ++
+ fs/btrfs/scrub.c | 10 ++++++++++
+ include/uapi/linux/btrfs.h | 13 +++++++++++++
+ include/uapi/linux/btrfs_tree.h | 7 +++++++
+ 5 files changed, 56 insertions(+), 8 deletions(-)
+
+diff --git a/fs/btrfs/dev-replace.c b/fs/btrfs/dev-replace.c
+index a48c5daae2302..50c2e53c148a4 100644
+--- a/fs/btrfs/dev-replace.c
++++ b/fs/btrfs/dev-replace.c
+@@ -81,6 +81,7 @@ int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
+ int item_size;
+ struct btrfs_dev_replace_item *ptr;
+ u64 src_devid;
++ u64 mode;
+
+ if (!dev_root)
+ return 0;
+@@ -108,6 +109,7 @@ int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
+ BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED;
+ dev_replace->cont_reading_from_srcdev_mode =
+ BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS;
++ dev_replace->flags = 0;
+ dev_replace->time_started = 0;
+ dev_replace->time_stopped = 0;
+ atomic64_set(&dev_replace->num_write_errors, 0);
+@@ -134,8 +136,10 @@ int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
+ }
+
+ src_devid = btrfs_dev_replace_src_devid(eb, ptr);
++ mode = btrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr);
+ dev_replace->cont_reading_from_srcdev_mode =
+- btrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr);
++ mode & BTRFS_DEV_REPLACE_ITEM_MODE_MASK;
++ dev_replace->flags = mode & BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE;
+ dev_replace->replace_state = btrfs_dev_replace_replace_state(eb, ptr);
+ dev_replace->time_started = btrfs_dev_replace_time_started(eb, ptr);
+ dev_replace->time_stopped =
+@@ -422,7 +426,7 @@ int btrfs_run_dev_replace(struct btrfs_trans_handle *trans)
+ else
+ btrfs_set_dev_replace_src_devid(eb, ptr, (u64)-1);
+ btrfs_set_dev_replace_cont_reading_from_srcdev_mode(eb, ptr,
+- dev_replace->cont_reading_from_srcdev_mode);
++ dev_replace->cont_reading_from_srcdev_mode | dev_replace->flags);
+ btrfs_set_dev_replace_replace_state(eb, ptr,
+ dev_replace->replace_state);
+ btrfs_set_dev_replace_time_started(eb, ptr, dev_replace->time_started);
+@@ -592,7 +596,7 @@ bool btrfs_finish_block_group_to_copy(struct btrfs_device *srcdev,
+
+ static int btrfs_dev_replace_start(struct btrfs_fs_info *fs_info,
+ const char *tgtdev_name, u64 srcdevid, const char *srcdev_name,
+- int read_src)
++ int read_src, u64 flags)
+ {
+ struct btrfs_root *root = fs_info->dev_root;
+ struct btrfs_trans_handle *trans;
+@@ -660,14 +664,17 @@ static int btrfs_dev_replace_start(struct btrfs_fs_info *fs_info,
+ }
+
+ dev_replace->cont_reading_from_srcdev_mode = read_src;
++ dev_replace->flags = flags;
+ dev_replace->srcdev = src_device;
+ dev_replace->tgtdev = tgt_device;
+
+ btrfs_info(fs_info,
+- "dev_replace from %s (devid %llu) to %s started",
++ "dev_replace from %s (devid %llu) to %s started%s",
+ btrfs_dev_name(src_device),
+ src_device->devid,
+- btrfs_dev_name(tgt_device));
++ btrfs_dev_name(tgt_device),
++ (flags & BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE) ?
++ ", aborting on uncorrectable read errors" : "");
+
+ /*
+ * from now on, the writes to the srcdev are all duplicated to
+@@ -750,9 +757,19 @@ static int btrfs_check_replace_dev_names(struct btrfs_ioctl_dev_replace_args *ar
+ int btrfs_dev_replace_by_ioctl(struct btrfs_fs_info *fs_info,
+ struct btrfs_ioctl_dev_replace_args *args)
+ {
++ const u64 mode = args->start.cont_reading_from_srcdev_mode &
++ BTRFS_IOCTL_DEV_REPLACE_MODE_MASK;
++ const u64 flags = args->start.cont_reading_from_srcdev_mode &
++ ~BTRFS_IOCTL_DEV_REPLACE_MODE_MASK;
+ int ret;
+
+- switch (args->start.cont_reading_from_srcdev_mode) {
++ static_assert(BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE ==
++ BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE);
++
++ if (flags & ~BTRFS_IOCTL_DEV_REPLACE_SUPPORTED_FLAGS)
++ return -EOPNOTSUPP;
++
++ switch (mode) {
+ case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS:
+ case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID:
+ break;
+@@ -765,8 +782,7 @@ int btrfs_dev_replace_by_ioctl(struct btrfs_fs_info *fs_info,
+
+ ret = btrfs_dev_replace_start(fs_info, args->start.tgtdev_name,
+ args->start.srcdevid,
+- args->start.srcdev_name,
+- args->start.cont_reading_from_srcdev_mode);
++ args->start.srcdev_name, mode, flags);
+ args->result = ret;
+ /* don't warn if EINPROGRESS, someone else might be running scrub */
+ if (ret == BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS ||
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index a3b0edf4025ce..4cf6672459e3a 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -379,6 +379,8 @@ struct btrfs_dev_replace {
+
+ /* See #define above */
+ u64 cont_reading_from_srcdev_mode;
++ /* BTRFS_DEV_REPLACE_ITEM_* flags, stored with the mode in the item */
++ u64 flags;
+
+ int is_valid;
+ int item_needs_writeback;
+diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
+index 3f888366c1442..42837969d572a 100644
+--- a/fs/btrfs/scrub.c
++++ b/fs/btrfs/scrub.c
+@@ -2976,6 +2976,16 @@ int scrub_enumerate_chunks(struct scrub_ctx *sctx,
+ ret = -EIO;
+ break;
+ }
++ if (unlikely(sctx->is_dev_replace &&
++ (dev_replace->flags &
++ BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE) &&
++ atomic64_read(&dev_replace->num_uncorrectable_read_errors) > 0)) {
++ btrfs_err(fs_info,
++ "dev_replace: %lld uncorrectable read errors, aborting as requested",
++ atomic64_read(&dev_replace->num_uncorrectable_read_errors));
++ ret = -EIO;
++ break;
++ }
+ if (sctx->stat.malloc_errors > 0) {
+ ret = -ENOMEM;
+ break;
+diff --git a/include/uapi/linux/btrfs.h b/include/uapi/linux/btrfs.h
+index b6f196bfa600a..e53650a60d8a4 100644
+--- a/include/uapi/linux/btrfs.h
++++ b/include/uapi/linux/btrfs.h
+@@ -201,6 +201,19 @@ struct btrfs_ioctl_scrub_args {
+
+ #define BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS 0
+ #define BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID 1
++/*
++ * The low 32 bits of cont_reading_from_srcdev_mode hold one of the modes
++ * above, the high 32 bits hold flags. Kernels that do not know a flag
++ * fail the start with -EINVAL (before this flag existed) or -EOPNOTSUPP.
++ */
++#define BTRFS_IOCTL_DEV_REPLACE_MODE_MASK 0xffffffffULL
++/*
++ * Cancel the replace, with -EIO, when a sector that is in use cannot be
++ * read from any copy. Without it such sectors are counted and skipped.
++ */
++#define BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE (1ULL << 32)
++#define BTRFS_IOCTL_DEV_REPLACE_SUPPORTED_FLAGS \
++ (BTRFS_IOCTL_DEV_REPLACE_ABORT_ON_UNCORRECTABLE)
+ struct btrfs_ioctl_dev_replace_start_params {
+ __u64 srcdevid; /* in, if 0, use srcdev_name instead */
+ __u64 cont_reading_from_srcdev_mode; /* in, see #define
+diff --git a/include/uapi/linux/btrfs_tree.h b/include/uapi/linux/btrfs_tree.h
+index 47ee52859b458..6eb00d5c00b77 100644
+--- a/include/uapi/linux/btrfs_tree.h
++++ b/include/uapi/linux/btrfs_tree.h
+@@ -1141,6 +1141,13 @@ struct btrfs_dev_stats_item {
+
+ #define BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS 0
+ #define BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID 1
++/*
++ * Flags in the high 32 bits of cont_reading_from_srcdev_mode, same values as
++ * the BTRFS_IOCTL_DEV_REPLACE_* flags. Older kernels ignore them and read
++ * the mode as BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS.
++ */
++#define BTRFS_DEV_REPLACE_ITEM_MODE_MASK 0xffffffffULL
++#define BTRFS_DEV_REPLACE_ITEM_ABORT_ON_UNCORRECTABLE (1ULL << 32)
+
+ struct btrfs_dev_replace_item {
+ /*
+--
+2.47.3
+
--- /dev/null
+From 8536334bdfdc30f8f18c85d8867eeb414dbd3ec0 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 29 Oct 2026 12:17:21 -0400
+Subject: [PATCH 09/10] btrfs: mount a single device filesystem with a device
+ replace in progress
+To: linux-btrfs@vger.kernel.org
+
+The target of a device replace has devid BTRFS_DEV_REPLACE_DEVID (0)
+until the replace finishes, and it is not counted in num_devices. On a
+single device filesystem, the superblocks of both the source and the
+target say num_devices == 1, and since v6.7 two changes for single
+device filesystems keep such a pair from being assembled:
+
+- btrfs_skip_registration() does not register a scanned device whose
+ superblock says num_devices == 1, so a device scan skips the target,
+ and only the device given to mount is registered.
+
+- find_fsid_by_device() gives a device whose superblock says
+ num_devices == 1 a temporary fsid when another device with the same
+ fsid is already registered, as it takes it for a clone. So even when
+ the target is registered, the source given to mount is put in a
+ separate btrfs_fs_devices with a temp-fsid.
+
+When a replace was in progress, e.g. suspended by an unmount, the mount
+then fails:
+
+ BTRFS warning (device ...): cannot mount because device replace operation is ongoing and
+ BTRFS warning (device ...): tgtdev (devid 0) is missing, need to run 'btrfs dev scan'?
+ BTRFS error (device ...): failed to init dev_replace: -EIO
+
+and running 'btrfs device scan' as suggested does not help.
+
+Register a scanned device whose superblock has the replace target devid,
+and do not give a temp-fsid to a device of a replace source and target
+pair, i.e. when either the new device or a device already registered
+with that fsid is the replace target. The filesystem can then be
+mounted from the source device after the target has been scanned, as one
+with more devices can, and the replace resumes. The source superblock
+gives no hint of the replace, so it is still not registered by a scan,
+and mounting from the target device still fails.
+
+A stale target superblock is now registered too. The mount then fails
+with "replace without active item, run 'device scan --forget' on the
+target device", as it already does on a filesystem with more devices.
+That needs a target superblock that was not overwritten when its
+replace ended, e.g. after a crash at that point.
+
+Fixes: bc27d6f0aa0e4 ("btrfs: scan but don't register device on single device filesystem")
+Fixes: a5b8a5f9f8355 ("btrfs: support cloned-device mount capability")
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/volumes.c | 32 +++++++++++++++++++++++++++++++-
+ 1 file changed, 31 insertions(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
+index ce78a9441c64f..4c3106acb295e 100644
+--- a/fs/btrfs/volumes.c
++++ b/fs/btrfs/volumes.c
+@@ -586,6 +586,27 @@ static int btrfs_free_stale_devices(dev_t devt, struct btrfs_device *skip_device
+ return ret;
+ }
+
++/*
++ * On a single device filesystem, the source and the target of a device
++ * replace share the fsid and both say num_devices == 1, but they are one
++ * filesystem, not clones. The target has devid BTRFS_DEV_REPLACE_DEVID.
++ */
++static bool is_dev_replace_pair(struct btrfs_fs_devices *fs_devices,
++ const struct btrfs_super_block *disk_super)
++{
++ struct btrfs_device *device;
++
++ if (btrfs_stack_device_id(&disk_super->dev_item) == BTRFS_DEV_REPLACE_DEVID)
++ return true;
++
++ list_for_each_entry(device, &fs_devices->devices, dev_list) {
++ if (device->devid == BTRFS_DEV_REPLACE_DEVID)
++ return true;
++ }
++
++ return false;
++}
++
+ static struct btrfs_fs_devices *find_fsid_by_device(
+ struct btrfs_super_block *disk_super,
+ dev_t devt, bool *same_fsid_diff_dev)
+@@ -644,6 +665,8 @@ static struct btrfs_fs_devices *find_fsid_by_device(
+ /* New device. */
+ if (fsid_fs_devices == NULL) {
+ return NULL;
++ } else if (is_dev_replace_pair(fsid_fs_devices, disk_super)) {
++ return fsid_fs_devices;
+ } else {
+ /* sb::fsid is already used create a new temp_fsid. */
+ *same_fsid_diff_dev = true;
+@@ -1460,8 +1483,15 @@ static bool btrfs_skip_registration(struct btrfs_super_block *disk_super,
+ mutex_unlock(&fs_devices->device_list_mutex);
+ }
+
++ /*
++ * The target of a device replace is not counted in num_devices, so
++ * the source and the target of a replace on a single device filesystem
++ * both say num_devices == 1. The target must be registered, or the
++ * filesystem cannot be mounted while the replace is in progress.
++ */
+ if (!mount_arg_dev && btrfs_super_num_devices(disk_super) == 1 &&
+- !(btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING))
++ !(btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) &&
++ btrfs_stack_device_id(&disk_super->dev_item) != BTRFS_DEV_REPLACE_DEVID)
+ return true;
+
+ return false;
+--
+2.47.3
+
--- /dev/null
+From 1a00c361d1af739637dd7663f72bd20a7a66dcc7 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 29 Oct 2026 17:52:59 -0400
+Subject: [PATCH 10/10] btrfs: scrub: stop scrub and device replace when the
+ filesystem has an error
+To: linux-btrfs@vger.kernel.org
+
+When the filesystem gets an error outside of a transaction commit, e.g.
+when a log tree sync aborts the transaction, __btrfs_handle_fs_error()
+forces it read-only and leaves a running scrub or device replace alone.
+It used to cancel them, but commit 1acd6831d9877 ("Btrfs: avoid risk of
+a deadlock in btrfs_handle_error") removed the cancel, because waiting
+for the scrub to stop from the error handler could deadlock. Only an
+abort in the commit path cancels the scrub, from cleanup_transaction().
+
+Nothing else stops them. Scrub checks only for cancel requests and
+freezing between extents, and at each block group
+btrfs_inc_block_group_ro() takes its sb_rdonly() path, which needs no
+transaction. So the scrub or the replace goes on reading the rest of
+the device, block group by block group, until it reaches the end or the
+filesystem is unmounted. A replace cannot record its progress on the
+read-only filesystem, and at the end btrfs_dev_replace_finishing() fails
+to start a transaction with -EROFS and leaves the replace started, to be
+resumed at the next writable mount from the last committed cursor. No
+data is lost, but all that I/O is wasted, and for a replace it is spent
+on a source device that may be the failing device being replaced.
+
+Make the scrub stop with -EROFS at the next extent once BTRFS_FS_ERROR()
+is set, next to the check for cancel requests, and do not start another
+block group in scrub_enumerate_chunks(). This also keeps the next block
+group from being marked read-only for nothing; on a filesystem whose
+error is set before it is forced read-only, btrfs_inc_block_group_ro()
+would fail to join a transaction and log "failed setting block group
+ro". Nothing waits for the scrub, so the deadlock the cancel had does
+not come back. The scrub ioctl returns -EROFS with the progress up to
+where it stopped. A replace keeps cursor_left at the start of the block
+group it was copying, as with any other error ("btrfs: dev-replace: do
+not skip the rest of a chunk when resuming a replace"), stays started,
+and resumes from there at the next writable mount.
+
+Update the comment in __btrfs_handle_fs_error(), which says that the
+replace goes on until it completes.
+
+Fixes: 1acd6831d9877 ("Btrfs: avoid risk of a deadlock in btrfs_handle_error")
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/messages.c | 13 +++++++------
+ fs/btrfs/scrub.c | 18 ++++++++++++++++++
+ 2 files changed, 25 insertions(+), 6 deletions(-)
+
+diff --git a/fs/btrfs/messages.c b/fs/btrfs/messages.c
+index 0704be7be8719..4c8098794924b 100644
+--- a/fs/btrfs/messages.c
++++ b/fs/btrfs/messages.c
+@@ -177,12 +177,13 @@ void __btrfs_handle_fs_error(struct btrfs_fs_info *fs_info, const char *function
+ btrfs_set_sb_rdonly(sb);
+ btrfs_info(fs_info, "forced readonly");
+ /*
+- * Note that a running device replace operation is not canceled here
+- * although there is no way to update the progress. It would add the
+- * risk of a deadlock, therefore the canceling is omitted. The only
+- * penalty is that some I/O remains active until the procedure
+- * completes. The next time when the filesystem is mounted writable
+- * again, the device replace operation continues.
++ * A running scrub or device replace is not canceled here: waiting for
++ * it would add the risk of a deadlock. It stops on its own with
++ * -EROFS at the next extent or block group it looks at, where scrub
++ * checks BTRFS_FS_ERROR() next to its cancel requests. A device
++ * replace stays in the started state, and continues from the start
++ * of the block group it was copying the next time the filesystem is
++ * mounted writable.
+ */
+ }
+
+diff --git a/fs/btrfs/scrub.c b/fs/btrfs/scrub.c
+index 42837969d572a..5b2b38c2e3664 100644
+--- a/fs/btrfs/scrub.c
++++ b/fs/btrfs/scrub.c
+@@ -2088,6 +2088,7 @@ static int queue_scrub_stripe(struct scrub_ctx *sctx, struct btrfs_block_group *
+ * indicate the reason:
+ * - -ECANCELED - Being explicitly canceled through ioctl.
+ * - -EINTR - Being interrupted by signal or fs/process freezing.
++ * - -EROFS - The filesystem has an error and was forced read-only.
+ */
+ static int should_cancel_scrub(const struct scrub_ctx *sctx)
+ {
+@@ -2097,6 +2098,14 @@ static int should_cancel_scrub(const struct scrub_ctx *sctx)
+ atomic_read(&sctx->cancel_req))
+ return -ECANCELED;
+
++ /*
++ * The filesystem has an error and was forced read-only: a replace can
++ * neither record its progress nor finish, and a scrub must not write
++ * repairs. Stop instead of reading the rest of the device.
++ */
++ if (BTRFS_FS_ERROR(fs_info))
++ return -EROFS;
++
+ /*
+ * The user (e.g. fsfreeze command) or power management (PM)
+ * suspend/hibernate can freeze the fs. And PM suspend/hibernate will
+@@ -2717,6 +2726,15 @@ int scrub_enumerate_chunks(struct scrub_ctx *sctx,
+ while (1) {
+ u64 dev_extent_len;
+
++ /*
++ * Do not start another block group on a filesystem with an
++ * error, see the per-extent check above.
++ */
++ if (BTRFS_FS_ERROR(fs_info)) {
++ ret = -EROFS;
++ break;
++ }
++
+ ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
+ if (ret < 0)
+ break;
+--
+2.47.3
+
uncorrectable sector stops at the end of that block group and leaves the
source in place, including after a resume; no WARN.
+**Patch numbers (2026-10-30).** The series is 10 patches now. Everything
+below up to "Patches 6, 9 and 10" uses the earlier 7-patch numbering, in
+which patch 6 (canceled progress) is now 7 and patch 7 (the abort flag)
+is now 8; 1-5 are unchanged. New: 6 (resume skips the rest of a chunk),
+9 (single device mount with a replace in progress), 10 (stop scrub and
+replace on a filesystem error). Patch 3 also changed after the rows
+below were run: the uncorrectable count is taken before the
+metadata-error abort check (review of 2026-10-29), so that the batch
+that aborts a replace is counted as well; that change was tested with
+its review round, not by the rows below.
+
Kernel under test for the "Current" column: misc-next zb64 568c45b64012
(uname 7.3.0-rc7+ #5, KASAN + lockdep) unless a row says otherwise. The
bzImage on ahive (md5 4383d0bc...) is the same binary as the r5fix
"once per bio" coincide; a multi-sector failed repair write would separate
them further (base: 1 + N).
+## Patches 6, 9 and 10 (2026-10-29/30)
+
+Tests: `replace-resume-gap-test.sh` (rrg; TEST-CATALOG 5r) and
+`scrub-fserror-stop-test.sh` (sfs; catalog 5s), on ehive. Final run on
+the promoted topics, kernels 6.18 #35 (zb64 1a4cb1d219b1) and misc-next
+#27 (zb64 9eaa03da92ed, replace-fixes c48e7d764b4a = this series without
+the patch 3 change above), harness cb6f8e7 / 9f7e61f. Evidence:
+`raid56-wh-harness/forensics/replace-resume-20261029/` (README.md there
+for the mechanism and the unfixed runs, `lane-20261030/` for the final
+runs).
+
+| test | verifies | patch | unfixed | fixed (6.18 #35 and misc-next #27) |
+|---|---|---|---|---|
+| rrg single, drop | umount mid-chunk while a subvolume drop keeps a transaction running; resume; remove the source; read every file | 6 | FAIL: 530 MiB (135680 blocks) EIO, all in the interrupted chunk, replace "finished, 0 errs" (lane 7.3); stock 6.12.90: 536 MiB EIO | PASS: 0 bad blocks, cursor stays at the chunk start |
+| rrg raid1, drop | same, raid1 data | 6 | FAIL: 138784 csum errors on the target (scrub -r), files read from the mirror | PASS: scrub -r 0 csum, raw scan 0 bad |
+| rrg single, idle umount | control: no running transaction at umount | 6 | PASS (hidden since v6.11) | PASS |
+| rrg control | no umount during the replace | 6 | PASS | PASS |
+| rrg onedev, drop | single device filesystem: umount-suspended replace, mount, resume | 9 | crash image does not mount: "failed to init dev_replace: -EIO" | PASS: mounts after a scan of the target, resumes, sha256 0 bad |
+| sfs scrub | scrub after a forced filesystem error | 10 | scrub read on through 5 more block groups, 1235 MiB, 76 s, and reported success | PASS: 0 more block groups, stops within 4 s, -EROFS |
+| sfs replace | replace after a forced filesystem error | 10 | (as scrub) | PASS: 0 more block groups read, stops in 1 s, stays STARTED, resumes clean at the next mount |
+
+No WARNING, BUG, KASAN, lockdep or hung task report (lockdep on,
+debug_locks 1), taint 0. Builds: W=1 fs/btrfs and bzImage at every
+commit of the topic, 0 warnings, both lanes.
+
+Not covered: the other triggers of patch 6 by code reading (the replace
+kthread starting the next chunk between sync_fs and close_ctree; the
+lanes' dev-stats commit at umount); pre-6.11 kernels, which should hit it
+on every mid-chunk umount, were not run; zoned replace resume, which
+skips every chunk regardless, is untouched.
+
## Not covered / open
- Patch 1's commit-failure branch (the commit after the cleanup fails; only
-From 2d41f2a9495dc15edd86861c4e57dcfd6bba3bf6 Mon Sep 17 00:00:00 2001
+From 8a5168fc52bb4f4c8a63561b47b1264a7a003a04 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:48 -0400
+Date: Fri, 30 Oct 2026 22:32:41 -0400
Subject: [PATCH 0/1] btrfs: resize: allow shrinking a missing device
To: linux-btrfs@vger.kernel.org
1 file changed, 28 insertions(+), 4 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
--
2.47.3
-From 2d41f2a9495dc15edd86861c4e57dcfd6bba3bf6 Mon Sep 17 00:00:00 2001
+From 8a5168fc52bb4f4c8a63561b47b1264a7a003a04 Mon Sep 17 00:00:00 2001
From: Qu Wenruo <wqu@suse.com>
Date: Mon, 18 Nov 2019 15:05:25 +0800
Subject: [PATCH 1/1] btrfs: resize: allow shrinking a missing device
-From bc8cd9cac405fb573a08f798266215560f19b234 Mon Sep 17 00:00:00 2001
+From 1944ff74ed890d045c8d8f7346c44c519f6a2dee Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 25 Oct 2026 03:13:40 -0400
-Subject: [RFC PATCH 000/116] btrfs: close the raid56 write hole for datacow with stripe-exclusive allocation
+Date: Fri, 30 Oct 2026 22:32:36 -0400
+Subject: [RFC PATCH 00/85] btrfs: close the raid56 write hole for datacow with stripe-exclusive allocation
To: linux-btrfs@vger.kernel.org
-[RFC draft. The series is described by subtopic, in the order the
-branch will be rebuilt:
-
- 1. Activation by property, basic no-RMW function
- 2. A second property that allows RMW for some writes
- 3. Stripe-only reclaim
- 4. Competing fsync implementations
- 5. stripe_meta (raid56 metadata)
- 6. Debugging code, not for merging
-
-Until then, patch numbers are the current export numbers
-(NNNN-*.patch), and the shortlog below is in the old order. Subtopic 5
-may be dropped; its section says why. REORDER-PLAN.md has the rebuild
-plan.]
-
This series closes the raid56 write hole for datacow data by changing
the allocator. There is no on-disk format change and no journal. The
policy is opt-in, per filesystem, through a property on the top-level
subvolume's root directory.
+It is an RFC. The 85 patches are ordered by subtopic, so that review can
+stop after any of them and a merge could take a prefix:
+
+ 1-35 1. Activation by property, basic no-RMW function
+ 36-44 2. A second property that allows RMW for some writes
+ 45-51 3. Stripe-only reclaim
+ 52-57 4. Competing fsync implementations
+ 58-67 6a. Debugging code, not for merging
+ 68-78 5. stripe_meta (raid56 metadata), which may be dropped
+ 79-85 6b. The parts of the debugging code that need stripe_meta
+
+The debugging code sits before stripe_meta because stripe_meta's patches
+are written against it. A patch that served several subtopics is split:
+its later parts are titled "<subject> (<subtopic> part)" and sit in the
+subtopic they belong to. The series applies on top of reclaim-fixes
+("btrfs: block group reclaim fixes for a full filesystem", 3 patches).
+
The write hole
==============
In-place writes (nodatacow files, writes into preallocated extents)
would reintroduce the hole for other files' committed data, so they are
-forced to COW while stripe_alloc is on. The data relocation inode is
-exempt: its extents live in relocation-class runs that never share a
-stripe with other data (I3). Subtopic 2 turns the forced COW into a
-policy.
+forced to COW while stripe_alloc is on (patch 6). The data relocation
+inode is exempt: its extents live in relocation-class runs that never
+share a stripe with other data (I3). Subtopic 2 turns the forced COW
+into a policy.
Relationship to other strategies
--------------------------------
Prerequisites and related series
================================
-The series applies on its own to the base (99bc6552614f). It was
-developed and tested on top of these separate series, and the
-guarantees below are stated with them applied. Each fixes a
-pre-existing bug that this series' tests found:
+The series applies on top of reclaim-fixes. It was developed and tested
+together with these separate series, and the guarantees below are stated
+with them applied. Each fixes a pre-existing bug that this series' tests
+found:
- raid56-fixes (11 patches for merging):
+ raid56-fixes (12 patches; the first two are Qu Wenruo's "btrfs: raid56:
+ minor fixes to rmw_rbio()"):
- "propagate a split bio's error when the failing split completes
last". Without it, a read of BTRFS_STRIPE_LEN or more over an
unrecoverable sector on a degraded array returns zeros and
the drop described under "A second failure mode" visible.
- Use-after-free and stale-cache fixes in the rbio cache (end_io
wakeups, stolen cached rbios, unhashing a plugged rbio, cached
- rbios of freed extents, the pages of a failed write). This series
- keeps rbios cached longer (patch 75), which makes some of these
- races frequent.
+ rbios of freed extents, and Qu's "don't cache rbio if an error is
+ hit"). This series keeps rbios cached longer (patch 31), which
+ makes some of these races frequent.
- Verification of reconstructed tree blocks, and raid56 repair
fixes (rebuild from Q, device error stats, write-back of the
sectors an RMW repaired).
- raid56-scrub-replace: the harness scrubs deliberately damaged
- filesystems, so its results depend on scrub not giving up at the
- first uncorrectable raid56 sector.
+ raid56-scrub-replace (on top of read-repair-fixes): the harness
+ scrubs deliberately damaged filesystems, so its results depend on
+ scrub not giving up at the first uncorrectable raid56 sector.
deadlock-fixes: three lock-ordering deadlocks found on the soak rig.
None involves raid56.
delalloc-fixes: "drain pending NOCOW writes before making a block
group read-only", found at the fill edge.
-low-space ("hold block groups free for relocation") conflicts with this
-series in the space accounting. The integration of the two exists only
-in the lane's merge (fixups/post-merge.patch in the export).
+low-space ("hold block groups free for relocation") applies on top of
+this series: its relocation reserve uses this series' relocation task
+tracking and reservation flags, and counts only claimable whole stripes
+of a held stripe_alloc group as reserve.
Subtopic 1: activation by property, basic no-RMW function
==========================================================
-Patches (61): 1-6, 8-12, 17, 23-27, 30, 32-37, 40, 41, 43-45, 54, 57,
-60, 62-64, 67-69, 73-77, 79, 82, 84, 86, 87, 89, 91, 92, 95-99, 101,
-109-112.
+Patches 1-35.
Under stripe_alloc, raid56 data is placed so that no partial stripe
write ever reaches a stripe holding committed data.
Mechanisms:
- The claim rule: allocation takes runs of wholly free stripes, including
- runs that span several free space entries or bitmaps (1, 26, 89, 101).
- A failed scan is cached per block group, so an aged group with no
- claimable run costs O(1) per allocation instead of a full scan under
- the free space lock (37).
+ runs that span several free space entries or bitmaps (1, 16). A
+ failed exhaustive scan is remembered per block group, so an aged group
+ with no claimable run costs O(1) per allocation instead of a full scan
+ under the free space lock (16, 22).
- Open runs: one per size band, so a small write lands in a nearly full
open stripe instead of a new one. When an allocation outgrows every
open run, the frontier run grows into the adjacent wholly free stripes
- instead of stranding its tail (2, 9, 10). A stripe covered by a live
- run is never claimed again (12).
-- Run IO is reported through the ordered-extent lifecycle (5, 87), and
- commit retirement closes and drains the runs (6).
+ instead of stranding its tail (2, 8, 9). A stripe covered by a live
+ run is never claimed again (10). Inodes that fsync allocate from
+ private per-inode runs (11); subtopics 2 and 4 build on them.
+- Run IO is reported through the ordered-extent lifecycle (5, 31), and
+ commit retirement closes and drains the runs (6). While stripe_alloc
+ is on, a range-limited writeback writes the whole allocated delalloc
+ range, as zoned does, so the drain never waits for allocated but
+ unsubmitted pages (6).
- Parking: a partial write into an open run keeps its stripe lock and
waits for later writes to the same stripe, which merge into it through
the existing lock_stripe_add() path. It goes down as one full-stripe
- write: one parity computation, no reads (11). Parks end when the
- stripe is covered, when allocation covers it (32), when a waiter kicks
+ write: one parity computation, no reads (10). Parks end when the
+ stripe is covered, when allocation covers it (21), when a waiter kicks
them, or at a deadline: 100 ms, 3 ms for sync writes, with a stuck cap
- of 10 times the deadline (11, 23, 32, 82). An optional congestion
- knob shortens the deadline while the parked backlog is large (35).
+ of 10 times the deadline (10, 21, 22). An optional congestion knob
+ shortens the deadline while the parked backlog is large (24).
- Padding: a partial write whose uncovered sectors hold nothing anyone
has written is zero-filled to a full stripe, with no read phase. The
- zeros are written, so scrub stays consistent (17). A per-sector
+ zeros are written, so scrub stays consistent (12). A per-sector
liveness map decides what may be padded, so padding never zeroes a
- sector an allocation owns (33). A written map, set as raid56 writes
+ sector an allocation owns (22). A written map, set as raid56 writes
complete, lets the first partial write also pad sectors whose write is
still to come; their own write is ordered after the pad by the stripe
- lock (76).
+ lock (32).
- Rbio pinning: a stripe stays in the rbio cache until its run has
written all of it, so a later write into the stripe takes the earlier
sectors from the cache instead of reading them back from the devices
- before the csum tree covers them (75, 79). At most 256 stripes are
- pinned (RBIO_PIN_MAX). Without the pin, a device that returns wrong
+ before the csum tree covers them (31). At most 256 stripes are pinned
+ (RBIO_PIN_MAX); stale pins are swept, and a commit is requested when
+ live pins run low (33). Without the pin, a device that returns wrong
data lost a file on the strip-fault fixture.
- Space accounting: free space in partially filled stripes is "trapped".
It is counted per block group as stripe_unusable, recomputed at commit
for groups whose free space changed, and subtracted from statfs
- f_bavail (8, 54). The claimable whole-stripe supply is counted
- directly (34).
+ f_bavail (7, 26). The claimable whole-stripe supply is counted
+ directly, debit-only between commits (23).
- Admission: data reservations are gated on claimable whole stripes,
with the open-run remainders, a per-extent margin and stripes stranded
behind live runs charged against them, so a write that cannot be
placed gets ENOSPC at write(2) instead of being dropped at writeback
- (24, 25, 36, 57, 60, 110, 111, 112). A group may go read-only only
- while the admitted bytes still fit the remaining supply (40).
+ (14, 15, 23, 25, 27). The charge is rounded to every full-stripe
+ width in use, by division, since the widths are not powers of two
+ (25). If a writeback allocation fails anyway, the stripes its
+ dropped range gives back are quarantined, so the next writer gets
+ ENOSPC instead of the same loss (35). A group may go read-only only
+ while the admitted bytes still fit the remaining supply (25).
- Relocation (balance, device remove, shrink) works under the gate: it
never waits on the gate, it is charged a margin per reservation, it can
fall back to the relocation group, it may allocate data chunks, and its
- runs are kept until relocation ends (41, 43-45, 73, 74, 84).
-- Lifecycle: runtime enable and disable, remount (99), the property
- applied before tree-log replay (77), errored filesystems (68, 69, 96),
- failed mounts and aborted unmounts (63), group deletion and teardown
- (92, 95), and allocation clusters left by the legacy allocator (62,
- 98).
+ runs are kept until relocation ends (3, 25, 30).
+- Lifecycle: runtime enable and disable, remount, and the property
+ applied before tree-log replay (4); errored filesystems (3, 52);
+ allocation clusters left by the legacy allocator (7, 16); teardown of
+ the park timer (10).
- raid5/6 groups with one data stripe, which upstream maps as
- RAID1/RAID1C3 since 49ba3a3c0d67, are left to the normal allocator
- (109), and their free space counts in admission (110).
+ RAID1/RAID1C3 since 49ba3a3c0d67, are left to the normal allocator,
+ and their free space counts in admission (34).
+
+Some fixes that subtopic 1 needs ended up later in the series, because
+they were folded into the patch whose code they touch:
+
+- private runs are matched by subvolume and inode only from patch 57 on
+ (subtopic 4); before it, by inode number alone, so same-numbered inodes
+ of two subvolumes can share a private run;
+- the cleaner's refusal to delete an unused group that still has a stripe
+ run is in patch 43 (subtopic 2);
+- the mount message is printed twice until patch 60 (subtopic 6a)
+ removes the enable path's copy.
+
+They will move forward in the next revision.
Interface:
- The btrfs.stripe_alloc property on the top-level subvolume's root
directory: "setfattr -n btrfs.stripe_alloc -v 1 /mnt" (patch 4).
Removing the xattr turns the policy off. Copies on other inodes,
- such as received or cloned subvolumes, are refused when set and
- ignored when loaded.
-- The property is refused, with a message, without the free space tree,
- with the remap-tree feature, on zoned filesystems and with mixed block
- groups.
+ such as received or cloned subvolumes, are ignored.
+- The property is refused, with a message, with space_cache=v1, with the
+ remap-tree feature, on zoned filesystems and with mixed block groups
+ (4, 6). The free space tree and no cache at all are both fine.
- Mount prints "using stripe-exclusive allocation for raid56 data
(filesystem property)" when the policy is on, and nothing when it is
- off (64). Log replay with the property set prints "stripe_alloc
- property in force for tree-log replay" (77).
+ off (29).
- Without subtopic 5, mount warns that raid56 metadata is not covered
- (27).
+ (17), and every RMW of an uncovered stripe is reported, rate-limited
+ (18).
- sysfs allocation/data/: bytes_stripe_unusable, bytes_stripe_claimable,
- bytes_stripe_open, bytes_stripe_margin, bytes_stripe_stranded.
+ bytes_stripe_open, bytes_stripe_margin, bytes_stripe_stranded,
+ bytes_stripe_quarantine.
- Park tunables in /sys/fs/btrfs/<uuid>/: stripe_park_timeout_ms (100),
stripe_park_sync_timeout_ms (3), stripe_park_congestion (0, off).
-- The enospc_debug space_info dump shows per-group trapped bytes (54).
+- Statistics: stripe_park_stats (13, 19, 21, 24, 31-33) and
+ stripe_run_stats (28, 30; later 47 and 57), and the pad-decline
+ tracepoint (20).
+ These are observability, kept in subtopic 1 because later patches
+ count into them.
+- The enospc_debug space_info dump shows per-group trapped bytes (26).
+ A data writeback allocation that fails with ENOSPC anyway is warned
+ about (15); patch 66 adds the space counters to that line.
Subtopic 2: a property to allow RMW for some writes
===================================================
-Patches (11): 18-21, 56, 58, 66, 85, 90, 100, 103.
+Patches 36-44.
Without this subtopic, stripe_alloc forces COW on nodatacow files and
preallocated extents. A second property lets the administrator allow
Mechanisms:
- While the policy allows in-place writes of a kind, those extents are
- placed in per-inode NOCOW-class runs, keyed by subvolume and inode
- (18, 58, 85).
+ placed in per-inode NOCOW-class runs (36, 43).
- Ownership check, per extent: the fast path accepts the inode's own
runs; the slow path accepts an extent that the committed extent tree
- shows has a single plain ref from the writing inode (19, 56, 100).
+ shows has a single plain ref from the writing inode (40, 43).
Anything that fails (extents from before isolation, reflinked or
snapshotted extents, relocated extents) stays force-COWed. The COWed
rewrite lands in the inode's private run, so a legacy nocow file
migrates itself in one COW generation.
- NOCOW runs survive commits and remounts while the policy allows
in-place writes, so a slowly appended nocow file packs sequentially
- (20, 58). Dead NOCOW runs are closed at commit (66).
-- Sync writes into NOCOW runs are not parked (21).
-- 90, 103: a stripe tail claimed in one lock section, and a dead field
- removed.
+ (43). Dead NOCOW runs are closed at commit (28).
+- Sync writes into NOCOW runs are not parked (40).
Interface: btrfs.stripe_alloc_allow_rmw, on the same root directory, a
word list separated by comma, space or colon. "nodatacow" and
Subtopic 3: stripe-only reclaim
===============================
-Patches (8): 42, 46, 47, 70, 113-116.
+Patches 45-51.
Trapped stripe tails accumulate until something relocates their group.
The stock reclaim trigger keys on used bytes, so it never sees them.
Trapped space is real free space, and balance reclaims it; this
subtopic lets the existing reclaim worker do it without an operator.
+It covers data block groups; patch 71 in subtopic 5 extends it to
+stripe_meta groups.
Mechanisms:
free space is queued for the existing reclaim worker, the way zoned
filesystems recycle zone_unusable space. The trigger runs from the
commit rescan and from the cleaner, needs room for the group's live
- data elsewhere, and has a five-minute hysteresis (46).
-- The worker relocates a queued group even while it has reserved or
- pinned bytes (47), and allocates a chunk to relocate into when the
- claimable supply is short (42).
+ data elsewhere, and has a five-minute hysteresis. The worker
+ relocates a queued group even while it has reserved or pinned bytes
+ (45). It allocates a chunk to relocate into when the claimable
+ supply is short (25, in subtopic 1).
- Compaction: a mostly live group is not relocated whole. Only the
- extents in its partially used stripes move, plus, for data, every
- extent that shares a stripe with one of them, transitively. The group
- stays, writable, with whole stripes. If that would move more than
- half the group's live bytes, the group is relocated whole instead
- (70).
-- Reclaim on demand (114).
-- The reclaim worker relocates with verbose=false and logs nothing.
- Patch 113 logs the start and end of each reclaim with btrfs_debug(),
- off unless enabled through dynamic debug. It was asked for as a
- production diagnostic ("a log message for reclaim that can be enabled
- through dynamic_printk"), so it is placed here, not in subtopic 6.
-- Backoff after ENOSPC (115). Three relocations in a row that fail
- with ENOSPC in one space_info stop reclaim there for 10 minutes.
- Reclaim resumes early when a chunk is added or removed, or when free
- space grows by what the last failed group held. A group that failed
- with ENOSPC is not requeued. The room check also requires metadata
- room for relocation's up-front reservation.
-- Sharing the exclusive operation (116). The worker holds the balance
- exclusive operation, and a long reclaim list used to hold it for the
- whole list: a queued balance, replace or resize waited up to 655 s in
- testing. The worker now releases it after each group and waits 12 s
- (BTRFS_RECLAIM_GAP) before the next. btrfs-progs checks sysfs
- exclusive_operation before calling the ioctl, and with --enqueue it
- sleeps 1-10 s after the notification, so only a gap lets it in; the 12
- s covers that sleep. A direct ioctl caller refused while the worker
- holds the operation makes it stand aside for 60 s after its current
- group. In three traced runs, the longest queued wait fell from 184,
- 176 and about 655 s to 82, 11 and 23 s, at 10-13 groups per 10
- minutes either way. A waiter can still wait behind one long group.
-
-These paths also serve subtopic 5's metadata groups.
+ extents in its partially used stripes move, plus every extent that
+ shares a stripe with one of them, transitively. The group stays,
+ writable, with whole stripes. If that would move more than half the
+ group's live bytes, the group is relocated whole instead (47).
+- Reclaim on demand (50).
+- The reclaim debug lines of reclaim-fixes say whether a group was
+ compacted or relocated, and how much was trapped (49).
+- The ENOSPC backoff of reclaim-fixes also holds for the paths that
+ queue trapped groups (the commit rescan and the cleaner), and the room
+ check also requires metadata room for relocation's up-front
+ reservation (51).
Interface:
- stripe_reclaim_now (write-only): "all" (or "1") queues every group the
reclaim predicate picks, ignoring the hysteresis; a block group's
logical start reclaims that group whatever its trapped space.
-- allocation/<type>/reclaim_backoffs (read-only): how many times reclaim
- backed off after ENOSPC.
-- echo 'file fs/btrfs/block-group.c format "reclaim: " +p' \
- > /sys/kernel/debug/dynamic_debug/control
Subtopic 4: competing fsync implementations
===========================================
-Patches (6): 13-16, 83, 88.
+Patches 52-57.
Subtopic 1 confines the write hole to the running transaction. Inside
it, two log commits can still share a stripe: fsync 1 writes the head
of a stripe, the open run keeps filling it, and a later write's RMW
rewrites the parity that protects fsync 1's data.
-The base (13) settles logged extents at each log commit. Before the
+The base (52) settles logged extents at each log commit. Before the
log super is written, the log commit closes the stripe's run, kicks the
-parked writes for it, and waits for its data IO. Patch 16 kicks the
-parked rbios before the fast fsync's writeback wait, so fsync does not
+parked writes for it, and waits for its data IO. The fast fsync path
+kicks the parked rbios before its writeback wait (10), so fsync does not
pay a park deadline. This closes the hole for completed fsyncs. The
cost is a trapped tail per fsync per touched stripe. Two
implementations pay that cost back:
-- Private runs with carry-forward (14, 15). Each log-active inode
+- Private runs with carry-forward (11, 55). Each log-active inode
(sticky from its first fsync) allocates from its own private LOG run,
and each of its log commits closes that run. The logged extents in
the closed run's final partial stripe are recorded, and the inode's
durable in its old stripe. Steady state is one partial stripe per
inode, and a back-to-back fsync loop rewrites its previous tail each
time.
-- Shared LOG runs per log transaction, the default (83, 88). LOG runs
+- Shared LOG runs per log transaction, the default (57). LOG runs
are keyed by (subvolume, log_transid), so the inodes logging in one log
transaction fill the same stripes. An allocation of a full stripe or
more keeps a private run. A log commit does not close a shared run;
Shared runs are the default because they measured better. On 5 x 8 GiB
raid5 data with raid1 and raid5 metadata, against private runs with
-carry-forward in the same rep (patch 83):
+carry-forward in the same rep (patch 57):
- 16 and 64 writers, and one fsync per inode: 1.2-2.9x the fsyncs/s
(one 64-writer rep of eight: 0.8x), 3-8x fewer device bytes per fsync,
- stripe_log_data_shared (sysfs, boolean, default 1; 0 selects private
runs with carry-forward).
- The "fsync" word of btrfs.stripe_alloc_allow_rmw waives the log-commit
- guarantee: no settle, no LOG steering, no carry. The fsync-window
- exposure of subtopic 1 returns, detectably.
+ guarantee: no settle, no LOG steering, no carry (54, 56). The
+ fsync-window exposure of subtopic 1 returns, detectably.
- Counters in stripe_run_stats: log_settle_waits and log_settle_wait_ns
(both modes), log_carry_ranges and log_carry_bytes (private runs),
log_seals and log_seal_bytes (shared runs).
+Subtopic 6a: debugging code, not for merging
+=============================================
+
+Patches 58-67.
+
+Carried for the test harness:
+
+- The write-hole invariant checker in the raid56 write path
+ (CONFIG_BTRFS_DEBUG), held off during a runtime enable until the
+ legacy allocator's writes have landed (58), and skipping groups that
+ hosted NOCOW runs (61).
+- The meta_rmw counter for RMWs of uncovered stripes (59).
+- Attribution of each data RMW to the reason padding declined (62).
+- The data RMW audit against the committed extent tree
+ (debug/stripe_rmw_audit, debug/stripe_rmw_audit_stats; 63). It
+ holds the full stripe lock, so it reads cached tree blocks only and
+ takes commit_root_sem only when it is free (a miss is counted), and
+ it skips mixed block groups.
+- The per-class breakdown of pins and open runs (64), and ordered
+ extents that end with sectors unwritten, with a rate-limited log line
+ (65).
+- The space counters in the data writeback ENOSPC warning, and on
+ debug builds one line per block group (66, 67). The counters in the
+ warning are a production diagnostic and can move to subtopic 1.
+- space_info/stripe_unusable_rescan (CONFIG_BTRFS_DEBUG), which is part
+ of patch 7 and will be split out.
+
+Patch 60 is not debugging code: it is the part of the mount-message
+patch (29) that removes the enable path's copy of the message, placed
+here because the code it edits arrives with the checker.
+
Subtopic 5: stripe_meta
=======================
-Patches (15): 38, 48-53, 61, 65, 81, 93, 102, 104, 105, 106. (104 and
-105 are comment cleanups of the whole series and stay whatever happens
-to stripe_meta.)
+Patches 68-78.
raid56 metadata gets the data rule. When the metadata or system profile
is raid56 and stripe_alloc is on, tree blocks come from metadata-class
- Completion reports: the extent buffer write endio reports written
blocks to their run, and the two paths that discard a tree block that
- will never be written report it abandoned (38, 102).
+ will never be written report it abandoned (68).
- Two-phase retirement: metadata runs stay open through the commit's
tree building and are closed and drained after the tree blocks are on
disk. Each run is stamped with the transaction that opened it, so a
- stripe only receives blocks of one transaction (38). The drain waits
- without a timeout and dumps the runs once after 60 s (106).
-- Trapped-space accounting for metadata groups (48).
-- Fill edge: the global reserve is backed by usable stripes (49). Two
- transactions' worth of whole-stripe claims are pre-paid, and a reserve
- of whole stripes (the largest group, at most a quarter of the
- space_info) is held back for relocation (50). The global reserve
- steal refuses below that reserve (51), and the transaction machinery's
- own reservations and the read-only flip for relocation may draw on it
- (52, 53). A group made read-only commits first instead of waiting for
- the periodic commit (93).
-- Runtime enable and disable (61), and raid56 system chunks (65).
+ stripe only receives blocks of one transaction (68). The drain waits
+ without a timeout and dumps the runs once after 60 s (77).
+- Trapped-space accounting for metadata groups, and the global reserve
+ backed by usable stripes (68).
+- Fill edge: two transactions' worth of whole-stripe claims are
+ pre-paid, and a reserve of whole stripes (the largest group, at most a
+ quarter of the space_info) is held back for relocation. The global
+ reserve steal refuses below that reserve, and the transaction
+ machinery's own reservations and the read-only flip for relocation may
+ draw on it (72). A group made read-only commits first instead of
+ waiting for the periodic commit (77).
+- Runtime enable and disable (72), and raid56 system chunks (75).
+- Stripe reclaim and compaction of metadata groups (71).
- Log-tree blocks: each log commit gets its own metadata run, keyed by
(root, log_transid, transid), so a later writer never RMWs log blocks
- that an fsync made durable (81). The space returns when the log tree
+ that an fsync made durable (77). The space returns when the log tree
is freed.
+- A mount whose log replay fails, and the unmount of an aborted
+ filesystem, release their open runs (68).
Interface:
bytes_stripe_reserve.
- stripe_log_run (sysfs, default 1): 0 puts log blocks back in the
transaction's metadata runs, which reopens the log-tree hole. It
- exists to measure patch 81 against itself.
-- Patch 38 narrows the mount warning of patch 27 to system chunks, and
- patch 65 removes it.
+ exists to measure patch 77 against itself.
+- Patch 68 narrows the mount warning of patch 17 to system chunks, and
+ patch 75 removes it.
+
+Subtopic 6b (79-85) holds the metadata RMW audit, which says whether a
+metadata RMW rewrites parity over a committed tree block (80), and the
+debugging parts of earlier patches that need stripe_meta. It is not for
+merging and goes if stripe_meta goes.
Why stripe_meta may be dropped
------------------------------
against raid1: create+fsync 0.92-0.93x the files/s, fsync p50
1.08-1.09x, fio 4K randwrite+fsync 0.94-0.95x the IOPS, rm -rf
1.11x the time. The only win was cold stat at 0.82-0.88x the time.
- That bench predates patch 81. With patch 81, device bytes per
+ That bench predates patch 77. With patch 77, device bytes per
fsync were 1.36x raid1's (geomean, 0.95-1.98x), with no consistent
fsync/s win. In theory, raid5 can win only for commits large enough
to fill stripes and perhaps for cold multi-device reads. It loses on
and raid5 used half of raid1's raw space. On churned, near-full or
fsync-heavy filesystems trapping reached 51% (fill edge), 82%
(6-device raid6 fsstress) and 88% (raid6 COW churn), and with patch
- 81 the settled metadata total was 2.15x the plain allocator's. The
+ 77 the settled metadata total was 2.15x the plain allocator's. The
saving disappears or reverses there. Compaction recovers some of it
(metadata 89 -> 24 MiB trapped in stripe-compact-test), but reclaim is
off by default. Not measured: a raid1-metadata arm on the same aged
churn workload.
3. The complexity is high, and so is the risk of metadata stalls and
- deadlocks. Holds. 13 patches are exclusively stripe_meta (+1150 /
- -126 lines), in the reservation, overcommit, global reserve, commit,
- log commit and relocation paths. Of the metadata fix patches, 6 fix
- ENOSPC aborts or liveness (48-53) and 3 fix stalls or deadlocks (81,
- 93, 94). Eight more shared patches were found through metadata, six
- of them for hangs or aborts. At least 5 more defects were folded
- away earlier. One ENOSPC abort class is still open: with a single
- metadata group the reserve is 0, and a tree block that finds no
- claimable stripe aborts the transaction (no acked data lost).
+ deadlocks. Holds. Subtopic 5 is 11 patches, +1137 / -99 lines net, in
+ the reservation, overcommit, global reserve, commit, log commit and
+ relocation paths. Patches 68 and 72 carry the fixes of six ENOSPC
+ aborts and liveness bugs found at the metadata fill edge, and 77 the
+ fix of a stall; more shared fixes were found through metadata, most
+ of them for hangs or aborts. One ENOSPC abort class is still open:
+ with a single metadata group the reserve is 0, and a tree block that
+ finds no claimable stripe aborts the transaction (no acked data
+ lost).
4. It collides with Johannes Thumshirn's recent zoned ENOSPC work and
has the same issues. Partly holds. The problems are the same:
accepts append-only placement and unusable-until-reclaim space, so
upstream has taken this kind of cost for metadata before.
-Dropping stripe_meta removes the 13 patches above (not 104/105), patch
-77 of subtopic 1 (its failure needs raid56 metadata; the raid1-metadata
-crash arm passed without it), about +1211 / -130 lines or 10% of the
-series' insertions, and the metadata hunks of about 9 shared patches.
-The series becomes data-only.
+Dropping stripe_meta removes patches 68-78 and 79-85, about 1430
+inserted lines or 13% of the series, and the metadata hunks of a few
+shared patches. Patch 4 applies the property before tree-log replay;
+that matters for data too, but its failure was only shown with raid56
+metadata. The series becomes data-only.
What users lose: write-hole protection for raid56 metadata, raid56
system chunks and log-tree blocks. A crash plus a lost member can then
write. On stock 7.3, a torn system-chunk write made the chunk tree
unreadable and the degraded mount was refused (sys-chunk-tear-test).
With plain stripe_alloc and raid5 metadata, 174 of 249 sub-stripe
-metadata writes rewrote parity over committed blocks (patch 29).
+metadata writes rewrote parity over committed blocks (measured with
+patch 80).
What users should do instead: use raid1 metadata with raid5 data, or
raid1c3 metadata with raid6 data, which tolerate the same number of lost
-mconvert=raid1c3". raid6 data with raid1c3 metadata is the tested
pairing (r6c3 below).
-Patch 27's mount warning then keeps its original scope, raid56 metadata
-or system chunks:
-
- stripe_alloc does not cover raid56 metadata: the write hole remains
- for metadata, consider converting it to raid1c3/raid1c4
-
-The rate-limited per-write warning ("read-modify-write of full stripe
-N: this block group is not covered by stripe_alloc, the raid56 write
-hole applies to it") is patch 28, which is in subtopic 6. If it should
-stay as a production warning for uncovered metadata, it moves to
-subtopic 1.
-
-Subtopic 6: debugging code, not for merging
-===========================================
-
-Patches (15): 7, 22, 28, 29, 31, 39, 55, 59, 71, 72, 78, 80, 94, 107,
-108.
-
-Carried for the test harness only:
-
-- The write-hole invariant checker in the raid56 write path
- (CONFIG_BTRFS_DEBUG), and the drain at a runtime enable that keeps it
- quiet for writes placed before the policy existed (7, 39).
-- The metadata RMW audit, which says whether a metadata RMW rewrites
- parity over a committed tree block (29, 55, 94).
-- The data RMW audit against the committed extent tree
- (debug/stripe_rmw_audit, debug/stripe_rmw_audit_stats; 72).
-- Attribution of each data RMW to the reason padding declined (71, 107),
- and the pad-decline tracepoint (31).
-- The "write hole applies" warning for RMWs of uncovered groups (28).
-- Statistics: stripe_park_stats (22), stripe_run_stats (59), refused
- pins and rbio-cache high water (78), the per-class breakdown (80), and
- ordered extents that end with sectors unwritten, with a rate-limited
- log line (108).
-- space_info/stripe_unusable_rescan (CONFIG_BTRFS_DEBUG), which is part
- of patch 8 today and will be split out.
-
-Open for the rebuild: whether stripe_park_stats, stripe_run_stats and
-the pad-decline tracepoint (22, 59, 31) are observability that belongs
-in subtopic 1, or debug code for subtopic 6. Later subtopic 1 patches
-increment their counters, and the liveness map (33) and pad-unwritten
-(76) are written against the pad information structure that 31
-introduced. Keeping them in subtopic 1 is a reorder; moving them to 6
-means rewriting 33 and 76.
-
-Some of this code sits in production paths today: the checker's
-RELOC_USED and NOCOW_USED flags are set in the allocation path, 39's
-drain worker runs on every runtime enable, and 28's warning prints on
-production kernels. The rebuild moves those hunks with their patches.
+Patch 17's mount warning then keeps its original scope, raid56 metadata
+or system chunks, and patch 18's rate-limited per-write warning ("this
+block group is not covered by stripe_alloc, the raid56 write hole
+applies to it") reports the RMWs that remain.
Interface and compatibility
===========================
The policy is a property, not a mount option. The kernel applies it
when the root directory inode loads its properties during mount, before
-any user IO, and before tree-log replay when the log is replayed (77).
+any user IO, and before tree-log replay when the log is replayed (4).
So the protection cannot lapse through an fstab edit or a rescue mount,
which are the times a degraded raid56 is most likely to be written. A
-remount does not revert it (99). Setting it on a live filesystem arms
+remount does not revert it (4). Setting it on a live filesystem arms
the policy at once; removing it disables the policy, and the open runs
drain at the next commit.
- zoned filesystems (own allocator, no hole);
- the remap-tree feature (its relocation writes bypass the
ordered-extent accounting);
-- filesystems without the free space tree;
+- space_cache=v1 (its cache inode is overwritten in place during
+ commit);
- mixed data+metadata block groups, permanently. fill_data_csums()
decides by block group whether to verify csums, so in a mixed group
it cannot tell a data stripe from a metadata stripe, and a data fill
For data written through a stripe run, the claim is in fact "no RMW".
The first partial write into a stripe pads the sectors still to come
-(76), and later writes take the earlier sectors from the pinned rbio
-(75). corrupt-churn measures zero data RMWs in stripe_alloc groups.
+(32), and later writes take the earlier sectors from the pinned rbio
+(31). corrupt-churn measures zero data RMWs in stripe_alloc groups.
A second failure mode, no crash required
========================================
The drop is silent upstream. A write error during writeback discards
the extent with no message, and write(2) had already succeeded, so an
application that does not fsync never learns of it. raid56-fixes patch
-1 logs the drop; it is still data loss.
+3 logs the drop; it is still data loss.
The cause is the same as the write hole's, and the same change removes
it: a stripe_alloc write lands only in a wholly free stripe, so it never
reads another file's blocks. The write succeeds, or the filesystem
returns ENOSPC at write(2). Measured: stock 20 dropped extents, the
series 0 (corrupt-devices); with fsstress and a churn writer on the
-damaged columns, stock 370, the series 0 (corrupt-churn). An earlier
-revision left a residual of 32-37 drops in the churn test; it is gone.
+damaged columns, stock 370, the series 0 (corrupt-churn).
Testing
=======
TESTING.md (in the export directory) lists every test with its last
-result, kernel, harness commit and evidence. The summary below is from
-it. The kernel under test for the current results is the misc-next
-lane's integration of all topics (7.3.0-rc7+ #5, KASAN, lockdep and
-BTRFS_DEBUG on), which includes the prerequisite series above.
+result, kernel, harness commit and evidence; its rows use the patch
+numbers of the 116-patch export of 2026-10-25, and a table there maps
+them to these. The summary below is from it. Unless stated otherwise
+the kernel is 7.3.0-rc7+ #5 (2026-10-18; KASAN, lockdep and BTRFS_DEBUG
+on), the misc-next lane's integration of all topics at the time, which
+includes the prerequisite series above.
+
+The series has been rearranged since, without changing what it does:
+the fixes appended over two review rounds were folded into the patches
+they fix, the generic reclaim parts moved to reclaim-fixes, and the
+patches were reordered by subtopic (125 patches became 4 + 86). The
+final tree of that rework equals the tree it started from except for one
+removed dead function. Every patch of the new order builds (fs/btrfs,
+no new warnings, CONFIG_BTRFS_DEBUG on) and the tip links. A review on
+2026-10-29/30 then made the RMW audit (63) non-blocking, moved two sysfs
+counter lines into the patches that add their counters (which emptied
+and removed the last patch, so 4 + 86 became 3 + 85, the fourth reclaim
+patch being a test-only change that is not posted), and moved a
+static_assert in 63 under CONFIG_BTRFS_DEBUG: with BTRFS_DEBUG off,
+raid56.c did not build from 63 on. The topic tip and every changed
+patch build with BTRFS_DEBUG off and on (W=1, no warnings). The
+regression subset was rerun on the reworked lane (2026-10-28, lockdep,
+with a KASAN run on the 6.18 lane), and again after the lane moved to
+the current base with Qu's raid56 patches (2026-10-28/29, KASAN +
+lockdep): all PASS, with one test (retire-wait-abort) skipping
+as on every baseline because the filesystem never reached the error
+state.
Write hole and damage to committed data:
raid56 metadata), retire-bail (an errored filesystem ends the drains),
the nocow lifecycle tests and prealloc-inplace all pass.
-New directed tests each have a negative control: one kernel with
-patches 67, 99, 109, 110 and 111 reverted and the commit in 93 removed
-fails every test that guards one of them.
+New directed tests have negative controls: one kernel with five of the
+fixes reverted and a sixth removed fails the test that guards each of
+them, except that the admission fix for single-data-stripe groups (in
+34) is not shown separately from the rest of 34.
Acceptance suite: 13 tests under a fault present for the whole run,
on a 6-device raid5. In the dead-disk role it passed 13/13 on one host.
Not rerun on this kernel: the silent-corruption role of the acceptance
suite, the 12-hour deadlock soak (last PASS on the 6.18 lane,
2026-09-08), and the raid56-metadata fsync-window characterization
-(162 armed cases, no committed damage; it predates patch 81).
+(162 armed cases, no committed damage; it predates patch 77).
-Not covered by a test of their own: 86 and 101 (need allocation fault
-injection), 100 (a blocking search in a NOWAIT write), and 94, 95, 97
-(lock-order and teardown races, covered only by lockdep and KASAN runs
-of the whole set).
+Not covered by a test of their own: the allocation-failure paths of 3
+and 16 (need fault injection), the NOWAIT extent tree search of 43, and
+the lock-order and teardown races fixed in 10, 12 and 80 (covered only
+by lockdep and KASAN runs of the whole set).
Performance
===========
Small-file writeback, which on stock is 100% sub-stripe RMW, goes to 86%
full-stripe writes with parking, and write rbios drop from 1537 to 335.
A mixed 4K-512K workload goes from 43% to 97% full-stripe writes (patch
-11). The congestion knob, on a throttled moderate stream, keeps three
+10). The congestion knob, on a throttled moderate stream, keeps three
times as many merges and 38% fewer RMW reads than a flat 3 ms deadline
-(patch 35).
+(patch 24).
Packing: on a 4-device raid5 mixed 4K-512K fill, usable capacity at
ENOSPC is 1561 MiB against stock's 1569 MiB (1421 MiB without growing
the frontier run). Trapped space at the end of the fill is 7.2 MiB
(111.1 MiB without growing), and parking collapses the trapped space
-of a mixed forward fill from about 87 MiB to 3 MiB (patches 10, 11).
+of a mixed forward fill from about 87 MiB to 3 MiB (patches 9, 10).
fsync: see subtopic 4 for the two implementations against each other.
The current default has not been re-measured against the stock
Claim cost: an aged 85 TiB raid5 with legacy-packed groups spun its
delalloc workers at 100% CPU, rescanning a whole group for a run that
-did not exist on every 4K allocation. Patch 37 caches the failed scan.
-[6.18 A/B of 2026-08-16, not in the forensics: average claim 1447 us ->
-0.8 us, fsync write storm 48 -> 218 files/s.]
+did not exist on every 4K allocation. Patch 16 remembers the failed
+scan. [6.18 A/B of 2026-08-16, not in the forensics: average claim
+1447 us -> 0.8 us, fsync write storm 48 -> 218 files/s.]
On filesystems that are not raid56, or without the property, the
series' hooks are early returns.
===========
- Trapped space. Free space in partially filled stripes cannot be
- allocated until the whole stripe frees. With churn, patch 10 measured
+ allocated until the whole stripe frees. With churn, patch 9 measured
usable capacity of 1486-1561 MiB against stock's 1569 MiB, depending
on the delete pattern. Stock reaches its full capacity by reusing
every sub-stripe hole, which is the write hole. Balance or subtopic
Relocating a group needs free space outside it, as with any balance.
- Admission is pessimistic by design: it refuses early rather than admit
a write the allocator cannot place, so a fragmented filesystem accepts
- less than its free bytes suggest.
+ less than its free bytes suggest. After a writeback ENOSPC, the
+ quarantine (35) refuses writes until real frees or a new group arrive.
- Async small-file fills to ENOSPC pay the park deadline. When each
file's neighbours land in the next file's stripe, a partial write
waits out its deadline and the stuck cap before it pads and goes down.
Every write still reaches disk correctly. stripe_park_congestion
shortens this; it is off by default. One large writer is already full
stripes and never parks.
+- While stripe_alloc is on, a small dedupe or clone of a large dirty
+ file waits for the whole allocated delalloc range to be written, as on
+ zoned (6).
- Under raid56 metadata (subtopic 5): the metadata total settles at
- about 2.15x the plain allocator's with patch 81, and without reclaim
+ about 2.15x the plain allocator's with patch 77, and without reclaim
the trapped metadata space grows until unlinks get ENOSPC. raid1 or
raid1c3 metadata has none of this.
- Up to 256 pinned stripes keep their pages in the rbio cache until
- Which fsync implementation to keep, or both (subtopic 4).
- Whether the log-commit protection gets its own property.
- The bg_reclaim_threshold default on non-zoned filesystems.
-- Whether the statistics files and the tracepoint stay (subtopic 6).
The harness, logs and test catalog are available on request.
-Zygo Blaxell (116):
+Zygo Blaxell (85):
btrfs: add btrfs_claim_free_stripe_run() for stripe-exclusive
allocation
btrfs: add open stripe run tracking for stripe-exclusive allocation
btrfs: stripe_alloc: control the policy with a filesystem property
btrfs: report stripe run data IO through the ordered extent lifecycle
btrfs: retire stripe runs at commit and gate stripe_alloc
- btrfs: add a write-hole invariant checker to the raid56 write path
btrfs: account stripe_alloc trapped free space for honest statfs
btrfs: stripe_alloc: keep an open run per size band to trap less
btrfs: stripe_alloc: grow the frontier run instead of stranding its
tail
btrfs: raid56: batch stripe_alloc partial writes into full-stripe
writes
- btrfs: stripe_alloc: never claim stripes covered by a live run
- btrfs: stripe_alloc: settle a logged extent's stripes at log commit
btrfs: stripe_alloc: private per-inode stripe runs for log-active
inodes
- btrfs: stripe_alloc: carry an inode's log tail forward at fsync
- btrfs: stripe_alloc: kick parked rbios before the fast fsync's
- writeback wait
btrfs: raid56: pad sub-stripe writes to full stripes in open runs
- btrfs: stripe_alloc: isolate nodatacow and preallocated extents by
- stripe
- btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated
- nocow extents
- btrfs: stripe_alloc: persist nocow runs across commits and remounts
- btrfs: raid56: do not park sync writes into nocow runs
btrfs: raid56: expose parking statistics in sysfs
- btrfs: raid56: skip parking for sync rbios finished by their unplug
- batch
btrfs: stripe_alloc: count open stripe run remainders against data
reservations
btrfs: stripe_alloc: pessimistic data reservation margin
entries
btrfs: stripe_alloc: warn when raid56 metadata is not covered
btrfs: stripe_alloc: report read-modify-write of uncovered stripes
- btrfs: raid56: say whether a metadata read-modify-write is a write
- hole
btrfs: stripe_alloc: tunable park deadlines, and say why padding
declined
btrfs: stripe_alloc: trace why padding declined, at the moment it
btrfs: raid56: adaptive park deadline from the parked-rbio backlog
btrfs: stripe_alloc: gate data admission on claimable whole-stripe
supply
- btrfs: stripe_alloc: cache a failed stripe run scan per block group
- btrfs: stripe_meta: allocate tree blocks by whole stripes
- btrfs: stripe_alloc: drain the legacy allocator's writes before arming
- the write-hole check at a runtime enable
- btrfs: stripe_alloc: keep the admitted bytes placeable when a group
- goes read-only
- btrfs: stripe_alloc: never let relocation wait on the whole-stripe
- gate
- btrfs: stripe_alloc: give a queued stripe group a chunk to relocate
- into when the supply is short
- btrfs: stripe_alloc: charge relocation a margin per reservation, not
- per extent
- btrfs: stripe_alloc: keep the relocation group's stripes out of the
- admission supply
- btrfs: stripe_alloc: let a data write fall back to the relocation
- group rather than drop
- btrfs: stripe_alloc: hand groups full of trapped free space to the
- reclaim worker
- btrfs: stripe_alloc: relocate a queued stripe group even while it has
- reserved or pinned bytes
- btrfs: stripe_meta: maintain trapped free space for metadata groups
- like data
- btrfs: stripe_meta: back the global reserve with usable stripes, and
- say when a tree block finds none
- btrfs: stripe_meta: hold back whole stripes so tree blocks always land
- and trapped groups can be reclaimed
- btrfs: stripe_meta: do not steal from the global reserve below the
- relocation reserve
- btrfs: stripe_meta: let the transaction machinery's own reservations
- draw on the reserve
- btrfs: stripe_meta: let a group go read-only for relocation against
- the reserve
btrfs: stripe_alloc: show per-group trapped bytes in the space info
dump
- btrfs: stripe_alloc: tell a dead tree block from a live one in the
- metadata RMW audit
- btrfs: stripe_alloc: do not read an inline backref off a keyed-ref
- extent item
btrfs: stripe_alloc: count whole stripes stranded behind live runs as
trapped
- btrfs: stripe_alloc: give nocow extents a private run only while they
- may be written in place
btrfs: stripe_alloc: count nocow run lifecycles and stranded stripes
in sysfs
- btrfs: stripe_alloc: hold a stripe of margin across a preallocation
- btrfs: stripe_meta: carry raid56 metadata groups through a runtime
- enable or disable
- btrfs: stripe_alloc: return a group's allocation cluster before
- scanning its stripes
- btrfs: stripe_alloc: release open stripe runs when a mount fails or an
- aborted filesystem unmounts
btrfs: stripe_alloc: say at mount whether the policy is on
- btrfs: stripe_meta: cover raid56 system chunks
- btrfs: stripe_alloc: close dead nocow stripe runs at commit
- btrfs: stripe_alloc: do not round a full stripe with power-of-two
- macros
- btrfs: stripe_alloc: do not wait for stripe runs to drain on an
- errored filesystem
- btrfs: stripe_alloc: end the commit-time and log drains on an errored
- filesystem too
- btrfs: stripe_alloc: compact mostly live groups instead of skipping
- them
- btrfs: stripe_alloc: attribute each data read-modify-write to why
- padding declined
- btrfs: stripe_alloc: optionally audit data read-modify-writes against
- the committed extent tree
btrfs: stripe_alloc: keep relocation's stripe runs until relocation
ends
- btrfs: stripe_alloc: let relocation allocate a data chunk before it
- fails
btrfs: stripe_alloc: keep a stripe in the rbio cache until its run has
written all of it
btrfs: stripe_alloc: pad a stripe's allocated sectors whose write is
still to come
- btrfs: stripe_alloc: apply the property before tree-log replay
btrfs: stripe_alloc: count refused rbio pins and track rbio cache high
water
- btrfs: stripe_alloc: sweep stale rbio pins, and commit when live pins
- run low
- btrfs: stripe_alloc: break rbio pins and open stripe runs down by run
- class
- btrfs: stripe_alloc: give each log commit its own metadata stripe run
- btrfs: stripe_alloc: don't make a parked rbio wait for sectors that
- will never be written
- btrfs: stripe_alloc: share LOG data runs per log transaction
- btrfs: stripe_alloc: let relocation allocate as many data chunks as
- its reservation needs
- btrfs: stripe_alloc: key private stripe runs by subvolume and inode
- btrfs: stripe_alloc: do not treat an allocation error as a found
- extent
- btrfs: stripe_alloc: mark an ended ordered extent's sectors written
- btrfs: stripe_alloc: read the shared LOG run mode once per log settle
- btrfs: stripe_alloc: remove only the set bits of a bitmap when
- claiming a split run
- btrfs: stripe_alloc: claim a stripe tail in one free space lock
- section
- btrfs: stripe_alloc: keep the stripe totals consistent with the groups
- during the commit scan
- btrfs: stripe_alloc: do not delete an unused block group that still
- has stripe runs
- btrfs: stripe_meta: commit before waiting for metadata runs when
- making a group read-only
- btrfs: raid56: do not read tree blocks under the stripe lock in the
- metadata RMW audit
- btrfs: raid56: stop the park timer before destroying the raid56
- workqueue
- btrfs: stripe_alloc: order the filesystem error before waking stripe
- drain waiters
- btrfs: raid56: set a padded rbio's data bitmap under bio_list_lock
- btrfs: stripe_alloc: forget the failed-claim verdict when a cluster
- returns its space
- btrfs: stripe_alloc: do not let a remount revert the stripe_alloc
- property
- btrfs: stripe_alloc: do not block a NOWAIT write in the nocow stripe
- check
- btrfs: stripe_alloc: keep the head of a claimed free space entry under
- the lock
- btrfs: stripe_meta: check the block group lookup when freeing an
- unwritten tree block
- btrfs: stripe_alloc: remove the unused stripe_rmw_opt field
- btrfs: stripe_alloc: correct and trim the block group comments
- btrfs: stripe_alloc: correct and trim the comments outside the block
- group code
- btrfs: stripe_meta: keep waiting for metadata runs that do not drain
- at commit
- btrfs: stripe_alloc: remove pad refusal reasons that no longer exist
- btrfs: stripe_alloc: count and log ordered extents that end with
- sectors unwritten
btrfs: stripe_alloc: skip RAID5/6 groups that are mapped as
RAID1/RAID1C3
- btrfs: stripe_alloc: count single-data-stripe groups' free space in
- write admission
- btrfs: stripe_alloc: account claimable stripes while a trim has them
- out
- btrfs: stripe_alloc: do not miss bitmap free space when debiting a
- trim
- btrfs: log block group reclaim at debug level
+ btrfs: stripe_alloc: do not count a writeback ENOSPC drop's give-back
+ as supply
+ btrfs: stripe_alloc: isolate nodatacow and preallocated extents by
+ stripe
+ btrfs: stripe_alloc: count nocow run lifecycles and stranded stripes
+ in sysfs (allow_rmw part)
+ btrfs: stripe_alloc: keep a stripe in the rbio cache until its run has
+ written all of it (allow_rmw part)
+ btrfs: stripe_alloc: pad a stripe's allocated sectors whose write is
+ still to come (allow_rmw part)
+ btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated
+ nocow extents
+ btrfs: stripe_alloc: tunable park deadlines, and say why padding
+ declined (allow_rmw part)
+ btrfs: stripe_alloc: track per-sector liveness and pad from the map
+ (allow_rmw part)
+ btrfs: stripe_alloc: persist nocow runs across commits and remounts
+ btrfs: stripe_alloc: count open stripe run remainders against data
+ reservations (allow_rmw part)
+ btrfs: stripe_alloc: hand groups full of trapped free space to the
+ reclaim worker
+ btrfs: stripe_alloc: count whole stripes stranded behind live runs as
+ trapped (reclaim part)
+ btrfs: stripe_alloc: compact mostly live groups instead of skipping
+ them
+ btrfs: stripe_alloc: keep relocation's stripe runs until relocation
+ ends (reclaim part)
+ btrfs: stripe_alloc: log compaction and trapped bytes in the reclaim
+ log
btrfs: stripe_alloc: add stripe_reclaim_now to reclaim stripes on
demand
- btrfs: stripe_alloc: back off block group reclaim after repeated
+ btrfs: stripe_alloc: back off stripe reclaim after repeated ENOSPC
+ btrfs: stripe_alloc: settle a logged extent's stripes at log commit
+ btrfs: stripe_alloc: count open stripe run remainders against data
+ reservations (fsync part)
+ btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated
+ nocow extents (fsync part)
+ btrfs: stripe_alloc: carry an inode's log tail forward at fsync
+ btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated
+ nocow extents (fsync part 2)
+ btrfs: stripe_alloc: share LOG data runs per log transaction
+ btrfs: add a write-hole invariant checker to the raid56 write path
+ btrfs: stripe_alloc: report read-modify-write of uncovered stripes
+ (debug part)
+ btrfs: stripe_alloc: say at mount whether the policy is on (debug
+ part)
+ btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated
+ nocow extents (debug part)
+ btrfs: stripe_alloc: attribute each data read-modify-write to why
+ padding declined
+ btrfs: stripe_alloc: optionally audit data read-modify-writes against
+ the committed extent tree
+ btrfs: stripe_alloc: break rbio pins and open stripe runs down by run
+ class
+ btrfs: stripe_alloc: count and log ordered extents that end with
+ sectors unwritten
+ btrfs: stripe_alloc: log the space counters when data writeback hits
ENOSPC
- btrfs: stripe_alloc: let queued exclusive operations in between
- reclaims
+ btrfs: stripe_alloc: do not count a writeback ENOSPC drop's give-back
+ as supply (debug part)
+ btrfs: stripe_meta: allocate tree blocks by whole stripes
+ btrfs: stripe_alloc: keep a stripe in the rbio cache until its run has
+ written all of it (stripe_meta part)
+ btrfs: stripe_alloc: skip RAID5/6 groups that are mapped as
+ RAID1/RAID1C3 (stripe_meta part)
+ btrfs: stripe_meta: extend stripe reclaim to metadata block groups
+ btrfs: stripe_meta: hold back whole stripes so tree blocks always land
+ and trapped groups can be reclaimed
+ btrfs: stripe_alloc: count whole stripes stranded behind live runs as
+ trapped (stripe_meta part)
+ btrfs: stripe_alloc: do not count a writeback ENOSPC drop's give-back
+ as supply (stripe_meta part)
+ btrfs: stripe_meta: cover raid56 system chunks
+ btrfs: stripe_alloc: skip RAID5/6 groups that are mapped as
+ RAID1/RAID1C3 (stripe_meta part 2)
+ btrfs: stripe_alloc: give each log commit its own metadata stripe run
+ btrfs: stripe_alloc: share LOG data runs per log transaction
+ (stripe_meta part)
+ btrfs: stripe_alloc: count and log ordered extents that end with
+ sectors unwritten (debug_meta part)
+ btrfs: raid56: say whether a metadata read-modify-write is a write
+ hole
+ btrfs: stripe_alloc: tunable park deadlines, and say why padding
+ declined (debug_meta part)
+ btrfs: stripe_alloc: trace why padding declined, at the moment it
+ declined (debug_meta part)
+ btrfs: stripe_alloc: attribute each data read-modify-write to why
+ padding declined (debug_meta part)
+ btrfs: raid56: adaptive park deadline from the parked-rbio backlog
+ (debug_meta part)
+ btrfs: stripe_alloc: keep a stripe in the rbio cache until its run has
+ written all of it (debug_meta part)
- fs/btrfs/block-group.c | 3993 ++++++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 314 ++-
+ fs/btrfs/block-group.c | 3870 ++++++++++++++++++++++++++++-
+ fs/btrfs/block-group.h | 313 ++-
fs/btrfs/block-rsv.c | 9 +-
fs/btrfs/btrfs_inode.h | 53 +
- fs/btrfs/defrag.c | 161 ++
+ fs/btrfs/defrag.c | 174 ++
fs/btrfs/defrag.h | 1 +
- fs/btrfs/delalloc-space.c | 63 +-
- fs/btrfs/delalloc-space.h | 5 +-
+ fs/btrfs/delalloc-space.c | 96 +-
+ fs/btrfs/delalloc-space.h | 8 +-
fs/btrfs/direct-io.c | 13 +-
fs/btrfs/disk-io.c | 48 +-
- fs/btrfs/extent-tree.c | 382 ++-
- fs/btrfs/extent-tree.h | 23 +-
+ fs/btrfs/extent-tree.c | 460 +++-
+ fs/btrfs/extent-tree.h | 31 +-
fs/btrfs/extent_io.c | 18 +
fs/btrfs/file.c | 74 +-
- fs/btrfs/free-space-cache.c | 1323 +++++++++-
- fs/btrfs/free-space-cache.h | 21 +
- fs/btrfs/fs.c | 29 +
- fs/btrfs/fs.h | 287 +++
- fs/btrfs/inode.c | 124 +-
+ fs/btrfs/free-space-cache.c | 1335 +++++++++-
+ fs/btrfs/free-space-cache.h | 23 +
+ fs/btrfs/fs.h | 291 +++
+ fs/btrfs/inode.c | 168 +-
fs/btrfs/messages.c | 3 +
- fs/btrfs/ordered-data.c | 84 +
+ fs/btrfs/ordered-data.c | 126 +
fs/btrfs/ordered-data.h | 14 +
fs/btrfs/props.c | 154 ++
fs/btrfs/props.h | 1 +
- fs/btrfs/raid56.c | 1493 ++++++++++-
+ fs/btrfs/qgroup.c | 12 +
+ fs/btrfs/qgroup.h | 3 +
+ fs/btrfs/raid56.c | 1509 ++++++++++-
fs/btrfs/raid56.h | 34 +
fs/btrfs/relocation.c | 302 ++-
fs/btrfs/relocation.h | 2 +-
- fs/btrfs/space-info.c | 340 ++-
- fs/btrfs/space-info.h | 87 +-
+ fs/btrfs/space-info.c | 552 +++-
+ fs/btrfs/space-info.h | 83 +-
fs/btrfs/super.c | 42 +
- fs/btrfs/sysfs.c | 428 ++++
+ fs/btrfs/sysfs.c | 432 ++++
fs/btrfs/tests/btrfs-tests.c | 6 +
- fs/btrfs/tests/free-space-tests.c | 490 ++++
+ fs/btrfs/tests/free-space-tests.c | 497 ++++
fs/btrfs/transaction.c | 74 +
fs/btrfs/transaction.h | 10 +
fs/btrfs/tree-log.c | 56 +
fs/btrfs/zoned.c | 10 -
fs/btrfs/zoned.h | 3 -
include/trace/events/btrfs.h | 60 +
- 42 files changed, 10553 insertions(+), 133 deletions(-)
+ 43 files changed, 10876 insertions(+), 146 deletions(-)
-base-commit: 99bc6552614f6b25a4a6f07789300d65d384d6ed
+base-commit: bf921b86bdf225f19ffd41533f5c779fba99012e
+prerequisite-patch-id: d27f13acdb7e1fb211a9524027f3f1c8c119f80b
+prerequisite-patch-id: 3ba444b908adb7eb7dd36a0bac6a3816516935c4
+prerequisite-patch-id: 9eebec1e5af9c3767f7de46e5a2406a7d140b135
--
2.47.3
-From 9b74e9eed7b1269451a10e04c2dbd5ffaf04f20b Mon Sep 17 00:00:00 2001
+From 81d6ce66c3eec1d688dde8c89f22d519a2a9784f Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 19 Sep 2026 13:17:26 -0400
-Subject: [RFC PATCH 001/116] btrfs: add btrfs_claim_free_stripe_run() for
+Subject: [RFC PATCH 01/85] btrfs: add btrfs_claim_free_stripe_run() for
stripe-exclusive allocation
To: linux-btrfs@vger.kernel.org
The raid56 stripe allocation policy will be its first non-test user.
Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
---
fs/btrfs/free-space-cache.c | 165 +++++++++++++++++++++++
fs/btrfs/free-space-cache.h | 2 +
-From edb82fe6c54fbdac3bdb6a7db37bc79827b5117d Mon Sep 17 00:00:00 2001
+From 54e8674b89c106739d94508eee48be798fca3d58 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 19 Sep 2026 13:17:26 -0400
-Subject: [RFC PATCH 002/116] btrfs: add open stripe run tracking for
+Subject: [RFC PATCH 02/85] btrfs: add open stripe run tracking for
stripe-exclusive allocation
To: linux-btrfs@vger.kernel.org
policy and the commit hook will be the first non-test users.
Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/block-group.c | 348 ++++++++++++++++++++++++++++++
- fs/btrfs/block-group.h | 27 +++
+ fs/btrfs/block-group.c | 343 ++++++++++++++++++++++++++++++
+ fs/btrfs/block-group.h | 26 +++
fs/btrfs/disk-io.c | 2 +
fs/btrfs/fs.h | 9 +
fs/btrfs/tests/btrfs-tests.c | 6 +
fs/btrfs/tests/free-space-tests.c | 127 +++++++++++
- 6 files changed, 519 insertions(+)
+ 6 files changed, 513 insertions(+)
diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 027830a53f7dc..9a5d80f77f3f7 100644
+index 0c8ce98021a41..22256a91ef3a6 100644
--- a/fs/btrfs/block-group.c
+++ b/fs/btrfs/block-group.c
-@@ -440,6 +440,350 @@ void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
+@@ -440,6 +440,345 @@ void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
}
+ return ret;
+}
+
-+/*
-+ * Report completed (or abandoned) data IO for an allocation made with
-+ * btrfs_alloc_from_open_stripe(). Every allocated byte must be reported
-+ * exactly once, in any number of pieces (e.g. after ordered extent splits).
-+ */
+void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+ u64 num_bytes)
+{
struct btrfs_caching_control *btrfs_get_caching_control(
struct btrfs_block_group *cache)
{
-@@ -2435,9 +2779,13 @@ static struct btrfs_block_group *btrfs_create_block_group(
+@@ -2536,9 +2875,13 @@ static struct btrfs_block_group *btrfs_create_block_group(
refcount_set(&cache->refs, 1);
spin_lock_init(&cache->lock);
INIT_LIST_HEAD(&cache->ro_list);
INIT_LIST_HEAD(&cache->discard_list);
diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index d567ed822e55d..3fb0e5dfc0adf 100644
+index f0bf50033d4b1..2e7d5afdaf705 100644
--- a/fs/btrfs/block-group.h
+++ b/fs/btrfs/block-group.h
@@ -18,6 +18,7 @@
struct btrfs_trans_handle;
enum btrfs_block_group_size_class {
-@@ -196,6 +197,24 @@ struct btrfs_block_group {
+@@ -196,6 +197,23 @@ struct btrfs_block_group {
*/
struct list_head cluster_list;
+ /*
+ * Open stripe runs for stripe-exclusive (raid56 write hole safe)
+ * allocation. The runs list, the open_stripe pointer and all run
-+ * fields are protected by stripe_run_lock, which is irq-safe
-+ * because completed data IO is reported from bio end_io context;
-+ * see the "Open stripe runs" comment in block-group.c.
++ * fields are protected by stripe_run_lock; see the "Open stripe runs"
++ * comment in block-group.c.
+ */
+ spinlock_t stripe_run_lock;
+ struct list_head open_stripe_runs;
/*
* Used for several lists:
*
-@@ -322,6 +341,14 @@ void btrfs_put_block_group(struct btrfs_block_group *cache);
+@@ -322,6 +340,14 @@ void btrfs_put_block_group(struct btrfs_block_group *cache);
void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
const u64 start);
void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg);
-From 37db945f876b595303f82b8a24d1bb29a8771479 Mon Sep 17 00:00:00 2001
+From 5c0d8a2033b534af23e2bad0e41dd8635374693d Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 19 Sep 2026 13:17:26 -0400
-Subject: [RFC PATCH 003/116] btrfs: add the stripe_alloc allocation policy for
+Subject: [RFC PATCH 03/85] btrfs: add the stripe_alloc allocation policy for
raid56 data
To: linux-btrfs@vger.kernel.org
the stripe_run_lock so no run can survive into or be created in a
read-only group.
+A write admitted just before a group was dedicated to relocation may still
+need that group's stripes, so the dedication excludes the group only from
+the allocator's first passes: a write no other group can serve falls back
+to it once the search reaches the chunk-allocation loop. The class tag
+already keeps the two sides out of each other's stripes; zoned's hard
+exclusion follows from append-only zones, which do not apply here.
+
+An error from the stripe allocation itself (-ENOMEM for a run) skips the
+group like any other failure, and is returned instead of -ENOSPC when no
+other group has space. It is never taken as a found extent, which would
+reserve an offset this group did not set.
+
+On a filesystem that has gone into error, the drain waits for a read-only
+group's runs and for the retirement of the open runs end at once: after a
+transaction abort the ordered extents holding a run's bytes in flight are
+only torn down at unmount, so the waits would never return (a reclaim
+worker hung in btrfs_inc_block_group_ro() on a degraded raid6 whose commit
+had hit ENOSPC, and the same wait would park the transaction kthread or
+wedge close_ctree()). The runs are left as they are, released at teardown,
+and a warning says when runs were left in flight.
+__btrfs_handle_fs_error() wakes the drain waiters, after the full barrier
+wake_up_var() needs when the condition is not set under a lock.
+
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 | 214 +++++++++++++++++++++---------
- fs/btrfs/block-group.h | 19 ++-
- fs/btrfs/extent-tree.c | 65 +++++++++
+ fs/btrfs/block-group.c | 268 ++++++++++++++++++++++--------
+ fs/btrfs/block-group.h | 20 ++-
+ fs/btrfs/extent-tree.c | 91 +++++++++-
fs/btrfs/fs.h | 1 +
+ fs/btrfs/messages.c | 3 +
fs/btrfs/relocation.c | 6 +
- fs/btrfs/tests/free-space-tests.c | 101 +++++++++++---
+ fs/btrfs/tests/free-space-tests.c | 101 ++++++++---
fs/btrfs/zoned.c | 10 --
fs/btrfs/zoned.h | 3 -
- 8 files changed, 322 insertions(+), 97 deletions(-)
+ 9 files changed, 401 insertions(+), 102 deletions(-)
diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 9a5d80f77f3f7..7a1b2c5b91484 100644
+index 22256a91ef3a6..90fc365ec782b 100644
--- a/fs/btrfs/block-group.c
+++ b/fs/btrfs/block-group.c
@@ -491,6 +491,7 @@ struct btrfs_open_stripe_run {
*ret_offset = start;
new_run = NULL;
ret = 0;
-@@ -678,33 +703,43 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+@@ -673,33 +698,43 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
}
/*
}
/* No run opened before @seq remains (open or draining). */
-@@ -784,6 +819,46 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info)
+@@ -725,12 +760,46 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
+ * prevent new allocations first (e.g. the block group is read-only),
+ * otherwise this can wait forever. Membership in fs_info->open_stripe_bgs
+ * is left for the next retire walk to collect.
++ *
++ * The wait also ends when the filesystem is in error: after a transaction
++ * abort the ordered extents holding a run's bytes may never complete. The
++ * runs are then left for btrfs_free_open_stripe_runs() at teardown.
+ */
+ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
+ {
++ struct btrfs_fs_info *fs_info = bg->fs_info;
++
+ close_block_group_stripe_runs(bg, U64_MAX);
+ wait_var_event(&bg->open_stripe_runs,
+- bg_open_stripes_settled(bg, U64_MAX));
++ bg_open_stripes_settled(bg, U64_MAX) ||
++ BTRFS_FS_ERROR(fs_info));
++ if (BTRFS_FS_ERROR(fs_info) && !bg_open_stripes_settled(bg, U64_MAX))
++ btrfs_warn(fs_info,
++"block group %llu read-only with stripe runs still in flight after a filesystem error; not waiting for them",
++ bg->start);
++}
++
++/*
++ * The filesystem has gone into error: wake every task waiting for a block
++ * group's stripe runs to drain, so the waits that give up on an error
++ * (btrfs_retire_block_group_stripes()) notice it. A run's own completion
++ * reports may never arrive now.
++ */
++void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info)
++{
++ struct btrfs_block_group *bg;
++
++ /*
++ * The caller set fs_error without a lock, and wake_up_var() checks
++ * for waiters without one: order the store before that check, or a
++ * waiter that has just tested BTRFS_FS_ERROR is missed. Pairs with
++ * the barrier in prepare_to_wait_event().
++ */
++ smp_mb();
++ spin_lock(&fs_info->open_stripe_lock);
++ list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
++ wake_up_var(&bg->open_stripe_runs);
++ spin_unlock(&fs_info->open_stripe_lock);
+ }
+
+ /*
+@@ -759,8 +828,19 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info)
+ while (!list_empty(&retire_list)) {
+ bg = list_first_entry(&retire_list, struct btrfs_block_group,
+ open_stripe_retire_list);
++ /*
++ * Same escape as btrfs_retire_block_group_stripes(): on an
++ * errored filesystem the bytes in flight may never be
++ * reported, and this wait sits in the transaction commit and
++ * in the teardown call from close_ctree().
++ */
+ wait_var_event(&bg->open_stripe_runs,
+- bg_open_stripes_settled(bg, seq));
++ bg_open_stripes_settled(bg, seq) ||
++ BTRFS_FS_ERROR(fs_info));
++ if (BTRFS_FS_ERROR(fs_info) && !bg_open_stripes_settled(bg, seq))
++ btrfs_warn(fs_info,
++"block group %llu has stripe runs still in flight at retirement after a filesystem error; not waiting for them",
++ bg->start);
+ list_del_init(&bg->open_stripe_retire_list);
+
+ /* Drop the membership if the group has no runs left. */
+@@ -779,6 +859,46 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info)
}
}
struct btrfs_caching_control *btrfs_get_caching_control(
struct btrfs_block_group *cache)
{
-@@ -1514,6 +1589,11 @@ int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
+@@ -1509,6 +1629,11 @@ int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
btrfs_clear_treelog_bg(block_group);
btrfs_clear_data_reloc_bg(block_group);
path = btrfs_alloc_path();
if (unlikely(!path)) {
-@@ -3581,6 +3661,14 @@ int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
+@@ -2511,7 +2636,10 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
+ LIST_HEAD(retry_list);
+ int reclaimed = 0;
+
+- /* Relocation cannot proceed on an errored filesystem. */
++ /*
++ * Relocation cannot proceed, and the stripe drain it starts with
++ * would wait for IO that will not complete.
++ */
+ if (BTRFS_FS_ERROR(fs_info))
+ return;
+
+@@ -3677,6 +3805,14 @@ int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
mutex_unlock(&fs_info->ro_block_group_mutex);
btrfs_end_transaction(trans);
}
diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 3fb0e5dfc0adf..2fabfd813f860 100644
+index 2e7d5afdaf705..ca43f0c5c8d27 100644
--- a/fs/btrfs/block-group.h
+++ b/fs/btrfs/block-group.h
@@ -21,6 +21,17 @@ struct btrfs_inode;
enum btrfs_block_group_size_class {
/* Unset */
BTRFS_BG_SZ_NONE,
-@@ -206,7 +217,7 @@ struct btrfs_block_group {
+@@ -205,7 +216,7 @@ struct btrfs_block_group {
*/
spinlock_t stripe_run_lock;
struct list_head open_stripe_runs;
/*
* Membership in fs_info->open_stripe_bgs, protected by
* fs_info->open_stripe_lock; holds a block group reference.
-@@ -342,13 +353,17 @@ void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
+@@ -341,13 +352,18 @@ void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
const u64 start);
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,
u64 num_bytes);
+void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
++void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info);
+void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg);
+void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info);
u64 bytenr);
void btrfs_dec_nocow_writers(struct btrfs_block_group *bg);
diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 9b0a5c6b96f3c..cce38377da1ee 100644
+index 9b0a5c6b96f3c..196ac04c08aca 100644
--- a/fs/btrfs/extent-tree.c
+++ b/fs/btrfs/extent-tree.c
-@@ -4191,12 +4191,77 @@ static int do_allocation_zoned(struct btrfs_block_group *block_group,
+@@ -4191,12 +4191,87 @@ static int do_allocation_zoned(struct btrfs_block_group *block_group,
return ret;
}
+ }
+ if (fs_info->data_reloc_bg &&
+ (ffe_ctl->for_data_reloc !=
-+ (block_group->start == fs_info->data_reloc_bg)))
-+ skip = true;
++ (block_group->start == fs_info->data_reloc_bg))) {
++ /*
++ * Relocation stays in its group. Others avoid it only while
++ * other groups can serve them: the dedication can land after a
++ * write was admitted against this group's stripes, and refusing
++ * that write here would drop its data. Runs are tagged by
++ * class, so the two never share a stripe either way.
++ */
++ if (ffe_ctl->for_data_reloc ||
++ ffe_ctl->loop < LOOP_ALLOC_CHUNK)
++ skip = true;
++ }
+ spin_unlock(&fs_info->relocation_bg_lock);
+ if (skip)
+ return 1;
return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
case BTRFS_EXTENT_ALLOC_ZONED:
return do_allocation_zoned(block_group, ffe_ctl, bg_ret);
+@@ -4561,6 +4636,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
+ struct btrfs_fs_info *fs_info = root->fs_info;
+ int ret = 0;
+ int cache_block_group_error = 0;
++ int alloc_error = 0;
+ struct btrfs_block_group *block_group = NULL;
+ struct btrfs_space_info *space_info;
+ bool full_search = false;
+@@ -4745,6 +4821,17 @@ static noinline int find_free_extent(struct btrfs_root *root,
+ ret = do_allocation(block_group, ffe_ctl, &bg_ret);
+ if (ret > 0)
+ goto loop;
++ if (ret < 0) {
++ /*
++ * The stripe allocator could not allocate its run
++ * tracking (-ENOMEM). ffe_ctl->found_offset is not
++ * valid; try the other groups and report the error
++ * if none of them has space.
++ */
++ if (!alloc_error)
++ alloc_error = ret;
++ goto loop;
++ }
+
+ if (bg_ret && bg_ret != block_group) {
+ btrfs_release_block_group(block_group, ffe_ctl->delalloc);
+@@ -4808,7 +4895,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
+ if (ret > 0)
+ goto search;
+
+- if (ret == -ENOSPC && !cache_block_group_error) {
++ if (ret == -ENOSPC && !cache_block_group_error && !alloc_error) {
+ /*
+ * Use ffe_ctl->total_free_space as fallback if we can't find
+ * any contiguous hole.
+@@ -4820,7 +4907,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
+ spin_unlock(&space_info->lock);
+ ins->offset = ffe_ctl->max_extent_size;
+ } else if (ret == -ENOSPC) {
+- ret = cache_block_group_error;
++ ret = cache_block_group_error ?: alloc_error;
+ }
+ return ret;
+ }
diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
index a09fee118dd11..b085e198f23da 100644
--- a/fs/btrfs/fs.h
};
/* These mount options require a full read-only fs, no new transaction is allowed. */
+diff --git a/fs/btrfs/messages.c b/fs/btrfs/messages.c
+index 0704be7be8719..785986c59ab6e 100644
+--- a/fs/btrfs/messages.c
++++ b/fs/btrfs/messages.c
+@@ -4,6 +4,7 @@
+ #include "messages.h"
+ #include "discard.h"
+ #include "super.h"
++#include "block-group.h"
+
+ #ifdef CONFIG_PRINTK
+
+@@ -163,6 +164,8 @@ void __btrfs_handle_fs_error(struct btrfs_fs_info *fs_info, const char *function
+ * send it down to the disk.
+ */
+ WRITE_ONCE(fs_info->fs_error, error);
++ /* Waiters for stripe run drains give up on an error; tell them. */
++ btrfs_wake_open_stripe_waiters(fs_info);
+
+ /* Don't go through full error handling during mount. */
+ if (!(sb->s_flags & SB_BORN))
diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
index b2ac5b836b217..b810115db9603 100644
--- a/fs/btrfs/relocation.c
out:
cache->full_stripe_len = orig_fsl;
diff --git a/fs/btrfs/zoned.c b/fs/btrfs/zoned.c
-index 1fa855a0c31a8..4082ac106551e 100644
+index 3192b86669b9b..49359bbe6df37 100644
--- a/fs/btrfs/zoned.c
+++ b/fs/btrfs/zoned.c
-@@ -2797,16 +2797,6 @@ void btrfs_schedule_zone_finish_bg(struct btrfs_block_group *bg,
+@@ -2802,16 +2802,6 @@ void btrfs_schedule_zone_finish_bg(struct btrfs_block_group *bg,
queue_work(system_dfl_wq, &bg->zone_finish_work);
}
-From 26dd0509689daee7517c91dc14320aba5f01fde2 Mon Sep 17 00:00:00 2001
+From a5e9eaa5277931ed08c3260641b01c767d505fa6 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 19 Sep 2026 13:17:26 -0400
-Subject: [RFC PATCH 004/116] btrfs: stripe_alloc: control the policy with a
+Subject: [RFC PATCH 04/85] btrfs: stripe_alloc: control the policy with a
filesystem property
To: linux-btrfs@vger.kernel.org
recovery boot -- which is exactly when a degraded raid56 is most likely
to be written.
-Control the policy with a "stripe_alloc" filesystem property,
-following the property system's compression precedent: a btrfs.
-namespace xattr, user-visible and admin-controlled, on the top-level
+Control the policy with a "stripe_alloc" filesystem property, following
+the property system's compression precedent: an xattr in the btrfs.*
+namespace, user-visible and admin-controlled, on the top-level
subvolume's root directory. Set it once (setfattr -n btrfs.stripe_alloc
-v 1, or btrfs property once btrfs-progs learns the name) and it is
persistent: the kernel applies it when the root directory inode loads
its properties during mount, before any user IO. Deleting the xattr
-disables the policy; open runs drain at the next commit's retirement,
-which runs unconditionally. Stray copies of the xattr -- a received or
-cloned subvolume -- are ignored: only the top-level root carries the
-policy, so receiving a stream from a stripe_alloc filesystem cannot
-flip the policy on the destination.
+disables the policy; open runs drain at the next commit's retirement
+(added later in this series), which runs whether or not the policy is
+on. Stray copies of the xattr -- a received or cloned subvolume -- are
+ignored: only the top-level root carries the policy, so receiving a
+stream from a stripe_alloc filesystem cannot flip the policy on the
+destination.
-The support checks (free space tree, not zoned, no remap-tree, not
+The support checks (no space_cache=v1, not zoned, no remap-tree, not
mixed block groups) are enforced both when the property is set and when
it is applied at mount. The mixed block group test matters most here:
without it the property would enable a policy the series does not
than widening this one, so their testing exposure can be controlled
independently.
+The property is also applied before tree-log replay, which allocates and
+commits: without the policy its allocations can land in the free sectors
+of partially written stripes next to committed data. The xattr item is
+read directly rather than through an inode, since replay may rewrite the
+root directory's inode item; the root directory's load after replay still
+applies the final state.
+
+A remount copies the whole mount_opt word from its fs_context snapshot, so
+the current STRIPE_ALLOC value is carried into the context first, or a
+property change made after the context was created would be undone
+without its enable or disable work.
+
Assisted-by: Claude:claude-fable-5
-(cherry picked from commit ecd4d3de8a0493f7c406d919d533f88e8b45390c)
+Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/block-group.c | 70 ++++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/block-group.h | 3 ++
- fs/btrfs/disk-io.c | 24 +++++++++++++++
- fs/btrfs/props.c | 65 +++++++++++++++++++++++++++++++++++++++
- 4 files changed, 162 insertions(+)
+ fs/btrfs/block-group.c | 70 ++++++++++++++++++++++++++
+ fs/btrfs/block-group.h | 3 ++
+ fs/btrfs/disk-io.c | 23 +++++++++
+ fs/btrfs/props.c | 112 +++++++++++++++++++++++++++++++++++++++++
+ fs/btrfs/props.h | 1 +
+ fs/btrfs/super.c | 10 ++++
+ 6 files changed, 219 insertions(+)
diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 7a1b2c5b91484..242a4b074e71d 100644
+index 90fc365ec782b..d424975f7adba 100644
--- a/fs/btrfs/block-group.c
+++ b/fs/btrfs/block-group.c
-@@ -760,6 +760,76 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
+@@ -755,6 +755,76 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
return ret;
}
* Close and drain all of a block group's stripe runs. The caller must
* prevent new allocations first (e.g. the block group is read-only),
diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 2fabfd813f860..93088b93e9496 100644
+index ca43f0c5c8d27..852f74b592aa0 100644
--- a/fs/btrfs/block-group.h
+++ b/fs/btrfs/block-group.h
@@ -361,6 +361,9 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
- u64 num_bytes);
void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
+ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
+int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
+int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
+void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg);
void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info);
diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index ccefc67fcbd68..7540f7d9e3de1 100644
+index ccefc67fcbd68..b1df5fd84a94f 100644
--- a/fs/btrfs/disk-io.c
+++ b/fs/btrfs/disk-io.c
-@@ -3762,6 +3762,30 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
+@@ -47,6 +47,7 @@
+ #include "root-tree.h"
+ #include "defrag.h"
+ #include "uuid-tree.h"
++#include "props.h"
+ #include "relocation.h"
+ #include "scrub.h"
+ #include "super.h"
+@@ -3749,6 +3750,8 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
+ if (btrfs_super_log_root(disk_super) != 0 &&
+ !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
+ btrfs_info(fs_info, "start tree-log replay");
++ /* Replay allocates tree blocks: the policy must hold for them. */
++ btrfs_load_stripe_alloc_prop_early(fs_info);
+ ret = btrfs_replay_log(fs_info, fs_devices);
+ if (ret)
+ goto fail_qgroup;
+@@ -3762,6 +3765,26 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
goto fail_qgroup;
}
+ /*
+ * Load the top-level root directory's properties (the stripe_alloc
-+ * policy) before anything that can allocate data -- the resumed
-+ * balance or dev replace kicked off below -- so filesystem-wide
-+ * policy is in force for every allocation this mount ever makes.
-+ * Log replay above needed no policy: it allocates no new data, only
-+ * re-references extents written before the crash. The iget applies
-+ * the properties as a side effect; the later iget from fill_super
-+ * finds them already applied.
++ * policy) before anything that can allocate data, such as the resumed
++ * balance or dev replace below. The iget applies them as a side
++ * effect; the later iget from fill_super finds them applied.
+ */
+ {
+ struct btrfs_inode *root_dir;
return 0;
diff --git a/fs/btrfs/props.c b/fs/btrfs/props.c
-index 7cc82366a1dfc..311c07cef6771 100644
+index 7cc82366a1dfc..334657a98fdc2 100644
--- a/fs/btrfs/props.c
+++ b/fs/btrfs/props.c
-@@ -15,6 +15,7 @@
+@@ -15,8 +15,10 @@
#include "space-info.h"
#include "fs.h"
#include "accessors.h"
+#include "block-group.h"
#include "super.h"
#include "dir-item.h"
++#include "disk-io.h"
+
+ #define BTRFS_PROP_HANDLERS_HT_BITS 8
+ static DEFINE_HASHTABLE(prop_handlers_ht, BTRFS_PROP_HANDLERS_HT_BITS);
+@@ -283,6 +285,52 @@ static void inode_prop_iterator(void *ctx,
+ set_bit(BTRFS_INODE_HAS_PROPS, &BTRFS_I(inode)->runtime_flags);
+ }
-@@ -370,6 +371,62 @@ static bool prop_compression_ignore(const struct btrfs_inode *inode)
++/*
++ * Apply the btrfs.stripe_alloc property before tree-log replay.
++ *
++ * The property normally takes effect when the top-level root directory's
++ * inode loads (prop_stripe_alloc_apply()), which open_ctree() does after
++ * log replay. Replay allocates tree blocks and commits, and without the
++ * policy those writes may read-modify-write stripes holding committed
++ * metadata.
++ *
++ * Read the xattr item directly: replay may rewrite the root directory's
++ * inode item, and an inode cached across replay would go stale. Only a set
++ * property is acted on here; the load after replay applies the final state
++ * (including any change the log carried) and reports errors.
++ */
++void btrfs_load_stripe_alloc_prop_early(struct btrfs_fs_info *fs_info)
++{
++ static const char name[] = XATTR_BTRFS_PREFIX "stripe_alloc";
++ struct btrfs_dir_item *di;
++ struct btrfs_root *root;
++ struct btrfs_path *path;
++ char value;
++
++ root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
++ if (IS_ERR(root))
++ return;
++ path = btrfs_alloc_path();
++ if (!path)
++ goto out;
++ di = btrfs_lookup_xattr(NULL, root, path, BTRFS_FIRST_FREE_OBJECTID,
++ name, strlen(name), 0);
++ if (IS_ERR_OR_NULL(di))
++ goto out;
++ if (btrfs_dir_data_len(path->nodes[0], di) != 1)
++ goto out;
++ read_extent_buffer(path->nodes[0], &value,
++ (unsigned long)(di + 1) +
++ btrfs_dir_name_len(path->nodes[0], di), 1);
++ btrfs_release_path(path);
++ if (value == '1' && !btrfs_enable_stripe_alloc(fs_info))
++ btrfs_info(fs_info,
++ "stripe_alloc property in force for tree-log replay");
++out:
++ btrfs_free_path(path);
++ btrfs_put_root(root);
++}
++
+ int btrfs_load_inode_props(struct btrfs_inode *inode, struct btrfs_path *path)
+ {
+ struct btrfs_root *root = inode->root;
+@@ -370,6 +418,62 @@ static bool prop_compression_ignore(const struct btrfs_inode *inode)
return false;
}
static const char *prop_compression_extract(const struct btrfs_inode *inode)
{
switch (inode->prop_compress) {
-@@ -393,6 +450,14 @@ static struct prop_handler prop_handlers[] = {
+@@ -393,6 +497,14 @@ static struct prop_handler prop_handlers[] = {
.ignore = prop_compression_ignore,
.inheritable = 1
},
};
int btrfs_inode_inherit_props(struct btrfs_trans_handle *trans,
+diff --git a/fs/btrfs/props.h b/fs/btrfs/props.h
+index 15d9a025c923d..f16ce20f68eee 100644
+--- a/fs/btrfs/props.h
++++ b/fs/btrfs/props.h
+@@ -23,6 +23,7 @@ int btrfs_validate_prop(const struct btrfs_inode *inode, const char *name,
+ bool btrfs_ignore_prop(const struct btrfs_inode *inode, const char *name);
+
+ int btrfs_load_inode_props(struct btrfs_inode *inode, struct btrfs_path *path);
++void btrfs_load_stripe_alloc_prop_early(struct btrfs_fs_info *fs_info);
+
+ int btrfs_inode_inherit_props(struct btrfs_trans_handle *trans,
+ struct btrfs_inode *inode,
+diff --git a/fs/btrfs/super.c b/fs/btrfs/super.c
+index b424cc836bd4a..05b41dd8c6d2f 100644
+--- a/fs/btrfs/super.c
++++ b/fs/btrfs/super.c
+@@ -1511,6 +1511,16 @@ static int btrfs_reconfigure(struct fs_context *fc)
+ if (ret < 0)
+ goto restore;
+
++ /*
++ * STRIPE_ALLOC is set by the stripe_alloc property, not by a mount
++ * option, and can change after @ctx copied fs_info->mount_opt (an
++ * fsconfig context lives as long as its caller wants). Keep the
++ * current value.
++ */
++ if (btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ btrfs_set_opt(ctx->mount_opt, STRIPE_ALLOC);
++ else
++ btrfs_clear_opt(ctx->mount_opt, STRIPE_ALLOC);
+ btrfs_ctx_to_info(fs_info, ctx);
+ btrfs_remount_begin(fs_info, old_ctx.mount_opt, fc->sb_flags);
+ btrfs_resize_thread_pool(fs_info, fs_info->thread_pool_size,
--
2.47.3
-From fddee442cc1300ee68be619ac1df4cbb9975eab6 Mon Sep 17 00:00:00 2001
+From 5dd1fc6bf065a109a19c30107069f65664b96424 Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 19 Sep 2026 13:17:26 -0400
-Subject: [RFC PATCH 005/116] btrfs: report stripe run data IO through the
+Subject: [RFC PATCH 05/85] btrfs: report stripe run data IO through the
ordered extent lifecycle
To: linux-btrfs@vger.kernel.org
this also covers relocation's data inode preallocations.
Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
---
fs/btrfs/block-group.c | 51 ++++++++++++++++++++++++++++++++++++++
fs/btrfs/block-group.h | 4 +++
fs/btrfs/extent-tree.c | 55 +++++++++++++++++++++++++++++++++++++++--
fs/btrfs/extent-tree.h | 2 ++
fs/btrfs/inode.c | 17 ++++++++++---
- fs/btrfs/ordered-data.c | 35 ++++++++++++++++++++++++++
+ fs/btrfs/ordered-data.c | 36 +++++++++++++++++++++++++++
fs/btrfs/ordered-data.h | 9 +++++++
- 7 files changed, 168 insertions(+), 5 deletions(-)
+ 7 files changed, 169 insertions(+), 5 deletions(-)
diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 242a4b074e71d..f4453da153f6a 100644
+index d424975f7adba..3e5b1b54b0160 100644
--- a/fs/btrfs/block-group.c
+++ b/fs/btrfs/block-group.c
-@@ -682,6 +682,57 @@ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+@@ -677,6 +677,57 @@ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
}
* Pointer-based variant of btrfs_open_stripe_write_done() for callers that
* recorded the run at allocation or ordered extent creation time; safe from
diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 93088b93e9496..bc6d22953f80e 100644
+index 852f74b592aa0..4957bcf576ffd 100644
--- a/fs/btrfs/block-group.h
+++ b/fs/btrfs/block-group.h
-@@ -359,6 +359,10 @@ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+@@ -358,6 +358,10 @@ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
u64 num_bytes);
void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
u64 num_bytes);
+ struct btrfs_fs_info *fs_info, u64 bytenr, u64 num_bytes);
void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
- int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
+ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index cce38377da1ee..2da8a7d5fa1c9 100644
+index 196ac04c08aca..76c0bfaf9d62a 100644
--- a/fs/btrfs/extent-tree.c
+++ b/fs/btrfs/extent-tree.c
-@@ -4253,6 +4253,25 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
+@@ -4263,6 +4263,25 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
return 0;
}
static int do_allocation(struct btrfs_block_group *block_group,
struct find_free_extent_ctl *ffe_ctl,
struct btrfs_block_group **bg_ret)
-@@ -4823,6 +4842,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
+@@ -4845,6 +4864,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
/* move on to the next group */
if (ffe_ctl->search_start + ffe_ctl->num_bytes >
btrfs_block_group_end(block_group)) {
btrfs_add_free_space_unused(block_group,
ffe_ctl->found_offset,
ffe_ctl->num_bytes);
-@@ -4839,6 +4859,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
+@@ -4861,6 +4881,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
ffe_ctl->delalloc,
ffe_ctl->loop >= LOOP_WRONG_SIZE_CLASS);
if (ret == -EAGAIN) {
btrfs_add_free_space_unused(block_group,
ffe_ctl->found_offset,
ffe_ctl->num_bytes);
-@@ -4990,8 +5011,9 @@ int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
+@@ -5012,8 +5033,9 @@ int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
return ret;
}
{
struct btrfs_block_group *cache;
-@@ -5002,6 +5024,15 @@ int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len
+@@ -5024,6 +5046,15 @@ int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len
return -ENOSPC;
}
btrfs_add_free_space(cache, start, len);
btrfs_free_reserved_bytes(cache, len, is_delalloc);
trace_btrfs_reserved_extent_free(fs_info, start, len);
-@@ -5010,6 +5041,26 @@ int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len
+@@ -5032,6 +5063,26 @@ int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len
return 0;
}
}
diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
-index df74c75d6c299..24fcca1afbd15 100644
+index df74c75d6c299..bf43ebca2dcde 100644
--- a/fs/btrfs/ordered-data.c
+++ b/fs/btrfs/ordered-data.c
-@@ -213,6 +213,22 @@ static struct btrfs_ordered_extent *alloc_ordered_extent(
+@@ -213,6 +213,23 @@ static struct btrfs_ordered_extent *alloc_ordered_extent(
init_waitqueue_head(&entry->wait);
INIT_LIST_HEAD(&entry->csum_list);
INIT_LIST_HEAD(&entry->log_list);
+ * block group membership is established before the allocation
+ * returns, so an ordered extent for a stripe-run allocation cannot
+ * observe an empty list. NOCOW and PREALLOC ordered extents write
-+ * to previously allocated extents, which can never sit inside a
-+ * stripe run (runs are claimed from fully-free stripes).
++ * into extents whose allocation was already reported (a
++ * preallocation is reported when it is reserved), so they have
++ * nothing to report.
+ */
+ if (!is_nocow &&
+ !list_empty_careful(&inode->root->fs_info->open_stripe_bgs))
INIT_LIST_HEAD(&entry->root_extent_list);
INIT_LIST_HEAD(&entry->work_list);
INIT_LIST_HEAD(&entry->bioc_list);
-@@ -378,6 +394,22 @@ static void finish_ordered_fn(struct btrfs_work *work)
+@@ -378,6 +395,22 @@ static void finish_ordered_fn(struct btrfs_work *work)
btrfs_finish_ordered_io(ordered_extent);
}
static bool can_finish_ordered_extent(struct btrfs_ordered_extent *ordered,
u64 file_offset, u64 len, bool uptodate)
{
-@@ -409,6 +441,7 @@ static bool can_finish_ordered_extent(struct btrfs_ordered_extent *ordered,
+@@ -409,6 +442,7 @@ static bool can_finish_ordered_extent(struct btrfs_ordered_extent *ordered,
* the finish_func to be executed.
*/
set_bit(BTRFS_ORDERED_IO_DONE, &ordered->flags);
cond_wake_up(&ordered->wait);
refcount_inc(&ordered->refs);
trace_btrfs_ordered_extent_mark_finished(inode, ordered);
-@@ -636,6 +669,8 @@ void btrfs_put_ordered_extent(struct btrfs_ordered_extent *entry)
+@@ -636,6 +670,8 @@ void btrfs_put_ordered_extent(struct btrfs_ordered_extent *entry)
ASSERT(list_empty(&entry->root_extent_list));
ASSERT(list_empty(&entry->log_list));
ASSERT(RB_EMPTY_NODE(&entry->rb_node));
-From 3a96b8a5cf6b3ca15e47511ad7e178eed3826067 Mon Sep 17 00:00:00 2001
+From 90328f8ca40d0895a8e06a8885909979e47d6eee Mon Sep 17 00:00:00 2001
From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Date: Sat, 19 Sep 2026 13:17:26 -0400
-Subject: [RFC PATCH 006/116] btrfs: retire stripe runs at commit and gate
+Subject: [RFC PATCH 06/85] btrfs: retire stripe runs at commit and gate
stripe_alloc
To: linux-btrfs@vger.kernel.org
-Hook stripe run retirement into the transaction commit, right after
-TRANS_STATE_COMMIT_DOING stops accepting joins with a single writer
-left. At that point every data extent the transaction references was
-inserted by an ordered extent completion that joined earlier, implying
-its own data IO is done; the retirement drain waits out in-flight
-neighbour writes in the same stripes (a pure data-IO wait, never an
-ordered extent wait, which would deadlock on the blocked join). After
-the drain, no stripe this transaction references can ever be written
-again, so a crash after the superblock write cannot tear it -- closing
-the raid56 write hole for stripe-allocated block groups without
-requiring flushoncommit. A defensive retirement in
+Hook stripe run retirement into the transaction commit, after the wait
+for pending ordered extents and before TRANS_STATE_COMMIT_DOING stops
+accepting joins. The retirement drain waits out in-flight data writes
+into the stripes of the transaction's runs: a pure data-IO wait, never
+an ordered extent wait. It must run while the transaction still
+accepts joins: a task holding unreported stripe run bytes (a reserved
+extent whose bio has not completed) can block on a transaction join,
+for example for a chunk allocation while walking a delalloc range, and
+the drain waits for those bytes, so retiring after joins are blocked
+would deadlock. After the drain, no stripe this transaction references
+can ever be written again, so a crash after the superblock write cannot
+tear it -- closing the raid56 write hole for stripe-allocated block
+groups without requiring flushoncommit. A defensive retirement in
btrfs_free_block_groups() covers the transaction abort path.
-An ordered extent whose stripe run was opened after the committing
-transaction's retire point cannot insert its file extent into that
-transaction, so btrfs_finish_one_ordered() ends its handle and waits
-for the commit's critical section to end. That wait must not be taken
+Joins are still accepted between the retirement and
+TRANS_STATE_COMMIT_DOING. An ordered extent whose stripe run was opened
+after the committing transaction's retire point cannot insert its file
+extent into that transaction, so btrfs_finish_one_ordered() ends its
+handle and waits for the commit's critical section to end. That wait
+must not be taken
under the range's extent lock: buffered writers block on the locked
range in lock_and_cleanup_extent_if_need() while holding their
prepared, locked folios, which stops the writeback flusher and
in relocation-class stripe runs that never share stripes with other
data, and relocation depends on in-place writes.
-Validate the policy when it is enabled: it requires the free space tree (the v1
-space cache overwrites its data in place during commit), and is
-refused with the remap-tree feature (whose relocation writes bypass
+Validate the policy when it is enabled: it is refused with
+space_cache=v1, whose cache inode is nodatacow, preallocated and nodatasum
+and is overwritten in place during commit (the free space tree and no cache
+at all are both fine: nothing in the allocator reads either), with the
+remap-tree feature (whose relocation writes bypass
the ordered extent accounting) and on zoned filesystems (which have
their own allocator and no write hole).
can share the one copy of the rule. (Metadata and system block groups
never carried the DATA flag, so they were already excluded.)
+The cache format can only be converted at mount, so space_cache=v1 is
+refused in btrfs_check_mountopts() and checked again after
+btrfs_reconfigure() restores the cache options to what is on disk, and
+cache_save_setup() declines to set a v1 cache up while stripe_alloc is on,
+at the point where the in-place write would be issued. v1 cache inodes
+left on disk by an earlier mount are harmless and not refused: nothing
+writes them without cache_save_setup().
+
+A range-limited writeback (filemap_fdatawrite_range() before a dedupe or
+clone, for example) allocates the whole contiguous delalloc range as
+ordered extents but submits only the folios inside its range. The rest
+stay allocated and unsubmitted until the flusher reaches the inode, and
+the commit's retirement waits for them: commits of 600 s were seen with
+vm.dirty_writeback_centisecs=60000. So while stripe_alloc is enabled,
+btrfs_run_delalloc_range() takes the zoned path, run_delalloc_cow() with
+extent_write_locked_range(), and writes the whole allocated range at once;
+run_delalloc_nocow() does the same after a range in which fallback_to_cow()
+ran. The cost is the zoned one: a small dedupe or clone of a large dirty
+file waits for up to max_extent_size of IO that the allocation had already
+committed to.
+
Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
---
- fs/btrfs/block-group.c | 118 +++++++++++++++++++++---------
+ fs/btrfs/block-group.c | 144 +++++++++++++++++++-----------
fs/btrfs/block-group.h | 8 +-
- fs/btrfs/extent-tree.c | 8 +-
- fs/btrfs/inode.c | 61 +++++++++++++++
- fs/btrfs/ordered-data.c | 9 ++-
+ fs/btrfs/extent-tree.c | 13 +--
+ fs/btrfs/inode.c | 94 +++++++++++++++++--
+ fs/btrfs/ordered-data.c | 9 +-
fs/btrfs/ordered-data.h | 7 +-
fs/btrfs/tests/free-space-tests.c | 4 +-
- fs/btrfs/transaction.c | 47 ++++++++++++
+ fs/btrfs/transaction.c | 47 ++++++++++
fs/btrfs/transaction.h | 10 +++
- 9 files changed, 228 insertions(+), 44 deletions(-)
+ 9 files changed, 269 insertions(+), 67 deletions(-)
diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index f4453da153f6a..d28895e03f766 100644
+index 3e5b1b54b0160..a5ce2b53e9898 100644
--- a/fs/btrfs/block-group.c
+++ b/fs/btrfs/block-group.c
-@@ -457,24 +457,28 @@ void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
- * closes the raid56 write hole for these block groups.
+@@ -447,40 +447,41 @@ void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
+ * The raid56 stripe allocation policy only allocates from "open stripe
+ * runs": contiguous, stripe-aligned regions claimed whole from the free
+ * space cache (btrfs_claim_free_stripe_run()) and filled strictly
+- * sequentially. A run stops accepting allocations when it is exhausted,
+- * when an allocation does not fit in its remainder, or when it is retired
+- * at transaction commit; a closed run is never reopened, and its
+- * unallocated tail returns to the free space cache where, being part of a
+- * partially filled stripe, it cannot be claimed again until the whole
+- * stripe frees. This guarantees a full stripe only receives writes
+- * between two commits of the same transaction window, which is what
+- * closes the raid56 write hole for these block groups.
++ * sequentially. A run is closed when it is exhausted, when it loses a
++ * band collision (stripe_run_place()), when a private run is too small and
++ * is replaced, when a metadata run belongs to an earlier transaction, or
++ * when it is retired at transaction commit. A closed run is never
++ * reopened, and its unallocated tail returns to the free space cache
++ * where, being part of a partially filled stripe, it cannot be claimed
++ * until the whole stripe frees. So every stripe is written within one
++ * run's lifetime, which closes the raid56 write hole for these block
++ * groups.
*
- * Each run counts the bytes reserved from it whose data IO has not yet
+- * Each run counts the bytes reserved from it whose data IO has not yet
- * completed (inflight_bytes). At commit time, once the transaction can
- * no longer accept joins (TRANS_STATE_COMMIT_DOING with a single writer
- * left), btrfs_retire_open_stripes() closes every run opened before the
- * reached disk before the superblock is written. This is a pure data-IO
- * wait: it must never wait for ordered extent *completion*, whose
- * processing needs a transaction join that is blocked at this stage.
-+ * completed (inflight_bytes). At commit time, while the transaction
-+ * still accepts joins (before TRANS_STATE_COMMIT_DOING),
-+ * btrfs_retire_open_stripes() closes every run opened before the commit
-+ * and waits for their inflight bytes to drain. The placement matters
-+ * twice over. It must be a pure data-IO wait, never an ordered extent
-+ * completion wait (whose processing needs a transaction join). And it
-+ * must run where joins still succeed: a task holding unreported run
-+ * bytes -- a reserved extent whose bio has not completed -- may block on
-+ * a transaction join, e.g. for a chunk allocation while walking a
-+ * delalloc range, and the drain waits for those very bytes.
++ * Each run counts the bytes reserved from it whose IO has not completed
++ * (inflight_bytes). At commit, while the transaction still accepts joins
++ * (before TRANS_STATE_COMMIT_DOING), btrfs_retire_open_stripes() closes
++ * the data runs opened before the commit and waits for them to drain. The
++ * wait must be a pure data-IO wait, never an ordered extent completion
++ * wait, and must happen where joins still succeed: a task holding
++ * unreported run bytes may block on a join (e.g. a chunk allocation during
++ * delalloc). Metadata runs are retired after tree writeback
++ * (btrfs_retire_meta_stripes()); persistent NOCOW runs survive commits.
*
- * Allocations racing with the commit open new runs stamped with a newer
+- * Allocations racing with the commit open new runs stamped with a newer
- * open_seq and are not retired or waited for: metadata referencing them
- * can only join the next transaction, so they belong to the next window.
- * The retire walk may only rely on this for allocations whose block group
- * collected its worklist; btrfs_alloc_from_open_stripe() therefore adds
- * the membership before returning, i.e. before the caller can create the
- * ordered extent for the allocation.
-+ * open_seq and are not retired or waited for: they belong to the next
-+ * window. Because the commit still accepts joins after the drain, an
-+ * ordered extent from such a run could complete fast and try to add its
-+ * file extent to the committing transaction; the finish path compares
-+ * the extent's run sequence with the transaction's retired sequence and
-+ * defers to the next transaction instead. The membership add, the
-+ * sequence read and the run installation happen atomically under
-+ * fs_info->open_stripe_lock against the walk's bump-and-snapshot, so
-+ * every run is either seen by the walk that retires its window or
-+ * stamped with a sequence that forces the deferral.
++ * Runs opened while the commit is in progress carry a newer open_seq and
++ * belong to the next window. An ordered extent from such a run that
++ * completes before the commit ends sees that its run's open_seq is not
++ * retired by this transaction and defers its file extent to the next one.
++ * The membership add, the sequence read and the run installation happen
++ * atomically under fs_info->open_stripe_lock, so every run is either seen
++ * by the walk that retires its window or stamped with a sequence that
++ * forces the deferral.
*
* Lock order: fs_info->open_stripe_lock outside bg->stripe_run_lock. The
- * stripe_run_lock is irq-safe because completed data IO is reported from
-@@ -535,18 +539,6 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
+- * stripe_run_lock is irq-safe because completed data IO is reported from
+- * bio end_io context. Membership in fs_info->open_stripe_bgs holds a
+- * block group reference and is removed only by the retire walk once the
+- * group has no runs left.
++ * stripe_run_lock is taken with interrupts disabled, which no current
++ * caller needs: completed IO is reported from bio completion work, which
++ * runs in task context. Membership in fs_info->open_stripe_bgs holds a
++ * block group reference, dropped by the retire walk once the group has no
++ * runs left, or by btrfs_free_open_stripe_runs() at teardown.
+ */
+
+ struct btrfs_open_stripe_run {
+@@ -535,18 +536,6 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
return tail_len;
}
/*
* Allocate num_bytes from the block group's open stripe run, opening a new
* run via btrfs_claim_free_stripe_run() when there is none or the current
-@@ -612,6 +604,21 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+@@ -612,6 +601,21 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
goto out;
}
spin_lock_irqsave(&bg->stripe_run_lock, flags);
if (bg->ro) {
/*
-@@ -620,6 +627,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+@@ -620,6 +624,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
* must not be installed.
*/
spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
btrfs_add_free_space(bg, start, len);
*available = 0;
ret = -ENOSPC;
-@@ -639,19 +647,18 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+@@ -639,19 +644,18 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
new_run->end = start + len;
new_run->offset = start + num_bytes;
new_run->inflight_bytes = num_bytes;
out:
kfree(new_run);
return ret;
-@@ -709,7 +716,8 @@ void btrfs_open_stripe_write_done_bytenr(struct btrfs_fs_info *fs_info,
+@@ -704,7 +708,8 @@ void btrfs_open_stripe_write_done_bytenr(struct btrfs_fs_info *fs_info,
* with inflight bytes is never freed.
*/
struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
{
struct btrfs_open_stripe_run *run = NULL;
struct btrfs_open_stripe_run *iter;
-@@ -725,6 +733,7 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
+@@ -720,6 +725,7 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
ASSERT(bytenr + num_bytes <= iter->offset);
ASSERT(iter->inflight_bytes >= num_bytes);
run = iter;
break;
}
}
-@@ -897,11 +906,17 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
+@@ -926,11 +932,17 @@ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info)
/*
* Commit-time retirement: close every stripe run opened before this call
* and wait for all data IO into the stripes of those runs to complete.
{
struct btrfs_block_group *bg;
LIST_HEAD(retire_list);
-@@ -910,6 +925,8 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info)
+@@ -939,6 +951,8 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info)
spin_lock(&fs_info->open_stripe_lock);
seq = ++fs_info->stripe_retire_seq;
list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
list_add_tail(&bg->open_stripe_retire_list, &retire_list);
spin_unlock(&fs_info->open_stripe_lock);
-@@ -940,6 +957,27 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info)
+@@ -980,6 +994,28 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info)
}
}
+/*
-+ * With stripe-exclusive allocation, no in-place (nocow/prealloc) write may
-+ * land in a raid56 data block group: it could tear a stripe containing
-+ * committed extents of other files, which is exactly the write hole. The
-+ * write paths use this to force COW for such extents.
++ * Does stripe-exclusive allocation force COW for an in-place (nocow or
++ * prealloc) write at @bytenr? True for any raid56 data group under
++ * stripe_alloc, since an in-place write could tear a stripe holding other
++ * files' committed extents. The caller may still allow the write when
++ * btrfs_stripe_nocow_writable() proves the stripes belong to the inode.
+ */
+bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr)
+{
/*
* Drop the dedication of a block group to data relocation. Shared by the
* zoned allocator and the stripe allocation policy; both dedicate one
-@@ -4911,6 +4949,14 @@ int btrfs_free_block_groups(struct btrfs_fs_info *info)
+@@ -5055,6 +5091,14 @@ int btrfs_free_block_groups(struct btrfs_fs_info *info)
struct btrfs_caching_control *caching_ctl;
struct rb_node *n;
if (info->active_meta_bg) {
btrfs_put_block_group(info->active_meta_bg);
diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index bc6d22953f80e..cf5920ca3e25d 100644
+index 4957bcf576ffd..5f85e5067e001 100644
--- a/fs/btrfs/block-group.h
+++ b/fs/btrfs/block-group.h
-@@ -362,15 +362,19 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+@@ -361,16 +361,20 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
void btrfs_open_stripe_write_done_bytenr(struct btrfs_fs_info *fs_info,
u64 start, u64 num_bytes);
struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
+ u64 *open_seq);
void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
+ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
u64 bytenr);
void btrfs_dec_nocow_writers(struct btrfs_block_group *bg);
diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 2da8a7d5fa1c9..4653ae595dbae 100644
+index 76c0bfaf9d62a..d45cde622dd40 100644
--- a/fs/btrfs/extent-tree.c
+++ b/fs/btrfs/extent-tree.c
-@@ -4196,11 +4196,17 @@ static int do_allocation_zoned(struct btrfs_block_group *block_group,
- * sub-stripe writes into stripes containing committed data is what closes
- * the raid56 write hole for datacow writes; see the "Open stripe runs"
- * comment in block-group.c.
-+ *
-+ * Data only, and not the data in a mixed block group: metadata is not ready
-+ * for this allocator (see the mixed block group rejection in
-+ * btrfs_check_mountopts(), which is the real gate -- the METADATA test here
-+ * is belt and braces for a block group that somehow reaches this path).
+@@ -4192,15 +4192,18 @@ static int do_allocation_zoned(struct btrfs_block_group *block_group,
+ }
+
+ /*
+- * Should this block group use stripe-exclusive allocation? Never issuing
+- * sub-stripe writes into stripes containing committed data is what closes
+- * the raid56 write hole for datacow writes; see the "Open stripe runs"
+- * comment in block-group.c.
++ * Should this data block group use stripe-exclusive allocation? Never
++ * issuing sub-stripe writes into stripes containing committed data is what
++ * closes the raid56 write hole; see "Open stripe runs" in block-group.c.
++ * Metadata is covered by btrfs_is_stripe_meta_bg(). Mixed groups are
++ * excluded: stripe_alloc refuses to enable on them
++ * (btrfs_stripe_alloc_check_support()).
*/
-static bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
+bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
}
diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index 5803f5d95d654..b69cc44f58d70 100644
+index 5803f5d95d654..b66dd823053f1 100644
--- a/fs/btrfs/inode.c
+++ b/fs/btrfs/inode.c
@@ -1869,6 +1869,18 @@ static int can_nocow_file_extent(struct btrfs_path *path,
/*
* Force COW if csums exist in the range. This ensures that csums for a
* given extent are either valid or do not exist.
-@@ -3262,6 +3274,55 @@ int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
+@@ -1970,7 +1982,8 @@ static int nocow_one_range(struct btrfs_inode *inode, struct folio *locked_folio
+ */
+ static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
+ struct folio *locked_folio,
+- const u64 start, const u64 end)
++ const u64 start, const u64 end,
++ struct writeback_control *wbc)
+ {
+ struct btrfs_fs_info *fs_info = inode->root->fs_info;
+ struct btrfs_root *root = inode->root;
+@@ -1986,6 +1999,8 @@ static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
+ u64 cow_end = 0;
+ u64 nocow_end = 0;
+ u64 cur_offset = start;
++ /* Set once fallback_to_cow() has allocated part of the range. */
++ bool cowed = false;
+ int ret;
+ bool check_prev = true;
+ u64 ino = btrfs_ino(inode);
+@@ -2157,6 +2172,7 @@ static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
+ goto error;
+ }
+ cow_start = (u64)-1;
++ cowed = true;
+ }
+
+ ret = nocow_one_range(inode, locked_folio, &cached_state,
+@@ -2181,6 +2197,7 @@ static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
+ goto error;
+ }
+ cow_start = (u64)-1;
++ cowed = true;
+ }
+
+ /*
+@@ -2188,10 +2205,21 @@ static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
+ *
+ * No need to touch the io tree range nor set folio ordered flag, as
+ * fallback_to_cow() and nocow_one_range() have already handled them.
++ *
++ * With stripe_alloc, a range fallback_to_cow() allocated must not be
++ * left for a later flush, for the reason given in
++ * btrfs_run_delalloc_range(): write the whole range while its folios
++ * are still locked, as run_delalloc_cow() does.
++ * extent_write_locked_range() unlocks every folio, the locked folio
++ * included.
+ */
+- extent_clear_unlock_delalloc(inode, start, end, locked_folio, NULL, 0, PAGE_UNLOCK);
+-
+ btrfs_free_path(path);
++ if (cowed && btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
++ extent_write_locked_range(&inode->vfs_inode, locked_folio,
++ start, end, wbc, true);
++ return 1;
++ }
++ extent_clear_unlock_delalloc(inode, start, end, locked_folio, NULL, 0, PAGE_UNLOCK);
+ return 0;
+
+ error:
+@@ -2435,14 +2463,21 @@ int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct folio *locked_fol
+ }
+
+ if (should_nocow(inode, start, end))
+- return run_delalloc_nocow(inode, locked_folio, start, end);
++ return run_delalloc_nocow(inode, locked_folio, start, end, wbc);
+
+ if (btrfs_inode_can_compress(inode) &&
+ inode_need_compress(inode, start, end, false) &&
+ run_delalloc_compressed(inode, locked_folio, start, end, wbc))
+ return 1;
+
+- if (zoned)
++ /*
++ * The delalloc range can extend well past the range the writeback asked
++ * for (up to max_extent_size), and all of it gets allocated here. Zoned
++ * needs it written in allocation order, and stripe_alloc's commit waits
++ * for every allocated extent in a stripe run to be written, so neither
++ * can leave the folios past the writeback range for a later flush.
++ */
++ if (zoned || btrfs_test_opt(inode->root->fs_info, STRIPE_ALLOC))
+ return run_delalloc_cow(inode, locked_folio, start, end, wbc, true);
+ else
+ return cow_file_range(inode, locked_folio, start, end, NULL, 0);
+@@ -3262,6 +3297,55 @@ int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
goto out;
}
ret = btrfs_insert_raid_extent(trans, ordered_extent);
diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
-index 24fcca1afbd15..0ca6b7dc7e497 100644
+index bf43ebca2dcde..eb6b2da628220 100644
--- a/fs/btrfs/ordered-data.c
+++ b/fs/btrfs/ordered-data.c
-@@ -225,10 +225,15 @@ static struct btrfs_ordered_extent *alloc_ordered_extent(
- * stripe run (runs are claimed from fully-free stripes).
+@@ -226,10 +226,15 @@ static struct btrfs_ordered_extent *alloc_ordered_extent(
+ * nothing to report.
*/
if (!is_nocow &&
- !list_empty_careful(&inode->root->fs_info->open_stripe_bgs))
--- /dev/null
+From 38248cd7451a2ab3525d133fa661462db65c9f4f Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:27 -0400
+Subject: [RFC PATCH 07/85] btrfs: account stripe_alloc trapped free space for
+ honest statfs
+To: linux-btrfs@vger.kernel.org
+
+Free space in the partially filled stripes of a stripe_alloc (raid56
+write-hole-safe) block group is real free space -- it is in the free
+space tree and cache -- but the stripe-exclusive allocator cannot hand it
+out until the whole stripe frees. statfs therefore over-reports available
+space, promising free space that a later allocation refuses with ENOSPC.
+
+Track this trapped space per block group as stripe_unusable, summed into
+space_info->bytes_stripe_unusable. It is derived, so there is no on-disk
+format change and the free space tree and cache are left untouched
+(preserving the extent-tree/free-space-tree consistency btrfs check
+verifies).
+
+stripe_unusable is defined by a scan that accumulates every free byte of
+the block group into a per-stripe array and then sums the stripes that are
+partially filled. A per-stripe accumulator, rather than a streaming sweep
+or a per-stripe cache search, is what makes the result correct regardless
+of the order the free space cache yields its ranges -- an offset-sorted
+bitmap entry can emit runs that lie past a following extent entry, so the
+ranges are not globally monotonic -- and regardless of whether free space
+is stored as extents or bitmaps. A debug-build assertion checks that the
+scan distributes exactly the cache's free space. Because trapped space
+only settles at commit -- when the retire path returns partially filled
+stripes and deleted extents are unpinned -- the scan is recomputed at
+commit for groups whose free space changed (flagged cheaply on the
+allocation and free paths), which suits the timescale of the reclaim it
+feeds far better than a running per-extent tally. The space_info total is
+recomputed as the sum of the armed groups after those rescans, so it
+cannot drift.
+
+statfs subtracts bytes_stripe_unusable from the data f_bavail so df
+reports what can actually be allocated, and the counter is exposed at
+/sys/fs/btrfs/<uuid>/allocation/data/bytes_stripe_unusable. It is
+deliberately not part of btrfs_space_info_used(), so the reservation layer
+is unchanged and this carries no ENOSPC-behaviour risk.
+
+The counter is armed once a group's free space cache is loaded, so a group
+contributes zero until then and statfs starts optimistic and settles to
+honest as groups cache and commit. It is disarmed when a group turns
+read-only (its free space is then accounted as read-only and already
+excluded from statfs) and re-armed by a rescan on the way back to
+read-write, so a balance both recovers trapped space and updates the
+counter. A CONFIG_BTRFS_DEBUG-only sysfs trigger, stripe_unusable_rescan,
+forces a full recompute for auditing the accounting.
+
+Two deliberate imprecisions, matching existing behaviour rather than
+bettering it: statfs subtracts bytes_stripe_unusable but not
+bytes_zone_unusable, so stripe_alloc df reports availability before reclaim
+while zoned df reports it after; and superblock stripes, permanently
+unusable in every profile, are left to the existing bytes_super accounting
+rather than separately reported here. Both await a maintainer decision on
+a common convention.
+
+Arming and disarming this accounting follows the policy:
+btrfs_enable_stripe_alloc() and btrfs_disable_stripe_alloc() sweep every
+raid56 data group whose cache is loaded. Block groups are read before
+the root directory's properties apply at mount, and a runtime property
+set can arrive at any point; groups still caching arm when their caching
+thread finishes, now that the policy is on.
+
+inc_block_group_ro() asks the other groups for as much free space as the
+group withdraws. The group's trapped bytes are already counted in
+btrfs_space_info_used() through bytes_stripe_unusable, so they are
+subtracted from that demand rather than counted twice. Otherwise a
+fragmented raid56 data group could never be made read-only, and scrub
+(which needs raid56 groups read-only) and device replace failed with
+"scrub: failed setting block group ro: -28" on a churned filesystem.
+
+The scan walks the group's free space tree, so the entries of an
+allocation cluster the legacy allocator set up are returned to the group
+before the scan, when arming and at the commit-time rescan.
+
+Assisted-by: Claude:claude-opus-4-8
+Assisted-by: Claude:claude-fable-5-1
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 164 ++++++++++++++++++++++-
+ fs/btrfs/block-group.h | 19 +++
+ fs/btrfs/free-space-cache.c | 244 +++++++++++++++++++++++++++++++++++
+ fs/btrfs/free-space-cache.h | 3 +
+ fs/btrfs/space-info.h | 8 ++
+ fs/btrfs/super.c | 18 +++
+ fs/btrfs/sysfs.c | 31 +++++
+ fs/btrfs/transaction.c | 6 +
+ include/trace/events/btrfs.h | 8 ++
+ 9 files changed, 500 insertions(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index a5ce2b53e9898..17b66c42d0898 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -847,6 +847,38 @@ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info)
+ return 0;
+ }
+
++/*
++ * Arm or disarm stripe_unusable accounting across all raid56 data block
++ * groups whose caches are loaded. Same walk as the commit-time rescan.
++ */
++static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
++{
++ struct btrfs_space_info *sinfo;
++
++ list_for_each_entry(sinfo, &fs_info->space_info, list) {
++ int raid;
++
++ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
++ continue;
++ down_read(&sinfo->groups_sem);
++ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
++ struct btrfs_block_group *bg;
++
++ if (!(btrfs_raid_array[raid].bg_flag &
++ BTRFS_BLOCK_GROUP_RAID56_MASK))
++ continue;
++ list_for_each_entry(bg, &sinfo->block_groups[raid],
++ list) {
++ if (!arm)
++ btrfs_block_group_disarm_stripe_unusable(bg);
++ else if (bg->cached == BTRFS_CACHE_FINISHED)
++ btrfs_block_group_init_stripe_unusable(bg);
++ }
++ }
++ up_read(&sinfo->groups_sem);
++ }
++}
++
+ /*
+ * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
+ * property on the top-level subvolume's root directory. Runs during mount
+@@ -863,6 +895,14 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ if (ret)
+ return ret;
+ btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
++ /*
++ * Arm stripe_unusable accounting for raid56 data groups whose caches
++ * loaded before the policy was enabled: block groups are read before
++ * the root directory's properties apply during mount, and a runtime
++ * property set can arrive at any point. Groups still caching arm
++ * when their caching thread finishes, now that the policy is on.
++ */
++ stripe_alloc_sweep_groups(fs_info, true);
+ btrfs_info(fs_info,
+ "using stripe-exclusive allocation for raid56 data");
+ return 0;
+@@ -877,6 +917,8 @@ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ {
+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
+ return;
++ /* Disarm while the policy bit still passes the per-group gate. */
++ stripe_alloc_sweep_groups(fs_info, false);
+ btrfs_clear_opt(fs_info->mount_opt, STRIPE_ALLOC);
+ btrfs_info(fs_info,
+ "stripe-exclusive allocation for raid56 data disabled");
+@@ -994,6 +1036,66 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
+ }
+ }
+
++/*
++ * Commit-time recompute of stripe_unusable for every stripe_alloc block group
++ * whose free space changed this transaction. Trapped free space only settles
++ * at commit -- partially filled stripes are returned by the retire above and
++ * deleted extents are unpinned into the free space cache -- so this is where
++ * the counter can be made authoritative. Called after btrfs_finish_extent_commit
++ * so the free space cache reflects this transaction's frees.
++ */
++void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
++{
++ struct btrfs_space_info *sinfo;
++
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return;
++
++ list_for_each_entry(sinfo, &fs_info->space_info, list) {
++ u64 total = 0;
++ int raid;
++
++ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
++ continue;
++ down_read(&sinfo->groups_sem);
++ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
++ struct btrfs_block_group *bg;
++
++ if (!(btrfs_raid_array[raid].bg_flag &
++ BTRFS_BLOCK_GROUP_RAID56_MASK))
++ continue;
++ list_for_each_entry(bg, &sinfo->block_groups[raid],
++ list) {
++ bool dirty = test_and_clear_bit(
++ BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY,
++ &bg->runtime_flags);
++
++ /*
++ * @force rescans every armed group regardless of
++ * the dirty flag (debug: isolates a missed
++ * dirty-marking from a genuine cache difference).
++ */
++ if (force || dirty)
++ btrfs_block_group_rescan_stripe_unusable(bg);
++ /*
++ * Sum the authoritative per-group values into the
++ * space_info total so it cannot drift from repeated
++ * arm/disarm/rescan deltas. Disarmed (read-only)
++ * groups are excluded; their free space is already
++ * accounted as read-only.
++ */
++ if (READ_ONCE(bg->stripe_unusable_ready))
++ total += READ_ONCE(bg->stripe_unusable);
++ }
++ }
++ up_read(&sinfo->groups_sem);
++
++ spin_lock(&sinfo->lock);
++ sinfo->bytes_stripe_unusable = total;
++ spin_unlock(&sinfo->lock);
++ }
++}
++
+ /*
+ * Does stripe-exclusive allocation force COW for an in-place (nocow or
+ * prealloc) write at @bytenr? True for any raid56 data group under
+@@ -1539,6 +1641,15 @@ static noinline void caching_thread(struct btrfs_work *work)
+ block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
+ spin_unlock(&block_group->lock);
+
++ /*
++ * The free space cache is now populated; compute the initial trapped
++ * free space of a stripe_alloc block group and arm incremental
++ * accounting. Nothing until this point counted against
++ * stripe_unusable, so the scan captures the full loaded state.
++ */
++ if (!ret)
++ btrfs_block_group_init_stripe_unusable(block_group);
++
+ #ifdef CONFIG_BTRFS_DEBUG
+ if (btrfs_should_fragment_free_space(block_group)) {
+ u64 bytes_used;
+@@ -1879,6 +1990,13 @@ int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
+ WARN_ON(!list_empty(&block_group->dirty_list));
+ spin_unlock(&trans->transaction->dirty_bgs_lock);
+
++ /*
++ * A removed group has already been marked read-only (which disarmed
++ * stripe_unusable), but disarm defensively before the free space cache
++ * is torn down so the space_info total never keeps a stale contribution.
++ */
++ btrfs_block_group_disarm_stripe_unusable(block_group);
++
+ btrfs_remove_free_space_cache(block_group);
+
+ spin_lock(&block_group->space_info->lock);
+@@ -2055,12 +2173,26 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
+ ret = 0;
+ } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
+ u64 sinfo_used = btrfs_space_info_used(sinfo, true);
++ u64 trapped = 0;
++
++ /*
++ * The free space of a stripe_alloc group that is trapped in
++ * partially used stripes is already counted as used in the
++ * space_info (bytes_stripe_unusable), and that contribution is
++ * dropped once the group is read-only (see the disarm below).
++ * Asking the rest of the filesystem to absorb it a second time
++ * means a fragmented raid56 data group can never be made
++ * read-only: scrub and device replace, which require it for
++ * raid56, then fail with ENOSPC on a half-full filesystem.
++ */
++ if (READ_ONCE(cache->stripe_unusable_ready))
++ trapped = min(READ_ONCE(cache->stripe_unusable), num_bytes);
+
+ /*
+ * Here we make sure if we mark this bg RO, we still have enough
+ * free space as buffer.
+ */
+- if (sinfo_used + num_bytes <= sinfo->total_bytes)
++ if (sinfo_used - trapped + num_bytes <= sinfo->total_bytes)
+ ret = 0;
+ } else {
+ /*
+@@ -2087,6 +2219,14 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
+ out:
+ spin_unlock(&cache->lock);
+ spin_unlock(&sinfo->lock);
++ /*
++ * A read-only group's free space (trapped included) is now accounted
++ * as read-only and excluded from statfs; drop its stripe_unusable
++ * contribution so it is not subtracted twice. Idempotent, so repeated
++ * ro increments are harmless.
++ */
++ if (!ret)
++ btrfs_block_group_disarm_stripe_unusable(cache);
+ if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
+ btrfs_info(cache->fs_info,
+ "unable to make block group %llu ro", cache->start);
+@@ -3317,6 +3457,15 @@ static int read_one_block_group(struct btrfs_fs_info *info,
+ trace_btrfs_add_block_group(info, cache, 0);
+ btrfs_add_bg_to_space_info(cache);
+
++ /*
++ * Full or empty groups are marked cached above without going through
++ * the caching thread, so arm their stripe_unusable accounting here
++ * (both cases scan to zero trapped space). Groups that still need
++ * caching are armed when caching_thread finishes.
++ */
++ if (cache->cached == BTRFS_CACHE_FINISHED)
++ btrfs_block_group_init_stripe_unusable(cache);
++
+ set_avail_alloc_bits(info, cache->flags);
+ if (btrfs_chunk_writeable(info, cache->start)) {
+ if (cache->used == 0 && cache->remap_bytes == 0) {
+@@ -3833,6 +3982,9 @@ struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *tran
+ btrfs_link_bg_list(cache, &trans->new_bgs);
+ btrfs_inc_delayed_refs_rsv_bg_inserts(fs_info);
+
++ /* A freshly created stripe_alloc group starts fully free (0 trapped). */
++ btrfs_block_group_init_stripe_unusable(cache);
++
+ set_avail_alloc_bits(fs_info, type);
+ return cache;
+ }
+@@ -3976,6 +4128,7 @@ int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
+ void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
+ {
+ struct btrfs_space_info *sinfo = cache->space_info;
++ bool became_rw = false;
+
+ BUG_ON(!cache->ro);
+
+@@ -3993,9 +4146,18 @@ void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
+ }
+ sinfo->bytes_readonly -= btrfs_block_group_available_space(cache);
+ list_del_init(&cache->ro_list);
++ became_rw = true;
+ }
+ spin_unlock(&cache->lock);
+ spin_unlock(&sinfo->lock);
++
++ /*
++ * Back to read-write: re-arm stripe_unusable accounting, rescanning
++ * the current free space (it may have changed while read-only). The
++ * scan re-adds this group's trapped free space to the space_info total.
++ */
++ if (became_rw)
++ btrfs_block_group_init_stripe_unusable(cache);
+ }
+
+ static int update_block_group_item(struct btrfs_trans_handle *trans,
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 5f85e5067e001..1c9115ecb3a64 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -100,6 +100,11 @@ enum btrfs_block_group_flags {
+ BLOCK_GROUP_FLAG_NEW,
+ BLOCK_GROUP_FLAG_FULLY_REMAPPED,
+ BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING,
++ /*
++ * Free space changed this transaction, so the group's stripe_unusable
++ * counter must be rescanned at commit (stripe_alloc only).
++ */
++ BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY,
+ };
+
+ enum btrfs_caching_type {
+@@ -225,6 +230,19 @@ struct btrfs_block_group {
+ /* Private to the commit-time retire walk. */
+ struct list_head open_stripe_retire_list;
+
++ /*
++ * Free bytes trapped in partially filled stripes of a stripe_alloc or
++ * stripe_meta block group: present in the free space cache, but not
++ * allocatable until the whole stripe frees. Computed at cache-in and
++ * by the commit rescan; space trapped in between is added only to
++ * space_info->bytes_stripe_unusable (which counts as used), until the
++ * commit scan resets that total to the sum of the groups. This
++ * counter and the ready flag change under both
++ * free_space_ctl->tree_lock and space_info->lock.
++ */
++ u64 stripe_unusable;
++ bool stripe_unusable_ready;
++
+ /*
+ * Used for several lists:
+ *
+@@ -375,6 +393,7 @@ void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg);
+ void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info);
+ bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr);
+ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg);
++void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force);
+ struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
+ u64 bytenr);
+ void btrfs_dec_nocow_writers(struct btrfs_block_group *bg);
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index c776d36b69776..67ce6dc643f76 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1491,6 +1491,8 @@ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
+ return 0;
+ }
+
++static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
++
+ int btrfs_add_free_space(struct btrfs_block_group *block_group,
+ u64 bytenr, u64 size)
+ {
+@@ -1506,6 +1508,7 @@ int btrfs_add_free_space(struct btrfs_block_group *block_group,
+ if (btrfs_test_opt(block_group->fs_info, DISCARD_SYNC))
+ trim_state = BTRFS_TRIM_STATE_TRIMMED;
+
++ stripe_unusable_mark_dirty(block_group);
+ return __btrfs_add_free_space(block_group, bytenr, size, trim_state);
+ }
+
+@@ -1884,6 +1887,245 @@ u64 btrfs_find_space_for_alloc(struct btrfs_block_group *block_group,
+ return ret;
+ }
+
++/*
++ * Distribute a free range [a, end) into the per-stripe free-byte accumulator,
++ * splitting at full stripe boundaries. Indexing by stripe makes the result
++ * independent of the order ranges arrive in -- the free space cache can visit
++ * them out of offset order (a bitmap entry spans past a later extent entry) --
++ * and of the extent-vs-bitmap representation.
++ */
++static void stripe_dist(u32 *freep, u64 bg_start, u64 fsl, u64 a, u64 end,
++ u64 *counted)
++{
++ while (a < end) {
++ u64 idx = div64_u64(a - bg_start, fsl);
++ u64 stripe_end = bg_start + (idx + 1) * fsl;
++ u64 c = min(end, stripe_end);
++
++ freep[idx] += c - a;
++ *counted += c - a;
++ a = c;
++ }
++}
++
++/* Number of full stripes in a block group; the size of the freep array. */
++static u64 stripe_unusable_nstripes(const struct btrfs_block_group *bg)
++{
++ u64 fsl = bg->full_stripe_len;
++
++ return div64_u64(bg->length + fsl - 1, fsl);
++}
++
++/*
++ * Total trapped free bytes (free space in partially filled stripes) over the
++ * whole block group -- the authoritative definition of stripe_unusable,
++ * recomputed at cache-in and after each commit that changed the group's free
++ * space. Every free byte is accumulated into a per-stripe array (so a stripe
++ * whose total free is neither zero nor a whole stripe is partially filled, and
++ * its free bytes are trapped). @freep is a zeroed array of stripe_unusable_
++ * nstripes() u32 entries the caller allocates before taking the tree lock (it
++ * can be large); this runs with ctl->tree_lock held.
++ */
++static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
++ u64 nstripes)
++{
++ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ const u32 unit = bg->fs_info->sectorsize;
++ const u64 fsl = bg->full_stripe_len;
++ const u64 bg_start = bg->start;
++ u64 counted = 0;
++ u64 trapped = 0;
++ struct rb_node *n;
++ u64 i;
++
++ lockdep_assert_held(&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);
++
++ if (e->bitmap) {
++ unsigned long b = 0;
++
++ while (b < BITS_PER_BITMAP) {
++ unsigned long z;
++
++ 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);
++ stripe_dist(freep, bg_start, fsl,
++ e->offset + (u64)b * unit,
++ e->offset + (u64)z * unit, &counted);
++ b = z;
++ }
++ } else {
++ stripe_dist(freep, bg_start, fsl, e->offset,
++ e->offset + e->bytes, &counted);
++ }
++ }
++
++ /* Every free byte was distributed to exactly one stripe (debug check). */
++ ASSERT(counted == ctl->free_space,
++ "stripe_unusable_scan counted=%llu != free_space=%llu",
++ counted, ctl->free_space);
++
++ for (i = 0; i < nstripes; i++)
++ if (freep[i] && freep[i] < fsl)
++ trapped += freep[i];
++ return trapped;
++}
++
++/*
++ * The legacy allocator parks a group's free space in an allocation cluster
++ * (for a metadata group, its whole initial extent), where the group's own
++ * tree no longer sees it and the stripe scan cannot count it.
++ * Stripe-exclusive allocation never uses clusters, so a group that is being
++ * armed -- or rescanned, if a legacy allocation was still in flight at a
++ * runtime enable -- hands the cluster's entries back first.
++ */
++static void stripe_return_clusters(struct btrfs_block_group *bg)
++{
++ struct btrfs_fs_info *fs_info = bg->fs_info;
++ struct btrfs_free_cluster *cluster;
++
++ if (list_empty_careful(&bg->cluster_list))
++ return;
++ cluster = &fs_info->data_alloc_cluster;
++ spin_lock(&cluster->refill_lock);
++ btrfs_return_cluster_to_free_space(bg, cluster);
++ spin_unlock(&cluster->refill_lock);
++ cluster = &fs_info->meta_alloc_cluster;
++ spin_lock(&cluster->refill_lock);
++ btrfs_return_cluster_to_free_space(bg, cluster);
++ spin_unlock(&cluster->refill_lock);
++}
++
++/*
++ * Compute a stripe_alloc block group's initial trapped free space once its
++ * free space cache is loaded, and enable incremental accounting from here on.
++ * Idempotent-safe to call on a not-yet-populated (new, empty) block group,
++ * where it simply arms accounting with a zero baseline.
++ */
++void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
++{
++ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ u64 trapped, nstripes;
++ u32 *freep;
++
++ if (!btrfs_is_stripe_alloc_bg(bg))
++ return;
++ if (READ_ONCE(bg->stripe_unusable_ready))
++ return;
++
++ nstripes = stripe_unusable_nstripes(bg);
++ freep = kvcalloc(nstripes, sizeof(*freep), GFP_NOFS);
++ if (!freep)
++ return;
++
++ stripe_return_clusters(bg);
++ spin_lock(&ctl->tree_lock);
++ if (bg->stripe_unusable_ready) {
++ spin_unlock(&ctl->tree_lock);
++ kvfree(freep);
++ return;
++ }
++ trapped = stripe_unusable_scan(bg, freep, nstripes);
++ bg->stripe_unusable = trapped;
++ bg->stripe_unusable_ready = true;
++ spin_unlock(&ctl->tree_lock);
++ kvfree(freep);
++
++ if (trapped) {
++ spin_lock(&bg->space_info->lock);
++ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
++ trapped);
++ spin_unlock(&bg->space_info->lock);
++ }
++}
++
++/*
++ * Remove a stripe_alloc block group's trapped-space contribution from the
++ * space_info total and stop incremental accounting. Used when the group turns
++ * read-only or is removed: from that point its free space is accounted
++ * elsewhere (bytes_readonly / removal) and statfs already excludes it, so
++ * leaving stripe_unusable armed would double count. Re-arm on the way back to
++ * read-write with btrfs_block_group_init_stripe_unusable(). Idempotent.
++ */
++void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
++{
++ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ u64 trapped;
++
++ if (!btrfs_is_stripe_alloc_bg(bg))
++ return;
++
++ spin_lock(&ctl->tree_lock);
++ if (!bg->stripe_unusable_ready) {
++ spin_unlock(&ctl->tree_lock);
++ return;
++ }
++ trapped = bg->stripe_unusable;
++ bg->stripe_unusable_ready = false;
++ spin_unlock(&ctl->tree_lock);
++
++ if (trapped) {
++ spin_lock(&bg->space_info->lock);
++ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
++ -(s64)trapped);
++ spin_unlock(&bg->space_info->lock);
++ }
++}
++
++
++/*
++ * Recompute a stripe_alloc block group's trapped free space from a fresh scan
++ * and fold the change into the space_info total. Called at commit for groups
++ * whose free space changed this transaction; trapped space only settles at the
++ * commit that returns partially filled stripes and unpins deleted extents, so
++ * a per-commit rescan is both correct and far cheaper than a running tally.
++ */
++void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
++{
++ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ u64 nstripes;
++ u32 *freep;
++
++ if (!btrfs_is_stripe_alloc_bg(bg))
++ return;
++
++ nstripes = stripe_unusable_nstripes(bg);
++ freep = kvcalloc(nstripes, sizeof(*freep), GFP_NOFS);
++ if (!freep)
++ return;
++
++ stripe_return_clusters(bg);
++ spin_lock(&ctl->tree_lock);
++ if (bg->stripe_unusable_ready) /* skip if disarmed (read-only) */
++ bg->stripe_unusable = stripe_unusable_scan(bg, freep, nstripes);
++ spin_unlock(&ctl->tree_lock);
++ kvfree(freep);
++ /*
++ * The space_info total is recomputed authoritatively from the sum of
++ * armed groups by btrfs_scan_stripe_unusable() after all rescans, so it
++ * cannot drift; no per-group delta is applied here.
++ */
++}
++
++/*
++ * Flag a stripe_alloc block group's stripe_unusable counter for recomputation
++ * at the next commit, because its free space just changed. Cheap (one bit) so
++ * it can sit on the hot allocation and free paths; the actual scan is deferred
++ * to commit. Reading stripe_unusable_ready without the tree lock is a benign
++ * race: a missed or spurious flag only delays or repeats a rescan.
++ */
++static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg)
++{
++ if (READ_ONCE(bg->stripe_unusable_ready))
++ set_bit(BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY, &bg->runtime_flags);
++}
++
+ /*
+ * Align an offset up to the next full stripe boundary. Full stripe geometry
+ * is relative to the start of the block group, which is not necessarily
+@@ -2043,6 +2285,8 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ btrfs_discard_update_discardable(block_group);
+ spin_unlock(&ctl->tree_lock);
+
++ if (!ret)
++ stripe_unusable_mark_dirty(block_group);
+ if (head_len)
+ __btrfs_add_free_space(block_group, head_start, head_len,
+ head_trim_state);
+diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
+index 06a6bc70d9ac4..6bee1e7a7913c 100644
+--- a/fs/btrfs/free-space-cache.h
++++ b/fs/btrfs/free-space-cache.h
+@@ -113,6 +113,9 @@ u64 btrfs_find_space_for_alloc(struct btrfs_block_group *block_group,
+ u64 *max_extent_size);
+ 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);
++void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
++void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
+ void btrfs_dump_free_space(struct btrfs_block_group *block_group,
+ u64 bytes);
+ int btrfs_find_space_cluster(struct btrfs_block_group *block_group,
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index fc4497cba313f..dbe86b3480b6c 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -150,6 +150,12 @@ struct btrfs_space_info {
+ u64 bytes_readonly; /* total bytes that are read only */
+ u64 bytes_zone_unusable; /* total bytes that are unusable until
+ resetting the device zone */
++ u64 bytes_stripe_unusable; /* total free bytes trapped in partially
++ filled stripes of stripe_alloc block
++ groups; free but not allocatable until
++ the whole stripe frees. Informational
++ only (subtracted in statfs); NOT part
++ of btrfs_space_info_used(). */
+
+ u64 max_extent_size; /* This will hold the maximum extent size of
+ the space info if we had an ENOSPC in the
+@@ -299,6 +305,7 @@ btrfs_space_info_update_##name(struct btrfs_space_info *sinfo, \
+ DECLARE_SPACE_INFO_UPDATE(bytes_may_use, "space_info");
+ DECLARE_SPACE_INFO_UPDATE(bytes_pinned, "pinned");
+ DECLARE_SPACE_INFO_UPDATE(bytes_zone_unusable, "zone_unusable");
++DECLARE_SPACE_INFO_UPDATE(bytes_stripe_unusable, "stripe_unusable");
+
+ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
+ bool may_use_included)
+@@ -308,6 +315,7 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
+ return s_info->bytes_used + s_info->bytes_reserved +
+ s_info->bytes_pinned + s_info->bytes_readonly +
+ s_info->bytes_zone_unusable +
++ s_info->bytes_stripe_unusable +
+ (may_use_included ? s_info->bytes_may_use : 0);
+ }
+
+diff --git a/fs/btrfs/super.c b/fs/btrfs/super.c
+index 05b41dd8c6d2f..aa1dd20bb7284 100644
+--- a/fs/btrfs/super.c
++++ b/fs/btrfs/super.c
+@@ -1745,6 +1745,24 @@ static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
+ factor = btrfs_bg_type_to_factor(
+ btrfs_raid_array[i].bg_flag);
+ }
++
++ /*
++ * Free space trapped in partially filled stripes of
++ * stripe_alloc (raid56 write-hole-safe) block groups is
++ * present in the free space tree but cannot be allocated
++ * until the whole stripe frees. Subtract it so f_bavail
++ * reflects what can actually be allocated. Only armed,
++ * non-read-only groups contribute (read-only groups are
++ * already removed above); the counter is logical, so
++ * scale it to the disk units of total_free_data.
++ */
++ if (found->bytes_stripe_unusable) {
++ u64 su = found->bytes_stripe_unusable * factor;
++
++ if (su > total_free_data)
++ su = total_free_data;
++ total_free_data -= su;
++ }
+ }
+
+ /*
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 96d43e5ef19f5..7852bd1c1e64b 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -778,6 +778,34 @@ static ssize_t btrfs_force_chunk_alloc_store(struct kobject *kobj,
+ }
+ BTRFS_ATTR_W(space_info, force_chunk_alloc, btrfs_force_chunk_alloc_store);
+
++/*
++ * Recompute stripe_unusable for every armed group now, ignoring the
++ * per-group dirty flags, to check the incremental accounting against a
++ * full scan.
++ */
++static ssize_t btrfs_stripe_unusable_rescan_store(struct kobject *kobj,
++ struct kobj_attribute *a,
++ const char *buf, size_t len)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
++ bool val;
++ int ret;
++
++ if (!capable(CAP_SYS_ADMIN))
++ return -EPERM;
++
++ ret = kstrtobool(buf, &val);
++ if (ret)
++ return ret;
++ if (!val)
++ return -EINVAL;
++
++ btrfs_scan_stripe_unusable(fs_info, true);
++ return len;
++}
++BTRFS_ATTR_W(space_info, stripe_unusable_rescan,
++ btrfs_stripe_unusable_rescan_store);
++
+ #endif
+
+ SPACE_INFO_ATTR(flags);
+@@ -788,6 +816,7 @@ SPACE_INFO_ATTR(bytes_reserved);
+ 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(disk_used);
+ SPACE_INFO_ATTR(disk_total);
+ SPACE_INFO_ATTR(reclaim_count);
+@@ -917,6 +946,7 @@ static struct attribute *space_info_attrs[] = {
+ BTRFS_ATTR_PTR(space_info, bytes_may_use),
+ 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, disk_used),
+ BTRFS_ATTR_PTR(space_info, disk_total),
+ BTRFS_ATTR_PTR(space_info, bg_reclaim_threshold),
+@@ -930,6 +960,7 @@ static struct attribute *space_info_attrs[] = {
+ BTRFS_ATTR_PTR(space_info, periodic_reclaim),
+ #ifdef CONFIG_BTRFS_DEBUG
+ BTRFS_ATTR_PTR(space_info, force_chunk_alloc),
++ BTRFS_ATTR_PTR(space_info, stripe_unusable_rescan),
+ #endif
+ NULL,
+ };
+diff --git a/fs/btrfs/transaction.c b/fs/btrfs/transaction.c
+index c2e9a4fd69d3b..4f781df772202 100644
+--- a/fs/btrfs/transaction.c
++++ b/fs/btrfs/transaction.c
+@@ -2684,6 +2684,12 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
+ if (unlikely(ret))
+ goto scrub_continue;
+
++ /*
++ * The free space cache now reflects this transaction's frees; recompute
++ * stripe_unusable for stripe_alloc groups whose free space changed.
++ */
++ btrfs_scan_stripe_unusable(fs_info, false);
++
+ if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
+ btrfs_clear_space_info_full(fs_info);
+
+diff --git a/include/trace/events/btrfs.h b/include/trace/events/btrfs.h
+index 6ecfab97c1a90..e1af4dd8287ce 100644
+--- a/include/trace/events/btrfs.h
++++ b/include/trace/events/btrfs.h
+@@ -3291,6 +3291,14 @@ DEFINE_EVENT(btrfs__space_info_update, update_bytes_zone_unusable,
+ TP_ARGS(fs_info, sinfo, old, diff)
+ );
+
++DEFINE_EVENT(btrfs__space_info_update, update_bytes_stripe_unusable,
++
++ TP_PROTO(const struct btrfs_fs_info *fs_info,
++ const struct btrfs_space_info *sinfo, u64 old, s64 diff),
++
++ TP_ARGS(fs_info, sinfo, old, diff)
++);
++
+ DECLARE_EVENT_CLASS(btrfs_raid56_bio,
+
+ TP_PROTO(const struct btrfs_raid_bio *rbio,
+--
+2.47.3
+
+++ /dev/null
-From 98133152306858e37e4e7d8cf05b155e992252d3 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:27 -0400
-Subject: [RFC PATCH 007/116] btrfs: add a write-hole invariant checker to the
- raid56 write path
-To: linux-btrfs@vger.kernel.org
-
-With stripe-exclusive allocation, a raid56 data stripe may only be
-written while an open or draining stripe run covers it: after its run
-retires and drains at a transaction commit, nothing may ever write to
-it again, and a write outside any run means an allocation bypassed the
-policy. Both cases are the write hole about to happen.
-
-Check the invariant (under CONFIG_BTRFS_DEBUG) for every raid56 write
-operation, full-stripe and sub-stripe alike, at rmw_rbio() time. This
-turns every upstream violation -- a missed allocation path, a
-retirement ordering bug, an accounting leak -- into a deterministic
-WARN at the moment of the offending write, instead of silent damage
-that needs a crash plus a device failure plus a scrub to observe. The
-bios gathered in an rbio have not reported their IO done yet, so their
-runs cannot drain under the check: no false positives from completion
-races.
-
-Block groups that ever hosted relocation-class runs are skipped
-(sticky, debug-only flag): relocation legitimately overwrites its
-preallocated extents in place after their runs drain, and the write
-path cannot tell those writes from violations.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 51 ++++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/block-group.h | 15 +++++++++++++
- fs/btrfs/extent-tree.c | 3 +++
- fs/btrfs/raid56.c | 11 +++++++++
- 4 files changed, 80 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index d28895e03f766..aa363733b4df4 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -978,6 +978,57 @@ bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr)
- return ret;
- }
-
-+#ifdef CONFIG_BTRFS_DEBUG
-+/*
-+ * Write-hole invariant checker, called for every raid56 write operation
-+ * (full-stripe and sub-stripe/RMW alike). With stripe-exclusive
-+ * allocation, a raid56 data stripe may only be written while an open or
-+ * draining stripe run covers it: once its run retires and drains, nothing
-+ * may ever write it again, and a write outside any run means an
-+ * allocation bypassed the policy. Either way it is the write hole about
-+ * to happen, caught deterministically at the point of the write instead
-+ * of probabilistically after a crash plus a device failure.
-+ *
-+ * Block groups that hosted relocation-class runs are skipped:
-+ * relocation legitimately overwrites its preallocated extents in place
-+ * after their runs drain.
-+ */
-+void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
-+ u64 full_stripe_start, bool sub_stripe)
-+{
-+ struct btrfs_open_stripe_run *run;
-+ struct btrfs_block_group *bg;
-+ unsigned long flags;
-+ bool live = false;
-+ u64 fsl;
-+
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return;
-+ bg = btrfs_lookup_block_group(fs_info, full_stripe_start);
-+ if (!bg)
-+ return;
-+ if (!btrfs_is_stripe_alloc_bg(bg) ||
-+ test_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED, &bg->runtime_flags))
-+ goto out;
-+ fsl = bg->full_stripe_len;
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (full_stripe_start < run->end &&
-+ full_stripe_start + fsl > run->start) {
-+ live = true;
-+ break;
-+ }
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ WARN_ONCE(!live,
-+"btrfs: %s write to stripe %llu (block group %llu) outside any live stripe run: write hole window violated",
-+ sub_stripe ? "sub-stripe" : "full-stripe",
-+ full_stripe_start, bg->start);
-+out:
-+ btrfs_put_block_group(bg);
-+}
-+#endif
-+
- /*
- * Drop the dedication of a block group to data relocation. Shared by the
- * zoned allocator and the stripe allocation policy; both dedicate one
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index cf5920ca3e25d..6c6b8b6dce4cd 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -100,6 +100,13 @@ enum btrfs_block_group_flags {
- BLOCK_GROUP_FLAG_NEW,
- BLOCK_GROUP_FLAG_FULLY_REMAPPED,
- BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING,
-+ /*
-+ * The group has hosted relocation-class stripe runs. Relocation
-+ * overwrites its preallocated extents in place after their runs
-+ * drain, so the write-hole debug check cannot tell those writes
-+ * from violations and skips such groups (sticky, debug only).
-+ */
-+ BLOCK_GROUP_FLAG_STRIPE_RELOC_USED,
- };
-
- enum btrfs_caching_type {
-@@ -375,6 +382,14 @@ void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg);
- void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info);
- bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr);
- bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg);
-+#ifdef CONFIG_BTRFS_DEBUG
-+void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
-+ u64 full_stripe_start, bool sub_stripe);
-+#else
-+static inline void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
-+ u64 full_stripe_start,
-+ bool sub_stripe) { }
-+#endif
- struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
- u64 bytenr);
- void btrfs_dec_nocow_writers(struct btrfs_block_group *bg);
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 4653ae595dbae..8755c8c4d0a0d 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4254,6 +4254,9 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- btrfs_clear_data_reloc_bg(block_group);
- return 1;
- }
-+ if (class == BTRFS_STRIPE_RUN_RELOC)
-+ set_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED,
-+ &block_group->runtime_flags);
- ffe_ctl->found_offset = offset;
- ffe_ctl->search_start = offset;
- return 0;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 59aad807f98ab..4be6361413f21 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -21,6 +21,7 @@
- #include "async-thread.h"
- #include "file-item.h"
- #include "btrfs_inode.h"
-+#include "block-group.h"
-
- /* set when additional merges to this rbio are not allowed */
- #define RBIO_RMW_LOCKED_BIT 1
-@@ -2468,6 +2469,16 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- int sectornr;
- int ret = 0;
-
-+ /*
-+ * Write-hole invariant check: every write must land in a stripe
-+ * covered by a live stripe run when stripe-exclusive allocation is
-+ * enabled. The bios gathered in this rbio have not reported their
-+ * IO done yet, so their runs cannot drain under us.
-+ */
-+ btrfs_stripe_check_write(rbio->bioc->fs_info,
-+ rbio->bioc->full_stripe_logical,
-+ !rbio_is_full(rbio));
-+
- /*
- * Allocate the pages for parity first, as P/Q pages will always be
- * needed for both full-stripe and sub-stripe writes.
---
-2.47.3
-
+++ /dev/null
-From 2f1ee8114d2451c80045b6bea0de84f7d3ca9e13 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:27 -0400
-Subject: [RFC PATCH 008/116] btrfs: account stripe_alloc trapped free space
- for honest statfs
-To: linux-btrfs@vger.kernel.org
-
-Free space in the partially filled stripes of a stripe_alloc (raid56
-write-hole-safe) block group is real free space -- it is in the free
-space tree and cache -- but the stripe-exclusive allocator cannot hand it
-out until the whole stripe frees. statfs therefore over-reports available
-space, promising free space that a later allocation refuses with ENOSPC.
-
-Track this trapped space per block group as stripe_unusable, summed into
-space_info->bytes_stripe_unusable. It is derived, so there is no on-disk
-format change and the free space tree and cache are left untouched
-(preserving the extent-tree/free-space-tree consistency btrfs check
-verifies).
-
-stripe_unusable is defined by a scan that accumulates every free byte of
-the block group into a per-stripe array and then sums the stripes that are
-partially filled. A per-stripe accumulator, rather than a streaming sweep
-or a per-stripe cache search, is what makes the result correct regardless
-of the order the free space cache yields its ranges -- an offset-sorted
-bitmap entry can emit runs that lie past a following extent entry, so the
-ranges are not globally monotonic -- and regardless of whether free space
-is stored as extents or bitmaps. A debug-build assertion checks that the
-scan distributes exactly the cache's free space. Because trapped space
-only settles at commit -- when the retire path returns partially filled
-stripes and deleted extents are unpinned -- the scan is recomputed at
-commit for groups whose free space changed (flagged cheaply on the
-allocation and free paths), which suits the timescale of the reclaim it
-feeds far better than a running per-extent tally. The space_info total is
-recomputed as the sum of the armed groups after those rescans, so it
-cannot drift.
-
-statfs subtracts bytes_stripe_unusable from the data f_bavail so df
-reports what can actually be allocated, and the counter is exposed at
-/sys/fs/btrfs/<uuid>/allocation/data/bytes_stripe_unusable. It is
-deliberately not part of btrfs_space_info_used(), so the reservation layer
-is unchanged and this carries no ENOSPC-behaviour risk.
-
-The counter is armed once a group's free space cache is loaded, so a group
-contributes zero until then and statfs starts optimistic and settles to
-honest as groups cache and commit. It is disarmed when a group turns
-read-only (its free space is then accounted as read-only and already
-excluded from statfs) and re-armed by a rescan on the way back to
-read-write, so a balance both recovers trapped space and updates the
-counter. A CONFIG_BTRFS_DEBUG-only sysfs trigger, stripe_unusable_rescan,
-forces a full recompute for auditing the accounting.
-
-Two deliberate imprecisions, matching existing behaviour rather than
-bettering it: statfs subtracts bytes_stripe_unusable but not
-bytes_zone_unusable, so stripe_alloc df reports availability before reclaim
-while zoned df reports it after; and superblock stripes, permanently
-unusable in every profile, are left to the existing bytes_super accounting
-rather than separately reported here. Both await a maintainer decision on
-a common convention.
-
-Arming and disarming this accounting follows the policy:
-btrfs_enable_stripe_alloc() and btrfs_disable_stripe_alloc() sweep every
-raid56 data group whose cache is loaded. Block groups are read before
-the root directory's properties apply at mount, and a runtime property
-set can arrive at any point; groups still caching arm when their caching
-thread finishes, now that the policy is on.
-
-Assisted-by: Claude:claude-opus-4-8
----
- fs/btrfs/block-group.c | 164 +++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 19 +++
- fs/btrfs/free-space-cache.c | 217 +++++++++++++++++++++++++++++++++++
- fs/btrfs/free-space-cache.h | 3 +
- fs/btrfs/space-info.h | 8 ++
- fs/btrfs/super.c | 18 +++
- fs/btrfs/sysfs.c | 32 ++++++
- fs/btrfs/transaction.c | 6 +
- include/trace/events/btrfs.h | 8 ++
- 9 files changed, 474 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index aa363733b4df4..03ecf86d707f6 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -855,6 +855,38 @@ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info)
- return 0;
- }
-
-+/*
-+ * Arm or disarm stripe_unusable accounting across all raid56 data block
-+ * groups whose caches are loaded. Same walk as the commit-time rescan.
-+ */
-+static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
-+{
-+ struct btrfs_space_info *sinfo;
-+
-+ list_for_each_entry(sinfo, &fs_info->space_info, list) {
-+ int raid;
-+
-+ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
-+ continue;
-+ down_read(&sinfo->groups_sem);
-+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-+ struct btrfs_block_group *bg;
-+
-+ if (!(btrfs_raid_array[raid].bg_flag &
-+ BTRFS_BLOCK_GROUP_RAID56_MASK))
-+ continue;
-+ list_for_each_entry(bg, &sinfo->block_groups[raid],
-+ list) {
-+ if (!arm)
-+ btrfs_block_group_disarm_stripe_unusable(bg);
-+ else if (bg->cached == BTRFS_CACHE_FINISHED)
-+ btrfs_block_group_init_stripe_unusable(bg);
-+ }
-+ }
-+ up_read(&sinfo->groups_sem);
-+ }
-+}
-+
- /*
- * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
- * property on the top-level subvolume's root directory. Runs during mount
-@@ -871,6 +903,14 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
- if (ret)
- return ret;
- btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
-+ /*
-+ * Arm stripe_unusable accounting for raid56 data groups whose caches
-+ * loaded before the policy was enabled: block groups are read before
-+ * the root directory's properties apply during mount, and a runtime
-+ * property set can arrive at any point. Groups still caching arm
-+ * when their caching thread finishes, now that the policy is on.
-+ */
-+ stripe_alloc_sweep_groups(fs_info, true);
- btrfs_info(fs_info,
- "using stripe-exclusive allocation for raid56 data");
- return 0;
-@@ -885,6 +925,8 @@ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
- {
- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
- return;
-+ /* Disarm while the policy bit still passes the per-group gate. */
-+ stripe_alloc_sweep_groups(fs_info, false);
- btrfs_clear_opt(fs_info->mount_opt, STRIPE_ALLOC);
- btrfs_info(fs_info,
- "stripe-exclusive allocation for raid56 data disabled");
-@@ -957,6 +999,66 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
- }
- }
-
-+/*
-+ * Commit-time recompute of stripe_unusable for every stripe_alloc block group
-+ * whose free space changed this transaction. Trapped free space only settles
-+ * at commit -- partially filled stripes are returned by the retire above and
-+ * deleted extents are unpinned into the free space cache -- so this is where
-+ * the counter can be made authoritative. Called after btrfs_finish_extent_commit
-+ * so the free space cache reflects this transaction's frees.
-+ */
-+void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
-+{
-+ struct btrfs_space_info *sinfo;
-+
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return;
-+
-+ list_for_each_entry(sinfo, &fs_info->space_info, list) {
-+ u64 total = 0;
-+ int raid;
-+
-+ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
-+ continue;
-+ down_read(&sinfo->groups_sem);
-+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-+ struct btrfs_block_group *bg;
-+
-+ if (!(btrfs_raid_array[raid].bg_flag &
-+ BTRFS_BLOCK_GROUP_RAID56_MASK))
-+ continue;
-+ list_for_each_entry(bg, &sinfo->block_groups[raid],
-+ list) {
-+ bool dirty = test_and_clear_bit(
-+ BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY,
-+ &bg->runtime_flags);
-+
-+ /*
-+ * @force rescans every armed group regardless of
-+ * the dirty flag (debug: isolates a missed
-+ * dirty-marking from a genuine cache difference).
-+ */
-+ if (force || dirty)
-+ btrfs_block_group_rescan_stripe_unusable(bg);
-+ /*
-+ * Sum the authoritative per-group values into the
-+ * space_info total so it cannot drift from repeated
-+ * arm/disarm/rescan deltas. Disarmed (read-only)
-+ * groups are excluded; their free space is already
-+ * accounted as read-only.
-+ */
-+ if (READ_ONCE(bg->stripe_unusable_ready))
-+ total += READ_ONCE(bg->stripe_unusable);
-+ }
-+ }
-+ up_read(&sinfo->groups_sem);
-+
-+ spin_lock(&sinfo->lock);
-+ sinfo->bytes_stripe_unusable = total;
-+ spin_unlock(&sinfo->lock);
-+ }
-+}
-+
- /*
- * With stripe-exclusive allocation, no in-place (nocow/prealloc) write may
- * land in a raid56 data block group: it could tear a stripe containing
-@@ -1552,6 +1654,15 @@ static noinline void caching_thread(struct btrfs_work *work)
- block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
- spin_unlock(&block_group->lock);
-
-+ /*
-+ * The free space cache is now populated; compute the initial trapped
-+ * free space of a stripe_alloc block group and arm incremental
-+ * accounting. Nothing until this point counted against
-+ * stripe_unusable, so the scan captures the full loaded state.
-+ */
-+ if (!ret)
-+ btrfs_block_group_init_stripe_unusable(block_group);
-+
- #ifdef CONFIG_BTRFS_DEBUG
- if (btrfs_should_fragment_free_space(block_group)) {
- u64 bytes_used;
-@@ -1892,6 +2003,13 @@ int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
- WARN_ON(!list_empty(&block_group->dirty_list));
- spin_unlock(&trans->transaction->dirty_bgs_lock);
-
-+ /*
-+ * A removed group has already been marked read-only (which disarmed
-+ * stripe_unusable), but disarm defensively before the free space cache
-+ * is torn down so the space_info total never keeps a stale contribution.
-+ */
-+ btrfs_block_group_disarm_stripe_unusable(block_group);
-+
- btrfs_remove_free_space_cache(block_group);
-
- spin_lock(&block_group->space_info->lock);
-@@ -2068,12 +2186,26 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
- ret = 0;
- } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
- u64 sinfo_used = btrfs_space_info_used(sinfo, true);
-+ u64 trapped = 0;
-+
-+ /*
-+ * The free space of a stripe_alloc group that is trapped in
-+ * partially used stripes is already counted as used in the
-+ * space_info (bytes_stripe_unusable), and that contribution is
-+ * dropped once the group is read-only (see the disarm below).
-+ * Asking the rest of the filesystem to absorb it a second time
-+ * means a fragmented raid56 data group can never be made
-+ * read-only: scrub and device replace, which require it for
-+ * raid56, then fail with ENOSPC on a half-full filesystem.
-+ */
-+ if (READ_ONCE(cache->stripe_unusable_ready))
-+ trapped = min(READ_ONCE(cache->stripe_unusable), num_bytes);
-
- /*
- * Here we make sure if we mark this bg RO, we still have enough
- * free space as buffer.
- */
-- if (sinfo_used + num_bytes <= sinfo->total_bytes)
-+ if (sinfo_used - trapped + num_bytes <= sinfo->total_bytes)
- ret = 0;
- } else {
- /*
-@@ -2100,6 +2232,14 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
- out:
- spin_unlock(&cache->lock);
- spin_unlock(&sinfo->lock);
-+ /*
-+ * A read-only group's free space (trapped included) is now accounted
-+ * as read-only and excluded from statfs; drop its stripe_unusable
-+ * contribution so it is not subtracted twice. Idempotent, so repeated
-+ * ro increments are harmless.
-+ */
-+ if (!ret)
-+ btrfs_block_group_disarm_stripe_unusable(cache);
- if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
- btrfs_info(cache->fs_info,
- "unable to make block group %llu ro", cache->start);
-@@ -3226,6 +3366,15 @@ static int read_one_block_group(struct btrfs_fs_info *info,
- trace_btrfs_add_block_group(info, cache, 0);
- btrfs_add_bg_to_space_info(cache);
-
-+ /*
-+ * Full or empty groups are marked cached above without going through
-+ * the caching thread, so arm their stripe_unusable accounting here
-+ * (both cases scan to zero trapped space). Groups that still need
-+ * caching are armed when caching_thread finishes.
-+ */
-+ if (cache->cached == BTRFS_CACHE_FINISHED)
-+ btrfs_block_group_init_stripe_unusable(cache);
-+
- set_avail_alloc_bits(info, cache->flags);
- if (btrfs_chunk_writeable(info, cache->start)) {
- if (cache->used == 0 && cache->remap_bytes == 0) {
-@@ -3742,6 +3891,9 @@ struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *tran
- btrfs_link_bg_list(cache, &trans->new_bgs);
- btrfs_inc_delayed_refs_rsv_bg_inserts(fs_info);
-
-+ /* A freshly created stripe_alloc group starts fully free (0 trapped). */
-+ btrfs_block_group_init_stripe_unusable(cache);
-+
- set_avail_alloc_bits(fs_info, type);
- return cache;
- }
-@@ -3885,6 +4037,7 @@ int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
- void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
- {
- struct btrfs_space_info *sinfo = cache->space_info;
-+ bool became_rw = false;
-
- BUG_ON(!cache->ro);
-
-@@ -3902,9 +4055,18 @@ void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
- }
- sinfo->bytes_readonly -= btrfs_block_group_available_space(cache);
- list_del_init(&cache->ro_list);
-+ became_rw = true;
- }
- spin_unlock(&cache->lock);
- spin_unlock(&sinfo->lock);
-+
-+ /*
-+ * Back to read-write: re-arm stripe_unusable accounting, rescanning
-+ * the current free space (it may have changed while read-only). The
-+ * scan re-adds this group's trapped free space to the space_info total.
-+ */
-+ if (became_rw)
-+ btrfs_block_group_init_stripe_unusable(cache);
- }
-
- static int update_block_group_item(struct btrfs_trans_handle *trans,
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 6c6b8b6dce4cd..89bdb04edb421 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -107,6 +107,11 @@ enum btrfs_block_group_flags {
- * from violations and skips such groups (sticky, debug only).
- */
- BLOCK_GROUP_FLAG_STRIPE_RELOC_USED,
-+ /*
-+ * Free space changed this transaction, so the group's stripe_unusable
-+ * counter must be rescanned at commit (stripe_alloc only).
-+ */
-+ BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY,
- };
-
- enum btrfs_caching_type {
-@@ -233,6 +238,19 @@ struct btrfs_block_group {
- /* Private to the commit-time retire walk. */
- struct list_head open_stripe_retire_list;
-
-+ /*
-+ * Free bytes trapped in partially filled stripes of a stripe_alloc
-+ * block group: they are genuine free space (present in the free space
-+ * cache and the free space tree, so no on-disk accounting changes) but
-+ * the stripe-exclusive allocator cannot hand them out until the whole
-+ * stripe frees. Computed once at cache-in and maintained incrementally
-+ * as free space is added; both this counter and the ready flag are
-+ * protected by free_space_ctl->tree_lock. Only statfs subtracts it
-+ * (honest f_bavail); the reservation layer is deliberately unchanged.
-+ */
-+ u64 stripe_unusable;
-+ bool stripe_unusable_ready;
-+
- /*
- * Used for several lists:
- *
-@@ -382,6 +400,7 @@ void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg);
- void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info);
- bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr);
- bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg);
-+void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force);
- #ifdef CONFIG_BTRFS_DEBUG
- void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
- u64 full_stripe_start, bool sub_stripe);
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index c776d36b69776..9837562d348a5 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1491,6 +1491,8 @@ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
- return 0;
- }
-
-+static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
-+
- int btrfs_add_free_space(struct btrfs_block_group *block_group,
- u64 bytenr, u64 size)
- {
-@@ -1506,6 +1508,7 @@ int btrfs_add_free_space(struct btrfs_block_group *block_group,
- if (btrfs_test_opt(block_group->fs_info, DISCARD_SYNC))
- trim_state = BTRFS_TRIM_STATE_TRIMMED;
-
-+ stripe_unusable_mark_dirty(block_group);
- return __btrfs_add_free_space(block_group, bytenr, size, trim_state);
- }
-
-@@ -1884,6 +1887,218 @@ u64 btrfs_find_space_for_alloc(struct btrfs_block_group *block_group,
- return ret;
- }
-
-+/*
-+ * Distribute a free range [a, end) into the per-stripe free-byte accumulator,
-+ * splitting at full stripe boundaries. Indexing by stripe makes the result
-+ * independent of the order ranges arrive in -- the free space cache can visit
-+ * them out of offset order (a bitmap entry spans past a later extent entry) --
-+ * and of the extent-vs-bitmap representation.
-+ */
-+static void stripe_dist(u32 *freep, u64 bg_start, u64 fsl, u64 a, u64 end,
-+ u64 *counted)
-+{
-+ while (a < end) {
-+ u64 idx = div64_u64(a - bg_start, fsl);
-+ u64 stripe_end = bg_start + (idx + 1) * fsl;
-+ u64 c = min(end, stripe_end);
-+
-+ freep[idx] += c - a;
-+ *counted += c - a;
-+ a = c;
-+ }
-+}
-+
-+/* Number of full stripes in a block group; the size of the freep array. */
-+static u64 stripe_unusable_nstripes(const struct btrfs_block_group *bg)
-+{
-+ u64 fsl = bg->full_stripe_len;
-+
-+ return div64_u64(bg->length + fsl - 1, fsl);
-+}
-+
-+/*
-+ * Total trapped free bytes (free space in partially filled stripes) over the
-+ * whole block group -- the authoritative definition of stripe_unusable,
-+ * recomputed at cache-in and after each commit that changed the group's free
-+ * space. Every free byte is accumulated into a per-stripe array (so a stripe
-+ * whose total free is neither zero nor a whole stripe is partially filled, and
-+ * its free bytes are trapped). @freep is a zeroed array of stripe_unusable_
-+ * nstripes() u32 entries the caller allocates before taking the tree lock (it
-+ * can be large); this runs with ctl->tree_lock held.
-+ */
-+static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
-+ u64 nstripes)
-+{
-+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-+ const u32 unit = bg->fs_info->sectorsize;
-+ const u64 fsl = bg->full_stripe_len;
-+ const u64 bg_start = bg->start;
-+ u64 counted = 0;
-+ u64 trapped = 0;
-+ struct rb_node *n;
-+ u64 i;
-+
-+ lockdep_assert_held(&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);
-+
-+ if (e->bitmap) {
-+ unsigned long b = 0;
-+
-+ while (b < BITS_PER_BITMAP) {
-+ unsigned long z;
-+
-+ 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);
-+ stripe_dist(freep, bg_start, fsl,
-+ e->offset + (u64)b * unit,
-+ e->offset + (u64)z * unit, &counted);
-+ b = z;
-+ }
-+ } else {
-+ stripe_dist(freep, bg_start, fsl, e->offset,
-+ e->offset + e->bytes, &counted);
-+ }
-+ }
-+
-+ /* Every free byte was distributed to exactly one stripe (debug check). */
-+ ASSERT(counted == ctl->free_space,
-+ "stripe_unusable_scan counted=%llu != free_space=%llu",
-+ counted, ctl->free_space);
-+
-+ for (i = 0; i < nstripes; i++)
-+ if (freep[i] && freep[i] < fsl)
-+ trapped += freep[i];
-+ return trapped;
-+}
-+
-+/*
-+ * Compute a stripe_alloc block group's initial trapped free space once its
-+ * free space cache is loaded, and enable incremental accounting from here on.
-+ * Idempotent-safe to call on a not-yet-populated (new, empty) block group,
-+ * where it simply arms accounting with a zero baseline.
-+ */
-+void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-+ u64 trapped, nstripes;
-+ u32 *freep;
-+
-+ if (!btrfs_is_stripe_alloc_bg(bg))
-+ return;
-+ if (READ_ONCE(bg->stripe_unusable_ready))
-+ return;
-+
-+ nstripes = stripe_unusable_nstripes(bg);
-+ freep = kvcalloc(nstripes, sizeof(*freep), GFP_NOFS);
-+ if (!freep)
-+ return;
-+
-+ spin_lock(&ctl->tree_lock);
-+ if (bg->stripe_unusable_ready) {
-+ spin_unlock(&ctl->tree_lock);
-+ kvfree(freep);
-+ return;
-+ }
-+ trapped = stripe_unusable_scan(bg, freep, nstripes);
-+ bg->stripe_unusable = trapped;
-+ bg->stripe_unusable_ready = true;
-+ spin_unlock(&ctl->tree_lock);
-+ kvfree(freep);
-+
-+ if (trapped) {
-+ spin_lock(&bg->space_info->lock);
-+ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
-+ trapped);
-+ spin_unlock(&bg->space_info->lock);
-+ }
-+}
-+
-+/*
-+ * Remove a stripe_alloc block group's trapped-space contribution from the
-+ * space_info total and stop incremental accounting. Used when the group turns
-+ * read-only or is removed: from that point its free space is accounted
-+ * elsewhere (bytes_readonly / removal) and statfs already excludes it, so
-+ * leaving stripe_unusable armed would double count. Re-arm on the way back to
-+ * read-write with btrfs_block_group_init_stripe_unusable(). Idempotent.
-+ */
-+void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-+ u64 trapped;
-+
-+ if (!btrfs_is_stripe_alloc_bg(bg))
-+ return;
-+
-+ spin_lock(&ctl->tree_lock);
-+ if (!bg->stripe_unusable_ready) {
-+ spin_unlock(&ctl->tree_lock);
-+ return;
-+ }
-+ trapped = bg->stripe_unusable;
-+ bg->stripe_unusable_ready = false;
-+ spin_unlock(&ctl->tree_lock);
-+
-+ if (trapped) {
-+ spin_lock(&bg->space_info->lock);
-+ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
-+ -(s64)trapped);
-+ spin_unlock(&bg->space_info->lock);
-+ }
-+}
-+
-+
-+/*
-+ * Recompute a stripe_alloc block group's trapped free space from a fresh scan
-+ * and fold the change into the space_info total. Called at commit for groups
-+ * whose free space changed this transaction; trapped space only settles at the
-+ * commit that returns partially filled stripes and unpins deleted extents, so
-+ * a per-commit rescan is both correct and far cheaper than a running tally.
-+ */
-+void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-+ u64 nstripes;
-+ u32 *freep;
-+
-+ if (!btrfs_is_stripe_alloc_bg(bg))
-+ return;
-+
-+ nstripes = stripe_unusable_nstripes(bg);
-+ freep = kvcalloc(nstripes, sizeof(*freep), GFP_NOFS);
-+ if (!freep)
-+ return;
-+
-+ spin_lock(&ctl->tree_lock);
-+ if (bg->stripe_unusable_ready) /* skip if disarmed (read-only) */
-+ bg->stripe_unusable = stripe_unusable_scan(bg, freep, nstripes);
-+ spin_unlock(&ctl->tree_lock);
-+ kvfree(freep);
-+ /*
-+ * The space_info total is recomputed authoritatively from the sum of
-+ * armed groups by btrfs_scan_stripe_unusable() after all rescans, so it
-+ * cannot drift; no per-group delta is applied here.
-+ */
-+}
-+
-+/*
-+ * Flag a stripe_alloc block group's stripe_unusable counter for recomputation
-+ * at the next commit, because its free space just changed. Cheap (one bit) so
-+ * it can sit on the hot allocation and free paths; the actual scan is deferred
-+ * to commit. Reading stripe_unusable_ready without the tree lock is a benign
-+ * race: a missed or spurious flag only delays or repeats a rescan.
-+ */
-+static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg)
-+{
-+ if (READ_ONCE(bg->stripe_unusable_ready))
-+ set_bit(BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY, &bg->runtime_flags);
-+}
-+
- /*
- * Align an offset up to the next full stripe boundary. Full stripe geometry
- * is relative to the start of the block group, which is not necessarily
-@@ -2043,6 +2258,8 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- btrfs_discard_update_discardable(block_group);
- spin_unlock(&ctl->tree_lock);
-
-+ if (!ret)
-+ stripe_unusable_mark_dirty(block_group);
- if (head_len)
- __btrfs_add_free_space(block_group, head_start, head_len,
- head_trim_state);
-diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
-index 06a6bc70d9ac4..6bee1e7a7913c 100644
---- a/fs/btrfs/free-space-cache.h
-+++ b/fs/btrfs/free-space-cache.h
-@@ -113,6 +113,9 @@ u64 btrfs_find_space_for_alloc(struct btrfs_block_group *block_group,
- u64 *max_extent_size);
- 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);
-+void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
-+void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
- void btrfs_dump_free_space(struct btrfs_block_group *block_group,
- u64 bytes);
- int btrfs_find_space_cluster(struct btrfs_block_group *block_group,
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 0456b0d2d1b4a..51098227f9171 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -150,6 +150,12 @@ struct btrfs_space_info {
- u64 bytes_readonly; /* total bytes that are read only */
- u64 bytes_zone_unusable; /* total bytes that are unusable until
- resetting the device zone */
-+ u64 bytes_stripe_unusable; /* total free bytes trapped in partially
-+ filled stripes of stripe_alloc block
-+ groups; free but not allocatable until
-+ the whole stripe frees. Informational
-+ only (subtracted in statfs); NOT part
-+ of btrfs_space_info_used(). */
-
- u64 max_extent_size; /* This will hold the maximum extent size of
- the space info if we had an ENOSPC in the
-@@ -282,6 +288,7 @@ btrfs_space_info_update_##name(struct btrfs_space_info *sinfo, \
- DECLARE_SPACE_INFO_UPDATE(bytes_may_use, "space_info");
- DECLARE_SPACE_INFO_UPDATE(bytes_pinned, "pinned");
- DECLARE_SPACE_INFO_UPDATE(bytes_zone_unusable, "zone_unusable");
-+DECLARE_SPACE_INFO_UPDATE(bytes_stripe_unusable, "stripe_unusable");
-
- static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
- bool may_use_included)
-@@ -291,6 +298,7 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
- return s_info->bytes_used + s_info->bytes_reserved +
- s_info->bytes_pinned + s_info->bytes_readonly +
- s_info->bytes_zone_unusable +
-+ s_info->bytes_stripe_unusable +
- (may_use_included ? s_info->bytes_may_use : 0);
- }
-
-diff --git a/fs/btrfs/super.c b/fs/btrfs/super.c
-index b424cc836bd4a..a64d9cd48d12e 100644
---- a/fs/btrfs/super.c
-+++ b/fs/btrfs/super.c
-@@ -1735,6 +1735,24 @@ static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf)
- factor = btrfs_bg_type_to_factor(
- btrfs_raid_array[i].bg_flag);
- }
-+
-+ /*
-+ * Free space trapped in partially filled stripes of
-+ * stripe_alloc (raid56 write-hole-safe) block groups is
-+ * present in the free space tree but cannot be allocated
-+ * until the whole stripe frees. Subtract it so f_bavail
-+ * reflects what can actually be allocated. Only armed,
-+ * non-read-only groups contribute (read-only groups are
-+ * already removed above); the counter is logical, so
-+ * scale it to the disk units of total_free_data.
-+ */
-+ if (found->bytes_stripe_unusable) {
-+ u64 su = found->bytes_stripe_unusable * factor;
-+
-+ if (su > total_free_data)
-+ su = total_free_data;
-+ total_free_data -= su;
-+ }
- }
-
- /*
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 89b0a4ef4063e..357c669e6ea15 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -778,6 +778,35 @@ static ssize_t btrfs_force_chunk_alloc_store(struct kobject *kobj,
- }
- BTRFS_ATTR_W(space_info, force_chunk_alloc, btrfs_force_chunk_alloc_store);
-
-+/*
-+ * Force a full recompute of stripe_unusable across every armed stripe_alloc
-+ * block group, ignoring the per-group dirty flag. If the reported value rises
-+ * to match a fresh umount/mount scan, groups were being missed by dirty
-+ * marking; if it stays put, the live cache genuinely differs from a reload.
-+ */
-+static ssize_t btrfs_stripe_unusable_rescan_store(struct kobject *kobj,
-+ struct kobj_attribute *a,
-+ const char *buf, size_t len)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
-+ bool val;
-+ int ret;
-+
-+ if (!capable(CAP_SYS_ADMIN))
-+ return -EPERM;
-+
-+ ret = kstrtobool(buf, &val);
-+ if (ret)
-+ return ret;
-+ if (!val)
-+ return -EINVAL;
-+
-+ btrfs_scan_stripe_unusable(fs_info, true);
-+ return len;
-+}
-+BTRFS_ATTR_W(space_info, stripe_unusable_rescan,
-+ btrfs_stripe_unusable_rescan_store);
-+
- #endif
-
- SPACE_INFO_ATTR(flags);
-@@ -788,6 +817,7 @@ SPACE_INFO_ATTR(bytes_reserved);
- 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(disk_used);
- SPACE_INFO_ATTR(disk_total);
- SPACE_INFO_ATTR(reclaim_count);
-@@ -916,6 +946,7 @@ static struct attribute *space_info_attrs[] = {
- BTRFS_ATTR_PTR(space_info, bytes_may_use),
- 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, disk_used),
- BTRFS_ATTR_PTR(space_info, disk_total),
- BTRFS_ATTR_PTR(space_info, bg_reclaim_threshold),
-@@ -928,6 +959,7 @@ static struct attribute *space_info_attrs[] = {
- BTRFS_ATTR_PTR(space_info, periodic_reclaim),
- #ifdef CONFIG_BTRFS_DEBUG
- BTRFS_ATTR_PTR(space_info, force_chunk_alloc),
-+ BTRFS_ATTR_PTR(space_info, stripe_unusable_rescan),
- #endif
- NULL,
- };
-diff --git a/fs/btrfs/transaction.c b/fs/btrfs/transaction.c
-index c2e9a4fd69d3b..4f781df772202 100644
---- a/fs/btrfs/transaction.c
-+++ b/fs/btrfs/transaction.c
-@@ -2684,6 +2684,12 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
- if (unlikely(ret))
- goto scrub_continue;
-
-+ /*
-+ * The free space cache now reflects this transaction's frees; recompute
-+ * stripe_unusable for stripe_alloc groups whose free space changed.
-+ */
-+ btrfs_scan_stripe_unusable(fs_info, false);
-+
- if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &cur_trans->flags))
- btrfs_clear_space_info_full(fs_info);
-
-diff --git a/include/trace/events/btrfs.h b/include/trace/events/btrfs.h
-index 6ecfab97c1a90..e1af4dd8287ce 100644
---- a/include/trace/events/btrfs.h
-+++ b/include/trace/events/btrfs.h
-@@ -3291,6 +3291,14 @@ DEFINE_EVENT(btrfs__space_info_update, update_bytes_zone_unusable,
- TP_ARGS(fs_info, sinfo, old, diff)
- );
-
-+DEFINE_EVENT(btrfs__space_info_update, update_bytes_stripe_unusable,
-+
-+ TP_PROTO(const struct btrfs_fs_info *fs_info,
-+ const struct btrfs_space_info *sinfo, u64 old, s64 diff),
-+
-+ TP_ARGS(fs_info, sinfo, old, diff)
-+);
-+
- DECLARE_EVENT_CLASS(btrfs_raid56_bio,
-
- TP_PROTO(const struct btrfs_raid_bio *rbio,
---
-2.47.3
-
--- /dev/null
+From 0e2243bd9a29d331bf39433f9651464ef445416f Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:27 -0400
+Subject: [RFC PATCH 08/85] btrfs: stripe_alloc: keep an open run per size band
+ to trap less
+To: linux-btrfs@vger.kernel.org
+
+A single open stripe run per class forces every allocation that does not
+fit the current run's remainder to close that run -- trapping its
+unallocated tail in a now partially filled stripe -- and claim a fresh
+fully-free stripe. A workload that interleaves small and large extents
+(the common case) therefore strands a tail on every size change, even
+though a later small allocation could have filled it.
+
+Keep one open run per power-of-two band of remaining free space instead
+(band k holds a run with remaining in [2^k, 2^(k+1)) sectors), per class.
+An allocation takes the run in the smallest band that still fits --
+segregated best fit -- so a small write lands in an already-open, nearly
+full stripe rather than opening a new one, while a large write that no
+open run can hold opens a fresh stripe and leaves the smaller runs open
+for the small writes that do fit them. After each allocation the run is
+re-placed into the band its new remainder falls in; when two runs collide
+in a band the fuller one is kept -- it can serve larger future
+allocations, and closing it would trap more -- and the other is closed,
+its tail returned to the free space cache.
+
+16 bands cover a full stripe of up to 2^16 sectors, far more than any
+raid56 geometry (nr_data_stripes * stripe_len / sectorsize is 158 sectors
+at 10 data stripes and a 64K stripe). Commit-time retirement and the
+read-only / removal paths now walk every band of every class; only the
+bg->open_stripe[][] slots can ever hold an open run, so one pass still
+suffices, and the obsolete single-slot assertions are dropped.
+
+This does not touch the write-hole guarantee: every run is still a
+contiguous fill of fully-free stripes, closed at commit and never
+reopened. It only changes which open run an allocation joins, reducing
+the free space trapped in partial stripes -- and thus stripe_unusable --
+for mixed-size workloads.
+
+The open-stripe selftest is rewritten to the multi-cursor contract: a
+misfit allocation now keeps the old run open (its tail is not returned to
+the cache) and a later small allocation backfills it, so fewer stripes are
+claimed before the free space is exhausted.
+
+Assisted-by: Claude:claude-opus-4-8
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 146 ++++++++++++++++++++++--------
+ fs/btrfs/block-group.h | 13 ++-
+ fs/btrfs/tests/free-space-tests.c | 83 +++++++++++------
+ 3 files changed, 176 insertions(+), 66 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 17b66c42d0898..6aaa6e22deb7e 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -501,12 +501,30 @@ static bool open_stripe_run_drained(const struct btrfs_open_stripe_run *run)
+ return !run->open && run->inflight_bytes == 0;
+ }
+
++/*
++ * 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))
++ * sectors). Runs are kept at most one per band so an allocation can take the
++ * smallest band that fits.
++ */
++static int stripe_run_band(const struct btrfs_block_group *bg, u64 remaining)
++{
++ u32 sectors = remaining >> bg->fs_info->sectorsize_bits;
++ int band;
++
++ if (!sectors)
++ return 0;
++ band = fls(sectors) - 1;
++ if (band >= BTRFS_STRIPE_RUN_NR_BANDS)
++ band = BTRFS_STRIPE_RUN_NR_BANDS - 1;
++ return band;
++}
++
+ /* 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)
+ {
+ ASSERT(open_stripe_run_drained(run));
+- ASSERT(bg->open_stripe[run->class] != run);
+ list_del(&run->list);
+ kfree(run);
+ wake_up_var(&bg->open_stripe_runs);
+@@ -514,9 +532,9 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
+
+ /*
+ * Close a run: no further allocation may join it, and its unallocated tail
+- * must be returned to the free space cache by the caller (after dropping
+- * the lock). Caller holds bg->stripe_run_lock. Returns the tail length
+- * and sets *tail_start.
++ * must be returned to the free space cache by the caller (after dropping the
++ * lock). The caller has already removed @run from bg->open_stripe[][].
++ * Caller holds bg->stripe_run_lock. Returns the tail length, sets *tail_start.
+ */
+ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
+ struct btrfs_open_stripe_run *run,
+@@ -525,9 +543,7 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
+ u64 tail_len;
+
+ ASSERT(run->open);
+- ASSERT(bg->open_stripe[run->class] == run);
+ run->open = false;
+- bg->open_stripe[run->class] = NULL;
+ *tail_start = run->offset;
+ tail_len = run->end - run->offset;
+ run->end = run->offset;
+@@ -536,6 +552,37 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
+ return tail_len;
+ }
+
++/*
++ * Install @run (not currently in any band slot) into its remaining-space band.
++ * If a run already occupies that band, keep whichever has more remaining -- it
++ * can serve larger future allocations, and closing the other traps less -- and
++ * close the loser, returning its tail via *tail_start. Caller holds
++ * bg->stripe_run_lock. Returns the closed tail length, or 0 if no collision.
++ */
++static u64 stripe_run_place(struct btrfs_block_group *bg,
++ struct btrfs_open_stripe_run *run, u64 *tail_start)
++{
++ int class = run->class;
++ int band = stripe_run_band(bg, run->end - run->offset);
++ struct btrfs_open_stripe_run *occ = bg->open_stripe[class][band];
++
++ if (occ) {
++ struct btrfs_open_stripe_run *keep, *shut;
++
++ if (run->end - run->offset >= occ->end - occ->offset) {
++ keep = run;
++ shut = occ;
++ } else {
++ keep = occ;
++ shut = run;
++ }
++ bg->open_stripe[class][band] = keep;
++ return close_open_stripe_run(bg, shut, tail_start);
++ }
++ bg->open_stripe[class][band] = run;
++ return 0;
++}
++
+ /*
+ * Allocate num_bytes from the block group's open stripe run, opening a new
+ * run via btrfs_claim_free_stripe_run() when there is none or the current
+@@ -558,26 +605,46 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ u64 tail_len = 0;
+ u64 start;
+ u64 len;
++ int band;
+ int ret;
+
+ ASSERT(num_bytes);
+ *available = 0;
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+- run = bg->open_stripe[class];
+- if (run && num_bytes <= run->end - run->offset) {
++ /*
++ * Best fit: take the run in the smallest band that can hold this
++ * allocation, and track the largest remaining across all bands as the
++ * retry hint should nothing fit.
++ */
++ run = NULL;
++ for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++) {
++ struct btrfs_open_stripe_run *r = bg->open_stripe[class][band];
++ u64 rem;
++
++ if (!r)
++ continue;
++ rem = r->end - r->offset;
++ if (rem > *available)
++ *available = rem;
++ if (!run && num_bytes <= rem) {
++ run = r;
++ bg->open_stripe[class][band] = NULL;
++ }
++ }
++ if (run) {
+ *ret_offset = run->offset;
+ run->offset += num_bytes;
+ run->inflight_bytes += num_bytes;
+- if (run->offset == run->end) {
+- run->open = false;
+- bg->open_stripe[class] = NULL;
+- }
++ if (run->offset == run->end)
++ run->open = false; /* full: closed, no tail */
++ else
++ tail_len = stripe_run_place(bg, run, &tail_start);
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ if (tail_len)
++ btrfs_add_free_space(bg, tail_start, tail_len);
+ return 0;
+ }
+- if (run)
+- *available = run->end - run->offset;
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+
+ new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
+@@ -630,14 +697,6 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ ret = -ENOSPC;
+ goto out;
+ }
+- /*
+- * Close this class's open run if one (re)appeared: it was too small
+- * for us, or a racing opener's. Closing is always safe; the last
+- * opener wins.
+- */
+- run = bg->open_stripe[class];
+- if (run)
+- tail_len = close_open_stripe_run(bg, run, &tail_start);
+ new_run->bg = bg;
+ new_run->class = class;
+ new_run->start = start;
+@@ -647,7 +706,13 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ new_run->open_seq = fs_info->stripe_retire_seq;
+ new_run->open = (new_run->offset != new_run->end);
+ list_add_tail(&new_run->list, &bg->open_stripe_runs);
+- bg->open_stripe[class] = new_run->open ? new_run : NULL;
++ /*
++ * Place the new run in its remaining-space band, closing whichever run
++ * loses a band collision (the last, fuller opener wins). Other bands'
++ * open runs are untouched.
++ */
++ if (new_run->open)
++ tail_len = stripe_run_place(bg, new_run, &tail_start);
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ spin_unlock(&fs_info->open_stripe_lock);
+
+@@ -757,32 +822,37 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+ /*
+ * Close the block group's open runs that predate @seq and return their
+ * unallocated tails to the free space cache. Does not wait for inflight
+- * IO. Only the bg->open_stripe[] slots can ever be open, so one pass over
+- * the classes suffices.
++ * IO. Metadata runs are left to btrfs_retire_meta_stripes() and persistent
++ * NOCOW runs stay open unless dead, except when @seq is U64_MAX (read-only,
++ * removal, unmount), which closes everything.
+ */
+ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
+ u64 seq)
+ {
+- u64 tail_start[BTRFS_STRIPE_RUN_NR_CLASSES];
+- u64 tail_len[BTRFS_STRIPE_RUN_NR_CLASSES];
++ u64 tail_start[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
++ u64 tail_len[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
+ struct btrfs_open_stripe_run *run;
+ unsigned long flags;
+- int class;
++ int class, band;
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++) {
+- tail_len[class] = 0;
+- run = bg->open_stripe[class];
+- if (run && run->open_seq < seq)
+- tail_len[class] = close_open_stripe_run(bg, run,
+- &tail_start[class]);
++ for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++) {
++ tail_len[class][band] = 0;
++ run = bg->open_stripe[class][band];
++ if (run && run->open_seq < seq) {
++ bg->open_stripe[class][band] = NULL;
++ tail_len[class][band] = close_open_stripe_run(
++ bg, run, &tail_start[class][band]);
++ }
++ }
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+- for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++) {
+- if (tail_len[class])
+- btrfs_add_free_space(bg, tail_start[class],
+- tail_len[class]);
+- }
++ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
++ for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++)
++ if (tail_len[class][band])
++ btrfs_add_free_space(bg, tail_start[class][band],
++ tail_len[class][band]);
+ }
+
+ /*
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 1c9115ecb3a64..b76c44f09d532 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -32,6 +32,16 @@ enum btrfs_stripe_run_class {
+ BTRFS_STRIPE_RUN_RELOC,
+ BTRFS_STRIPE_RUN_NR_CLASSES,
+ };
++
++/*
++ * Open stripe runs are kept in power-of-two bands of remaining free space:
++ * band k holds a run whose remaining is in [2^k, 2^(k+1)) sectors. An
++ * allocation takes the smallest band that fits (segregated best fit), so it
++ * lands in an already-open stripe sized to it instead of forcing a fresh
++ * claim and trapping the old run's tail. 16 bands cover a full stripe of up
++ * to 2^16 sectors, far more than any raid56 geometry.
++ */
++#define BTRFS_STRIPE_RUN_NR_BANDS 16
+ enum btrfs_block_group_size_class {
+ /* Unset */
+ BTRFS_BG_SZ_NONE,
+@@ -221,7 +231,8 @@ struct btrfs_block_group {
+ */
+ spinlock_t stripe_run_lock;
+ struct list_head open_stripe_runs;
+- struct btrfs_open_stripe_run *open_stripe[BTRFS_STRIPE_RUN_NR_CLASSES];
++ struct btrfs_open_stripe_run
++ *open_stripe[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
+ /*
+ * Membership in fs_info->open_stripe_bgs, protected by
+ * fs_info->open_stripe_lock; holds a block group reference.
+diff --git a/fs/btrfs/tests/free-space-tests.c b/fs/btrfs/tests/free-space-tests.c
+index 197db1694c1b0..8dcc4d8aafa2e 100644
+--- a/fs/btrfs/tests/free-space-tests.c
++++ b/fs/btrfs/tests/free-space-tests.c
+@@ -1257,7 +1257,12 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
+ goto out;
+ }
+
+- /* Doesn't fit the remainder: closes the run, opens the next stripe. */
++ /*
++ * A full-stripe allocation cannot fit the open run's remainder, so it
++ * opens a fresh stripe. With multiple cursors the old run stays open in
++ * its remaining-space band (its tail is not trapped); a single cursor
++ * would have closed it here.
++ */
+ ret = btrfs_alloc_from_open_stripe(cache, fsl, BTRFS_STRIPE_RUN_COW,
+ &offset, &avail);
+ if (ret || offset != 2 * fsl) {
+@@ -1265,29 +1270,34 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
+ ret = -EINVAL;
+ goto out;
+ }
+- /* The closed run's tail went back to the free space cache... */
+- if (!test_check_exists(cache, fsl + 4 * sectorsize,
+- fsl - 4 * sectorsize)) {
+- test_err("closed run tail missing from free space");
++ /* The old run is still open, so its tail is NOT back in the cache. */
++ if (test_check_exists(cache, fsl + 4 * sectorsize,
++ fsl - 4 * sectorsize)) {
++ test_err("kept-open run tail wrongly freed");
+ ret = -EINVAL;
+ goto out;
+ }
+- /* ...but is part of a partial stripe, so the next alloc skips it. */
++ /* A small allocation backtracks to fill the still-open run. */
+ ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
+ BTRFS_STRIPE_RUN_COW, &offset,
+ &avail);
+- if (ret || offset != 3 * fsl) {
+- test_err("post-close alloc wrong: ret %d offset %llu",
++ if (ret || offset != fsl + 4 * sectorsize) {
++ test_err("backfill alloc wrong: ret %d offset %llu",
+ ret, offset);
+ ret = -EINVAL;
+ goto out;
+ }
+
+- /* A different class never joins the cow run: fresh stripe. */
++ /*
++ * A different class never joins the cow run: it opens a fresh stripe.
++ * Only stripes #1 and #2 have been claimed so far (multi-cursor kept
++ * #1 open and backfilled it rather than claiming a new stripe for the
++ * small allocations), so the reloc class claims #3.
++ */
+ ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
+ BTRFS_STRIPE_RUN_RELOC, &offset,
+ &avail);
+- if (ret || offset != 4 * fsl) {
++ if (ret || offset != 3 * fsl) {
+ test_err("reloc class alloc wrong: ret %d offset %llu",
+ ret, offset);
+ ret = -EINVAL;
+@@ -1297,51 +1307,66 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
+ ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
+ BTRFS_STRIPE_RUN_COW, &offset,
+ &avail);
+- if (ret || offset != 3 * fsl + sectorsize) {
++ if (ret || offset != fsl + 5 * sectorsize) {
+ test_err("cow run lost by class open: ret %d offset %llu",
+ ret, offset);
+ ret = -EINVAL;
+ goto out;
+ }
+
+- /* Report all data IO complete, in pieces. */
++ /* Report all data IO complete, in pieces, at the offsets allocated. */
+ btrfs_open_stripe_write_done(cache, fsl, 2 * sectorsize);
+ btrfs_open_stripe_write_done(cache, fsl + 2 * sectorsize,
+ 2 * sectorsize);
++ btrfs_open_stripe_write_done(cache, fsl + 4 * sectorsize, sectorsize);
++ btrfs_open_stripe_write_done(cache, fsl + 5 * sectorsize, sectorsize);
+ btrfs_open_stripe_write_done(cache, 2 * fsl, fsl);
+ btrfs_open_stripe_write_done(cache, 3 * fsl, sectorsize);
+- btrfs_open_stripe_write_done(cache, 3 * fsl + sectorsize, sectorsize);
+- btrfs_open_stripe_write_done(cache, 4 * fsl, sectorsize);
+
+ /*
+- * Commit-style retirement: closes both classes' open runs, returns
+- * their tails, drains (instantly, all IO reported done) and drops
+- * the block group's membership in fs_info->open_stripe_bgs.
++ * Commit-style retirement: closes every open run in every band of both
++ * classes, returns their tails, drains (instantly, all IO reported
++ * done) and drops the block group's membership in
++ * fs_info->open_stripe_bgs. The cow run filled [fsl, fsl+6*sectorsize)
++ * and the reloc run filled [3*fsl, 3*fsl+sectorsize); each tail returns.
+ */
+ btrfs_retire_open_stripes(fs_info, NULL);
+- if (!test_check_exists(cache, 3 * fsl + 2 * sectorsize,
+- fsl - 2 * sectorsize)) {
++ if (!test_check_exists(cache, fsl + 6 * sectorsize,
++ fsl - 6 * sectorsize)) {
+ test_err("retired cow run tail missing from free space");
+ ret = -EINVAL;
+ goto out;
+ }
+- if (!test_check_exists(cache, 4 * fsl + sectorsize,
++ if (!test_check_exists(cache, 3 * fsl + sectorsize,
+ fsl - sectorsize)) {
+ test_err("retired reloc run tail missing from free space");
+ ret = -EINVAL;
+ goto out;
+ }
+
+- /* Stripe #5 was never claimed and is still fully free. */
++ /* Stripe #4 was never claimed and is still fully free. */
+ ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
+ BTRFS_STRIPE_RUN_COW, &offset,
+ &avail);
+- if (ret || offset != 5 * fsl) {
++ if (ret || offset != 4 * fsl) {
+ test_err("post-retire alloc wrong: ret %d offset %llu",
+ ret, offset);
+ ret = -EINVAL;
+ goto out;
+ }
++ btrfs_open_stripe_write_done(cache, 4 * fsl, sectorsize);
++ btrfs_retire_open_stripes(fs_info, NULL);
++
++ /* Stripe #5 is the last fully-free stripe. */
++ ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
++ BTRFS_STRIPE_RUN_COW, &offset,
++ &avail);
++ if (ret || offset != 5 * fsl) {
++ test_err("last-stripe alloc wrong: ret %d offset %llu",
++ ret, offset);
++ ret = -EINVAL;
++ goto out;
++ }
+ btrfs_open_stripe_write_done(cache, 5 * fsl, sectorsize);
+ btrfs_retire_open_stripes(fs_info, NULL);
+
+@@ -1355,20 +1380,24 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
+ goto out;
+ }
+
+- /* Clean up the partial-stripe remainders. */
++ /*
++ * Clean up the partial-stripe remainders: stripe #0's head, stripe #1's
++ * cow tail (10 sectors), and the 15-sector tails of stripes #3 (reloc),
++ * #4 and #5. Stripe #2 was filled completely and has no remainder.
++ */
+ ret = btrfs_remove_free_space(cache, sectorsize, fsl - sectorsize);
+ if (ret) {
+ test_err("error cleaning up head %d", ret);
+ goto out;
+ }
+- ret = btrfs_remove_free_space(cache, fsl + 4 * sectorsize,
+- fsl - 4 * sectorsize);
++ ret = btrfs_remove_free_space(cache, fsl + 6 * sectorsize,
++ fsl - 6 * sectorsize);
+ if (ret) {
+ test_err("error cleaning up tail 1 %d", ret);
+ goto out;
+ }
+- ret = btrfs_remove_free_space(cache, 3 * fsl + 2 * sectorsize,
+- fsl - 2 * sectorsize);
++ ret = btrfs_remove_free_space(cache, 3 * fsl + sectorsize,
++ fsl - sectorsize);
+ if (ret) {
+ test_err("error cleaning up tail 2 %d", ret);
+ goto out;
+--
+2.47.3
+
--- /dev/null
+From 38f0f97adcd4fa6d4d124e8bc7846a41b974a7db Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:27 -0400
+Subject: [RFC PATCH 09/85] btrfs: stripe_alloc: grow the frontier run instead
+ of stranding its tail
+To: linux-btrfs@vger.kernel.org
+
+When an allocation is larger than every open run's remainder, the
+allocator claims fresh fully-free stripes and opens a separate run,
+leaving the old run's tail behind. The banded cursors keep that tail
+open for a while, but a band collision or the commit eventually closes
+it, and the tail -- perfectly usable space that a misfit merely jumped
+over -- is stranded in a partially filled stripe. In a forward fill
+this happens at every size upshift, and measurement shows it is where
+nearly all of stripe_alloc's trapped space comes from: on a mixed-size
+fill it strands ~14% of the data written, a figure that band-granularity
+tuning moves by at most a tenth and commit frequency does not move at
+all.
+
+Grow the frontier run instead. If the freshly claimed stripes directly
+follow the end of an open run of the same class, extend that run to
+absorb them and place the allocation at the run's old tail, spilling
+contiguously into the new stripes. Nothing is stranded, and the extent
+is physically contiguous. In a forward fill the by-size claim naturally
+returns the stripes adjacent to the frontier, so the single frontier run
+just keeps growing -- the allocator packs the way the stock allocator
+does, while keeping stripe exclusivity: the grown stripes were claimed
+fully free, the run still closes at the next commit and is never
+reopened, so every stripe of the run is filled within one open-run
+lifetime. A grown run keeps its open_seq; it can only still be in a
+band slot if the retire walk for its window has not yet run, which the
+open_stripe_lock nesting at the claim site excludes from racing.
+
+Measured on a 4-device raid5 with a deterministic interleaved 4K-512K
+fill (trapped space via the stripe_unusable counter, byte-identical data
+both sides): 111.1 MiB trapped without growing, 7.2 MiB with -- a 94%
+reduction, and usable capacity at ENOSPC within 0.5% of the stock
+allocator (1561 vs 1569 MiB, vs 1421 MiB without growing). The benefit
+survives churn: with age-correlated deletion the grown runs' contiguous
+packing lets whole stripes free together, and steady-state usable
+capacity stays at 1486-1561 MiB versus 1284-1421 MiB without growing
+across correlated and adversarial small-file deletion patterns. Data
+integrity verified by scrub and full sha256 read-back over mixed
+random-content files, and trapped-space accounting still returns to
+zero when all files are deleted.
+
+The open-stripe selftest is updated: the misfit allocation now grows the
+run and lands at the run's old tail, spanning the stripe boundary, and
+the relocation-class case doubles as a check that a claim adjacent to
+another class's run never grows it.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 42 +++++++++++++++++++---
+ fs/btrfs/tests/free-space-tests.c | 60 +++++++++++++++++--------------
+ 2 files changed, 71 insertions(+), 31 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 6aaa6e22deb7e..21eae818ab5de 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -584,10 +584,13 @@ static u64 stripe_run_place(struct btrfs_block_group *bg,
+ }
+
+ /*
+- * Allocate num_bytes from the block group's open stripe run, opening a new
+- * run via btrfs_claim_free_stripe_run() when there is none or the current
+- * one does not fit. The allocation counts toward the run's inflight bytes
+- * until btrfs_open_stripe_write_done() reports its data IO complete.
++ * Allocate num_bytes from the block group's shared open runs of @class,
++ * best fit across the remaining-space bands, claiming a new run via
++ * btrfs_claim_free_stripe_run() when none fits. If the freshly claimed
++ * stripes directly follow an open run of the same class, that run grows to
++ * absorb them instead (see the comment at the claim site). The allocation
++ * counts toward the run's inflight bytes until its IO is reported done or
++ * abandoned.
+ *
+ * Returns 0 and sets *ret_offset, -ENOSPC if no fully-free stripe run in
+ * this block group can satisfy the allocation, or -ENOMEM.
+@@ -697,6 +700,37 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ ret = -ENOSPC;
+ goto out;
+ }
++ /*
++ * Growable frontier: if the claimed region directly follows an open run
++ * of the same class, grow that run over it and place this allocation at
++ * the run's old tail, so the tail is used rather than stranded when the
++ * run closes. Stripe exclusivity holds: the grown stripes were claimed
++ * fully free, and the run is still retired at commit. The run keeps
++ * its open_seq: it can only still be in a band slot if the retire walk
++ * for its window has not run, which this lock nesting excludes.
++ */
++ for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++) {
++ struct btrfs_open_stripe_run *r = bg->open_stripe[class][band];
++
++ if (!r || r->end != start)
++ continue;
++ ASSERT(r->open);
++ bg->open_stripe[class][band] = NULL;
++ *ret_offset = r->offset;
++ r->end = start + len;
++ r->offset += num_bytes;
++ r->inflight_bytes += num_bytes;
++ if (r->offset == r->end)
++ r->open = false; /* full: closed, no tail */
++ else
++ tail_len = stripe_run_place(bg, r, &tail_start);
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ spin_unlock(&fs_info->open_stripe_lock);
++ if (tail_len)
++ btrfs_add_free_space(bg, tail_start, tail_len);
++ ret = 0;
++ goto out; /* frees the unused new_run */
++ }
+ new_run->bg = bg;
+ new_run->class = class;
+ new_run->start = start;
+diff --git a/fs/btrfs/tests/free-space-tests.c b/fs/btrfs/tests/free-space-tests.c
+index 8dcc4d8aafa2e..1ee9632d7e0b6 100644
+--- a/fs/btrfs/tests/free-space-tests.c
++++ b/fs/btrfs/tests/free-space-tests.c
+@@ -1258,41 +1258,43 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
+ }
+
+ /*
+- * A full-stripe allocation cannot fit the open run's remainder, so it
+- * opens a fresh stripe. With multiple cursors the old run stays open in
+- * its remaining-space band (its tail is not trapped); a single cursor
+- * would have closed it here.
++ * A full-stripe allocation cannot fit the open run's remainder. The
++ * claimed stripe #2 directly follows the run's end, so the run GROWS to
++ * absorb it and the allocation starts at the run's old tail, spanning
++ * the stripe boundary: nothing is stranded and the extent is placed at
++ * fsl + 4 * sectorsize, not at the fresh stripe's start.
+ */
+ ret = btrfs_alloc_from_open_stripe(cache, fsl, BTRFS_STRIPE_RUN_COW,
+ &offset, &avail);
+- if (ret || offset != 2 * fsl) {
+- test_err("misfit alloc wrong: ret %d offset %llu", ret, offset);
++ if (ret || offset != fsl + 4 * sectorsize) {
++ test_err("grown misfit alloc wrong: ret %d offset %llu",
++ ret, offset);
+ ret = -EINVAL;
+ goto out;
+ }
+- /* The old run is still open, so its tail is NOT back in the cache. */
+- if (test_check_exists(cache, fsl + 4 * sectorsize,
++ /* The grown run's new tail is open, NOT back in the free cache. */
++ if (test_check_exists(cache, 2 * fsl + 4 * sectorsize,
+ fsl - 4 * sectorsize)) {
+- test_err("kept-open run tail wrongly freed");
++ test_err("grown run tail wrongly freed");
+ ret = -EINVAL;
+ goto out;
+ }
+- /* A small allocation backtracks to fill the still-open run. */
++ /* A small allocation keeps filling the grown run. */
+ ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
+ BTRFS_STRIPE_RUN_COW, &offset,
+ &avail);
+- if (ret || offset != fsl + 4 * sectorsize) {
+- test_err("backfill alloc wrong: ret %d offset %llu",
++ if (ret || offset != 2 * fsl + 4 * sectorsize) {
++ test_err("post-grow alloc wrong: ret %d offset %llu",
+ ret, offset);
+ ret = -EINVAL;
+ goto out;
+ }
+
+ /*
+- * A different class never joins the cow run: it opens a fresh stripe.
+- * Only stripes #1 and #2 have been claimed so far (multi-cursor kept
+- * #1 open and backfilled it rather than claiming a new stripe for the
+- * small allocations), so the reloc class claims #3.
++ * A different class never joins -- or grows -- the cow run. The reloc
++ * claim of stripe #3 directly follows the cow run's end (the grown run
++ * covers stripes #1-#2), which is exactly the growable case within a
++ * class, yet the reloc allocation must open its own fresh run there.
+ */
+ ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
+ BTRFS_STRIPE_RUN_RELOC, &offset,
+@@ -1307,7 +1309,7 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
+ ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
+ BTRFS_STRIPE_RUN_COW, &offset,
+ &avail);
+- if (ret || offset != fsl + 5 * sectorsize) {
++ if (ret || offset != 2 * fsl + 5 * sectorsize) {
+ test_err("cow run lost by class open: ret %d offset %llu",
+ ret, offset);
+ ret = -EINVAL;
+@@ -1318,20 +1320,23 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
+ btrfs_open_stripe_write_done(cache, fsl, 2 * sectorsize);
+ btrfs_open_stripe_write_done(cache, fsl + 2 * sectorsize,
+ 2 * sectorsize);
+- btrfs_open_stripe_write_done(cache, fsl + 4 * sectorsize, sectorsize);
+- btrfs_open_stripe_write_done(cache, fsl + 5 * sectorsize, sectorsize);
+- btrfs_open_stripe_write_done(cache, 2 * fsl, fsl);
++ btrfs_open_stripe_write_done(cache, fsl + 4 * sectorsize, fsl);
++ btrfs_open_stripe_write_done(cache, 2 * fsl + 4 * sectorsize,
++ sectorsize);
++ btrfs_open_stripe_write_done(cache, 2 * fsl + 5 * sectorsize,
++ sectorsize);
+ btrfs_open_stripe_write_done(cache, 3 * fsl, sectorsize);
+
+ /*
+ * Commit-style retirement: closes every open run in every band of both
+ * classes, returns their tails, drains (instantly, all IO reported
+ * done) and drops the block group's membership in
+- * fs_info->open_stripe_bgs. The cow run filled [fsl, fsl+6*sectorsize)
+- * and the reloc run filled [3*fsl, 3*fsl+sectorsize); each tail returns.
++ * fs_info->open_stripe_bgs. The grown cow run covers stripes #1-#2 and
++ * filled [fsl, 2*fsl+6*sectorsize); the reloc run filled
++ * [3*fsl, 3*fsl+sectorsize); each tail returns.
+ */
+ btrfs_retire_open_stripes(fs_info, NULL);
+- if (!test_check_exists(cache, fsl + 6 * sectorsize,
++ if (!test_check_exists(cache, 2 * fsl + 6 * sectorsize,
+ fsl - 6 * sectorsize)) {
+ test_err("retired cow run tail missing from free space");
+ ret = -EINVAL;
+@@ -1381,16 +1386,17 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
+ }
+
+ /*
+- * Clean up the partial-stripe remainders: stripe #0's head, stripe #1's
+- * cow tail (10 sectors), and the 15-sector tails of stripes #3 (reloc),
+- * #4 and #5. Stripe #2 was filled completely and has no remainder.
++ * Clean up the partial-stripe remainders: stripe #0's head, the grown
++ * cow run's 10-sector tail in stripe #2, and the 15-sector tails of
++ * stripes #3 (reloc), #4 and #5. Stripe #1 was filled completely and
++ * has no remainder.
+ */
+ ret = btrfs_remove_free_space(cache, sectorsize, fsl - sectorsize);
+ if (ret) {
+ test_err("error cleaning up head %d", ret);
+ goto out;
+ }
+- ret = btrfs_remove_free_space(cache, fsl + 6 * sectorsize,
++ ret = btrfs_remove_free_space(cache, 2 * fsl + 6 * sectorsize,
+ fsl - 6 * sectorsize);
+ if (ret) {
+ test_err("error cleaning up tail 1 %d", ret);
+--
+2.47.3
+
+++ /dev/null
-From 427ea2e48fe7637468e2647834a26d2c9b069800 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:27 -0400
-Subject: [RFC PATCH 009/116] btrfs: stripe_alloc: keep an open run per size
- band to trap less
-To: linux-btrfs@vger.kernel.org
-
-A single open stripe run per class forces every allocation that does not
-fit the current run's remainder to close that run -- trapping its
-unallocated tail in a now partially filled stripe -- and claim a fresh
-fully-free stripe. A workload that interleaves small and large extents
-(the common case) therefore strands a tail on every size change, even
-though a later small allocation could have filled it.
-
-Keep one open run per power-of-two band of remaining free space instead
-(band k holds a run with remaining in [2^k, 2^(k+1)) sectors), per class.
-An allocation takes the run in the smallest band that still fits --
-segregated best fit -- so a small write lands in an already-open, nearly
-full stripe rather than opening a new one, while a large write that no
-open run can hold opens a fresh stripe and leaves the smaller runs open
-for the small writes that do fit them. After each allocation the run is
-re-placed into the band its new remainder falls in; when two runs collide
-in a band the fuller one is kept -- it can serve larger future
-allocations, and closing it would trap more -- and the other is closed,
-its tail returned to the free space cache.
-
-16 bands cover a full stripe of up to 2^16 sectors, far more than any
-raid56 geometry (nr_data_stripes * stripe_len / sectorsize is 158 sectors
-at 10 data stripes and a 64K stripe). Commit-time retirement and the
-read-only / removal paths now walk every band of every class; only the
-bg->open_stripe[][] slots can ever hold an open run, so one pass still
-suffices, and the obsolete single-slot assertions are dropped.
-
-This does not touch the write-hole guarantee: every run is still a
-contiguous fill of fully-free stripes, closed at commit and never
-reopened. It only changes which open run an allocation joins, reducing
-the free space trapped in partial stripes -- and thus stripe_unusable --
-for mixed-size workloads.
-
-The open-stripe selftest is rewritten to the multi-cursor contract: a
-misfit allocation now keeps the old run open (its tail is not returned to
-the cache) and a later small allocation backfills it, so fewer stripes are
-claimed before the free space is exhausted.
-
-Assisted-by: Claude:claude-opus-4-8
----
- fs/btrfs/block-group.c | 147 ++++++++++++++++++++++--------
- fs/btrfs/block-group.h | 13 ++-
- fs/btrfs/tests/free-space-tests.c | 83 +++++++++++------
- 3 files changed, 176 insertions(+), 67 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 03ecf86d707f6..0141b06ed0639 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -504,12 +504,30 @@ static bool open_stripe_run_drained(const struct btrfs_open_stripe_run *run)
- return !run->open && run->inflight_bytes == 0;
- }
-
-+/*
-+ * 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))
-+ * sectors). Runs are kept at most one per band so an allocation can take the
-+ * smallest band that fits.
-+ */
-+static int stripe_run_band(const struct btrfs_block_group *bg, u64 remaining)
-+{
-+ u32 sectors = remaining >> bg->fs_info->sectorsize_bits;
-+ int band;
-+
-+ if (!sectors)
-+ return 0;
-+ band = fls(sectors) - 1;
-+ if (band >= BTRFS_STRIPE_RUN_NR_BANDS)
-+ band = BTRFS_STRIPE_RUN_NR_BANDS - 1;
-+ return band;
-+}
-+
- /* 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)
- {
- ASSERT(open_stripe_run_drained(run));
-- ASSERT(bg->open_stripe[run->class] != run);
- list_del(&run->list);
- kfree(run);
- wake_up_var(&bg->open_stripe_runs);
-@@ -517,9 +535,9 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
-
- /*
- * Close a run: no further allocation may join it, and its unallocated tail
-- * must be returned to the free space cache by the caller (after dropping
-- * the lock). Caller holds bg->stripe_run_lock. Returns the tail length
-- * and sets *tail_start.
-+ * must be returned to the free space cache by the caller (after dropping the
-+ * lock). The caller has already removed @run from bg->open_stripe[][].
-+ * Caller holds bg->stripe_run_lock. Returns the tail length, sets *tail_start.
- */
- static u64 close_open_stripe_run(struct btrfs_block_group *bg,
- struct btrfs_open_stripe_run *run,
-@@ -528,9 +546,7 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
- u64 tail_len;
-
- ASSERT(run->open);
-- ASSERT(bg->open_stripe[run->class] == run);
- run->open = false;
-- bg->open_stripe[run->class] = NULL;
- *tail_start = run->offset;
- tail_len = run->end - run->offset;
- run->end = run->offset;
-@@ -539,6 +555,37 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
- return tail_len;
- }
-
-+/*
-+ * Install @run (not currently in any band slot) into its remaining-space band.
-+ * If a run already occupies that band, keep whichever has more remaining -- it
-+ * can serve larger future allocations, and closing the other traps less -- and
-+ * close the loser, returning its tail via *tail_start. Caller holds
-+ * bg->stripe_run_lock. Returns the closed tail length, or 0 if no collision.
-+ */
-+static u64 stripe_run_place(struct btrfs_block_group *bg,
-+ struct btrfs_open_stripe_run *run, u64 *tail_start)
-+{
-+ int class = run->class;
-+ int band = stripe_run_band(bg, run->end - run->offset);
-+ struct btrfs_open_stripe_run *occ = bg->open_stripe[class][band];
-+
-+ if (occ) {
-+ struct btrfs_open_stripe_run *keep, *shut;
-+
-+ if (run->end - run->offset >= occ->end - occ->offset) {
-+ keep = run;
-+ shut = occ;
-+ } else {
-+ keep = occ;
-+ shut = run;
-+ }
-+ bg->open_stripe[class][band] = keep;
-+ return close_open_stripe_run(bg, shut, tail_start);
-+ }
-+ bg->open_stripe[class][band] = run;
-+ return 0;
-+}
-+
- /*
- * Allocate num_bytes from the block group's open stripe run, opening a new
- * run via btrfs_claim_free_stripe_run() when there is none or the current
-@@ -561,26 +608,46 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- u64 tail_len = 0;
- u64 start;
- u64 len;
-+ int band;
- int ret;
-
- ASSERT(num_bytes);
- *available = 0;
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
-- run = bg->open_stripe[class];
-- if (run && num_bytes <= run->end - run->offset) {
-+ /*
-+ * Best fit: take the run in the smallest band that can hold this
-+ * allocation, and track the largest remaining across all bands as the
-+ * retry hint should nothing fit.
-+ */
-+ run = NULL;
-+ for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++) {
-+ struct btrfs_open_stripe_run *r = bg->open_stripe[class][band];
-+ u64 rem;
-+
-+ if (!r)
-+ continue;
-+ rem = r->end - r->offset;
-+ if (rem > *available)
-+ *available = rem;
-+ if (!run && num_bytes <= rem) {
-+ run = r;
-+ bg->open_stripe[class][band] = NULL;
-+ }
-+ }
-+ if (run) {
- *ret_offset = run->offset;
- run->offset += num_bytes;
- run->inflight_bytes += num_bytes;
-- if (run->offset == run->end) {
-- run->open = false;
-- bg->open_stripe[class] = NULL;
-- }
-+ if (run->offset == run->end)
-+ run->open = false; /* full; drains then is freed */
-+ else
-+ tail_len = stripe_run_place(bg, run, &tail_start);
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ if (tail_len)
-+ btrfs_add_free_space(bg, tail_start, tail_len);
- return 0;
- }
-- if (run)
-- *available = run->end - run->offset;
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-
- new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
-@@ -633,14 +700,6 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- ret = -ENOSPC;
- goto out;
- }
-- /*
-- * Close this class's open run if one (re)appeared: it was too small
-- * for us, or a racing opener's. Closing is always safe; the last
-- * opener wins.
-- */
-- run = bg->open_stripe[class];
-- if (run)
-- tail_len = close_open_stripe_run(bg, run, &tail_start);
- new_run->bg = bg;
- new_run->class = class;
- new_run->start = start;
-@@ -650,7 +709,13 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- new_run->open_seq = fs_info->stripe_retire_seq;
- new_run->open = (new_run->offset != new_run->end);
- list_add_tail(&new_run->list, &bg->open_stripe_runs);
-- bg->open_stripe[class] = new_run->open ? new_run : NULL;
-+ /*
-+ * Place the new run in its remaining-space band, closing whichever run
-+ * loses a band collision (the last, fuller opener wins). Other bands'
-+ * open runs are untouched.
-+ */
-+ if (new_run->open)
-+ tail_len = stripe_run_place(bg, new_run, &tail_start);
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- spin_unlock(&fs_info->open_stripe_lock);
-
-@@ -764,33 +829,37 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
-
- /*
- * Close the block group's open runs that predate @seq and return their
-- * unallocated tails to the free space cache. Does not wait for inflight
-- * IO. Only the bg->open_stripe[] slots can ever be open, so one pass over
-- * the classes suffices.
-+ * unallocated tails to the free space cache. Does not wait for inflight IO.
-+ * Only the bg->open_stripe[][] slots can ever be open, so one pass over the
-+ * classes and their remaining-space bands suffices.
- */
- static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
- u64 seq)
- {
-- u64 tail_start[BTRFS_STRIPE_RUN_NR_CLASSES];
-- u64 tail_len[BTRFS_STRIPE_RUN_NR_CLASSES];
-+ u64 tail_start[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
-+ u64 tail_len[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
- struct btrfs_open_stripe_run *run;
- unsigned long flags;
-- int class;
-+ int class, band;
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++) {
-- tail_len[class] = 0;
-- run = bg->open_stripe[class];
-- if (run && run->open_seq < seq)
-- tail_len[class] = close_open_stripe_run(bg, run,
-- &tail_start[class]);
-+ for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++) {
-+ tail_len[class][band] = 0;
-+ run = bg->open_stripe[class][band];
-+ if (run && run->open_seq < seq) {
-+ bg->open_stripe[class][band] = NULL;
-+ tail_len[class][band] = close_open_stripe_run(
-+ bg, run, &tail_start[class][band]);
-+ }
-+ }
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-- for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++) {
-- if (tail_len[class])
-- btrfs_add_free_space(bg, tail_start[class],
-- tail_len[class]);
-- }
-+ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
-+ for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++)
-+ if (tail_len[class][band])
-+ btrfs_add_free_space(bg, tail_start[class][band],
-+ tail_len[class][band]);
- }
-
- /*
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 89bdb04edb421..63052c4761b29 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -32,6 +32,16 @@ enum btrfs_stripe_run_class {
- BTRFS_STRIPE_RUN_RELOC,
- BTRFS_STRIPE_RUN_NR_CLASSES,
- };
-+
-+/*
-+ * Open stripe runs are kept in power-of-two bands of remaining free space:
-+ * band k holds a run whose remaining is in [2^k, 2^(k+1)) sectors. An
-+ * allocation takes the smallest band that fits (segregated best fit), so it
-+ * lands in an already-open stripe sized to it instead of forcing a fresh
-+ * claim and trapping the old run's tail. 16 bands cover a full stripe of up
-+ * to 2^16 sectors, far more than any raid56 geometry.
-+ */
-+#define BTRFS_STRIPE_RUN_NR_BANDS 16
- enum btrfs_block_group_size_class {
- /* Unset */
- BTRFS_BG_SZ_NONE,
-@@ -229,7 +239,8 @@ struct btrfs_block_group {
- */
- spinlock_t stripe_run_lock;
- struct list_head open_stripe_runs;
-- struct btrfs_open_stripe_run *open_stripe[BTRFS_STRIPE_RUN_NR_CLASSES];
-+ struct btrfs_open_stripe_run
-+ *open_stripe[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
- /*
- * Membership in fs_info->open_stripe_bgs, protected by
- * fs_info->open_stripe_lock; holds a block group reference.
-diff --git a/fs/btrfs/tests/free-space-tests.c b/fs/btrfs/tests/free-space-tests.c
-index 197db1694c1b0..8dcc4d8aafa2e 100644
---- a/fs/btrfs/tests/free-space-tests.c
-+++ b/fs/btrfs/tests/free-space-tests.c
-@@ -1257,7 +1257,12 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
- goto out;
- }
-
-- /* Doesn't fit the remainder: closes the run, opens the next stripe. */
-+ /*
-+ * A full-stripe allocation cannot fit the open run's remainder, so it
-+ * opens a fresh stripe. With multiple cursors the old run stays open in
-+ * its remaining-space band (its tail is not trapped); a single cursor
-+ * would have closed it here.
-+ */
- ret = btrfs_alloc_from_open_stripe(cache, fsl, BTRFS_STRIPE_RUN_COW,
- &offset, &avail);
- if (ret || offset != 2 * fsl) {
-@@ -1265,29 +1270,34 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
- ret = -EINVAL;
- goto out;
- }
-- /* The closed run's tail went back to the free space cache... */
-- if (!test_check_exists(cache, fsl + 4 * sectorsize,
-- fsl - 4 * sectorsize)) {
-- test_err("closed run tail missing from free space");
-+ /* The old run is still open, so its tail is NOT back in the cache. */
-+ if (test_check_exists(cache, fsl + 4 * sectorsize,
-+ fsl - 4 * sectorsize)) {
-+ test_err("kept-open run tail wrongly freed");
- ret = -EINVAL;
- goto out;
- }
-- /* ...but is part of a partial stripe, so the next alloc skips it. */
-+ /* A small allocation backtracks to fill the still-open run. */
- ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
- BTRFS_STRIPE_RUN_COW, &offset,
- &avail);
-- if (ret || offset != 3 * fsl) {
-- test_err("post-close alloc wrong: ret %d offset %llu",
-+ if (ret || offset != fsl + 4 * sectorsize) {
-+ test_err("backfill alloc wrong: ret %d offset %llu",
- ret, offset);
- ret = -EINVAL;
- goto out;
- }
-
-- /* A different class never joins the cow run: fresh stripe. */
-+ /*
-+ * A different class never joins the cow run: it opens a fresh stripe.
-+ * Only stripes #1 and #2 have been claimed so far (multi-cursor kept
-+ * #1 open and backfilled it rather than claiming a new stripe for the
-+ * small allocations), so the reloc class claims #3.
-+ */
- ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
- BTRFS_STRIPE_RUN_RELOC, &offset,
- &avail);
-- if (ret || offset != 4 * fsl) {
-+ if (ret || offset != 3 * fsl) {
- test_err("reloc class alloc wrong: ret %d offset %llu",
- ret, offset);
- ret = -EINVAL;
-@@ -1297,51 +1307,66 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
- ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
- BTRFS_STRIPE_RUN_COW, &offset,
- &avail);
-- if (ret || offset != 3 * fsl + sectorsize) {
-+ if (ret || offset != fsl + 5 * sectorsize) {
- test_err("cow run lost by class open: ret %d offset %llu",
- ret, offset);
- ret = -EINVAL;
- goto out;
- }
-
-- /* Report all data IO complete, in pieces. */
-+ /* Report all data IO complete, in pieces, at the offsets allocated. */
- btrfs_open_stripe_write_done(cache, fsl, 2 * sectorsize);
- btrfs_open_stripe_write_done(cache, fsl + 2 * sectorsize,
- 2 * sectorsize);
-+ btrfs_open_stripe_write_done(cache, fsl + 4 * sectorsize, sectorsize);
-+ btrfs_open_stripe_write_done(cache, fsl + 5 * sectorsize, sectorsize);
- btrfs_open_stripe_write_done(cache, 2 * fsl, fsl);
- btrfs_open_stripe_write_done(cache, 3 * fsl, sectorsize);
-- btrfs_open_stripe_write_done(cache, 3 * fsl + sectorsize, sectorsize);
-- btrfs_open_stripe_write_done(cache, 4 * fsl, sectorsize);
-
- /*
-- * Commit-style retirement: closes both classes' open runs, returns
-- * their tails, drains (instantly, all IO reported done) and drops
-- * the block group's membership in fs_info->open_stripe_bgs.
-+ * Commit-style retirement: closes every open run in every band of both
-+ * classes, returns their tails, drains (instantly, all IO reported
-+ * done) and drops the block group's membership in
-+ * fs_info->open_stripe_bgs. The cow run filled [fsl, fsl+6*sectorsize)
-+ * and the reloc run filled [3*fsl, 3*fsl+sectorsize); each tail returns.
- */
- btrfs_retire_open_stripes(fs_info, NULL);
-- if (!test_check_exists(cache, 3 * fsl + 2 * sectorsize,
-- fsl - 2 * sectorsize)) {
-+ if (!test_check_exists(cache, fsl + 6 * sectorsize,
-+ fsl - 6 * sectorsize)) {
- test_err("retired cow run tail missing from free space");
- ret = -EINVAL;
- goto out;
- }
-- if (!test_check_exists(cache, 4 * fsl + sectorsize,
-+ if (!test_check_exists(cache, 3 * fsl + sectorsize,
- fsl - sectorsize)) {
- test_err("retired reloc run tail missing from free space");
- ret = -EINVAL;
- goto out;
- }
-
-- /* Stripe #5 was never claimed and is still fully free. */
-+ /* Stripe #4 was never claimed and is still fully free. */
- ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
- BTRFS_STRIPE_RUN_COW, &offset,
- &avail);
-- if (ret || offset != 5 * fsl) {
-+ if (ret || offset != 4 * fsl) {
- test_err("post-retire alloc wrong: ret %d offset %llu",
- ret, offset);
- ret = -EINVAL;
- goto out;
- }
-+ btrfs_open_stripe_write_done(cache, 4 * fsl, sectorsize);
-+ btrfs_retire_open_stripes(fs_info, NULL);
-+
-+ /* Stripe #5 is the last fully-free stripe. */
-+ ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
-+ BTRFS_STRIPE_RUN_COW, &offset,
-+ &avail);
-+ if (ret || offset != 5 * fsl) {
-+ test_err("last-stripe alloc wrong: ret %d offset %llu",
-+ ret, offset);
-+ ret = -EINVAL;
-+ goto out;
-+ }
- btrfs_open_stripe_write_done(cache, 5 * fsl, sectorsize);
- btrfs_retire_open_stripes(fs_info, NULL);
-
-@@ -1355,20 +1380,24 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
- goto out;
- }
-
-- /* Clean up the partial-stripe remainders. */
-+ /*
-+ * Clean up the partial-stripe remainders: stripe #0's head, stripe #1's
-+ * cow tail (10 sectors), and the 15-sector tails of stripes #3 (reloc),
-+ * #4 and #5. Stripe #2 was filled completely and has no remainder.
-+ */
- ret = btrfs_remove_free_space(cache, sectorsize, fsl - sectorsize);
- if (ret) {
- test_err("error cleaning up head %d", ret);
- goto out;
- }
-- ret = btrfs_remove_free_space(cache, fsl + 4 * sectorsize,
-- fsl - 4 * sectorsize);
-+ ret = btrfs_remove_free_space(cache, fsl + 6 * sectorsize,
-+ fsl - 6 * sectorsize);
- if (ret) {
- test_err("error cleaning up tail 1 %d", ret);
- goto out;
- }
-- ret = btrfs_remove_free_space(cache, 3 * fsl + 2 * sectorsize,
-- fsl - 2 * sectorsize);
-+ ret = btrfs_remove_free_space(cache, 3 * fsl + sectorsize,
-+ fsl - sectorsize);
- if (ret) {
- test_err("error cleaning up tail 2 %d", ret);
- goto out;
---
-2.47.3
-
--- /dev/null
+From 9a0221ec59bc5466fff131a68edd4fe72da935d1 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:29 -0400
+Subject: [RFC PATCH 10/85] btrfs: raid56: batch stripe_alloc partial writes
+ into full-stripe writes
+To: linux-btrfs@vger.kernel.org
+
+A raid56 sub-stripe write pays a read-modify-write: read the rest of the
+stripe, recompute parity, write. The plug callback merges rbios submitted
+within one plug window and the stripe cache saves re-reads for
+back-to-back writes, but measurement shows what survives them: on a
+4-device raid5, small-file writeback produces 100% sub-stripe rbios (zero
+full-stripe writes) and a mixed 4K-512K workload ~55%, so parity is
+recomputed and rewritten once per file that lands in a stripe.
+
+Stripe-exclusive allocation gives raid56 something the allocator never
+guaranteed before: the rest of an open run's stripe is either written
+before the run closes -- within the current transaction -- or not at all.
+That makes holding a partial write a sound bet, so park it: a partial
+write rbio whose stripe belongs to a stripe run keeps the stripe
+lock but does not start its RMW. Later writes to the stripe merge into
+it through the existing lock_stripe_add() path, and the moment its data
+bitmap covers the stripe it is submitted as a single full-stripe write:
+one parity computation, no reads.
+
+A draining run counts, not just an open one. A run closes the moment it
+is fully allocated -- typically milliseconds before its last writes reach
+the raid56 layer -- so gating on "open" would leave exactly those tail
+writes unable to park and unable to pad, and they are the bulk of the
+read-modify-writes this patch exists to remove. A draining run is in
+fact the safest thing to park against: its frontier is frozen, so
+everything below it is inflight IO the commit drain already waits for
+(arrival guaranteed) and everything above it is dead space the pad may
+fill.
+
+Completion accounting can never trigger the flush of runts -- parked bios
+have not been submitted, and preallocated or discarded allocations
+produce no bios at all -- so liveness comes from explicit flushes: the
+run retirement paths flush before the commit's IO drain (which waits on
+the very bios parked here), ordered-extent waiters flush their range on a
+short retry period, and a timer bounds everything else. Writes with a
+blocked waiter (REQ_SYNC: fsync- and sync-driven writeback) park with a
+~3ms deadline instead of 100ms -- long enough for the rest of one
+writeback pass over the stripe to merge in, short enough to stay
+invisible in fsync latency -- and a sync bio merging into a parked rbio
+pulls the deadline in. Only the bg->open_stripe slots are consulted for
+eligibility, and a parked rbio that a racing retirement closed out from
+under is bounded by the timer, never by the drain.
+
+Measured (same 4-device raid5, deterministic workloads, classifying every
+write rbio at rmw_rbio):
+
+ workload full-stripe rbios total write rbios
+ streaming 99% -> 99% unchanged
+ mixed 4K-512K 43% -> 97% 2478 -> 1615
+ small files 0% -> 86% 1537 -> 335 (stripe reads 311->23)
+ fsync-per-file 0% -> 0% unchanged (nothing co-pending)
+
+fsync latency is 12ms vs 8ms unpatched (each fsync pays one short park).
+Batching also collapses trapped free space in a mixed-size forward fill
+from ~87 MiB to ~3 MiB: stripes now fill completely before the commit
+closes their run, so the frontier strands almost nothing.
+
+Validated: btrfs selftests; mixed-size + concurrency + churn + balance
+workload with trapped-space accounting returning to zero after deleting
+everything; scrub and full sha256 read-back over 4005 mixed random files;
+and the dm-log-writes write-hole crash matrix (24/24 controls clean, 0/36
+armed cases with committed data damage) -- parking does not perturb the
+stripe-exclusivity guarantee it rides on.
+
+Parking widens a run's post-close drain from microseconds to the park
+deadline, which exposes an assumption of the range-to-run lookups: at most
+one run on a block group's list covers any address. A reservation
+discarded before anything references it (the cow_file_range() error path
+under ENOSPC, the find_free_extent() backout paths) returns its bytes to
+the free space cache at once, so a stripe can become fully free while its
+old run is still draining and be claimed into a new run.
+btrfs_claim_free_stripe_run() therefore trims a candidate to end before
+the first live run overlapping it, or rejects it if its head overlaps.
+Without that, fill-to-ENOSPC/delete cycles with balance and fsstress on a
+4-device raid5 hit an inflight accounting assertion within 15 minutes.
+
+The fast fsync path waits for page writeback without the ordered extent
+wait that flushes parked rbios, so it flushes the parked rbios covering its
+ordered extents before the wait. A sync rbio leaving a raid_unplug() batch
+(a sync(2) or WB_SYNC_ALL sweep, whose whole flush shares one plug) has
+nothing more coming and a waiter behind it, so it does not park; unplugged
+sync submissions (the fsync flush) still park and merge their sibling bios.
+
+rbio_try_park() keeps reading the rbio after publishing it (to queue the
+timer and recheck rbio_is_full()), while a flusher may already have taken,
+written and freed it, so the parking thread holds its own reference across
+that window. Whatever is still parked at unmount or on a failed mount is
+sent down, and the park timer cancelled, before the raid56 workqueue is
+destroyed.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 292 ++++++++++++++++++++++--------------
+ fs/btrfs/block-group.h | 3 +
+ fs/btrfs/disk-io.c | 2 +
+ fs/btrfs/file.c | 23 +++
+ fs/btrfs/free-space-cache.c | 7 +-
+ fs/btrfs/ordered-data.c | 22 +++
+ fs/btrfs/raid56.c | 292 +++++++++++++++++++++++++++++++++++-
+ fs/btrfs/raid56.h | 12 ++
+ 8 files changed, 538 insertions(+), 115 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 21eae818ab5de..0c1cd5bc8e208 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -760,6 +760,176 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ return ret;
+ }
+
++/*
++ * 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
++ * (abandoned allocations): a second run over the same range would make the
++ * range-to-run lookups (ordered extent attach, IO reporting) ambiguous and
++ * corrupt the inflight accounting. Trim the candidate to end before the
++ * first overlapping run, and reject it if its head overlaps or less than a
++ * full stripe remains. Caller holds ctl->tree_lock; stripe_run_lock nests
++ * inside it.
++ */
++bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
++ u64 run_start, u64 *run_len)
++{
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ u64 len = *run_len;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (run->end <= run_start || run->start >= run_start + len)
++ continue;
++ if (run->start <= run_start) {
++ len = 0;
++ break;
++ }
++ len = run->start - run_start;
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ if (len < bg->full_stripe_len)
++ return false;
++ *run_len = len;
++ return true;
++}
++
++/*
++ * Can stripe-exclusive allocation be enabled on this filesystem? Called for
++ * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
++ * finalized) filesystem.
++ */
++int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info)
++{
++ if (!btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
++ btrfs_err(fs_info,
++ "stripe_alloc requires the free space tree (space_cache=v2)");
++ return -EINVAL;
++ }
++ if (btrfs_fs_incompat(fs_info, REMAP_TREE)) {
++ btrfs_err(fs_info,
++ "stripe_alloc is not supported together with the remap-tree feature");
++ return -EINVAL;
++ }
++ if (btrfs_is_zoned(fs_info)) {
++ btrfs_err(fs_info,
++ "stripe_alloc is not supported on zoned filesystems");
++ return -EINVAL;
++ }
++ /*
++ * A mixed group is excluded from the claim rule anyway
++ * (btrfs_is_stripe_alloc_bg() requires DATA without METADATA), so
++ * enabling here would protect nothing while reporting success.
++ */
++ if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
++ btrfs_err(fs_info,
++ "stripe_alloc is not supported on mixed block groups");
++ return -EINVAL;
++ }
++ return 0;
++}
++
++/*
++ * Arm or disarm stripe_unusable accounting across all raid56 data block
++ * groups whose caches are loaded. Same walk as the commit-time rescan.
++ */
++static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
++{
++ struct btrfs_space_info *sinfo;
++
++ list_for_each_entry(sinfo, &fs_info->space_info, list) {
++ int raid;
++
++ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
++ continue;
++ down_read(&sinfo->groups_sem);
++ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
++ struct btrfs_block_group *bg;
++
++ if (!(btrfs_raid_array[raid].bg_flag &
++ BTRFS_BLOCK_GROUP_RAID56_MASK))
++ continue;
++ list_for_each_entry(bg, &sinfo->block_groups[raid],
++ list) {
++ if (!arm)
++ btrfs_block_group_disarm_stripe_unusable(bg);
++ else if (bg->cached == BTRFS_CACHE_FINISHED)
++ btrfs_block_group_init_stripe_unusable(bg);
++ }
++ }
++ up_read(&sinfo->groups_sem);
++ }
++}
++
++int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
++{
++ int ret;
++
++ if (btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return 0;
++ ret = btrfs_stripe_alloc_check_support(fs_info);
++ if (ret)
++ return ret;
++ btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
++ /*
++ * Arm stripe_unusable accounting for raid56 data groups whose caches
++ * loaded before the policy was enabled: block groups are read before
++ * the root directory's properties apply during mount, and a runtime
++ * property set can arrive at any point. Groups still caching arm
++ * when their caching thread finishes, now that the policy is on.
++ */
++ stripe_alloc_sweep_groups(fs_info, true);
++ btrfs_info(fs_info,
++ "using stripe-exclusive allocation for raid56 data");
++ return 0;
++}
++
++/*
++ * Turn off stripe-exclusive allocation (property deleted). Open runs are
++ * not touched here: the commit-time retirement runs unconditionally and
++ * drains them at the next transaction commit.
++ */
++void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
++{
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return;
++ /* Disarm while the policy bit still passes the per-group gate. */
++ stripe_alloc_sweep_groups(fs_info, false);
++ btrfs_clear_opt(fs_info->mount_opt, STRIPE_ALLOC);
++ btrfs_info(fs_info,
++ "stripe-exclusive allocation for raid56 data disabled");
++}
++
++/*
++ * Does @logical lie within a stripe run, open or draining? The raid56 layer
++ * uses this to decide whether a partial write may be parked to merge into a
++ * full-stripe write. An open run fills the rest of the stripe later or
++ * never; a draining run's frontier is frozen, so everything below it is IO
++ * the commit drain already waits for and everything above it is dead space
++ * padding may fill.
++ */
++bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
++{
++ struct btrfs_block_group *bg;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ bool ret = false;
++
++ bg = btrfs_lookup_block_group(fs_info, logical);
++ if (!bg)
++ return false;
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (logical >= run->start && logical < run->end) {
++ ret = true;
++ break;
++ }
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ btrfs_put_block_group(bg);
++ return ret;
++}
++
+ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+ u64 num_bytes)
+ {
+@@ -916,118 +1086,6 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
+ return ret;
+ }
+
+-/*
+- * Can stripe-exclusive allocation be enabled on this filesystem? Called for
+- * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
+- * finalized) filesystem.
+- */
+-int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info)
+-{
+- if (!btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
+- btrfs_err(fs_info,
+- "stripe_alloc requires the free space tree (space_cache=v2)");
+- return -EINVAL;
+- }
+- if (btrfs_fs_incompat(fs_info, REMAP_TREE)) {
+- btrfs_err(fs_info,
+- "stripe_alloc is not supported together with the remap-tree feature");
+- return -EINVAL;
+- }
+- if (btrfs_is_zoned(fs_info)) {
+- btrfs_err(fs_info,
+- "stripe_alloc is not supported on zoned filesystems");
+- return -EINVAL;
+- }
+- /*
+- * A mixed group is excluded from the claim rule anyway
+- * (btrfs_is_stripe_alloc_bg() requires DATA without METADATA), so
+- * enabling here would protect nothing while reporting success.
+- */
+- if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
+- btrfs_err(fs_info,
+- "stripe_alloc is not supported on mixed block groups");
+- return -EINVAL;
+- }
+- return 0;
+-}
+-
+-/*
+- * Arm or disarm stripe_unusable accounting across all raid56 data block
+- * groups whose caches are loaded. Same walk as the commit-time rescan.
+- */
+-static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
+-{
+- struct btrfs_space_info *sinfo;
+-
+- list_for_each_entry(sinfo, &fs_info->space_info, list) {
+- int raid;
+-
+- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
+- continue;
+- down_read(&sinfo->groups_sem);
+- for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
+- struct btrfs_block_group *bg;
+-
+- if (!(btrfs_raid_array[raid].bg_flag &
+- BTRFS_BLOCK_GROUP_RAID56_MASK))
+- continue;
+- list_for_each_entry(bg, &sinfo->block_groups[raid],
+- list) {
+- if (!arm)
+- btrfs_block_group_disarm_stripe_unusable(bg);
+- else if (bg->cached == BTRFS_CACHE_FINISHED)
+- btrfs_block_group_init_stripe_unusable(bg);
+- }
+- }
+- up_read(&sinfo->groups_sem);
+- }
+-}
+-
+-/*
+- * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
+- * property on the top-level subvolume's root directory. Runs during mount
+- * when the root directory inode loads its properties -- before any user IO
+- * -- or at runtime from btrfs_set_prop().
+- */
+-int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
+-{
+- int ret;
+-
+- if (btrfs_test_opt(fs_info, STRIPE_ALLOC))
+- return 0;
+- ret = btrfs_stripe_alloc_check_support(fs_info);
+- if (ret)
+- return ret;
+- btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
+- /*
+- * Arm stripe_unusable accounting for raid56 data groups whose caches
+- * loaded before the policy was enabled: block groups are read before
+- * the root directory's properties apply during mount, and a runtime
+- * property set can arrive at any point. Groups still caching arm
+- * when their caching thread finishes, now that the policy is on.
+- */
+- stripe_alloc_sweep_groups(fs_info, true);
+- btrfs_info(fs_info,
+- "using stripe-exclusive allocation for raid56 data");
+- return 0;
+-}
+-
+-/*
+- * Turn off stripe-exclusive allocation (property deleted). Open runs are
+- * not touched here: the commit-time retirement runs unconditionally and
+- * drains them at the next transaction commit.
+- */
+-void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
+-{
+- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
+- return;
+- /* Disarm while the policy bit still passes the per-group gate. */
+- stripe_alloc_sweep_groups(fs_info, false);
+- btrfs_clear_opt(fs_info->mount_opt, STRIPE_ALLOC);
+- btrfs_info(fs_info,
+- "stripe-exclusive allocation for raid56 data disabled");
+-}
+-
+ /*
+ * Close and drain all of a block group's stripe runs. The caller must
+ * prevent new allocations first (e.g. the block group is read-only),
+@@ -1043,6 +1101,8 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
+ struct btrfs_fs_info *fs_info = bg->fs_info;
+
+ close_block_group_stripe_runs(bg, U64_MAX);
++ /* Parked partial-stripe rbios hold the very bios the wait drains. */
++ btrfs_flush_parked_rbios(bg->fs_info, bg->start, bg->length);
+ wait_var_event(&bg->open_stripe_runs,
+ bg_open_stripes_settled(bg, U64_MAX) ||
+ BTRFS_FS_ERROR(fs_info));
+@@ -1106,6 +1166,14 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
+ list_for_each_entry(bg, &retire_list, open_stripe_retire_list)
+ close_block_group_stripe_runs(bg, seq);
+
++ /*
++ * Parked partial-stripe write rbios (see raid56.c) hold bios whose
++ * write_done the drain below waits for; kick them all down first.
++ * A racing park that saw its run still open lands after this flush
++ * and is bounded by the park timer, not by us.
++ */
++ btrfs_flush_parked_rbios(fs_info, 0, U64_MAX);
++
+ while (!list_empty(&retire_list)) {
+ bg = list_first_entry(&retire_list, struct btrfs_block_group,
+ open_stripe_retire_list);
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index b76c44f09d532..7f2df9d2fc31c 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -395,6 +395,9 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
+ void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
+ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
+ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
++bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
++bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
++ u64 run_start, u64 *run_len);
+ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
+ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
+ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
+diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
+index b1df5fd84a94f..28f360e84f110 100644
+--- a/fs/btrfs/disk-io.c
++++ b/fs/btrfs/disk-io.c
+@@ -3846,6 +3846,7 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
+ invalidate_and_check_btree_folios(fs_info);
+
+ fail_sb_buffer:
++ btrfs_stop_parked_rbios(fs_info);
+ btrfs_stop_all_workers(fs_info);
+ btrfs_free_block_groups(fs_info);
+ fail_alloc:
+@@ -4608,6 +4609,7 @@ void __cold close_ctree(struct btrfs_fs_info *fs_info)
+ * submit after we stop all workers.
+ */
+ invalidate_and_check_btree_folios(fs_info);
++ btrfs_stop_parked_rbios(fs_info);
+ btrfs_stop_all_workers(fs_info);
+
+ /*
+diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
+index f978c6524aa03..2dc1fbf569cf3 100644
+--- a/fs/btrfs/file.c
++++ b/fs/btrfs/file.c
+@@ -35,6 +35,7 @@
+ #include "extent-tree.h"
+ #include "file-item.h"
+ #include "ioctl.h"
++#include "raid56.h"
+ #include "file.h"
+ #include "super.h"
+ #include "print-tree.h"
+@@ -1635,6 +1636,28 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
+ * checksums attached to the ordered extents.
+ */
+ btrfs_get_ordered_extents_for_logging(inode, &ctx.ordered_extents);
++
++ /*
++ * The writeback wait below completes only when the raid56
++ * layer writes this fsync's data, but a partial-stripe rbio
++ * parks (collecting merges) until its sync deadline, and on
++ * this path nothing else unparks it before the wait -- the
++ * stripes are settled only later, in the logging itself. All
++ * of this fsync's writes are submitted by now, so nothing
++ * more can merge; kick the parked rbios covering our ordered
++ * extents instead of sleeping out their deadline.
++ */
++ if (btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
++ struct btrfs_ordered_extent *tmp_oe;
++
++ list_for_each_entry(tmp_oe, &ctx.ordered_extents,
++ log_list)
++ if (tmp_oe->disk_num_bytes)
++ btrfs_flush_parked_rbios(fs_info,
++ tmp_oe->disk_bytenr,
++ tmp_oe->disk_num_bytes);
++ }
++
+ ret = filemap_fdatawait_range(inode->vfs_inode.i_mapping, start, end);
+ if (ret)
+ goto out_release_extents;
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 67ce6dc643f76..391a50a4dd0b7 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -2238,7 +2238,9 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+
+ if (entry->bitmap) {
+ if (find_stripe_run_in_bitmap(ctl, entry, want_bytes,
+- &run_start, &run_len))
++ &run_start, &run_len) &&
++ btrfs_stripe_run_range_usable(block_group,
++ run_start, &run_len))
+ goto found;
+ continue;
+ }
+@@ -2249,6 +2251,9 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ run_len = min(want_bytes,
+ div64_u64(entry->offset + entry->bytes - run_start,
+ fsl) * fsl);
++ if (!btrfs_stripe_run_range_usable(block_group, run_start,
++ &run_len))
++ continue;
+ goto found;
+ }
+ goto out;
+diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
+index eb6b2da628220..44122090fe4f4 100644
+--- a/fs/btrfs/ordered-data.c
++++ b/fs/btrfs/ordered-data.c
+@@ -20,6 +20,7 @@
+ #include "subpage.h"
+ #include "file.h"
+ #include "block-group.h"
++#include "raid56.h"
+
+ static struct kmem_cache *btrfs_ordered_extent_cache;
+
+@@ -923,6 +924,27 @@ void btrfs_start_ordered_extent_nowriteback(struct btrfs_ordered_extent *entry,
+ }
+
+ btrfs_might_wait_for_event(inode->root->fs_info, btrfs_ordered_extent);
++ /*
++ * A parked partial-stripe write rbio (raid56 full-stripe batching) may
++ * be holding this extent's bios; kick it down or the wait is bounded
++ * by the park timer instead of the IO. The park happens on a worker
++ * after the submission above returns, so a single flush can run too
++ * early and miss it -- retry on a short period until the extent
++ * completes. Only stripe_alloc filesystems ever park, so everything
++ * else takes the plain single sleep below.
++ */
++ while (btrfs_test_opt(inode->root->fs_info, STRIPE_ALLOC) &&
++ entry->disk_num_bytes &&
++ !test_bit(BTRFS_ORDERED_COMPLETE, &entry->flags)) {
++ btrfs_flush_parked_rbios(inode->root->fs_info,
++ entry->disk_bytenr,
++ entry->disk_num_bytes);
++ if (wait_event_timeout(entry->wait,
++ test_bit(BTRFS_ORDERED_COMPLETE,
++ &entry->flags),
++ msecs_to_jiffies(10)))
++ break;
++ }
+ wait_event(entry->wait, test_bit(BTRFS_ORDERED_COMPLETE, &entry->flags));
+ }
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 7dd937fa0c262..71ff75c8c93ff 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -21,6 +21,7 @@
+ #include "async-thread.h"
+ #include "file-item.h"
+ #include "btrfs_inode.h"
++#include "block-group.h"
+
+ /* set when additional merges to this rbio are not allowed */
+ #define RBIO_RMW_LOCKED_BIT 1
+@@ -36,8 +37,29 @@
+ */
+ #define RBIO_CACHE_READY_BIT 3
+
++/*
++ * Set while a partial write rbio is parked: it owns the stripe lock but its
++ * RMW has not been started, so writes filling the rest of an open stripe
++ * run's stripe merge into it (see rbio_try_park()). Whoever clears this bit
++ * owns starting the rbio's work, exactly once.
++ */
++#define RBIO_PARKED_BIT 4
++
++/*
++ * Set when an unplug callback finished merging this rbio's submission
++ * batch: the submitter has no more bios coming. A sync rbio past this
++ * point gains nothing from parking (its own batch is fully merged and a
++ * waiter is behind it), so it skips straight to the write.
++ */
++#define RBIO_BATCH_DONE_BIT 6
++
+ #define RBIO_CACHE_SIZE 1024
+
++#define BTRFS_RBIO_PARK_TIMEOUT_MS 100
++#define BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS 3
++/* Scan period of the park timer while anything is parked. */
++#define BTRFS_RBIO_PARK_SCAN_MS 3
++
+ #define BTRFS_STRIPE_HASH_TABLE_BITS 11
+
+ static void dump_bioc(const struct btrfs_fs_info *fs_info, const struct btrfs_io_context *bioc)
+@@ -130,6 +152,14 @@ struct btrfs_stripe_hash_table {
+ struct list_head stripe_cache;
+ spinlock_t cache_lock;
+ int cache_size;
++ /*
++ * Parked partial write rbios (RBIO_PARKED_BIT), in park order.
++ * parked_lock nests inside the hash and bio_list locks.
++ */
++ spinlock_t parked_lock;
++ struct list_head parked;
++ struct delayed_work parked_work;
++ struct btrfs_fs_info *fs_info;
+ struct btrfs_stripe_hash table[];
+ };
+
+@@ -141,6 +171,7 @@ struct btrfs_stripe_hash_table {
+
+ static void rmw_rbio_work(struct work_struct *work);
+ static void rmw_rbio_work_locked(struct work_struct *work);
++static void parked_rbios_timeout_work(struct work_struct *work);
+ static void index_rbio_pages(struct btrfs_raid_bio *rbio);
+ static int alloc_rbio_pages(struct btrfs_raid_bio *rbio);
+
+@@ -214,6 +245,10 @@ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info)
+
+ spin_lock_init(&table->cache_lock);
+ INIT_LIST_HEAD(&table->stripe_cache);
++ spin_lock_init(&table->parked_lock);
++ INIT_LIST_HEAD(&table->parked);
++ INIT_DELAYED_WORK(&table->parked_work, parked_rbios_timeout_work);
++ table->fs_info = info;
+
+ h = table->table;
+
+@@ -483,6 +518,27 @@ static void btrfs_clear_rbio_cache(struct btrfs_fs_info *info)
+ spin_unlock(&table->cache_lock);
+ }
+
++/*
++ * Send every parked rbio down and stop the park timer, before the raid56
++ * workqueue is destroyed: the timer queues its expired rbios there. By
++ * now nothing should be parked; a few passes cover an rbio that parks
++ * again on its way down.
++ */
++void btrfs_stop_parked_rbios(struct btrfs_fs_info *fs_info)
++{
++ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
++
++ if (!table || !fs_info->rmw_workers)
++ return;
++ for (int i = 0; i < 3 && !list_empty_careful(&table->parked); i++) {
++ btrfs_flush_parked_rbios(fs_info, 0, U64_MAX);
++ flush_workqueue(fs_info->rmw_workers);
++ }
++ cancel_delayed_work_sync(&table->parked_work);
++ flush_workqueue(fs_info->rmw_workers);
++ WARN_ON(!list_empty_careful(&table->parked));
++}
++
+ /*
+ * remove all cached entries and free the hash table
+ * used by unmount
+@@ -491,6 +547,8 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info)
+ {
+ if (!info->stripe_hash_table)
+ return;
++ cancel_delayed_work_sync(&info->stripe_hash_table->parked_work);
++ WARN_ON(!list_empty(&info->stripe_hash_table->parked));
+ btrfs_clear_rbio_cache(info);
+ kvfree(info->stripe_hash_table);
+ info->stripe_hash_table = NULL;
+@@ -616,6 +674,201 @@ static int rbio_can_merge(struct btrfs_raid_bio *last,
+ return 1;
+ }
+
++/*
++ * Full-stripe write batching for stripe-exclusive allocation.
++ *
++ * A partial write rbio whose stripe belongs to an open stripe run is parked:
++ * it keeps the stripe lock but its RMW is not started, so the writes that
++ * fill the rest of the stripe -- guaranteed to arrive before the run closes,
++ * or not at all -- merge into it through lock_stripe_add() instead of each
++ * paying a read-modify-write. The moment the data bitmap fills, the rbio is
++ * submitted as a single full-stripe write: one parity computation, no reads.
++ *
++ * Completion accounting can never be the flush trigger -- parked bios have
++ * not been submitted, and preallocated or discarded allocations produce no
++ * bios at all -- so everything that does not fill is flushed by the run
++ * retirement paths (before the commit's IO drain, which waits on the very
++ * bios parked here), by ordered-extent waiters, and by a timer that bounds
++ * both latency and the memory the parked pages pin.
++ */
++
++/* Caller holds table->parked_lock. */
++static void rbio_unpark_locked(struct btrfs_raid_bio *rbio)
++{
++ list_del_init(&rbio->parked_node);
++ clear_bit(RBIO_PARKED_BIT, &rbio->flags);
++}
++
++/* Does any bio gathered in @rbio carry a sync hint (a blocked waiter)? */
++static bool rbio_has_sync_bio(struct btrfs_raid_bio *rbio)
++{
++ struct bio *bio;
++
++ bio_list_for_each(bio, &rbio->bio_list)
++ if (bio->bi_opf & REQ_SYNC)
++ return true;
++ return false;
++}
++
++/*
++ * Park a partial write rbio that owns its stripe lock, if its stripe is
++ * covered by an open stripe run. Returns true if the rbio was parked (or
++ * concurrently filled and requeued); false if the caller should proceed
++ * with the RMW itself.
++ */
++static bool rbio_try_park(struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
++ unsigned int timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
++
++ if (!btrfs_stripe_in_open_run(fs_info, rbio->bioc->full_stripe_logical))
++ return false;
++
++ spin_lock(&rbio->bio_list_lock);
++ if (rbio_has_sync_bio(rbio))
++ timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
++ spin_unlock(&rbio->bio_list_lock);
++
++ /*
++ * A sync rbio whose submission batch was already merged by its
++ * unplug callback has nothing more coming from its submitter; the
++ * only thing parking can add is its deadline. (Unplugged sync
++ * submissions -- the fsync flush -- still park: their sibling bios
++ * arrive one by one and merge into the parked rbio, and the fsync
++ * path kicks it as soon as they have all been submitted.)
++ */
++ if (test_bit(RBIO_BATCH_DONE_BIT, &rbio->flags) &&
++ timeout_ms == BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS)
++ return false;
++
++ spin_lock(&table->parked_lock);
++ set_bit(RBIO_PARKED_BIT, &rbio->flags);
++ rbio->park_deadline = jiffies + msecs_to_jiffies(timeout_ms);
++ /*
++ * Take a reference of our own before publishing: once parked_lock is
++ * dropped, a flusher can unpark this rbio and run it to completion,
++ * consuming the initial and hash-list references, while we still read
++ * it in the fullness recheck below. It must be owned by this function,
++ * not by the parked list, since the unparker is the thread racing us.
++ */
++ refcount_inc(&rbio->refs);
++ list_add_tail(&rbio->parked_node, &table->parked);
++ spin_unlock(&table->parked_lock);
++ queue_delayed_work(system_percpu_wq, &table->parked_work,
++ msecs_to_jiffies(BTRFS_RBIO_PARK_SCAN_MS));
++
++ /*
++ * A merge may have filled us between the caller's fullness check and
++ * the park above; reclaim the park so the full stripe goes straight
++ * down. If the merger's unpark won instead, it queued the work.
++ */
++ if (rbio_is_full(rbio)) {
++ spin_lock(&table->parked_lock);
++ if (test_bit(RBIO_PARKED_BIT, &rbio->flags)) {
++ rbio_unpark_locked(rbio);
++ spin_unlock(&table->parked_lock);
++ free_raid_bio(rbio);
++ return false;
++ }
++ spin_unlock(&table->parked_lock);
++ }
++ /*
++ * Done reading it. Dropping our reference here cannot be the last
++ * one: a parked rbio still owns the stripe lock, and the only thing
++ * that completes it is the RMW a flusher starts after taking it off
++ * the list.
++ */
++ free_raid_bio(rbio);
++ return true;
++}
++
++/*
++ * A merge just filled a parked rbio: unpark it and start its (now read-free)
++ * write. Callers may hold the stripe hash and bio_list locks; parked_lock
++ * nests inside both.
++ */
++static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_stripe_hash_table *table =
++ rbio->bioc->fs_info->stripe_hash_table;
++
++ spin_lock(&table->parked_lock);
++ if (!test_bit(RBIO_PARKED_BIT, &rbio->flags)) {
++ spin_unlock(&table->parked_lock);
++ return;
++ }
++ rbio_unpark_locked(rbio);
++ spin_unlock(&table->parked_lock);
++ start_async_work(rbio, rmw_rbio_work_locked);
++}
++
++/*
++ * Flush every parked rbio overlapping [start, start + num_bytes) down its
++ * normal RMW path. Called by run retirement (before the commit's IO drain),
++ * ordered-extent waiters, and the park timer.
++ */
++void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
++ u64 num_bytes)
++{
++ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
++ struct btrfs_raid_bio *rbio;
++ struct btrfs_raid_bio *tmp;
++ LIST_HEAD(flush);
++
++ if (!table || list_empty_careful(&table->parked))
++ return;
++ spin_lock(&table->parked_lock);
++ list_for_each_entry_safe(rbio, tmp, &table->parked, parked_node) {
++ u64 rbio_start = rbio->bioc->full_stripe_logical;
++ u64 rbio_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
++
++ if (rbio_start + rbio_len <= start ||
++ (num_bytes != U64_MAX && rbio_start >= start + num_bytes))
++ continue;
++ rbio_unpark_locked(rbio);
++ list_add_tail(&rbio->parked_node, &flush);
++ }
++ spin_unlock(&table->parked_lock);
++
++ list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
++ list_del_init(&rbio->parked_node);
++ start_async_work(rbio, rmw_rbio_work_locked);
++ }
++}
++
++/* Flush parked rbios whose deadline has passed; re-arm while any remain. */
++static void parked_rbios_timeout_work(struct work_struct *work)
++{
++ struct btrfs_stripe_hash_table *table =
++ container_of(work, struct btrfs_stripe_hash_table,
++ parked_work.work);
++ struct btrfs_raid_bio *rbio;
++ struct btrfs_raid_bio *tmp;
++ LIST_HEAD(flush);
++ bool rearm = false;
++
++ spin_lock(&table->parked_lock);
++ list_for_each_entry_safe(rbio, tmp, &table->parked, parked_node) {
++ /* Deadlines are not ordered (sync parks are shorter). */
++ if (time_before(jiffies, rbio->park_deadline)) {
++ rearm = true;
++ continue;
++ }
++ rbio_unpark_locked(rbio);
++ list_add_tail(&rbio->parked_node, &flush);
++ }
++ spin_unlock(&table->parked_lock);
++
++ list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
++ list_del_init(&rbio->parked_node);
++ start_async_work(rbio, rmw_rbio_work_locked);
++ }
++ if (rearm)
++ queue_delayed_work(system_percpu_wq, &table->parked_work,
++ msecs_to_jiffies(BTRFS_RBIO_PARK_SCAN_MS));
++}
++
+ /* Return the sector index for @stripe_nr and @sector_nr. */
+ static unsigned int rbio_sector_index(const struct btrfs_raid_bio *rbio,
+ unsigned int stripe_nr,
+@@ -731,7 +984,35 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
+
+ /* Can we merge into the lock owner? */
+ if (rbio_can_merge(cur, rbio)) {
++ bool sync = rbio_has_sync_bio(rbio);
++
+ merge_rbio(cur, rbio);
++ /*
++ * Our bios may have completed a parked stripe. We
++ * hold cur->bio_list_lock, so test fullness directly
++ * (rbio_is_full() would self-deadlock on it). A sync
++ * bio merging into a still-partial parked rbio pulls
++ * its flush deadline in: a waiter is now blocked on
++ * this stripe.
++ */
++ if (test_bit(RBIO_PARKED_BIT, &cur->flags)) {
++ if (cur->bio_list_bytes ==
++ cur->nr_data * cur->bioc->stripe_len) {
++ unpark_full_rbio(cur);
++ } else if (sync) {
++ struct btrfs_stripe_hash_table *table =
++ cur->bioc->fs_info->stripe_hash_table;
++ unsigned long dl = jiffies +
++ msecs_to_jiffies(BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS);
++
++ spin_lock(&table->parked_lock);
++ if (test_bit(RBIO_PARKED_BIT,
++ &cur->flags) &&
++ time_before(dl, cur->park_deadline))
++ cur->park_deadline = dl;
++ spin_unlock(&table->parked_lock);
++ }
++ }
+ spin_unlock(&cur->bio_list_lock);
+ freeit = rbio;
+ ret = 1;
+@@ -1031,6 +1312,7 @@ static struct btrfs_raid_bio *alloc_rbio(struct btrfs_fs_info *fs_info,
+ spin_lock_init(&rbio->bio_list_lock);
+ INIT_LIST_HEAD(&rbio->stripe_cache);
+ INIT_LIST_HEAD(&rbio->hash_list);
++ INIT_LIST_HEAD(&rbio->parked_node);
+ btrfs_get_bioc(bioc);
+ rbio->bioc = bioc;
+ rbio->nr_pages = num_pages;
+@@ -1721,12 +2003,15 @@ static void raid_unplug(struct blk_plug_cb *cb, bool from_schedule)
+ free_raid_bio(cur);
+ continue;
+ }
++ set_bit(RBIO_BATCH_DONE_BIT, &last->flags);
+ start_async_work(last, rmw_rbio_work);
+ }
+ last = cur;
+ }
+- if (last)
++ if (last) {
++ set_bit(RBIO_BATCH_DONE_BIT, &last->flags);
+ start_async_work(last, rmw_rbio_work);
++ }
+ kfree(plug);
+ }
+
+@@ -2472,8 +2757,11 @@ static void rmw_rbio_work(struct work_struct *work)
+ struct btrfs_raid_bio *rbio;
+
+ rbio = container_of(work, struct btrfs_raid_bio, work);
+- if (lock_stripe_add(rbio) == 0)
++ if (lock_stripe_add(rbio) == 0) {
++ if (!rbio_is_full(rbio) && rbio_try_park(rbio))
++ return;
+ rmw_rbio(rbio);
++ }
+ }
+
+ static void rmw_rbio_work_locked(struct work_struct *work)
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index 8700910b8dc99..1dc9608587ff7 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -130,6 +130,15 @@ struct btrfs_raid_bio {
+ */
+ struct list_head plug_list;
+
++ /*
++ * Membership in the stripe hash table's parked list: partial write
++ * rbios for stripes of open stripe runs (stripe_alloc) are held back,
++ * collecting merges until they can go down as one full-stripe write.
++ * Protected by the table's parked_lock.
++ */
++ struct list_head parked_node;
++ unsigned long park_deadline;
++
+ /* Flags that tell us if it is safe to merge with this bio. */
+ unsigned long flags;
+
+@@ -282,5 +291,8 @@ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
+
+ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
+ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
++void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
++ u64 num_bytes);
++void btrfs_stop_parked_rbios(struct btrfs_fs_info *fs_info);
+
+ #endif
+--
+2.47.3
+
+++ /dev/null
-From 03b190f8691326607d8d2ef286b54bde277fe7bc Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:27 -0400
-Subject: [RFC PATCH 010/116] btrfs: stripe_alloc: grow the frontier run
- instead of stranding its tail
-To: linux-btrfs@vger.kernel.org
-
-When an allocation is larger than every open run's remainder, the
-allocator claims fresh fully-free stripes and opens a separate run,
-leaving the old run's tail behind. The banded cursors keep that tail
-open for a while, but a band collision or the commit eventually closes
-it, and the tail -- perfectly usable space that a misfit merely jumped
-over -- is stranded in a partially filled stripe. In a forward fill
-this happens at every size upshift, and measurement shows it is where
-nearly all of stripe_alloc's trapped space comes from: on a mixed-size
-fill it strands ~14% of the data written, a figure that band-granularity
-tuning moves by at most a tenth and commit frequency does not move at
-all.
-
-Grow the frontier run instead. If the freshly claimed stripes directly
-follow the end of an open run of the same class, extend that run to
-absorb them and place the allocation at the run's old tail, spilling
-contiguously into the new stripes. Nothing is stranded, and the extent
-is physically contiguous. In a forward fill the by-size claim naturally
-returns the stripes adjacent to the frontier, so the single frontier run
-just keeps growing -- the allocator packs the way the stock allocator
-does, while keeping stripe exclusivity: the grown stripes were claimed
-fully free, the run still closes at the next commit and is never
-reopened, so every stripe of the run is filled within one open-run
-lifetime. A grown run keeps its open_seq; it can only still be in a
-band slot if the retire walk for its window has not yet run, which the
-open_stripe_lock nesting at the claim site excludes from racing.
-
-Measured on a 4-device raid5 with a deterministic interleaved 4K-512K
-fill (trapped space via the stripe_unusable counter, byte-identical data
-both sides): 111.1 MiB trapped without growing, 7.2 MiB with -- a 94%
-reduction, and usable capacity at ENOSPC within 0.5% of the stock
-allocator (1561 vs 1569 MiB, vs 1421 MiB without growing). The benefit
-survives churn: with age-correlated deletion the grown runs' contiguous
-packing lets whole stripes free together, and steady-state usable
-capacity stays at 1486-1561 MiB versus 1284-1421 MiB without growing
-across correlated and adversarial small-file deletion patterns. Data
-integrity verified by scrub and full sha256 read-back over mixed
-random-content files, and trapped-space accounting still returns to
-zero when all files are deleted.
-
-The open-stripe selftest is updated: the misfit allocation now grows the
-run and lands at the run's old tail, spanning the stripe boundary, and
-the relocation-class case doubles as a check that a claim adjacent to
-another class's run never grows it.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 45 +++++++++++++++++++++--
- fs/btrfs/tests/free-space-tests.c | 60 +++++++++++++++++--------------
- 2 files changed, 76 insertions(+), 29 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 0141b06ed0639..f88fc9fe9bd10 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -589,8 +589,11 @@ static u64 stripe_run_place(struct btrfs_block_group *bg,
- /*
- * Allocate num_bytes from the block group's open stripe run, opening a new
- * run via btrfs_claim_free_stripe_run() when there is none or the current
-- * one does not fit. The allocation counts toward the run's inflight bytes
-- * until btrfs_open_stripe_write_done() reports its data IO complete.
-+ * one does not fit. If the freshly claimed stripes directly follow an open
-+ * run of the same class, that run grows to absorb them instead (see the
-+ * comment at the claim site). The allocation counts toward the run's
-+ * inflight bytes until btrfs_open_stripe_write_done() reports its data IO
-+ * complete.
- *
- * Returns 0 and sets *ret_offset, -ENOSPC if no fully-free stripe run in
- * this block group can satisfy the allocation, or -ENOMEM.
-@@ -700,6 +703,44 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- ret = -ENOSPC;
- goto out;
- }
-+ /*
-+ * Growable frontier: if the claimed region [start, start+len) directly
-+ * follows the end of an open run of the same class, grow that run to
-+ * absorb it and place this allocation at the run's old tail, spilling
-+ * contiguously into the claimed stripes. Without this, an allocation
-+ * larger than every open run's remainder would open a separate run and
-+ * the old tail -- perfectly usable space the misfit merely jumped over
-+ * -- would sit unfillable until a small allocation happened to find it,
-+ * or be stranded outright when a band collision or commit closed the
-+ * run. Growing preserves stripe exclusivity: the grown stripes were
-+ * claimed fully free, and the run still closes at the next commit and
-+ * is never reopened, so every stripe of the run is filled within one
-+ * open-run lifetime. The run keeps its open_seq: it can only still be
-+ * in a band slot if the retire walk for its window has not run, which
-+ * this lock nesting excludes from racing us.
-+ */
-+ for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++) {
-+ struct btrfs_open_stripe_run *r = bg->open_stripe[class][band];
-+
-+ if (!r || r->end != start)
-+ continue;
-+ ASSERT(r->open);
-+ bg->open_stripe[class][band] = NULL;
-+ *ret_offset = r->offset;
-+ r->end = start + len;
-+ r->offset += num_bytes;
-+ r->inflight_bytes += num_bytes;
-+ if (r->offset == r->end)
-+ r->open = false; /* full; drains then is freed */
-+ else
-+ tail_len = stripe_run_place(bg, r, &tail_start);
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ spin_unlock(&fs_info->open_stripe_lock);
-+ if (tail_len)
-+ btrfs_add_free_space(bg, tail_start, tail_len);
-+ ret = 0;
-+ goto out; /* frees the unused new_run */
-+ }
- new_run->bg = bg;
- new_run->class = class;
- new_run->start = start;
-diff --git a/fs/btrfs/tests/free-space-tests.c b/fs/btrfs/tests/free-space-tests.c
-index 8dcc4d8aafa2e..1ee9632d7e0b6 100644
---- a/fs/btrfs/tests/free-space-tests.c
-+++ b/fs/btrfs/tests/free-space-tests.c
-@@ -1258,41 +1258,43 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
- }
-
- /*
-- * A full-stripe allocation cannot fit the open run's remainder, so it
-- * opens a fresh stripe. With multiple cursors the old run stays open in
-- * its remaining-space band (its tail is not trapped); a single cursor
-- * would have closed it here.
-+ * A full-stripe allocation cannot fit the open run's remainder. The
-+ * claimed stripe #2 directly follows the run's end, so the run GROWS to
-+ * absorb it and the allocation starts at the run's old tail, spanning
-+ * the stripe boundary: nothing is stranded and the extent is placed at
-+ * fsl + 4 * sectorsize, not at the fresh stripe's start.
- */
- ret = btrfs_alloc_from_open_stripe(cache, fsl, BTRFS_STRIPE_RUN_COW,
- &offset, &avail);
-- if (ret || offset != 2 * fsl) {
-- test_err("misfit alloc wrong: ret %d offset %llu", ret, offset);
-+ if (ret || offset != fsl + 4 * sectorsize) {
-+ test_err("grown misfit alloc wrong: ret %d offset %llu",
-+ ret, offset);
- ret = -EINVAL;
- goto out;
- }
-- /* The old run is still open, so its tail is NOT back in the cache. */
-- if (test_check_exists(cache, fsl + 4 * sectorsize,
-+ /* The grown run's new tail is open, NOT back in the free cache. */
-+ if (test_check_exists(cache, 2 * fsl + 4 * sectorsize,
- fsl - 4 * sectorsize)) {
-- test_err("kept-open run tail wrongly freed");
-+ test_err("grown run tail wrongly freed");
- ret = -EINVAL;
- goto out;
- }
-- /* A small allocation backtracks to fill the still-open run. */
-+ /* A small allocation keeps filling the grown run. */
- ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
- BTRFS_STRIPE_RUN_COW, &offset,
- &avail);
-- if (ret || offset != fsl + 4 * sectorsize) {
-- test_err("backfill alloc wrong: ret %d offset %llu",
-+ if (ret || offset != 2 * fsl + 4 * sectorsize) {
-+ test_err("post-grow alloc wrong: ret %d offset %llu",
- ret, offset);
- ret = -EINVAL;
- goto out;
- }
-
- /*
-- * A different class never joins the cow run: it opens a fresh stripe.
-- * Only stripes #1 and #2 have been claimed so far (multi-cursor kept
-- * #1 open and backfilled it rather than claiming a new stripe for the
-- * small allocations), so the reloc class claims #3.
-+ * A different class never joins -- or grows -- the cow run. The reloc
-+ * claim of stripe #3 directly follows the cow run's end (the grown run
-+ * covers stripes #1-#2), which is exactly the growable case within a
-+ * class, yet the reloc allocation must open its own fresh run there.
- */
- ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
- BTRFS_STRIPE_RUN_RELOC, &offset,
-@@ -1307,7 +1309,7 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
- ret = btrfs_alloc_from_open_stripe(cache, sectorsize,
- BTRFS_STRIPE_RUN_COW, &offset,
- &avail);
-- if (ret || offset != fsl + 5 * sectorsize) {
-+ if (ret || offset != 2 * fsl + 5 * sectorsize) {
- test_err("cow run lost by class open: ret %d offset %llu",
- ret, offset);
- ret = -EINVAL;
-@@ -1318,20 +1320,23 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
- btrfs_open_stripe_write_done(cache, fsl, 2 * sectorsize);
- btrfs_open_stripe_write_done(cache, fsl + 2 * sectorsize,
- 2 * sectorsize);
-- btrfs_open_stripe_write_done(cache, fsl + 4 * sectorsize, sectorsize);
-- btrfs_open_stripe_write_done(cache, fsl + 5 * sectorsize, sectorsize);
-- btrfs_open_stripe_write_done(cache, 2 * fsl, fsl);
-+ btrfs_open_stripe_write_done(cache, fsl + 4 * sectorsize, fsl);
-+ btrfs_open_stripe_write_done(cache, 2 * fsl + 4 * sectorsize,
-+ sectorsize);
-+ btrfs_open_stripe_write_done(cache, 2 * fsl + 5 * sectorsize,
-+ sectorsize);
- btrfs_open_stripe_write_done(cache, 3 * fsl, sectorsize);
-
- /*
- * Commit-style retirement: closes every open run in every band of both
- * classes, returns their tails, drains (instantly, all IO reported
- * done) and drops the block group's membership in
-- * fs_info->open_stripe_bgs. The cow run filled [fsl, fsl+6*sectorsize)
-- * and the reloc run filled [3*fsl, 3*fsl+sectorsize); each tail returns.
-+ * fs_info->open_stripe_bgs. The grown cow run covers stripes #1-#2 and
-+ * filled [fsl, 2*fsl+6*sectorsize); the reloc run filled
-+ * [3*fsl, 3*fsl+sectorsize); each tail returns.
- */
- btrfs_retire_open_stripes(fs_info, NULL);
-- if (!test_check_exists(cache, fsl + 6 * sectorsize,
-+ if (!test_check_exists(cache, 2 * fsl + 6 * sectorsize,
- fsl - 6 * sectorsize)) {
- test_err("retired cow run tail missing from free space");
- ret = -EINVAL;
-@@ -1381,16 +1386,17 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
- }
-
- /*
-- * Clean up the partial-stripe remainders: stripe #0's head, stripe #1's
-- * cow tail (10 sectors), and the 15-sector tails of stripes #3 (reloc),
-- * #4 and #5. Stripe #2 was filled completely and has no remainder.
-+ * Clean up the partial-stripe remainders: stripe #0's head, the grown
-+ * cow run's 10-sector tail in stripe #2, and the 15-sector tails of
-+ * stripes #3 (reloc), #4 and #5. Stripe #1 was filled completely and
-+ * has no remainder.
- */
- ret = btrfs_remove_free_space(cache, sectorsize, fsl - sectorsize);
- if (ret) {
- test_err("error cleaning up head %d", ret);
- goto out;
- }
-- ret = btrfs_remove_free_space(cache, fsl + 6 * sectorsize,
-+ ret = btrfs_remove_free_space(cache, 2 * fsl + 6 * sectorsize,
- fsl - 6 * sectorsize);
- if (ret) {
- test_err("error cleaning up tail 1 %d", ret);
---
-2.47.3
-
+++ /dev/null
-From 760a3334bc0d471e65f3dda103c4f4dcb6518588 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:29 -0400
-Subject: [RFC PATCH 011/116] btrfs: raid56: batch stripe_alloc partial writes
- into full-stripe writes
-To: linux-btrfs@vger.kernel.org
-
-A raid56 sub-stripe write pays a read-modify-write: read the rest of the
-stripe, recompute parity, write. The plug callback merges rbios submitted
-within one plug window and the stripe cache saves re-reads for
-back-to-back writes, but measurement shows what survives them: on a
-4-device raid5, small-file writeback produces 100% sub-stripe rbios (zero
-full-stripe writes) and a mixed 4K-512K workload ~55%, so parity is
-recomputed and rewritten once per file that lands in a stripe.
-
-Stripe-exclusive allocation gives raid56 something the allocator never
-guaranteed before: the rest of an open run's stripe is either written
-before the run closes -- within the current transaction -- or not at all.
-That makes holding a partial write a sound bet, so park it: a partial
-write rbio whose stripe belongs to a stripe run keeps the stripe
-lock but does not start its RMW. Later writes to the stripe merge into
-it through the existing lock_stripe_add() path, and the moment its data
-bitmap covers the stripe it is submitted as a single full-stripe write:
-one parity computation, no reads.
-
-A draining run counts, not just an open one. A run closes the moment it
-is fully allocated -- typically milliseconds before its last writes reach
-the raid56 layer -- so gating on "open" would leave exactly those tail
-writes unable to park and unable to pad, and they are the bulk of the
-read-modify-writes this patch exists to remove. A draining run is in
-fact the safest thing to park against: its frontier is frozen, so
-everything below it is inflight IO the commit drain already waits for
-(arrival guaranteed) and everything above it is dead space the pad may
-fill.
-
-Completion accounting can never trigger the flush of runts -- parked bios
-have not been submitted, and preallocated or discarded allocations
-produce no bios at all -- so liveness comes from explicit flushes: the
-run retirement paths flush before the commit's IO drain (which waits on
-the very bios parked here), ordered-extent waiters flush their range on a
-short retry period, and a timer bounds everything else. Writes with a
-blocked waiter (REQ_SYNC: fsync- and sync-driven writeback) park with a
-~3ms deadline instead of 100ms -- long enough for the rest of one
-writeback pass over the stripe to merge in, short enough to stay
-invisible in fsync latency -- and a sync bio merging into a parked rbio
-pulls the deadline in. Only the bg->open_stripe slots are consulted for
-eligibility, and a parked rbio that a racing retirement closed out from
-under is bounded by the timer, never by the drain.
-
-Measured (same 4-device raid5, deterministic workloads, classifying every
-write rbio at rmw_rbio):
-
- workload full-stripe rbios total write rbios
- streaming 99% -> 99% unchanged
- mixed 4K-512K 43% -> 97% 2478 -> 1615
- small files 0% -> 86% 1537 -> 335 (stripe reads 311->23)
- fsync-per-file 0% -> 0% unchanged (nothing co-pending)
-
-fsync latency is 12ms vs 8ms unpatched (each fsync pays one short park).
-Batching also collapses trapped free space in a mixed-size forward fill
-from ~87 MiB to ~3 MiB: stripes now fill completely before the commit
-closes their run, so the frontier strands almost nothing.
-
-Validated: btrfs selftests; mixed-size + concurrency + churn + balance
-workload with trapped-space accounting returning to zero after deleting
-everything; scrub and full sha256 read-back over 4005 mixed random files;
-and the dm-log-writes write-hole crash matrix (24/24 controls clean, 0/36
-armed cases with committed data damage) -- parking does not perturb the
-stripe-exclusivity guarantee it rides on.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 268 +++++++++++++++++++++++-----------------
- fs/btrfs/block-group.h | 1 +
- fs/btrfs/ordered-data.c | 22 ++++
- fs/btrfs/raid56.c | 259 +++++++++++++++++++++++++++++++++++++-
- fs/btrfs/raid56.h | 11 ++
- 5 files changed, 448 insertions(+), 113 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index f88fc9fe9bd10..a10d59bb8aa49 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -770,6 +770,152 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- return ret;
- }
-
-+/*
-+ * Can stripe-exclusive allocation be enabled on this filesystem? Called for
-+ * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
-+ * finalized) filesystem.
-+ */
-+int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info)
-+{
-+ if (!btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
-+ btrfs_err(fs_info,
-+ "stripe_alloc requires the free space tree (space_cache=v2)");
-+ return -EINVAL;
-+ }
-+ if (btrfs_fs_incompat(fs_info, REMAP_TREE)) {
-+ btrfs_err(fs_info,
-+ "stripe_alloc is not supported together with the remap-tree feature");
-+ return -EINVAL;
-+ }
-+ if (btrfs_is_zoned(fs_info)) {
-+ btrfs_err(fs_info,
-+ "stripe_alloc is not supported on zoned filesystems");
-+ return -EINVAL;
-+ }
-+ /*
-+ * A mixed group is excluded from the claim rule anyway
-+ * (btrfs_is_stripe_alloc_bg() requires DATA without METADATA), so
-+ * enabling here would protect nothing while reporting success.
-+ */
-+ if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
-+ btrfs_err(fs_info,
-+ "stripe_alloc is not supported on mixed block groups");
-+ return -EINVAL;
-+ }
-+ return 0;
-+}
-+
-+/*
-+ * Arm or disarm stripe_unusable accounting across all raid56 data block
-+ * groups whose caches are loaded. Same walk as the commit-time rescan.
-+ */
-+static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
-+{
-+ struct btrfs_space_info *sinfo;
-+
-+ list_for_each_entry(sinfo, &fs_info->space_info, list) {
-+ int raid;
-+
-+ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
-+ continue;
-+ down_read(&sinfo->groups_sem);
-+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-+ struct btrfs_block_group *bg;
-+
-+ if (!(btrfs_raid_array[raid].bg_flag &
-+ BTRFS_BLOCK_GROUP_RAID56_MASK))
-+ continue;
-+ list_for_each_entry(bg, &sinfo->block_groups[raid],
-+ list) {
-+ if (!arm)
-+ btrfs_block_group_disarm_stripe_unusable(bg);
-+ else if (bg->cached == BTRFS_CACHE_FINISHED)
-+ btrfs_block_group_init_stripe_unusable(bg);
-+ }
-+ }
-+ up_read(&sinfo->groups_sem);
-+ }
-+}
-+
-+/*
-+ * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
-+ * property on the top-level subvolume's root directory. Runs during mount
-+ * when the root directory inode loads its properties -- before any user IO
-+ * -- or at runtime from btrfs_set_prop().
-+ */
-+int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
-+{
-+ int ret;
-+
-+ if (btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return 0;
-+ ret = btrfs_stripe_alloc_check_support(fs_info);
-+ if (ret)
-+ return ret;
-+ btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
-+ /*
-+ * Arm stripe_unusable accounting for raid56 data groups whose caches
-+ * loaded before the policy was enabled: block groups are read before
-+ * the root directory's properties apply during mount, and a runtime
-+ * property set can arrive at any point. Groups still caching arm
-+ * when their caching thread finishes, now that the policy is on.
-+ */
-+ stripe_alloc_sweep_groups(fs_info, true);
-+ btrfs_info(fs_info,
-+ "using stripe-exclusive allocation for raid56 data");
-+ return 0;
-+}
-+
-+/*
-+ * Turn off stripe-exclusive allocation (property deleted). Open runs are
-+ * not touched here: the commit-time retirement runs unconditionally and
-+ * drains them at the next transaction commit.
-+ */
-+void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
-+{
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return;
-+ /* Disarm while the policy bit still passes the per-group gate. */
-+ stripe_alloc_sweep_groups(fs_info, false);
-+ btrfs_clear_opt(fs_info->mount_opt, STRIPE_ALLOC);
-+ btrfs_info(fs_info,
-+ "stripe-exclusive allocation for raid56 data disabled");
-+}
-+
-+/*
-+ * Does @logical lie within a stripe run (open or draining)? Used by the
-+ * raid56 layer to decide whether a partial write to this stripe may be
-+ * parked to collect into a full-stripe write: an open run guarantees the
-+ * rest of the stripe is either filled before the run closes or never, and
-+ * a draining run's frozen frontier makes "never" decidable -- everything
-+ * allocated below it is inflight IO the commit drain already waits for,
-+ * and everything above it is dead space the pad fills. Excluding draining
-+ * runs made every run's tail writes unparkable -- a run closes on
-+ * exhaustion in the gap between allocation and write arrival -- and those
-+ * writes are the bulk of stripe_alloc's read-modify-writes.
-+ */
-+bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
-+{
-+ struct btrfs_block_group *bg;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ bool ret = false;
-+
-+ bg = btrfs_lookup_block_group(fs_info, logical);
-+ if (!bg)
-+ return false;
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (logical >= run->start && logical < run->end) {
-+ ret = true;
-+ break;
-+ }
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ btrfs_put_block_group(bg);
-+ return ret;
-+}
-+
- /*
- * Report completed (or abandoned) data IO for an allocation made with
- * btrfs_alloc_from_open_stripe(). Every allocated byte must be reported
-@@ -930,118 +1076,6 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
- return ret;
- }
-
--/*
-- * Can stripe-exclusive allocation be enabled on this filesystem? Called for
-- * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
-- * finalized) filesystem.
-- */
--int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info)
--{
-- if (!btrfs_test_opt(fs_info, FREE_SPACE_TREE)) {
-- btrfs_err(fs_info,
-- "stripe_alloc requires the free space tree (space_cache=v2)");
-- return -EINVAL;
-- }
-- if (btrfs_fs_incompat(fs_info, REMAP_TREE)) {
-- btrfs_err(fs_info,
-- "stripe_alloc is not supported together with the remap-tree feature");
-- return -EINVAL;
-- }
-- if (btrfs_is_zoned(fs_info)) {
-- btrfs_err(fs_info,
-- "stripe_alloc is not supported on zoned filesystems");
-- return -EINVAL;
-- }
-- /*
-- * A mixed group is excluded from the claim rule anyway
-- * (btrfs_is_stripe_alloc_bg() requires DATA without METADATA), so
-- * enabling here would protect nothing while reporting success.
-- */
-- if (btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
-- btrfs_err(fs_info,
-- "stripe_alloc is not supported on mixed block groups");
-- return -EINVAL;
-- }
-- return 0;
--}
--
--/*
-- * Arm or disarm stripe_unusable accounting across all raid56 data block
-- * groups whose caches are loaded. Same walk as the commit-time rescan.
-- */
--static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
--{
-- struct btrfs_space_info *sinfo;
--
-- list_for_each_entry(sinfo, &fs_info->space_info, list) {
-- int raid;
--
-- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
-- continue;
-- down_read(&sinfo->groups_sem);
-- for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-- struct btrfs_block_group *bg;
--
-- if (!(btrfs_raid_array[raid].bg_flag &
-- BTRFS_BLOCK_GROUP_RAID56_MASK))
-- continue;
-- list_for_each_entry(bg, &sinfo->block_groups[raid],
-- list) {
-- if (!arm)
-- btrfs_block_group_disarm_stripe_unusable(bg);
-- else if (bg->cached == BTRFS_CACHE_FINISHED)
-- btrfs_block_group_init_stripe_unusable(bg);
-- }
-- }
-- up_read(&sinfo->groups_sem);
-- }
--}
--
--/*
-- * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
-- * property on the top-level subvolume's root directory. Runs during mount
-- * when the root directory inode loads its properties -- before any user IO
-- * -- or at runtime from btrfs_set_prop().
-- */
--int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
--{
-- int ret;
--
-- if (btrfs_test_opt(fs_info, STRIPE_ALLOC))
-- return 0;
-- ret = btrfs_stripe_alloc_check_support(fs_info);
-- if (ret)
-- return ret;
-- btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
-- /*
-- * Arm stripe_unusable accounting for raid56 data groups whose caches
-- * loaded before the policy was enabled: block groups are read before
-- * the root directory's properties apply during mount, and a runtime
-- * property set can arrive at any point. Groups still caching arm
-- * when their caching thread finishes, now that the policy is on.
-- */
-- stripe_alloc_sweep_groups(fs_info, true);
-- btrfs_info(fs_info,
-- "using stripe-exclusive allocation for raid56 data");
-- return 0;
--}
--
--/*
-- * Turn off stripe-exclusive allocation (property deleted). Open runs are
-- * not touched here: the commit-time retirement runs unconditionally and
-- * drains them at the next transaction commit.
-- */
--void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
--{
-- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-- return;
-- /* Disarm while the policy bit still passes the per-group gate. */
-- stripe_alloc_sweep_groups(fs_info, false);
-- btrfs_clear_opt(fs_info->mount_opt, STRIPE_ALLOC);
-- btrfs_info(fs_info,
-- "stripe-exclusive allocation for raid56 data disabled");
--}
--
- /*
- * Close and drain all of a block group's stripe runs. The caller must
- * prevent new allocations first (e.g. the block group is read-only),
-@@ -1051,6 +1085,8 @@ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
- {
- close_block_group_stripe_runs(bg, U64_MAX);
-+ /* Parked partial-stripe rbios hold the very bios the wait drains. */
-+ btrfs_flush_parked_rbios(bg->fs_info, bg->start, bg->length);
- wait_var_event(&bg->open_stripe_runs,
- bg_open_stripes_settled(bg, U64_MAX));
- }
-@@ -1086,6 +1122,14 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
- list_for_each_entry(bg, &retire_list, open_stripe_retire_list)
- close_block_group_stripe_runs(bg, seq);
-
-+ /*
-+ * Parked partial-stripe write rbios (see raid56.c) hold bios whose
-+ * write_done the drain below waits for; kick them all down first.
-+ * A racing park that saw its run still open lands after this flush
-+ * and is bounded by the park timer, not by us.
-+ */
-+ btrfs_flush_parked_rbios(fs_info, 0, U64_MAX);
-+
- while (!list_empty(&retire_list)) {
- bg = list_first_entry(&retire_list, struct btrfs_block_group,
- open_stripe_retire_list);
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 63052c4761b29..a726f9da7f1fc 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -402,6 +402,7 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
- u64 *open_seq);
- void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
-+bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
- int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
- int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
- void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
-diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
-index 0ca6b7dc7e497..e7aeee5c7172d 100644
---- a/fs/btrfs/ordered-data.c
-+++ b/fs/btrfs/ordered-data.c
-@@ -20,6 +20,7 @@
- #include "subpage.h"
- #include "file.h"
- #include "block-group.h"
-+#include "raid56.h"
-
- static struct kmem_cache *btrfs_ordered_extent_cache;
-
-@@ -922,6 +923,27 @@ void btrfs_start_ordered_extent_nowriteback(struct btrfs_ordered_extent *entry,
- }
-
- btrfs_might_wait_for_event(inode->root->fs_info, btrfs_ordered_extent);
-+ /*
-+ * A parked partial-stripe write rbio (raid56 full-stripe batching) may
-+ * be holding this extent's bios; kick it down or the wait is bounded
-+ * by the park timer instead of the IO. The park happens on a worker
-+ * after the submission above returns, so a single flush can run too
-+ * early and miss it -- retry on a short period until the extent
-+ * completes. Only stripe_alloc filesystems ever park, so everything
-+ * else takes the plain single sleep below.
-+ */
-+ while (btrfs_test_opt(inode->root->fs_info, STRIPE_ALLOC) &&
-+ entry->disk_num_bytes &&
-+ !test_bit(BTRFS_ORDERED_COMPLETE, &entry->flags)) {
-+ btrfs_flush_parked_rbios(inode->root->fs_info,
-+ entry->disk_bytenr,
-+ entry->disk_num_bytes);
-+ if (wait_event_timeout(entry->wait,
-+ test_bit(BTRFS_ORDERED_COMPLETE,
-+ &entry->flags),
-+ msecs_to_jiffies(10)))
-+ break;
-+ }
- wait_event(entry->wait, test_bit(BTRFS_ORDERED_COMPLETE, &entry->flags));
- }
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 4be6361413f21..279c15cf229e8 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -37,8 +37,28 @@
- */
- #define RBIO_CACHE_READY_BIT 3
-
-+/*
-+ * Set while a partial write rbio is parked: it owns the stripe lock but its
-+ * RMW has not been started, so writes filling the rest of an open stripe
-+ * run's stripe merge into it (see rbio_try_park()). Whoever clears this bit
-+ * owns starting the rbio's work, exactly once.
-+ */
-+#define RBIO_PARKED_BIT 4
-+
- #define RBIO_CACHE_SIZE 1024
-
-+/*
-+ * How long a parked partial write rbio may wait for merges before flushing.
-+ * Sync writes (fsync- or sync-driven writeback, REQ_SYNC) have a waiter
-+ * blocked on their completion, so they get a much shorter deadline: long
-+ * enough for the rest of one writeback pass over the same stripe to merge
-+ * in, short enough to stay invisible in fsync latency.
-+ */
-+#define BTRFS_RBIO_PARK_TIMEOUT_MS 100
-+#define BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS 3
-+/* Scan period of the park timer while anything is parked. */
-+#define BTRFS_RBIO_PARK_SCAN_MS 3
-+
- #define BTRFS_STRIPE_HASH_TABLE_BITS 11
-
- static void dump_bioc(const struct btrfs_fs_info *fs_info, const struct btrfs_io_context *bioc)
-@@ -131,6 +151,14 @@ struct btrfs_stripe_hash_table {
- struct list_head stripe_cache;
- spinlock_t cache_lock;
- int cache_size;
-+ /*
-+ * Parked partial write rbios (RBIO_PARKED_BIT), in park order.
-+ * parked_lock nests inside the hash and bio_list locks.
-+ */
-+ spinlock_t parked_lock;
-+ struct list_head parked;
-+ struct delayed_work parked_work;
-+ struct btrfs_fs_info *fs_info;
- struct btrfs_stripe_hash table[];
- };
-
-@@ -142,6 +170,7 @@ struct btrfs_stripe_hash_table {
-
- static void rmw_rbio_work(struct work_struct *work);
- static void rmw_rbio_work_locked(struct work_struct *work);
-+static void parked_rbios_timeout_work(struct work_struct *work);
- static void index_rbio_pages(struct btrfs_raid_bio *rbio);
- static int alloc_rbio_pages(struct btrfs_raid_bio *rbio);
-
-@@ -215,6 +244,10 @@ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info)
-
- spin_lock_init(&table->cache_lock);
- INIT_LIST_HEAD(&table->stripe_cache);
-+ spin_lock_init(&table->parked_lock);
-+ INIT_LIST_HEAD(&table->parked);
-+ INIT_DELAYED_WORK(&table->parked_work, parked_rbios_timeout_work);
-+ table->fs_info = info;
-
- h = table->table;
-
-@@ -567,6 +600,8 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info)
- {
- if (!info->stripe_hash_table)
- return;
-+ cancel_delayed_work_sync(&info->stripe_hash_table->parked_work);
-+ WARN_ON(!list_empty(&info->stripe_hash_table->parked));
- btrfs_clear_rbio_cache(info);
- kvfree(info->stripe_hash_table);
- info->stripe_hash_table = NULL;
-@@ -692,6 +727,196 @@ static int rbio_can_merge(struct btrfs_raid_bio *last,
- return 1;
- }
-
-+/*
-+ * Full-stripe write batching for stripe-exclusive allocation.
-+ *
-+ * A partial write rbio whose stripe belongs to an open stripe run is parked:
-+ * it keeps the stripe lock but its RMW is not started, so the writes that
-+ * fill the rest of the stripe -- guaranteed to arrive before the run closes,
-+ * or not at all -- merge into it through lock_stripe_add() instead of each
-+ * paying a read-modify-write. The moment the data bitmap fills, the rbio is
-+ * submitted as a single full-stripe write: one parity computation, no reads.
-+ *
-+ * Completion accounting can never be the flush trigger -- parked bios have
-+ * not been submitted, and preallocated or discarded allocations produce no
-+ * bios at all -- so everything that does not fill is flushed by the run
-+ * retirement paths (before the commit's IO drain, which waits on the very
-+ * bios parked here), by ordered-extent waiters, and by a timer that bounds
-+ * both latency and the memory the parked pages pin.
-+ */
-+
-+/* Caller holds table->parked_lock. */
-+static void rbio_unpark_locked(struct btrfs_raid_bio *rbio)
-+{
-+ list_del_init(&rbio->parked_node);
-+ clear_bit(RBIO_PARKED_BIT, &rbio->flags);
-+}
-+
-+/* Does any bio gathered in @rbio carry a sync hint (a blocked waiter)? */
-+static bool rbio_has_sync_bio(struct btrfs_raid_bio *rbio)
-+{
-+ struct bio *bio;
-+
-+ bio_list_for_each(bio, &rbio->bio_list)
-+ if (bio->bi_opf & REQ_SYNC)
-+ return true;
-+ return false;
-+}
-+
-+/*
-+ * Park a partial write rbio that owns its stripe lock, if its stripe is
-+ * covered by an open stripe run. Returns true if the rbio was parked (or
-+ * concurrently filled and requeued); false if the caller should proceed
-+ * with the RMW itself.
-+ */
-+static bool rbio_try_park(struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
-+ unsigned int timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
-+
-+ if (!btrfs_stripe_in_open_run(fs_info, rbio->bioc->full_stripe_logical))
-+ return false;
-+
-+ spin_lock(&rbio->bio_list_lock);
-+ if (rbio_has_sync_bio(rbio))
-+ timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
-+ spin_unlock(&rbio->bio_list_lock);
-+
-+ spin_lock(&table->parked_lock);
-+ set_bit(RBIO_PARKED_BIT, &rbio->flags);
-+ rbio->park_deadline = jiffies + msecs_to_jiffies(timeout_ms);
-+ /*
-+ * Take a reference of our own before publishing. The moment
-+ * parked_lock is dropped this rbio is visible to every flusher, and a
-+ * flusher that claims it starts the RMW, which runs to completion and
-+ * frees the rbio -- while we are still in this function, about to read
-+ * it again in the fullness recheck below. Its other two references,
-+ * the initial one and the stripe hash list's, are both consumed by
-+ * that completion, so neither protects us.
-+ *
-+ * It has to be OUR reference, not one owned by the parked list: an
-+ * unparker would inherit a list reference and drop it, and the
-+ * unparker is exactly the thread racing us here. Nobody can consume
-+ * this one but us.
-+ */
-+ refcount_inc(&rbio->refs);
-+ list_add_tail(&rbio->parked_node, &table->parked);
-+ spin_unlock(&table->parked_lock);
-+ queue_delayed_work(system_percpu_wq, &table->parked_work,
-+ msecs_to_jiffies(BTRFS_RBIO_PARK_SCAN_MS));
-+
-+ /*
-+ * A merge may have filled us between the caller's fullness check and
-+ * the park above; reclaim the park so the full stripe goes straight
-+ * down. If the merger's unpark won instead, it queued the work.
-+ */
-+ if (rbio_is_full(rbio)) {
-+ spin_lock(&table->parked_lock);
-+ if (test_bit(RBIO_PARKED_BIT, &rbio->flags)) {
-+ rbio_unpark_locked(rbio);
-+ spin_unlock(&table->parked_lock);
-+ free_raid_bio(rbio);
-+ return false;
-+ }
-+ spin_unlock(&table->parked_lock);
-+ }
-+ /*
-+ * Done reading it. Dropping our reference here cannot be the last
-+ * one: a parked rbio still owns the stripe lock, and the only thing
-+ * that completes it is the RMW a flusher starts after taking it off
-+ * the list.
-+ */
-+ free_raid_bio(rbio);
-+ return true;
-+}
-+
-+/*
-+ * A merge just filled a parked rbio: unpark it and start its (now read-free)
-+ * write. Callers may hold the stripe hash and bio_list locks; parked_lock
-+ * nests inside both.
-+ */
-+static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_stripe_hash_table *table =
-+ rbio->bioc->fs_info->stripe_hash_table;
-+
-+ spin_lock(&table->parked_lock);
-+ if (!test_bit(RBIO_PARKED_BIT, &rbio->flags)) {
-+ spin_unlock(&table->parked_lock);
-+ return;
-+ }
-+ rbio_unpark_locked(rbio);
-+ spin_unlock(&table->parked_lock);
-+ start_async_work(rbio, rmw_rbio_work_locked);
-+}
-+
-+/*
-+ * Flush every parked rbio overlapping [start, start + num_bytes) down its
-+ * normal RMW path. Called by run retirement (before the commit's IO drain),
-+ * ordered-extent waiters, and the park timer.
-+ */
-+void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
-+ u64 num_bytes)
-+{
-+ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
-+ struct btrfs_raid_bio *rbio;
-+ struct btrfs_raid_bio *tmp;
-+ LIST_HEAD(flush);
-+
-+ if (!table || list_empty_careful(&table->parked))
-+ return;
-+ spin_lock(&table->parked_lock);
-+ list_for_each_entry_safe(rbio, tmp, &table->parked, parked_node) {
-+ u64 rbio_start = rbio->bioc->full_stripe_logical;
-+ u64 rbio_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
-+
-+ if (rbio_start + rbio_len <= start ||
-+ (num_bytes != U64_MAX && rbio_start >= start + num_bytes))
-+ continue;
-+ rbio_unpark_locked(rbio);
-+ list_add_tail(&rbio->parked_node, &flush);
-+ }
-+ spin_unlock(&table->parked_lock);
-+
-+ list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
-+ list_del_init(&rbio->parked_node);
-+ start_async_work(rbio, rmw_rbio_work_locked);
-+ }
-+}
-+
-+/* Flush parked rbios whose deadline has passed; re-arm while any remain. */
-+static void parked_rbios_timeout_work(struct work_struct *work)
-+{
-+ struct btrfs_stripe_hash_table *table =
-+ container_of(work, struct btrfs_stripe_hash_table,
-+ parked_work.work);
-+ struct btrfs_raid_bio *rbio;
-+ struct btrfs_raid_bio *tmp;
-+ LIST_HEAD(flush);
-+ bool rearm = false;
-+
-+ spin_lock(&table->parked_lock);
-+ list_for_each_entry_safe(rbio, tmp, &table->parked, parked_node) {
-+ /* Deadlines are not ordered (sync parks are shorter). */
-+ if (time_before(jiffies, rbio->park_deadline)) {
-+ rearm = true;
-+ continue;
-+ }
-+ rbio_unpark_locked(rbio);
-+ list_add_tail(&rbio->parked_node, &flush);
-+ }
-+ spin_unlock(&table->parked_lock);
-+
-+ list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
-+ list_del_init(&rbio->parked_node);
-+ start_async_work(rbio, rmw_rbio_work_locked);
-+ }
-+ if (rearm)
-+ queue_delayed_work(system_percpu_wq, &table->parked_work,
-+ msecs_to_jiffies(BTRFS_RBIO_PARK_SCAN_MS));
-+}
-+
- /* Return the sector index for @stripe_nr and @sector_nr. */
- static unsigned int rbio_sector_index(const struct btrfs_raid_bio *rbio,
- unsigned int stripe_nr,
-@@ -807,7 +1032,35 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
-
- /* Can we merge into the lock owner? */
- if (rbio_can_merge(cur, rbio)) {
-+ bool sync = rbio_has_sync_bio(rbio);
-+
- merge_rbio(cur, rbio);
-+ /*
-+ * Our bios may have completed a parked stripe. We
-+ * hold cur->bio_list_lock, so test fullness directly
-+ * (rbio_is_full() would self-deadlock on it). A sync
-+ * bio merging into a still-partial parked rbio pulls
-+ * its flush deadline in: a waiter is now blocked on
-+ * this stripe.
-+ */
-+ if (test_bit(RBIO_PARKED_BIT, &cur->flags)) {
-+ if (cur->bio_list_bytes ==
-+ cur->nr_data * cur->bioc->stripe_len) {
-+ unpark_full_rbio(cur);
-+ } else if (sync) {
-+ struct btrfs_stripe_hash_table *table =
-+ cur->bioc->fs_info->stripe_hash_table;
-+ unsigned long dl = jiffies +
-+ msecs_to_jiffies(BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS);
-+
-+ spin_lock(&table->parked_lock);
-+ if (test_bit(RBIO_PARKED_BIT,
-+ &cur->flags) &&
-+ time_before(dl, cur->park_deadline))
-+ cur->park_deadline = dl;
-+ spin_unlock(&table->parked_lock);
-+ }
-+ }
- spin_unlock(&cur->bio_list_lock);
- freeit = rbio;
- ret = 1;
-@@ -1107,6 +1360,7 @@ static struct btrfs_raid_bio *alloc_rbio(struct btrfs_fs_info *fs_info,
- spin_lock_init(&rbio->bio_list_lock);
- INIT_LIST_HEAD(&rbio->stripe_cache);
- INIT_LIST_HEAD(&rbio->hash_list);
-+ INIT_LIST_HEAD(&rbio->parked_node);
- btrfs_get_bioc(bioc);
- rbio->bioc = bioc;
- rbio->nr_pages = num_pages;
-@@ -2563,8 +2817,11 @@ static void rmw_rbio_work(struct work_struct *work)
- struct btrfs_raid_bio *rbio;
-
- rbio = container_of(work, struct btrfs_raid_bio, work);
-- if (lock_stripe_add(rbio) == 0)
-+ if (lock_stripe_add(rbio) == 0) {
-+ if (!rbio_is_full(rbio) && rbio_try_park(rbio))
-+ return;
- rmw_rbio(rbio);
-+ }
- }
-
- static void rmw_rbio_work_locked(struct work_struct *work)
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index 8700910b8dc99..f5b8d788b1fff 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -130,6 +130,15 @@ struct btrfs_raid_bio {
- */
- struct list_head plug_list;
-
-+ /*
-+ * Membership in the stripe hash table's parked list: partial write
-+ * rbios for stripes of open stripe runs (stripe_alloc) are held back,
-+ * collecting merges until they can go down as one full-stripe write.
-+ * Protected by the table's parked_lock.
-+ */
-+ struct list_head parked_node;
-+ unsigned long park_deadline;
-+
- /* Flags that tell us if it is safe to merge with this bio. */
- unsigned long flags;
-
-@@ -282,5 +291,7 @@ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
-
- int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
-+void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
-+ u64 num_bytes);
-
- #endif
---
-2.47.3
-
--- /dev/null
+From 72dcaf543ee045269a9d09cc1b25887fa6227e0d Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:31 -0400
+Subject: [RFC PATCH 11/85] btrfs: stripe_alloc: private per-inode stripe runs
+ for log-active inodes
+To: linux-btrfs@vger.kernel.org
+
+An fsync-heavy inode shares the open band runs with every other writer.
+Closing the open stripe run covering every logged extent at each log
+commit, which "btrfs: stripe_alloc: settle a logged extent's stripes at
+log commit" does later in this series to make completed fsyncs
+crash-safe, would then close a shared run at each of its log commits,
+fragmenting concurrent write streams and trapping the shared run's tail.
+
+Give log-active inodes their own runs instead. The first fsync of an
+inode sets a sticky runtime flag (at btrfs_sync_file entry, before the
+fsync flushes its own delalloc, so even that first fsync's allocations
+are steered). Datacow allocations for a flagged inode come from a
+private LOG-class run: claimed like any run but never placed in the
+shared band slots, owned by the inode, and found by owner lookup under
+the block group's stripe_run_lock. A per-inode hint seeds the
+allocator's search with the run's location; the hint is advisory (a
+stale hint costs a lookup miss, never a wrong run, since the owner
+match is authoritative). When no fully-free stripes remain for a
+private run the allocation falls back to the shared runs, restoring
+the previous placement with unchanged safety.
+
+One inode's log commit then settles only its own stripes: other
+writers' runs stay open and their streams stay contiguous, and the
+only trapped tails are the fsyncing inode's own. Private runs also
+give each log-active inode exclusive stripes, which a later change
+uses to copy live tails forward and reclaim them without touching
+foreign extents.
+
+The commit-time retirement closed runs by walking the band slots,
+which private runs never occupy; walk the block group's run list
+instead so every open run, slotted or private, is closed and drained
+under invariant I2 (no open run survives a transaction commit).
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 154 ++++++++++++++++++++++++++++++++++++-----
+ fs/btrfs/block-group.h | 11 +++
+ fs/btrfs/btrfs_inode.h | 19 +++++
+ fs/btrfs/direct-io.c | 2 +-
+ fs/btrfs/extent-tree.c | 49 ++++++++++++-
+ fs/btrfs/extent-tree.h | 9 ++-
+ fs/btrfs/file.c | 11 +++
+ fs/btrfs/inode.c | 12 ++--
+ fs/btrfs/relocation.c | 8 +--
+ 9 files changed, 244 insertions(+), 31 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 0c1cd5bc8e208..9e5df9eb0c155 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -492,6 +492,7 @@ struct btrfs_open_stripe_run {
+ u64 offset; /* next unallocated byte */
+ u64 inflight_bytes; /* reserved bytes with data IO pending */
+ u64 open_seq; /* fs_info->stripe_retire_seq at open */
++ u64 owner; /* LOG class: btrfs_ino of the owner */
+ enum btrfs_stripe_run_class class;
+ bool open; /* accepting allocations */
+ };
+@@ -566,6 +567,9 @@ static u64 stripe_run_place(struct btrfs_block_group *bg,
+ int band = stripe_run_band(bg, run->end - run->offset);
+ struct btrfs_open_stripe_run *occ = bg->open_stripe[class][band];
+
++ /* Private runs (LOG, NOCOW, META_LOG) never occupy a band slot. */
++ ASSERT(class != BTRFS_STRIPE_RUN_LOG);
++
+ if (occ) {
+ struct btrfs_open_stripe_run *keep, *shut;
+
+@@ -733,6 +737,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->owner = 0;
+ new_run->start = start;
+ new_run->end = start + len;
+ new_run->offset = start + num_bytes;
+@@ -760,6 +765,116 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ return ret;
+ }
+
++/*
++ * Allocate num_bytes for a log-active inode from its private LOG-class run
++ * in this block group, claiming a fresh run when the inode has none here or
++ * the current one does not fit. Private runs are never placed in the shared
++ * band slots and are found by owner lookup, so no other allocation can join
++ * an inode's run and one inode's log commit settles only its own stripes.
++ *
++ * A replaced run (too small for this allocation) is closed immediately: the
++ * inode moves on to the fresh run, so keeping the remainder open would only
++ * strand it until the commit-time retirement. Two racing allocations for
++ * the same inode can each claim a fresh run; the owner walk then serves one
++ * of them and the other drains and retires at the next commit -- an
++ * occasional trapped tail, not a correctness problem.
++ *
++ * 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,
++ u64 num_bytes, u64 *ret_offset,
++ u64 *available)
++{
++ struct btrfs_fs_info *fs_info = bg->fs_info;
++ const u64 fsl = bg->full_stripe_len;
++ struct btrfs_open_stripe_run *new_run;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ u64 tail_start = 0;
++ u64 tail_len = 0;
++ u64 start;
++ u64 len;
++ int ret;
++
++ ASSERT(num_bytes);
++ *available = 0;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (run->class != BTRFS_STRIPE_RUN_LOG || run->owner != ino ||
++ !run->open)
++ continue;
++ if (num_bytes <= run->end - run->offset) {
++ *ret_offset = run->offset;
++ run->offset += num_bytes;
++ run->inflight_bytes += num_bytes;
++ if (run->offset == run->end)
++ run->open = false; /* full: closed, no tail */
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ return 0;
++ }
++ tail_len = close_open_stripe_run(bg, run, &tail_start);
++ break;
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ if (tail_len)
++ btrfs_add_free_space(bg, tail_start, tail_len);
++
++ new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
++ if (!new_run)
++ return -ENOMEM;
++
++ ret = btrfs_claim_free_stripe_run(bg,
++ div64_u64(num_bytes + fsl - 1, fsl) * fsl,
++ &start, &len);
++ if (ret)
++ goto out;
++ if (len < num_bytes) {
++ /* Only a shorter run is free; see btrfs_alloc_from_open_stripe(). */
++ btrfs_add_free_space(bg, start, len);
++ *available = len;
++ ret = -ENOSPC;
++ goto out;
++ }
++
++ /* See the installation comment in btrfs_alloc_from_open_stripe(). */
++ spin_lock(&fs_info->open_stripe_lock);
++ if (list_empty(&bg->open_stripe_bg_list)) {
++ btrfs_get_block_group(bg);
++ list_add_tail(&bg->open_stripe_bg_list,
++ &fs_info->open_stripe_bgs);
++ }
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ if (bg->ro) {
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ spin_unlock(&fs_info->open_stripe_lock);
++ btrfs_add_free_space(bg, start, len);
++ *available = 0;
++ ret = -ENOSPC;
++ goto out;
++ }
++ new_run->bg = bg;
++ new_run->class = BTRFS_STRIPE_RUN_LOG;
++ new_run->owner = ino;
++ new_run->start = start;
++ new_run->end = start + len;
++ new_run->offset = start + num_bytes;
++ new_run->inflight_bytes = num_bytes;
++ new_run->open_seq = fs_info->stripe_retire_seq;
++ new_run->open = (new_run->offset != new_run->end);
++ list_add_tail(&new_run->list, &bg->open_stripe_runs);
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ spin_unlock(&fs_info->open_stripe_lock);
++
++ *ret_offset = start;
++ new_run = NULL;
++ ret = 0;
++out:
++ kfree(new_run);
++ return ret;
++}
++
+ /*
+ * 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
+@@ -1033,30 +1148,35 @@ 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)
+ {
+- u64 tail_start[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
+- u64 tail_len[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
+ struct btrfs_open_stripe_run *run;
+ unsigned long flags;
+ int class, band;
+
++restart:
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+- for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++) {
+- for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++) {
+- tail_len[class][band] = 0;
+- run = bg->open_stripe[class][band];
+- if (run && run->open_seq < seq) {
+- bg->open_stripe[class][band] = NULL;
+- tail_len[class][band] = close_open_stripe_run(
+- bg, run, &tail_start[class][band]);
+- }
+- }
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ u64 tail_start;
++ u64 tail_len;
++
++ if (!run->open || run->open_seq >= seq)
++ continue;
++ 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)
++ bg->open_stripe[class][band] = NULL;
++ tail_len = close_open_stripe_run(bg, run, &tail_start);
++ /*
++ * Closing may have freed the run, and returning its tail to
++ * the free space cache needs the lock dropped, so rescan.
++ * Each pass closes one run and open runs are bounded (band
++ * slots plus the private runs of inodes logged this window).
++ */
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ if (tail_len)
++ btrfs_add_free_space(bg, tail_start, tail_len);
++ goto restart;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+- for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
+- for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++)
+- if (tail_len[class][band])
+- btrfs_add_free_space(bg, tail_start[class][band],
+- tail_len[class][band]);
+ }
+
+ /*
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 7f2df9d2fc31c..6d83c79e8c02e 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -30,6 +30,14 @@ struct btrfs_trans_handle;
+ enum btrfs_stripe_run_class {
+ BTRFS_STRIPE_RUN_COW,
+ BTRFS_STRIPE_RUN_RELOC,
++ /*
++ * Data of log-active (fsync-heavy) inodes. Never placed in the band
++ * slots: runs are found by subvolume and owner, either the inode or,
++ * with stripe_log_data_shared, the subvolume's current log transaction
++ * (stripe_run_owner()), so a log commit settles only stripes holding
++ * its own extents.
++ */
++ BTRFS_STRIPE_RUN_LOG,
+ BTRFS_STRIPE_RUN_NR_CLASSES,
+ };
+
+@@ -383,6 +391,9 @@ 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,
++ u64 num_bytes, u64 *ret_offset,
++ u64 *available);
+ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+ u64 num_bytes);
+ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+diff --git a/fs/btrfs/btrfs_inode.h b/fs/btrfs/btrfs_inode.h
+index f7aa0d1451851..a3aab18d60337 100644
+--- a/fs/btrfs/btrfs_inode.h
++++ b/fs/btrfs/btrfs_inode.h
+@@ -87,6 +87,16 @@ enum {
+ BTRFS_INODE_VERITY_IN_PROGRESS,
+ /* Set when this inode is a free space inode. */
+ BTRFS_INODE_FREE_SPACE_INODE,
++ /*
++ * Set the first time this inode is fsynced under stripe-exclusive
++ * allocation, and kept while the inode stays cached. A log-active
++ * inode's datacow allocations go to LOG-class stripe runs (per inode,
++ * or shared per log transaction with stripe_log_data_shared), so log
++ * commits settle only stripes holding logged extents instead of
++ * closing runs shared with other writers. Placement only: correctness
++ * comes from log-commit settling, which works on runs of any class.
++ */
++ BTRFS_INODE_LOG_ALLOC,
+ /* Set when there are no capabilities in XATTs for the inode. */
+ BTRFS_INODE_NO_CAP_XATTR,
+ /*
+@@ -319,6 +329,15 @@ struct btrfs_inode {
+ u64 ref_root_id;
+ };
+
++ /*
++ * Start of the last extent allocated from one of this inode's private
++ * stripe runs (LOG or NOCOW class). Only a search hint, so
++ * consecutive allocations find the block group holding the run; the
++ * run is found by owner lookup, so a stale hint costs a miss, never a
++ * wrong run.
++ */
++ u64 log_run_hint;
++
+ /* Backwards incompatible flags, lower half of inode_item::flags */
+ u32 flags;
+ /* Read-only compatibility flags, upper half of inode_item::flags */
+diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c
+index ed3914257d395..8bdfae5ebe694 100644
+--- a/fs/btrfs/direct-io.c
++++ b/fs/btrfs/direct-io.c
+@@ -185,7 +185,7 @@ static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
+
+ alloc_hint = btrfs_get_extent_allocation_hint(inode, start, len);
+ again:
+- ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
++ ret = btrfs_reserve_extent(root, inode, len, len, fs_info->sectorsize,
+ 0, alloc_hint, &ins, true, true);
+ if (ret == -EAGAIN) {
+ ASSERT(btrfs_is_zoned(fs_info));
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index d45cde622dd40..dea9af5b7845a 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4249,6 +4249,31 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
+ if (skip)
+ return 1;
+
++ /*
++ * A log-active inode allocates from its own private LOG-class run so
++ * its log commits settle only its own stripes. If this block group
++ * has no fully-free stripes left for a private run, fall through to
++ * the shared runs: the data is then placed exactly as before 3b.1
++ * and the log-commit settling keeps it safe, just less cheaply.
++ */
++ if (ffe_ctl->for_log_inode) {
++ struct btrfs_inode *log_inode = ffe_ctl->for_log_inode;
++
++ ret = btrfs_alloc_from_inode_stripe_run(block_group,
++ btrfs_ino(log_inode), ffe_ctl->num_bytes,
++ &offset, &available);
++ if (ret == -ENOMEM)
++ return ret;
++ if (!ret) {
++ WRITE_ONCE(log_inode->log_run_hint, offset);
++ ffe_ctl->found_offset = offset;
++ ffe_ctl->search_start = offset;
++ return 0;
++ }
++ if (available > ffe_ctl->max_extent_size)
++ ffe_ctl->max_extent_size = available;
++ }
++
+ ret = btrfs_alloc_from_open_stripe(block_group, ffe_ctl->num_bytes,
+ class, &offset, &available);
+ if (ret == -ENOMEM)
+@@ -4981,8 +5006,8 @@ static noinline int find_free_extent(struct btrfs_root *root,
+ * case -ENOSPC is returned then @ins->offset will contain the size of the
+ * largest available hole the allocator managed to find.
+ */
+-int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
+- u64 num_bytes, u64 min_alloc_size,
++int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
++ u64 ram_bytes, u64 num_bytes, u64 min_alloc_size,
+ u64 empty_size, u64 hint_byte,
+ struct btrfs_key *ins, bool is_data, bool delalloc)
+ {
+@@ -4993,6 +5018,23 @@ int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
+ int ret;
+ bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
+ bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
++ struct btrfs_inode *for_log_inode = NULL;
++
++ /*
++ * Steer a log-active inode's datacow data into its private LOG-class
++ * stripe run, seeded with the run's location as the search hint; see
++ * BTRFS_INODE_LOG_ALLOC. Purely placement: any allocation that
++ * cannot be served from a private run falls back to the shared runs.
++ */
++ if (inode && is_data && !for_data_reloc &&
++ btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
++ test_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags)) {
++ u64 log_hint = READ_ONCE(inode->log_run_hint);
++
++ for_log_inode = inode;
++ if (log_hint)
++ hint_byte = log_hint;
++ }
+
+ flags = get_alloc_profile_by_root(root, is_data);
+ again:
+@@ -5007,6 +5049,7 @@ int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
+ ffe_ctl.hint_byte = hint_byte;
+ ffe_ctl.for_treelog = for_treelog;
+ ffe_ctl.for_data_reloc = for_data_reloc;
++ ffe_ctl.for_log_inode = for_log_inode;
+
+ ret = find_free_extent(root, ins, &ffe_ctl);
+ if (!ret && !is_data) {
+@@ -5510,7 +5553,7 @@ struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
+ if (IS_ERR(block_rsv))
+ return ERR_CAST(block_rsv);
+
+- ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
++ ret = btrfs_reserve_extent(root, NULL, blocksize, blocksize, blocksize,
+ empty_size, hint, &ins, false, false);
+ if (ret)
+ goto out_unuse;
+diff --git a/fs/btrfs/extent-tree.h b/fs/btrfs/extent-tree.h
+index bc847c03470ed..a75eb49437030 100644
+--- a/fs/btrfs/extent-tree.h
++++ b/fs/btrfs/extent-tree.h
+@@ -49,6 +49,12 @@ struct find_free_extent_ctl {
+ /* Allocation is called for data relocation */
+ bool for_data_reloc;
+
++ /*
++ * Data allocation for a log-active inode under stripe-exclusive
++ * allocation: steer it into the inode's private LOG-class stripe run.
++ */
++ struct btrfs_inode *for_log_inode;
++
+ /*
+ * Set to true if we're retrying the allocation on this block group
+ * after waiting for caching progress, this is so that we retry only
+@@ -135,7 +141,8 @@ int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
+ int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
+ u64 root_objectid, u64 owner, u64 offset,
+ struct btrfs_key *ins);
+-int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes, u64 num_bytes,
++int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
++ u64 ram_bytes, u64 num_bytes,
+ u64 min_alloc_size, u64 empty_size, u64 hint_byte,
+ struct btrfs_key *ins, bool is_data, bool delalloc);
+ int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
+diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
+index 2dc1fbf569cf3..89d71cec371d6 100644
+--- a/fs/btrfs/file.c
++++ b/fs/btrfs/file.c
+@@ -1545,6 +1545,17 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
+
+ trace_btrfs_sync_file_enter(file, datasync);
+
++ /*
++ * Under stripe-exclusive allocation, mark the inode log-active before
++ * this fsync flushes its delalloc, so that even the first fsync's
++ * allocations are steered into LOG-class stripe runs (see
++ * BTRFS_INODE_LOG_ALLOC). Sticky while the inode stays cached:
++ * one fsync is taken as a signal that more will follow.
++ */
++ if (btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
++ !test_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags))
++ set_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags);
++
+ btrfs_init_log_ctx(&ctx, inode);
+
+ /*
+diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
+index b66dd823053f1..3190191b41d6d 100644
+--- a/fs/btrfs/inode.c
++++ b/fs/btrfs/inode.c
+@@ -1070,7 +1070,7 @@ static void submit_one_async_extent(struct async_chunk *async_chunk,
+ }
+
+ compressed_size = async_extent->cb->bbio.bio.bi_iter.bi_size;
+- ret = btrfs_reserve_extent(root, async_extent->ram_size,
++ ret = btrfs_reserve_extent(root, inode, async_extent->ram_size,
+ compressed_size, compressed_size,
+ 0, *alloc_hint, &ins, true, true);
+ if (ret) {
+@@ -1216,8 +1216,9 @@ static int cow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
+ u64 cur_end;
+ int ret;
+
+- ret = btrfs_reserve_extent(root, num_bytes, num_bytes, min_alloc_size,
+- 0, alloc_hint, ins, true, true);
++ ret = btrfs_reserve_extent(root, inode, num_bytes, num_bytes,
++ min_alloc_size, 0, alloc_hint, ins, true,
++ true);
+ if (ret < 0) {
+ *ret_alloc_size = cur_len;
+ return ret;
+@@ -8117,6 +8118,7 @@ struct inode *btrfs_alloc_inode(struct super_block *sb)
+ ei->last_unlink_trans = 0;
+ ei->last_reflink_trans = 0;
+ ei->last_log_commit = 0;
++ ei->log_run_hint = 0;
+
+ spin_lock_init(&ei->lock);
+ ei->outstanding_extents = 0;
+@@ -9278,7 +9280,7 @@ int btrfs_prealloc_file_range(struct inode *inode, int mode,
+ * sized chunks.
+ */
+ cur_bytes = min(cur_bytes, last_alloc);
+- ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
++ ret = btrfs_reserve_extent(root, NULL, cur_bytes, cur_bytes,
+ min_size, 0, *alloc_hint, &ins, true, false);
+ if (ret)
+ break;
+@@ -10115,7 +10117,7 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
+ }
+ }
+
+- ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
++ ret = btrfs_reserve_extent(root, inode, disk_num_bytes, disk_num_bytes,
+ disk_num_bytes, 0, 0, &ins, true, true);
+ if (ret)
+ goto out_delalloc_release;
+diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
+index b810115db9603..a41f57559ee74 100644
+--- a/fs/btrfs/relocation.c
++++ b/fs/btrfs/relocation.c
+@@ -4285,8 +4285,8 @@ static int move_existing_remap(struct btrfs_fs_info *fs_info,
+ else
+ min_size = fs_info->nodesize;
+
+- ret = btrfs_reserve_extent(fs_info->fs_root, length, length, min_size,
+- 0, 0, &ins, is_data, false);
++ ret = btrfs_reserve_extent(fs_info->fs_root, NULL, length, length,
++ min_size, 0, 0, &ins, is_data, false);
+ if (unlikely(ret)) {
+ spin_lock(&sinfo->lock);
+ btrfs_space_info_update_bytes_may_use(sinfo, -length);
+@@ -5114,8 +5114,8 @@ static int do_remap_reloc_trans(struct btrfs_fs_info *fs_info,
+ * of the identity remap that we're processing, and will tackle the
+ * rest of it the next time round.
+ */
+- ret = btrfs_reserve_extent(fs_info->fs_root, remap_length, remap_length,
+- min_size, 0, 0, &ins, is_data, false);
++ ret = btrfs_reserve_extent(fs_info->fs_root, NULL, remap_length,
++ remap_length, min_size, 0, 0, &ins, is_data, false);
+ if (ret) {
+ spin_lock(&sinfo->lock);
+ btrfs_space_info_update_bytes_may_use(sinfo, -remap_length);
+--
+2.47.3
+
--- /dev/null
+From bc8976c3642036cfdb102312af296f4c31450d4f Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:38 -0400
+Subject: [RFC PATCH 12/85] btrfs: raid56: pad sub-stripe writes to full
+ stripes in open runs
+To: linux-btrfs@vger.kernel.org
+
+A sub-stripe write does a full RMW: read every untouched data sector of
+the stripe, recompute parity, write. Under stripe-exclusive allocation
+the read phase is usually pointless: a stripe covered by a live stripe
+run has never been written at or past the run's allocation frontier, so
+the sectors being read contain nothing.
+
+When every data sector the rbio does not cover lies at or past the
+frontier, zero-fill those sectors instead of reading them and write
+them out with the stripe -- the zeros must reach the disk, or the
+parity (computed over them) would not match what scrub reads back. The
+partial write becomes one full-stripe write: no read phase, one parity
+pass. A frontier that grows during the attempt is safe: the newer
+allocation's write serializes behind this rbio's stripe lock and lands
+over the zeros. If any uncovered sector is below the frontier (already
+allocated to someone else), fall back to the normal RMW.
+
+Together with kicking parked rbios before the fast fsync's writeback
+wait, this removes both stalls the raid56 layer added to fsync under
+stripe_alloc: the park deadline and the RMW read round trip.
+
+The pad sets the rbio's data bitmap under bio_list_lock: until
+RBIO_RMW_LOCKED_BIT is set another writer can merge into the rbio and OR
+its bits in under that lock, and a lost pad bit would leave rows out of
+the write while the cached stripe marks their zero-filled pages up to date.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 43 ++++++++++++++++++
+ fs/btrfs/block-group.h | 3 ++
+ fs/btrfs/raid56.c | 98 +++++++++++++++++++++++++++++++++++++++++-
+ 3 files changed, 142 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 9e5df9eb0c155..86a8c9e1afb6d 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -909,6 +909,49 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ return true;
+ }
+
++/*
++ * For the raid56 pad-to-full optimization: a sub-stripe write into a
++ * stripe covered by a live stripe run may zero-fill (instead of read) any
++ * sector at or past the run's allocation frontier, because such sectors
++ * have never been written in the run's lifetime and, once the run closes,
++ * its stripe's tail cannot be reallocated while the stripe holds live
++ * data. Returns true and sets *pad_from to the frontier when the stripe
++ * at [stripe_start, stripe_start + stripe_len) has a paddable tail. The
++ * frontier can grow right after this returns; that is safe, because the
++ * later allocation's write serializes behind the caller's stripe lock
++ * and overwrites the zeros.
++ */
++bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
++ u64 stripe_start, u64 stripe_len,
++ u64 *pad_from)
++{
++ struct btrfs_block_group *bg;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ bool ret = false;
++
++ if (list_empty_careful(&fs_info->open_stripe_bgs))
++ return false;
++ bg = btrfs_lookup_block_group(fs_info, stripe_start);
++ if (!bg)
++ return false;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (stripe_start < run->start || stripe_start >= run->end)
++ continue;
++ if (run->offset > stripe_start &&
++ run->offset < stripe_start + stripe_len) {
++ *pad_from = run->offset;
++ ret = true;
++ }
++ break;
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ btrfs_put_block_group(bg);
++ return ret;
++}
++
+ /*
+ * Can stripe-exclusive allocation be enabled on this filesystem? Called for
+ * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 6d83c79e8c02e..981ebbd6b8149 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -409,6 +409,9 @@ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
+ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
+ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ u64 run_start, u64 *run_len);
++bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
++ u64 stripe_start, u64 stripe_len,
++ u64 *pad_from);
+ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
+ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
+ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 71ff75c8c93ff..49c1163bc1f28 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -45,6 +45,15 @@
+ */
+ #define RBIO_PARKED_BIT 4
+
++/*
++ * Set when a partial write rbio's uncovered data sectors were zero-filled
++ * instead of read, because the covering stripe run says they hold nothing
++ * (see rmw_try_pad_full()). The zeroes are written with the stripe so
++ * parity matches the disk: the partial write becomes a full-stripe write
++ * with no read phase.
++ */
++#define RBIO_PADDED_BIT 5
++
+ /*
+ * Set when an unplug callback finished merging this rbio's submission
+ * batch: the submitter has no more bios coming. A sync rbio past this
+@@ -1688,7 +1697,12 @@ static int rmw_assemble_write_bios(struct btrfs_raid_bio *rbio,
+ continue;
+
+ if (stripe < rbio->nr_data) {
+- paddrs = sector_paddrs_in_rbio(rbio, stripe, sectornr, 1);
++ /*
++ * A padded rbio writes its zero-filled stripe sectors
++ * too, so parity matches the disk (see RBIO_PADDED_BIT).
++ */
++ paddrs = sector_paddrs_in_rbio(rbio, stripe, sectornr,
++ !test_bit(RBIO_PADDED_BIT, &rbio->flags));
+ if (paddrs == NULL)
+ continue;
+ } else {
+@@ -2643,6 +2657,79 @@ static void submit_write_bios(struct btrfs_raid_bio *rbio,
+ }
+ }
+
++/*
++ * Try to avoid the RMW read phase of a sub-stripe write by zero-filling
++ * the uncovered data sectors. Legal only when every uncovered sector
++ * lies at or past its stripe run's allocation frontier -- never written
++ * in the run's lifetime, and unreachable by other allocations while this
++ * stripe holds live data (see btrfs_stripe_run_pad_start()). A frontier
++ * that grows under us is safe: the newer allocation's write serializes
++ * behind this rbio's stripe lock and lands over the zeros.
++ */
++static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ const u64 stripe_start = rbio->bioc->full_stripe_logical;
++ const u32 sectorsize = fs_info->sectorsize;
++ const u64 stripe_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
++ u64 pad_from;
++ int i;
++
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return false;
++ if (!btrfs_stripe_run_pad_start(fs_info, stripe_start, stripe_len,
++ &pad_from))
++ return false;
++
++ /* Populate bio_paddrs so covered sectors are visible below. */
++ index_rbio_pages(rbio);
++
++ /* Every data sector this rbio does not cover must be paddable. */
++ for (i = 0; i < rbio->nr_data * rbio->stripe_nsectors; i++) {
++ const int stripe_nr = i / rbio->stripe_nsectors;
++ const int sectornr = i % rbio->stripe_nsectors;
++ u64 logical = stripe_start + stripe_nr * BTRFS_STRIPE_LEN +
++ (u64)sectornr * sectorsize;
++
++ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
++ continue;
++ if (logical < pad_from)
++ return false;
++ }
++
++ if (alloc_rbio_data_pages(rbio) < 0)
++ return false;
++
++ for (i = 0; i < rbio->nr_data * rbio->stripe_nsectors; i++) {
++ const int stripe_nr = i / rbio->stripe_nsectors;
++ const int sectornr = i % rbio->stripe_nsectors;
++ int step;
++
++ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
++ continue;
++ for (step = 0; step < rbio->sector_nsteps; step++) {
++ phys_addr_t paddr = rbio_stripe_paddr(rbio, stripe_nr,
++ sectornr, step);
++ void *kaddr = kmap_local_paddr(paddr);
++
++ memset(kaddr, 0, min_t(u32, sectorsize, PAGE_SIZE));
++ kunmap_local(kaddr);
++ }
++ set_bit(i, rbio->stripe_uptodate_bitmap);
++ }
++
++ set_bit(RBIO_PADDED_BIT, &rbio->flags);
++ /*
++ * The whole stripe goes out: every vertical position is written.
++ * Under bio_list_lock: until RBIO_RMW_LOCKED_BIT is set, merge_rbio()
++ * can still OR another rbio's bits into this bitmap.
++ */
++ spin_lock(&rbio->bio_list_lock);
++ bitmap_set(&rbio->dbitmap, 0, rbio->stripe_nsectors);
++ spin_unlock(&rbio->bio_list_lock);
++ return true;
++}
++
+ /*
+ * To determine if we need to read any sector from the disk.
+ * Should only be utilized in RMW path, to skip cached rbio.
+@@ -2684,8 +2771,15 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ /*
+ * Either full stripe write, or we have every data sector already
+ * cached, can go to write path immediately.
++ *
++ * Try padding before trusting the cache: a cached rbio can hold pages
++ * from the stripe's previous life, before its extents were freed and
++ * the stripe re-claimed, and parity computed from them matches the
++ * disk only if every uncovered column still holds that data. Padding
++ * writes every uncovered column, so the stripe needs nothing on disk.
+ */
+- if (!rbio_is_full(rbio) && need_read_stripe_sectors(rbio)) {
++ if (!rbio_is_full(rbio) && !rmw_try_pad_full(rbio) &&
++ need_read_stripe_sectors(rbio)) {
+ /*
+ * Now we're doing sub-stripe write, also need all data stripes
+ * to do the full RMW.
+--
+2.47.3
+
+++ /dev/null
-From 39bf390edbf806623171491e8928f1c26b15062a Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:30 -0400
-Subject: [RFC PATCH 012/116] btrfs: stripe_alloc: never claim stripes covered
- by a live run
-To: linux-btrfs@vger.kernel.org
-
-The range-to-run lookups -- attaching an ordered extent to its stripe run
-and reporting completed data IO by bytenr -- assume that at most one run
-on a block group's list covers any given address. Nothing enforced that.
-
-A reservation that is discarded before anything references it (the
-cow_file_range error path under ENOSPC, the find_free_extent backout
-paths) returns its bytes to the free space cache immediately, with no
-pinning: there is no committed state to protect. When an ENOSPC failure
-storm discards every allocation in a stripe, the stripe is fully free
-again and the claim rule -- correctly, by its own lights -- hands it out
-as part of a new run while the old run object is still on the list
-draining its other stripes' IO. Full-stripe write batching widened a
-run's post-close drain from microseconds to the parked-write timeout, and
-the soak test hit the overlap within minutes: new allocations' ordered
-extents attached to the old run (first match by range), their completions
-drained the old run's inflight accounting into an assertion failure, and
-the new run's accounting never drained, wedging the commit's retire wait.
-The overlap is harmless to data -- a stripe can only be re-claimed if
-every byte of it is free, and discarded reservations never issued bios --
-but the accounting corruption is fatal.
-
-Freed committed extents cannot reproduce this: they return to the free
-cache only in the unpin phase at the tail of a commit, and the same
-commit's retirement already drained -- and freed -- every run opened
-before it. Only the unpinned immediate-free paths race with a draining
-run.
-
-Rather than enumerate those paths, enforce the lookups' assumption at the
-claim site: btrfs_claim_free_stripe_run() now trims a candidate to end
-before the first live run overlapping it, or rejects it if its head
-overlaps. Re-claiming such stripes just waits until the old run drains
-off the list, which only comes up inside ENOSPC failure storms.
-
-Reproduced with concurrent fill-to-ENOSPC/delete cycles, balance, and
-fsstress on a 4-device raid5: the assertion fired within ~15 minutes
-unpatched, and ~10 hours of the same load ran clean with this fix.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 34 ++++++++++++++++++++++++++++++++++
- fs/btrfs/block-group.h | 2 ++
- fs/btrfs/free-space-cache.c | 7 ++++++-
- 3 files changed, 42 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index a10d59bb8aa49..7e820fd50bb03 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -770,6 +770,40 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- return ret;
- }
-
-+/*
-+ * A live stripe run's address range must not be re-claimed while the run
-+ * object still exists: an ENOSPC discard storm can return every byte of a
-+ * stripe to the free cache while its run is still draining other stripes'
-+ * IO, and a second run claimed over the same range would make the
-+ * range-to-run lookups (ordered extent attach, IO reporting) ambiguous and
-+ * corrupt the inflight accounting. Trim the candidate to end before the
-+ * first overlapping run; reject it outright if its head overlaps. Caller
-+ * holds ctl->tree_lock; stripe_run_lock nests inside it.
-+ */
-+bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
-+ u64 run_start, u64 *run_len)
-+{
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ u64 len = *run_len;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (run->end <= run_start || run->start >= run_start + len)
-+ continue;
-+ if (run->start <= run_start) {
-+ len = 0;
-+ break;
-+ }
-+ len = run->start - run_start;
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ if (len < bg->full_stripe_len)
-+ return false;
-+ *run_len = len;
-+ return true;
-+}
-+
- /*
- * Can stripe-exclusive allocation be enabled on this filesystem? Called for
- * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index a726f9da7f1fc..6740c65870222 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -403,6 +403,8 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
- void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
-+bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
-+ u64 run_start, u64 *run_len);
- int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
- int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
- void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 9837562d348a5..4a1db014b19b0 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2211,7 +2211,9 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
-
- if (entry->bitmap) {
- if (find_stripe_run_in_bitmap(ctl, entry, want_bytes,
-- &run_start, &run_len))
-+ &run_start, &run_len) &&
-+ btrfs_stripe_run_range_usable(block_group,
-+ run_start, &run_len))
- goto found;
- continue;
- }
-@@ -2222,6 +2224,9 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- run_len = min(want_bytes,
- div64_u64(entry->offset + entry->bytes - run_start,
- fsl) * fsl);
-+ if (!btrfs_stripe_run_range_usable(block_group, run_start,
-+ &run_len))
-+ continue;
- goto found;
- }
- goto out;
---
-2.47.3
-
--- /dev/null
+From cebc5592ab68c4ab3067f4c832a57fdea905722c Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:43 -0400
+Subject: [RFC PATCH 13/85] btrfs: raid56: expose parking statistics in sysfs
+To: linux-btrfs@vger.kernel.org
+
+/sys/fs/btrfs/<uuid>/stripe_park_stats reports lifetime counters for
+the parking machinery: rbios parked, bytes merged into parked rbios,
+and how each park ended (filled to a full stripe, kicked by a waiter or
+a settle/retire flush, or expired at its deadline), plus how many
+flushed writes were padded to full stripes versus still needing the
+RMW read phase. The filled/kicked/expired split shows directly whether
+the deadlines are sized right for a given system -- expired parks that
+later reappear as rmw_reads are the batching the window failed to
+capture -- so any future retuning (or an adaptive deadline) can argue
+from measurements instead of taste.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/fs.h | 14 ++++++++++++++
+ fs/btrfs/raid56.c | 16 ++++++++++++++++
+ fs/btrfs/sysfs.c | 24 ++++++++++++++++++++++++
+ 3 files changed, 54 insertions(+)
+
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index b085e198f23da..d0198cfe1c850 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -793,6 +793,20 @@ struct btrfs_fs_info {
+ u32 data_chunk_allocations;
+ u32 metadata_ratio;
+
++ /*
++ * raid56 parking observability (see rbio_try_park()): lifetime
++ * counters exposed through sysfs stripe_park_stats.
++ */
++ struct {
++ atomic64_t parked;
++ atomic64_t merged_bytes;
++ atomic64_t filled;
++ atomic64_t expired;
++ atomic64_t kicked;
++ atomic64_t rmw_reads;
++ atomic64_t padded;
++ } stripe_park_stats;
++
+ /* Private scrub information */
+ struct mutex scrub_lock;
+ atomic_t scrubs_running;
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 49c1163bc1f28..a9fac8fc28e4f 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -62,6 +62,9 @@
+ */
+ #define RBIO_BATCH_DONE_BIT 6
+
++/* Set at park time and never cleared: this rbio once parked (stats). */
++#define RBIO_WAS_PARKED_BIT 7
++
+ #define RBIO_CACHE_SIZE 1024
+
+ #define BTRFS_RBIO_PARK_TIMEOUT_MS 100
+@@ -423,6 +426,9 @@ static void steal_rbio(struct btrfs_raid_bio *src, struct btrfs_raid_bio *dest)
+ static void merge_rbio(struct btrfs_raid_bio *dest,
+ struct btrfs_raid_bio *victim)
+ {
++ if (test_bit(RBIO_PARKED_BIT, &dest->flags))
++ atomic64_add(victim->bio_list_bytes,
++ &dest->bioc->fs_info->stripe_park_stats.merged_bytes);
+ bio_list_merge_init(&dest->bio_list, &victim->bio_list);
+ dest->bio_list_bytes += victim->bio_list_bytes;
+ /* Also inherit the bitmaps from @victim. */
+@@ -753,6 +759,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+
+ spin_lock(&table->parked_lock);
+ set_bit(RBIO_PARKED_BIT, &rbio->flags);
++ set_bit(RBIO_WAS_PARKED_BIT, &rbio->flags);
+ rbio->park_deadline = jiffies + msecs_to_jiffies(timeout_ms);
+ /*
+ * Take a reference of our own before publishing: once parked_lock is
+@@ -764,6 +771,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ refcount_inc(&rbio->refs);
+ list_add_tail(&rbio->parked_node, &table->parked);
+ spin_unlock(&table->parked_lock);
++ atomic64_inc(&fs_info->stripe_park_stats.parked);
+ queue_delayed_work(system_percpu_wq, &table->parked_work,
+ msecs_to_jiffies(BTRFS_RBIO_PARK_SCAN_MS));
+
+@@ -809,6 +817,7 @@ static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
+ }
+ rbio_unpark_locked(rbio);
+ spin_unlock(&table->parked_lock);
++ atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.filled);
+ start_async_work(rbio, rmw_rbio_work_locked);
+ }
+
+@@ -842,6 +851,7 @@ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
+
+ list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
+ list_del_init(&rbio->parked_node);
++ atomic64_inc(&fs_info->stripe_park_stats.kicked);
+ start_async_work(rbio, rmw_rbio_work_locked);
+ }
+ }
+@@ -871,6 +881,7 @@ static void parked_rbios_timeout_work(struct work_struct *work)
+
+ list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
+ list_del_init(&rbio->parked_node);
++ atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.expired);
+ start_async_work(rbio, rmw_rbio_work_locked);
+ }
+ if (rearm)
+@@ -2727,6 +2738,7 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ spin_lock(&rbio->bio_list_lock);
+ bitmap_set(&rbio->dbitmap, 0, rbio->stripe_nsectors);
+ spin_unlock(&rbio->bio_list_lock);
++ atomic64_inc(&fs_info->stripe_park_stats.padded);
+ return true;
+ }
+
+@@ -2780,6 +2792,10 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ */
+ if (!rbio_is_full(rbio) && !rmw_try_pad_full(rbio) &&
+ need_read_stripe_sectors(rbio)) {
++ /* A parked-then-flushed write that still had to read. */
++ if (test_bit(RBIO_WAS_PARKED_BIT, &rbio->flags))
++ atomic64_inc(&rbio->bioc->fs_info->
++ stripe_park_stats.rmw_reads);
+ /*
+ * Now we're doing sub-stripe write, also need all data stripes
+ * to do the full RMW.
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 7852bd1c1e64b..6d21fd7963115 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1110,6 +1110,29 @@ static ssize_t btrfs_commit_stats_store(struct kobject *kobj,
+ }
+ BTRFS_ATTR_RW(, commit_stats, btrfs_commit_stats_show, btrfs_commit_stats_store);
+
++static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
++ struct kobj_attribute *a, char *buf)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++
++ return sysfs_emit(buf,
++ "parked %lld\n"
++ "merged_bytes %lld\n"
++ "filled %lld\n"
++ "kicked %lld\n"
++ "expired %lld\n"
++ "padded %lld\n"
++ "rmw_reads %lld\n",
++ atomic64_read(&fs_info->stripe_park_stats.parked),
++ atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
++ atomic64_read(&fs_info->stripe_park_stats.filled),
++ atomic64_read(&fs_info->stripe_park_stats.kicked),
++ atomic64_read(&fs_info->stripe_park_stats.expired),
++ atomic64_read(&fs_info->stripe_park_stats.padded),
++ atomic64_read(&fs_info->stripe_park_stats.rmw_reads));
++}
++BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
++
+ static ssize_t btrfs_clone_alignment_show(struct kobject *kobj,
+ struct kobj_attribute *a, char *buf)
+ {
+@@ -1476,6 +1499,7 @@ static const struct attribute *btrfs_attrs[] = {
+ BTRFS_ATTR_PTR(, read_policy),
+ BTRFS_ATTR_PTR(, bg_reclaim_threshold),
+ BTRFS_ATTR_PTR(, commit_stats),
++ BTRFS_ATTR_PTR(, stripe_park_stats),
+ BTRFS_ATTR_PTR(, temp_fsid),
+ NULL,
+ };
+--
+2.47.3
+
+++ /dev/null
-From 6841c0aaa73bc51fea259a58d46b66268d6cd7ab Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:31 -0400
-Subject: [RFC PATCH 013/116] btrfs: stripe_alloc: settle a logged extent's
- stripes at log commit
-To: linux-btrfs@vger.kernel.org
-
-Stripe-exclusive allocation bounds degraded-crash damage to the current
-transaction, but within that window two log commits can still share a
-stripe: fsync 1 writes the head of a stripe, the open run keeps filling
-it, and a later write's read-modify-write rewrites the parity that
-protects fsync 1's data. A degraded crash during the second write tears
-the first -- the write hole's shape, confined to the log window, and the
-reason the fsync guarantee has so far been "loss is detectable" rather
-than "completed fsyncs survive".
-
-Close it with a case analysis. A logged extent in a full stripe is
-already safe: nothing ever writes a full stripe again, since COW never
-overwrites and there are no free sectors left to allocate. A logged
-extent in a partial stripe is exposed only to future writes into that
-stripe's remaining sectors -- so at log commit, close the stripe's open
-run (nothing further allocates into it), kick any parked partial writes
-for it, and wait for its in-flight data IO before the log super is
-written. This is the log-window analogue of invariant I2, which the
-commit-time retirement provides for full commits. Both log paths are
-hooked: the fast path per extent map in log_one_extent(), and the
-full-sync path where copy_items() walks new data extents (old-transaction
-extents are skipped there, and are exactly the ones already settled by
-their own commit).
-
-The drain is bounded and join-free: run inflight is counted from
-allocation, which happens during writeback with submission following in
-the same pass, so the wait is bio flight time plus the parked-write
-deadline that the flush short-circuits; write_done reporting needs no
-transaction join, so waiting under the inode log mutex and a running
-transaction handle is safe.
-
-The cost is spatial: every fsync that logs an extent in a partial stripe
-retires that stripe early, trapping its unwritten tail like any other
-partially filled stripe until it frees or balance reclaims it.
-Fsync-heavy workloads therefore burn a stripe tail per touched stripe
-per fsync; the follow-up per-inode log runs and copy-forward relocation
-exist to reclaim exactly that cost, and are optimizations on top of the
-guarantee this patch completes.
-
-Assisted-by: Claude:claude-fable-5
-(cherry picked from commit 53c44fdbca58bd1fa267a5648e236ed4238d99ed)
----
- fs/btrfs/block-group.c | 80 ++++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/block-group.h | 2 ++
- fs/btrfs/tree-log.c | 29 +++++++++++++++
- 3 files changed, 111 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 7e820fd50bb03..c5f7df4ca8f3d 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -804,6 +804,86 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- return true;
- }
-
-+/* No open or draining run covers @bytenr any more. */
-+static bool stripe_log_range_settled(struct btrfs_block_group *bg, u64 bytenr)
-+{
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ bool settled = true;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (bytenr >= run->start && bytenr < run->offset) {
-+ settled = false;
-+ break;
-+ }
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ return settled;
-+}
-+
-+/*
-+ * A log commit is about to make the extent at [bytenr, bytenr + num_bytes)
-+ * durable. Once the log super lands, no later write may extend or RMW the
-+ * extent's stripes -- the log-window analogue of invariant I2, which the
-+ * commit-time retirement provides for full commits. Close the open run
-+ * covering the extent so nothing further allocates into its stripes, kick
-+ * any parked partial writes for it, and wait for all data IO into it to
-+ * finish. Extents in full or already-settled stripes cost one list walk.
-+ *
-+ * The drain is bounded: run inflight is counted from allocation, which
-+ * happens during writeback with submission following in the same pass, so
-+ * the wait is bio flight time plus the parked-write deadline that the flush
-+ * below short-circuits. It is a pure data-IO wait (no transaction joins),
-+ * safe under the inode log mutex and a running transaction handle.
-+ */
-+void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
-+ u64 num_bytes)
-+{
-+ struct btrfs_block_group *bg;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ u64 tail_start = 0;
-+ u64 tail_len = 0;
-+ u64 flush_start = 0;
-+ u64 flush_len = 0;
-+
-+ if (list_empty_careful(&fs_info->open_stripe_bgs))
-+ return;
-+ bg = btrfs_lookup_block_group(fs_info, bytenr);
-+ if (!bg)
-+ return;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (bytenr < run->start || bytenr >= run->offset)
-+ continue;
-+ flush_start = run->start;
-+ flush_len = run->end - run->start;
-+ if (run->open) {
-+ int class;
-+ int band;
-+
-+ 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)
-+ bg->open_stripe[class][band] = NULL;
-+ tail_len = close_open_stripe_run(bg, run, &tail_start);
-+ }
-+ break;
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+
-+ if (tail_len)
-+ btrfs_add_free_space(bg, tail_start, tail_len);
-+ if (flush_len) {
-+ btrfs_flush_parked_rbios(fs_info, flush_start, flush_len);
-+ wait_var_event(&bg->open_stripe_runs,
-+ stripe_log_range_settled(bg, bytenr));
-+ }
-+ btrfs_put_block_group(bg);
-+}
-+
- /*
- * Can stripe-exclusive allocation be enabled on this filesystem? Called for
- * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 6740c65870222..74528f0175e98 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -405,6 +405,8 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
- bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- u64 run_start, u64 *run_len);
-+void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
-+ u64 num_bytes);
- int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
- int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
- void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
-diff --git a/fs/btrfs/tree-log.c b/fs/btrfs/tree-log.c
-index e50f924bca59f..6aa8db5b1044e 100644
---- a/fs/btrfs/tree-log.c
-+++ b/fs/btrfs/tree-log.c
-@@ -4875,6 +4875,23 @@ static noinline int copy_items(struct btrfs_trans_handle *trans,
- return BTRFS_LOG_FORCE_COMMIT;
- }
-
-+ /*
-+ * New data extent made durable by this log commit: settle its
-+ * stripes. This must not hide behind the csum skips below --
-+ * a nodatasum inode's extents need their stripes settled all
-+ * the same. Inline extents and holes have no stripes.
-+ */
-+ if (!is_old_extent &&
-+ btrfs_file_extent_type(src, extent) == BTRFS_FILE_EXTENT_REG) {
-+ disk_bytenr = btrfs_file_extent_disk_bytenr(src, extent);
-+ disk_num_bytes =
-+ btrfs_file_extent_disk_num_bytes(src, extent);
-+ if (disk_bytenr)
-+ btrfs_log_settle_stripes(trans->fs_info,
-+ disk_bytenr,
-+ disk_num_bytes);
-+ }
-+
- if (skip_csum)
- goto add_to_batch;
-
-@@ -5163,6 +5180,18 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
-
- block_len = em->disk_num_bytes;
- compress_type = btrfs_extent_map_compression(em);
-+
-+ /*
-+ * This log commit makes the extent durable: settle its stripes so no
-+ * later write in this transaction can tear them (see
-+ * btrfs_log_settle_stripes()). Preallocated extents carry no data
-+ * and holes have no stripes; both are skipped.
-+ */
-+ if (!(em->flags & EXTENT_FLAG_PREALLOC) &&
-+ em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
-+ btrfs_log_settle_stripes(inode->root->fs_info, em->disk_bytenr,
-+ em->disk_num_bytes);
-+
- if (compress_type != BTRFS_COMPRESS_NONE) {
- btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start);
- btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
---
-2.47.3
-
--- /dev/null
+From f1536f5012fef160581f7103b7a4f43224eea5c7 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:45 -0400
+Subject: [RFC PATCH 14/85] btrfs: stripe_alloc: count open stripe run
+ remainders against data reservations
+To: linux-btrfs@vger.kernel.org
+
+Close the remaining reservation-vs-allocation windows the commit-time
+stripe_unusable rescan cannot see:
+
+- bytes_stripe_open (new): the sum of open runs' unallocated
+ remainders, maintained per block group under stripe_run_lock at
+ every open/alloc/grow/close, synced into the space_info after each
+ mutation, and counted in btrfs_space_info_used(). Claimed bytes are
+ invisible to the free space cache and will either be allocated or
+ become trapped tails at close, so reservations must not be admitted
+ against them.
+
+A closed run's returned tail is still only counted as trapped by the
+commit-time rescan, so reservations can race the retire-to-rescan window
+inside a commit and be admitted against freshly trapped tails. The next
+patch closes that window from the free space cache side, where every
+returning range is seen and no call site can be missed.
+
+Measured on the fill-to-ENOSPC rolling test before this change (with
+only the bytes_stripe_unusable accounting): tree 'b' still lost 3.3%
+(8532 blocks) and tree 'c' 30% (62371 blocks) to silent writeback
+allocation failure as trapping compounded.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 51 +++++++++++++++++++++++++++++++++++++++++-
+ fs/btrfs/block-group.h | 8 +++++++
+ fs/btrfs/space-info.h | 22 ++++++++++++------
+ 3 files changed, 73 insertions(+), 8 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 86a8c9e1afb6d..d5a1f6f2070b2 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -548,11 +548,46 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
+ *tail_start = run->offset;
+ tail_len = run->end - run->offset;
+ run->end = run->offset;
++ bg->stripe_open_remainder -= tail_len;
+ if (open_stripe_run_drained(run))
+ free_open_stripe_run(bg, run);
+ return tail_len;
+ }
+
++/*
++ * Fold this block group's open-run remainder delta into the space_info
++ * counter that reservations see. Bytes inside an open run are invisible
++ * to the free space cache (the claim removed them) and will either be
++ * allocated or become trapped tails when the run closes, so the data
++ * reservation path must not admit writes against them: a reservation
++ * that cannot allocate at writeback time discards the pages silently.
++ * Called after every remainder mutation. Compute and apply are one
++ * critical section (sinfo->lock nests inside stripe_run_lock): applied
++ * out of order, a negative delta could overtake the positive it was
++ * computed against and transiently underflow the space_info sum.
++ */
++static void stripe_open_remainder_sync(struct btrfs_block_group *bg)
++{
++ struct btrfs_space_info *sinfo = bg->space_info;
++ unsigned long flags;
++ s64 delta;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ delta = (s64)(bg->stripe_open_remainder - bg->stripe_open_reported);
++ bg->stripe_open_reported = bg->stripe_open_remainder;
++ if (delta && sinfo) {
++ spin_lock(&sinfo->lock);
++ if (delta < 0 && sinfo->bytes_stripe_open < (u64)-delta) {
++ WARN_ON_ONCE(1);
++ sinfo->bytes_stripe_open = 0;
++ } else {
++ sinfo->bytes_stripe_open += delta;
++ }
++ spin_unlock(&sinfo->lock);
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++}
++
+ /*
+ * Install @run (not currently in any band slot) into its remaining-space band.
+ * If a run already occupies that band, keep whichever has more remaining -- it
+@@ -643,6 +678,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ *ret_offset = run->offset;
+ run->offset += num_bytes;
+ run->inflight_bytes += num_bytes;
++ bg->stripe_open_remainder -= num_bytes;
+ if (run->offset == run->end)
+ run->open = false; /* full: closed, no tail */
+ else
+@@ -650,6 +686,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ if (tail_len)
+ btrfs_add_free_space(bg, tail_start, tail_len);
++ stripe_open_remainder_sync(bg);
+ return 0;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+@@ -724,6 +761,8 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ r->end = start + len;
+ r->offset += num_bytes;
+ r->inflight_bytes += num_bytes;
++ bg->stripe_open_remainder += len;
++ bg->stripe_open_remainder -= num_bytes;
+ if (r->offset == r->end)
+ r->open = false; /* full: closed, no tail */
+ else
+@@ -732,6 +771,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ spin_unlock(&fs_info->open_stripe_lock);
+ if (tail_len)
+ btrfs_add_free_space(bg, tail_start, tail_len);
++ stripe_open_remainder_sync(bg);
+ ret = 0;
+ goto out; /* frees the unused new_run */
+ }
+@@ -745,6 +785,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ new_run->open_seq = fs_info->stripe_retire_seq;
+ new_run->open = (new_run->offset != new_run->end);
+ list_add_tail(&new_run->list, &bg->open_stripe_runs);
++ bg->stripe_open_remainder += new_run->end - new_run->offset;
+ /*
+ * Place the new run in its remaining-space band, closing whichever run
+ * loses a band collision (the last, fuller opener wins). Other bands'
+@@ -757,6 +798,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+
+ if (tail_len)
+ btrfs_add_free_space(bg, tail_start, tail_len);
++ stripe_open_remainder_sync(bg);
+ *ret_offset = start;
+ new_run = NULL;
+ ret = 0;
+@@ -809,17 +851,21 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ *ret_offset = run->offset;
+ run->offset += num_bytes;
+ run->inflight_bytes += num_bytes;
++ bg->stripe_open_remainder -= num_bytes;
+ if (run->offset == run->end)
+ run->open = false; /* full: closed, no tail */
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ stripe_open_remainder_sync(bg);
+ return 0;
+ }
+ tail_len = close_open_stripe_run(bg, run, &tail_start);
+ break;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+- if (tail_len)
++ if (tail_len) {
+ btrfs_add_free_space(bg, tail_start, tail_len);
++ stripe_open_remainder_sync(bg);
++ }
+
+ new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
+ if (!new_run)
+@@ -864,9 +910,11 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ new_run->open_seq = fs_info->stripe_retire_seq;
+ new_run->open = (new_run->offset != new_run->end);
+ list_add_tail(&new_run->list, &bg->open_stripe_runs);
++ bg->stripe_open_remainder += new_run->end - new_run->offset;
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ spin_unlock(&fs_info->open_stripe_lock);
+
++ stripe_open_remainder_sync(bg);
+ *ret_offset = start;
+ new_run = NULL;
+ ret = 0;
+@@ -1217,6 +1265,7 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ if (tail_len)
+ btrfs_add_free_space(bg, tail_start, tail_len);
++ stripe_open_remainder_sync(bg);
+ goto restart;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 981ebbd6b8149..883f6c1746862 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -241,6 +241,14 @@ struct btrfs_block_group {
+ struct list_head open_stripe_runs;
+ struct btrfs_open_stripe_run
+ *open_stripe[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
++ /*
++ * Sum of the open runs' unallocated remainders (end - offset), and
++ * the portion of it already folded into the space_info's
++ * bytes_stripe_open. Both under stripe_run_lock; synced by
++ * stripe_open_remainder_sync() after every mutation.
++ */
++ u64 stripe_open_remainder;
++ u64 stripe_open_reported;
+ /*
+ * Membership in fs_info->open_stripe_bgs, protected by
+ * fs_info->open_stripe_lock; holds a block group reference.
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index dbe86b3480b6c..83b56c20d5250 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -150,12 +150,20 @@ struct btrfs_space_info {
+ u64 bytes_readonly; /* total bytes that are read only */
+ u64 bytes_zone_unusable; /* total bytes that are unusable until
+ resetting the device zone */
+- u64 bytes_stripe_unusable; /* total free bytes trapped in partially
+- filled stripes of stripe_alloc block
+- groups; free but not allocatable until
+- the whole stripe frees. Informational
+- only (subtracted in statfs); NOT part
+- of btrfs_space_info_used(). */
++ u64 bytes_stripe_unusable; /* free bytes stripe_alloc and
++ stripe_meta groups cannot allocate:
++ partially filled stripes, and whole
++ stripes stranded behind live runs.
++ Counted as used, and subtracted in
++ statfs. */
++ u64 bytes_stripe_open; /* sum of open stripe runs' unallocated
++ remainders. Claimed out of the free
++ space cache but not yet allocated;
++ will either be allocated or become
++ trapped tails when the runs close, so
++ reservations must not count on it
++ either. Synced from the block groups'
++ stripe_open_remainder. */
+
+ u64 max_extent_size; /* This will hold the maximum extent size of
+ the space info if we had an ENOSPC in the
+@@ -315,7 +323,7 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
+ return s_info->bytes_used + s_info->bytes_reserved +
+ s_info->bytes_pinned + s_info->bytes_readonly +
+ s_info->bytes_zone_unusable +
+- s_info->bytes_stripe_unusable +
++ s_info->bytes_stripe_unusable + s_info->bytes_stripe_open +
+ (may_use_included ? s_info->bytes_may_use : 0);
+ }
+
+--
+2.47.3
+
+++ /dev/null
-From c92a00aaf5df8f99c84022b2efbf24badeb03954 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:31 -0400
-Subject: [RFC PATCH 014/116] btrfs: stripe_alloc: private per-inode stripe
- runs for log-active inodes
-To: linux-btrfs@vger.kernel.org
-
-Closing the open stripe run covering every logged extent at each log
-commit made completed fsyncs crash-safe, but at a placement cost: an
-fsync-heavy inode shares the open band runs with every other writer, so
-each of its log commits closes a shared run, fragmenting concurrent
-write streams and trapping the shared run's tail.
-
-Give log-active inodes their own runs instead. The first fsync of an
-inode sets a sticky runtime flag (at btrfs_sync_file entry, before the
-fsync flushes its own delalloc, so even that first fsync's allocations
-are steered). Datacow allocations for a flagged inode come from a
-private LOG-class run: claimed like any run but never placed in the
-shared band slots, owned by the inode, and found by owner lookup under
-the block group's stripe_run_lock. A per-inode hint seeds the
-allocator's search with the run's location; the hint is advisory (a
-stale hint costs a lookup miss, never a wrong run, since the owner
-match is authoritative). When no fully-free stripes remain for a
-private run the allocation falls back to the shared runs, restoring
-the previous placement with unchanged safety.
-
-One inode's log commit now settles only its own stripes: other
-writers' runs stay open and their streams stay contiguous, and the
-only trapped tails are the fsyncing inode's own. Private runs also
-give each log-active inode exclusive stripes, which a later change
-uses to copy live tails forward and reclaim them without touching
-foreign extents.
-
-The commit-time retirement closed runs by walking the band slots,
-which private runs never occupy; walk the block group's run list
-instead so every open run, slotted or private, is closed and drained
-under invariant I2 (no open run survives a transaction commit).
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 154 ++++++++++++++++++++++++++++++++++++-----
- fs/btrfs/block-group.h | 10 +++
- fs/btrfs/btrfs_inode.h | 21 ++++++
- fs/btrfs/direct-io.c | 2 +-
- fs/btrfs/extent-tree.c | 49 ++++++++++++-
- fs/btrfs/extent-tree.h | 9 ++-
- fs/btrfs/file.c | 11 +++
- fs/btrfs/inode.c | 12 ++--
- fs/btrfs/relocation.c | 8 +--
- 9 files changed, 245 insertions(+), 31 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index c5f7df4ca8f3d..25cb8dac15a9e 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -495,6 +495,7 @@ struct btrfs_open_stripe_run {
- u64 offset; /* next unallocated byte */
- u64 inflight_bytes; /* reserved bytes with data IO pending */
- u64 open_seq; /* fs_info->stripe_retire_seq at open */
-+ u64 owner; /* LOG class: btrfs_ino of the owner */
- enum btrfs_stripe_run_class class;
- bool open; /* accepting allocations */
- };
-@@ -569,6 +570,9 @@ static u64 stripe_run_place(struct btrfs_block_group *bg,
- int band = stripe_run_band(bg, run->end - run->offset);
- struct btrfs_open_stripe_run *occ = bg->open_stripe[class][band];
-
-+ /* Per-inode LOG runs are private and never occupy a band slot. */
-+ ASSERT(class != BTRFS_STRIPE_RUN_LOG);
-+
- if (occ) {
- struct btrfs_open_stripe_run *keep, *shut;
-
-@@ -743,6 +747,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->owner = 0;
- new_run->start = start;
- new_run->end = start + len;
- new_run->offset = start + num_bytes;
-@@ -770,6 +775,116 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- return ret;
- }
-
-+/*
-+ * Allocate num_bytes for a log-active inode from its private LOG-class run
-+ * in this block group, claiming a fresh run when the inode has none here or
-+ * the current one does not fit. Private runs are never placed in the shared
-+ * band slots and are found by owner lookup, so no other allocation can join
-+ * an inode's run and one inode's log commit settles only its own stripes.
-+ *
-+ * A replaced run (too small for this allocation) is closed immediately: the
-+ * inode moves on to the fresh run, so keeping the remainder open would only
-+ * strand it until the commit-time retirement. Two racing allocations for
-+ * the same inode can each claim a fresh run; the owner walk then serves one
-+ * of them and the other drains and retires at the next commit -- an
-+ * occasional trapped tail, not a correctness problem.
-+ *
-+ * 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,
-+ u64 num_bytes, u64 *ret_offset,
-+ u64 *available)
-+{
-+ struct btrfs_fs_info *fs_info = bg->fs_info;
-+ const u64 fsl = bg->full_stripe_len;
-+ struct btrfs_open_stripe_run *new_run;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ u64 tail_start = 0;
-+ u64 tail_len = 0;
-+ u64 start;
-+ u64 len;
-+ int ret;
-+
-+ ASSERT(num_bytes);
-+ *available = 0;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (run->class != BTRFS_STRIPE_RUN_LOG || run->owner != ino ||
-+ !run->open)
-+ continue;
-+ if (num_bytes <= run->end - run->offset) {
-+ *ret_offset = run->offset;
-+ run->offset += num_bytes;
-+ run->inflight_bytes += num_bytes;
-+ if (run->offset == run->end)
-+ run->open = false; /* full; drains, is freed */
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ return 0;
-+ }
-+ tail_len = close_open_stripe_run(bg, run, &tail_start);
-+ break;
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ if (tail_len)
-+ btrfs_add_free_space(bg, tail_start, tail_len);
-+
-+ new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
-+ if (!new_run)
-+ return -ENOMEM;
-+
-+ ret = btrfs_claim_free_stripe_run(bg,
-+ div64_u64(num_bytes + fsl - 1, fsl) * fsl,
-+ &start, &len);
-+ if (ret)
-+ goto out;
-+ if (len < num_bytes) {
-+ /* Only a shorter run is free; see btrfs_alloc_from_open_stripe(). */
-+ btrfs_add_free_space(bg, start, len);
-+ *available = len;
-+ ret = -ENOSPC;
-+ goto out;
-+ }
-+
-+ /* See the installation comment in btrfs_alloc_from_open_stripe(). */
-+ spin_lock(&fs_info->open_stripe_lock);
-+ if (list_empty(&bg->open_stripe_bg_list)) {
-+ btrfs_get_block_group(bg);
-+ list_add_tail(&bg->open_stripe_bg_list,
-+ &fs_info->open_stripe_bgs);
-+ }
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ if (bg->ro) {
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ spin_unlock(&fs_info->open_stripe_lock);
-+ btrfs_add_free_space(bg, start, len);
-+ *available = 0;
-+ ret = -ENOSPC;
-+ goto out;
-+ }
-+ new_run->bg = bg;
-+ new_run->class = BTRFS_STRIPE_RUN_LOG;
-+ new_run->owner = ino;
-+ new_run->start = start;
-+ new_run->end = start + len;
-+ new_run->offset = start + num_bytes;
-+ new_run->inflight_bytes = num_bytes;
-+ new_run->open_seq = fs_info->stripe_retire_seq;
-+ new_run->open = (new_run->offset != new_run->end);
-+ list_add_tail(&new_run->list, &bg->open_stripe_runs);
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ spin_unlock(&fs_info->open_stripe_lock);
-+
-+ *ret_offset = start;
-+ new_run = NULL;
-+ ret = 0;
-+out:
-+ kfree(new_run);
-+ return ret;
-+}
-+
- /*
- * A live stripe run's address range must not be re-claimed while the run
- * object still exists: an ENOSPC discard storm can return every byte of a
-@@ -1137,30 +1252,35 @@ 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)
- {
-- u64 tail_start[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
-- u64 tail_len[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
- struct btrfs_open_stripe_run *run;
- unsigned long flags;
- int class, band;
-
-+restart:
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
-- for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++) {
-- for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++) {
-- tail_len[class][band] = 0;
-- run = bg->open_stripe[class][band];
-- if (run && run->open_seq < seq) {
-- bg->open_stripe[class][band] = NULL;
-- tail_len[class][band] = close_open_stripe_run(
-- bg, run, &tail_start[class][band]);
-- }
-- }
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ u64 tail_start;
-+ u64 tail_len;
-+
-+ if (!run->open || run->open_seq >= seq)
-+ continue;
-+ 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)
-+ bg->open_stripe[class][band] = NULL;
-+ tail_len = close_open_stripe_run(bg, run, &tail_start);
-+ /*
-+ * Closing may have freed the run, and returning its tail to
-+ * the free space cache needs the lock dropped, so rescan.
-+ * Each pass closes one run and open runs are bounded (band
-+ * slots plus the private runs of inodes logged this window).
-+ */
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ if (tail_len)
-+ btrfs_add_free_space(bg, tail_start, tail_len);
-+ goto restart;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-- for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
-- for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++)
-- if (tail_len[class][band])
-- btrfs_add_free_space(bg, tail_start[class][band],
-- tail_len[class][band]);
- }
-
- /*
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 74528f0175e98..15cb94eeaab0c 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -30,6 +30,13 @@ struct btrfs_trans_handle;
- enum btrfs_stripe_run_class {
- BTRFS_STRIPE_RUN_COW,
- BTRFS_STRIPE_RUN_RELOC,
-+ /*
-+ * Private per-inode runs for log-active (fsync-heavy) inodes. Never
-+ * placed in the shared band slots: each run is owned by one inode and
-+ * found by owner lookup, so one inode's log commit settles only its
-+ * own stripes.
-+ */
-+ BTRFS_STRIPE_RUN_LOG,
- BTRFS_STRIPE_RUN_NR_CLASSES,
- };
-
-@@ -391,6 +398,9 @@ 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,
-+ u64 num_bytes, u64 *ret_offset,
-+ u64 *available);
- void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
- u64 num_bytes);
- void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
-diff --git a/fs/btrfs/btrfs_inode.h b/fs/btrfs/btrfs_inode.h
-index f7aa0d1451851..979adcdbe32e3 100644
---- a/fs/btrfs/btrfs_inode.h
-+++ b/fs/btrfs/btrfs_inode.h
-@@ -87,6 +87,17 @@ enum {
- BTRFS_INODE_VERITY_IN_PROGRESS,
- /* Set when this inode is a free space inode. */
- BTRFS_INODE_FREE_SPACE_INODE,
-+ /*
-+ * Set the first time this inode is fsynced under stripe-exclusive
-+ * allocation and never cleared while the inode stays cached. A
-+ * log-active inode's datacow allocations are steered into the inode's
-+ * own private LOG-class stripe run, so that its log commits settle
-+ * only its own stripes instead of closing (and trapping the tails of)
-+ * runs shared with other writers. Purely an allocation placement
-+ * hint: correctness comes from the log-commit settling itself, which
-+ * works on runs of any class.
-+ */
-+ BTRFS_INODE_LOG_ALLOC,
- /* Set when there are no capabilities in XATTs for the inode. */
- BTRFS_INODE_NO_CAP_XATTR,
- /*
-@@ -319,6 +330,16 @@ struct btrfs_inode {
- u64 ref_root_id;
- };
-
-+ /*
-+ * Start of the last extent allocated from this inode's private
-+ * LOG-class stripe run (see BTRFS_INODE_LOG_ALLOC). Advisory only:
-+ * it seeds the allocator's search hint so consecutive allocations
-+ * find the block group holding the inode's run. The run itself is
-+ * found by owner lookup under the block group's stripe_run_lock, so a
-+ * stale hint costs a miss, never a wrong run.
-+ */
-+ u64 log_run_hint;
-+
- /* Backwards incompatible flags, lower half of inode_item::flags */
- u32 flags;
- /* Read-only compatibility flags, upper half of inode_item::flags */
-diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c
-index ed3914257d395..8bdfae5ebe694 100644
---- a/fs/btrfs/direct-io.c
-+++ b/fs/btrfs/direct-io.c
-@@ -185,7 +185,7 @@ static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
-
- alloc_hint = btrfs_get_extent_allocation_hint(inode, start, len);
- again:
-- ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
-+ ret = btrfs_reserve_extent(root, inode, len, len, fs_info->sectorsize,
- 0, alloc_hint, &ins, true, true);
- if (ret == -EAGAIN) {
- ASSERT(btrfs_is_zoned(fs_info));
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 8755c8c4d0a0d..e1b6c8a0cdf96 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4242,6 +4242,31 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- if (skip)
- return 1;
-
-+ /*
-+ * A log-active inode allocates from its own private LOG-class run so
-+ * its log commits settle only its own stripes. If this block group
-+ * has no fully-free stripes left for a private run, fall through to
-+ * the shared runs: the data is then placed exactly as before 3b.1
-+ * and the log-commit settling keeps it safe, just less cheaply.
-+ */
-+ if (ffe_ctl->for_log_inode) {
-+ struct btrfs_inode *log_inode = ffe_ctl->for_log_inode;
-+
-+ ret = btrfs_alloc_from_inode_stripe_run(block_group,
-+ btrfs_ino(log_inode), ffe_ctl->num_bytes,
-+ &offset, &available);
-+ if (ret == -ENOMEM)
-+ return ret;
-+ if (!ret) {
-+ WRITE_ONCE(log_inode->log_run_hint, offset);
-+ ffe_ctl->found_offset = offset;
-+ ffe_ctl->search_start = offset;
-+ return 0;
-+ }
-+ if (available > ffe_ctl->max_extent_size)
-+ ffe_ctl->max_extent_size = available;
-+ }
-+
- ret = btrfs_alloc_from_open_stripe(block_group, ffe_ctl->num_bytes,
- class, &offset, &available);
- if (ret == -ENOMEM)
-@@ -4965,8 +4990,8 @@ static noinline int find_free_extent(struct btrfs_root *root,
- * case -ENOSPC is returned then @ins->offset will contain the size of the
- * largest available hole the allocator managed to find.
- */
--int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
-- u64 num_bytes, u64 min_alloc_size,
-+int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
-+ u64 ram_bytes, u64 num_bytes, u64 min_alloc_size,
- u64 empty_size, u64 hint_byte,
- struct btrfs_key *ins, bool is_data, bool delalloc)
- {
-@@ -4977,6 +5002,23 @@ int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
- int ret;
- bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
- bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
-+ struct btrfs_inode *for_log_inode = NULL;
-+
-+ /*
-+ * Steer a log-active inode's datacow data into its private LOG-class
-+ * stripe run, seeded with the run's location as the search hint; see
-+ * BTRFS_INODE_LOG_ALLOC. Purely placement: any allocation that
-+ * cannot be served from a private run falls back to the shared runs.
-+ */
-+ if (inode && is_data && !for_data_reloc &&
-+ btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
-+ test_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags)) {
-+ u64 log_hint = READ_ONCE(inode->log_run_hint);
-+
-+ for_log_inode = inode;
-+ if (log_hint)
-+ hint_byte = log_hint;
-+ }
-
- flags = get_alloc_profile_by_root(root, is_data);
- again:
-@@ -4991,6 +5033,7 @@ int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
- ffe_ctl.hint_byte = hint_byte;
- ffe_ctl.for_treelog = for_treelog;
- ffe_ctl.for_data_reloc = for_data_reloc;
-+ ffe_ctl.for_log_inode = for_log_inode;
-
- ret = find_free_extent(root, ins, &ffe_ctl);
- if (!ret && !is_data) {
-@@ -5494,7 +5537,7 @@ struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
- if (IS_ERR(block_rsv))
- return ERR_CAST(block_rsv);
-
-- ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
-+ ret = btrfs_reserve_extent(root, NULL, blocksize, blocksize, blocksize,
- empty_size, hint, &ins, false, false);
- if (ret)
- goto out_unuse;
-diff --git a/fs/btrfs/extent-tree.h b/fs/btrfs/extent-tree.h
-index bc847c03470ed..a75eb49437030 100644
---- a/fs/btrfs/extent-tree.h
-+++ b/fs/btrfs/extent-tree.h
-@@ -49,6 +49,12 @@ struct find_free_extent_ctl {
- /* Allocation is called for data relocation */
- bool for_data_reloc;
-
-+ /*
-+ * Data allocation for a log-active inode under stripe-exclusive
-+ * allocation: steer it into the inode's private LOG-class stripe run.
-+ */
-+ struct btrfs_inode *for_log_inode;
-+
- /*
- * Set to true if we're retrying the allocation on this block group
- * after waiting for caching progress, this is so that we retry only
-@@ -135,7 +141,8 @@ int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
- int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
- u64 root_objectid, u64 owner, u64 offset,
- struct btrfs_key *ins);
--int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes, u64 num_bytes,
-+int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
-+ u64 ram_bytes, u64 num_bytes,
- u64 min_alloc_size, u64 empty_size, u64 hint_byte,
- struct btrfs_key *ins, bool is_data, bool delalloc);
- int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
-diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
-index f978c6524aa03..73cec267971ff 100644
---- a/fs/btrfs/file.c
-+++ b/fs/btrfs/file.c
-@@ -1544,6 +1544,17 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
-
- trace_btrfs_sync_file_enter(file, datasync);
-
-+ /*
-+ * Under stripe-exclusive allocation, mark the inode log-active before
-+ * this fsync flushes its delalloc, so that even the first fsync's
-+ * allocations are steered into the inode's own LOG-class stripe run
-+ * (see BTRFS_INODE_LOG_ALLOC). Sticky while the inode stays cached:
-+ * one fsync is taken as a signal that more will follow.
-+ */
-+ if (btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
-+ !test_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags))
-+ set_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags);
-+
- btrfs_init_log_ctx(&ctx, inode);
-
- /*
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index b69cc44f58d70..faa45e7231e79 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -1070,7 +1070,7 @@ static void submit_one_async_extent(struct async_chunk *async_chunk,
- }
-
- compressed_size = async_extent->cb->bbio.bio.bi_iter.bi_size;
-- ret = btrfs_reserve_extent(root, async_extent->ram_size,
-+ ret = btrfs_reserve_extent(root, inode, async_extent->ram_size,
- compressed_size, compressed_size,
- 0, *alloc_hint, &ins, true, true);
- if (ret) {
-@@ -1216,8 +1216,9 @@ static int cow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
- u64 cur_end;
- int ret;
-
-- ret = btrfs_reserve_extent(root, num_bytes, num_bytes, min_alloc_size,
-- 0, alloc_hint, ins, true, true);
-+ ret = btrfs_reserve_extent(root, inode, num_bytes, num_bytes,
-+ min_alloc_size, 0, alloc_hint, ins, true,
-+ true);
- if (ret < 0) {
- *ret_alloc_size = cur_len;
- return ret;
-@@ -8094,6 +8095,7 @@ struct inode *btrfs_alloc_inode(struct super_block *sb)
- ei->last_unlink_trans = 0;
- ei->last_reflink_trans = 0;
- ei->last_log_commit = 0;
-+ ei->log_run_hint = 0;
-
- spin_lock_init(&ei->lock);
- ei->outstanding_extents = 0;
-@@ -9255,7 +9257,7 @@ int btrfs_prealloc_file_range(struct inode *inode, int mode,
- * sized chunks.
- */
- cur_bytes = min(cur_bytes, last_alloc);
-- ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
-+ ret = btrfs_reserve_extent(root, NULL, cur_bytes, cur_bytes,
- min_size, 0, *alloc_hint, &ins, true, false);
- if (ret)
- break;
-@@ -10092,7 +10094,7 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
- }
- }
-
-- ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
-+ ret = btrfs_reserve_extent(root, inode, disk_num_bytes, disk_num_bytes,
- disk_num_bytes, 0, 0, &ins, true, true);
- if (ret)
- goto out_delalloc_release;
-diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
-index b810115db9603..a41f57559ee74 100644
---- a/fs/btrfs/relocation.c
-+++ b/fs/btrfs/relocation.c
-@@ -4285,8 +4285,8 @@ static int move_existing_remap(struct btrfs_fs_info *fs_info,
- else
- min_size = fs_info->nodesize;
-
-- ret = btrfs_reserve_extent(fs_info->fs_root, length, length, min_size,
-- 0, 0, &ins, is_data, false);
-+ ret = btrfs_reserve_extent(fs_info->fs_root, NULL, length, length,
-+ min_size, 0, 0, &ins, is_data, false);
- if (unlikely(ret)) {
- spin_lock(&sinfo->lock);
- btrfs_space_info_update_bytes_may_use(sinfo, -length);
-@@ -5114,8 +5114,8 @@ static int do_remap_reloc_trans(struct btrfs_fs_info *fs_info,
- * of the identity remap that we're processing, and will tackle the
- * rest of it the next time round.
- */
-- ret = btrfs_reserve_extent(fs_info->fs_root, remap_length, remap_length,
-- min_size, 0, 0, &ins, is_data, false);
-+ ret = btrfs_reserve_extent(fs_info->fs_root, NULL, remap_length,
-+ remap_length, min_size, 0, 0, &ins, is_data, false);
- if (ret) {
- spin_lock(&sinfo->lock);
- btrfs_space_info_update_bytes_may_use(sinfo, -remap_length);
---
-2.47.3
-
+++ /dev/null
-From 4a26f6f8349a32272a71baa5f307b73e65e7998b Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:37 -0400
-Subject: [RFC PATCH 015/116] btrfs: stripe_alloc: carry an inode's log tail
- forward at fsync
-To: linux-btrfs@vger.kernel.org
-
-Closing a log-active inode's private stripe run at each log commit
-traps the run's final partial stripe tail every time the inode fsyncs:
-a steady fsync stream burns one stripe per log commit until the stripes
-free or balance runs.
-
-Reclaim the tails by carrying the partial stripe's live data forward.
-At each log commit, the settling walk now computes the closed run's
-final partial stripe, and the logging paths record the file ranges of
-the logged extents that live inside it on a small per-inode table
-(bounded; overflow just means an extent is not carried). At the
-inode's next fsync, before its delalloc flush, each recorded range that
-still maps to the recorded disk bytenr is re-dirtied, defrag style
-(reserve, reset delalloc state, mark the folios dirty; absent folios
-are read back, which is a plain read of settled data). The flush then
-COWs the carried ranges together with the new data into the inode's
-current private run, and the old partial stripe empties and frees
-whole.
-
-Everything downstream is the ordinary COW pipeline: new extent maps,
-ordered extents, checksums, file extent items and delayed refs, and
-the log's modified-extents snapshot -- taken inside btrfs_log_inode
-after the flush -- picks up the new addresses by itself. Reflinked
-ranges need no special handling: foreign referents keep the old extent
-alive in its closed (never again written) stripe, and only the space
-reclaim degrades. A range that was rewritten, truncated, punched or
-compressed simply fails the mapping check and stays put.
-
-Crash safety does not regress. A carried extent's old copy is dropped
-through the normal paths: if it was committed, the free pins until the
-transaction commits; if it was logged but never committed, its ADD and
-DROP delayed refs cancel in cleanup_ref_head(), which also pins
-must_insert_reserved heads -- either way the old blocks cannot be
-reallocated before the log that references them is superseded.
-
-The settling walk also learned to report the partial stripe through a
-widened btrfs_log_settle_stripes() signature (inode and file range
-instead of fs_info); compressed extents pass a zero file length to opt
-out of carrying while still settling.
-
-The re-dirty reserves with NO_FLUSH. carry_one_range() takes the folio
-locks and the extent range lock before reserving, and a flushing
-(ticketed) reservation can sleep in wait_reserve_ticket() until the
-flusher makes progress -- but every way forward needs the locks we
-hold: FLUSH_DELALLOC has to write back the carried range, which blocks
-in __folio_lock() on our locked folio, and a transaction commit (with
-flushoncommit) waits for the same writeback. The whole filesystem then
-wedges behind the stuck commit. Carrying is best effort by design and
-the carried range's data is already durable in its old stripe, so on
-ENOSPC just skip the carry and let the old stripe free the slow way.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 85 ++++++++++++++++++++++-
- fs/btrfs/block-group.h | 4 +-
- fs/btrfs/btrfs_inode.h | 35 ++++++++++
- fs/btrfs/defrag.c | 151 +++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/defrag.h | 1 +
- fs/btrfs/file.c | 10 +++
- fs/btrfs/inode.c | 3 +
- fs/btrfs/tree-log.c | 15 ++--
- 8 files changed, 295 insertions(+), 9 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 25cb8dac15a9e..be8aa2fc103f8 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -937,6 +937,63 @@ static bool stripe_log_range_settled(struct btrfs_block_group *bg, u64 bytenr)
- return settled;
- }
-
-+/*
-+ * Remember, on the logging inode, a logged extent that lives in the final
-+ * partial stripe of one of the inode's recently closed runs, so that the
-+ * next fsync can re-dirty its file range and carry the data forward into
-+ * the then-current run -- letting the old partial stripe free whole. A
-+ * zero @file_len means the caller does not want this extent carried
-+ * (e.g. compressed extents, which would recompress). @ps_len is nonzero
-+ * when the settling walk could see the run and computed its final partial
-+ * stripe. Every table here is small and bounded; on overflow the extent
-+ * simply is not carried and its stripe frees the slow way. Caller holds
-+ * the inode's log_mutex, which serializes against the fsync-entry consumer.
-+ */
-+static void log_carry_record(struct btrfs_inode *inode, u64 file_start,
-+ u64 file_len, u64 bytenr, u64 num_bytes,
-+ u64 ps_start, u64 ps_len)
-+{
-+ struct btrfs_log_carry *carry = inode->log_carry;
-+ int n, i;
-+
-+ if (!carry) {
-+ carry = kzalloc(sizeof(*carry), GFP_NOFS);
-+ if (!carry)
-+ return;
-+ inode->log_carry = carry;
-+ }
-+ if (ps_len) {
-+ n = min_t(int, carry->nr_ps, BTRFS_LOG_CARRY_NR_PS);
-+ for (i = 0; i < n; i++)
-+ if (carry->ps_start[i] == ps_start)
-+ break;
-+ if (i == n) {
-+ int slot = carry->nr_ps % BTRFS_LOG_CARRY_NR_PS;
-+
-+ carry->ps_start[slot] = ps_start;
-+ carry->ps_len[slot] = ps_len;
-+ carry->nr_ps++;
-+ }
-+ }
-+ if (!file_len || carry->nr_ranges >= BTRFS_LOG_CARRY_NR_RANGES)
-+ return;
-+ n = min_t(int, carry->nr_ps, BTRFS_LOG_CARRY_NR_PS);
-+ for (i = 0; i < n; i++)
-+ if (bytenr < carry->ps_start[i] + carry->ps_len[i] &&
-+ bytenr + num_bytes > carry->ps_start[i])
-+ break;
-+ if (i == n)
-+ return;
-+ for (i = 0; i < carry->nr_ranges; i++)
-+ if (carry->range[i].start == file_start &&
-+ carry->range[i].len == file_len)
-+ return;
-+ carry->range[carry->nr_ranges].start = file_start;
-+ carry->range[carry->nr_ranges].len = file_len;
-+ carry->range[carry->nr_ranges].disk_bytenr = bytenr;
-+ carry->nr_ranges++;
-+}
-+
- /*
- * A log commit is about to make the extent at [bytenr, bytenr + num_bytes)
- * durable. Once the log super lands, no later write may extend or RMW the
-@@ -951,10 +1008,15 @@ static bool stripe_log_range_settled(struct btrfs_block_group *bg, u64 bytenr)
- * the wait is bio flight time plus the parked-write deadline that the flush
- * below short-circuits. It is a pure data-IO wait (no transaction joins),
- * safe under the inode log mutex and a running transaction handle.
-+ *
-+ * [file_start, file_start + file_len) is the extent's file range, recorded
-+ * for carry-forward when the extent sits in the run's final partial stripe;
-+ * file_len == 0 opts the extent out of carrying (settling still happens).
- */
--void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
-- u64 num_bytes)
-+void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
-+ u64 file_len, u64 bytenr, u64 num_bytes)
- {
-+ struct btrfs_fs_info *fs_info = inode->root->fs_info;
- struct btrfs_block_group *bg;
- struct btrfs_open_stripe_run *run;
- unsigned long flags;
-@@ -962,6 +1024,8 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
- u64 tail_len = 0;
- u64 flush_start = 0;
- u64 flush_len = 0;
-+ u64 ps_start = 0;
-+ u64 ps_len = 0;
-
- if (list_empty_careful(&fs_info->open_stripe_bgs))
- return;
-@@ -971,10 +1035,24 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ u64 filled;
-+
- if (bytenr < run->start || bytenr >= run->offset)
- continue;
- flush_start = run->start;
- flush_len = run->end - run->start;
-+ /*
-+ * The run's final partial stripe, whether this call closes
-+ * the run or an earlier settle already did (offset froze at
-+ * close). Runs start stripe-aligned, so alignment relative
-+ * to run->start is stripe alignment.
-+ */
-+ filled = run->offset - run->start;
-+ if (!IS_ALIGNED(filled, bg->full_stripe_len)) {
-+ ps_start = run->start +
-+ round_down(filled, bg->full_stripe_len);
-+ ps_len = bg->full_stripe_len;
-+ }
- if (run->open) {
- int class;
- int band;
-@@ -989,6 +1067,9 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-
-+ log_carry_record(inode, file_start, file_len, bytenr, num_bytes,
-+ ps_start, ps_len);
-+
- if (tail_len)
- btrfs_add_free_space(bg, tail_start, tail_len);
- if (flush_len) {
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 15cb94eeaab0c..0edfafab20eb4 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -415,8 +415,8 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
- bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- u64 run_start, u64 *run_len);
--void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
-- u64 num_bytes);
-+void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
-+ u64 file_len, u64 bytenr, u64 num_bytes);
- int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
- int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
- void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
-diff --git a/fs/btrfs/btrfs_inode.h b/fs/btrfs/btrfs_inode.h
-index 979adcdbe32e3..00fd4e6e668d6 100644
---- a/fs/btrfs/btrfs_inode.h
-+++ b/fs/btrfs/btrfs_inode.h
-@@ -142,6 +142,30 @@ enum {
- };
-
- /* in memory btrfs inode */
-+/*
-+ * Carry-forward bookkeeping for a log-active inode under stripe-exclusive
-+ * allocation. ps_start/ps_len remember the final partial stripes of the
-+ * inode's recently closed private runs (a small ring; older entries are
-+ * overwritten). range[] records the file ranges of logged extents living
-+ * in those partial stripes, for the next fsync to re-dirty; disk_bytenr
-+ * lets the consumer verify the range still maps there before carrying.
-+ * Bounded loss: when the ring or the range table overflows, the extra
-+ * extents simply stay put and their stripes free the slow way.
-+ */
-+#define BTRFS_LOG_CARRY_NR_PS 4
-+#define BTRFS_LOG_CARRY_NR_RANGES 48
-+struct btrfs_log_carry {
-+ int nr_ps;
-+ u64 ps_start[BTRFS_LOG_CARRY_NR_PS];
-+ u64 ps_len[BTRFS_LOG_CARRY_NR_PS];
-+ int nr_ranges;
-+ struct {
-+ u64 start;
-+ u64 len;
-+ u64 disk_bytenr;
-+ } range[BTRFS_LOG_CARRY_NR_RANGES];
-+};
-+
- struct btrfs_inode {
- /* which subvolume this inode belongs to */
- struct btrfs_root *root;
-@@ -330,6 +354,17 @@ struct btrfs_inode {
- u64 ref_root_id;
- };
-
-+ /*
-+ * Carry-forward state for a log-active inode (see
-+ * BTRFS_INODE_LOG_ALLOC): the file ranges of this inode's extents
-+ * that were left in the final partial stripe of a private stripe run
-+ * closed at a log commit. The next fsync re-dirties them so they
-+ * COW forward into the current run, letting the old partial stripe
-+ * free whole. Lazily allocated; both recording (during logging) and
-+ * consuming (at fsync entry) run under log_mutex.
-+ */
-+ struct btrfs_log_carry *log_carry;
-+
- /*
- * Start of the last extent allocated from this inode's private
- * LOG-class stripe run (see BTRFS_INODE_LOG_ALLOC). Advisory only:
-diff --git a/fs/btrfs/defrag.c b/fs/btrfs/defrag.c
-index cbc532b49c67d..d383a5abe7e2b 100644
---- a/fs/btrfs/defrag.c
-+++ b/fs/btrfs/defrag.c
-@@ -1263,6 +1263,157 @@ static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
- return ret;
- }
-
-+/*
-+ * Carry-forward for log-active inodes under stripe-exclusive allocation
-+ * (see struct btrfs_log_carry). Re-dirty a file range recorded at the
-+ * last log commit so the coming writeback COWs it into the inode's
-+ * current private stripe run and the old partial stripe can free whole.
-+ * The range is carried only while it still fully maps to the recorded
-+ * disk bytenr; a range that was rewritten, truncated, hole-punched or
-+ * already carried fails that check and is skipped -- skipping only costs
-+ * the space optimization, never correctness. Modeled on
-+ * defrag_one_range().
-+ */
-+static int carry_one_range(struct btrfs_inode *inode, u64 start, u64 len,
-+ u64 disk_bytenr)
-+{
-+ struct btrfs_fs_info *fs_info = inode->root->fs_info;
-+ struct extent_changeset *data_reserved = NULL;
-+ struct extent_state *cached_state = NULL;
-+ struct extent_map *em;
-+ struct folio **folios;
-+ const unsigned int nr_pages = ((start + len - 1) >> PAGE_SHIFT) -
-+ (start >> PAGE_SHIFT) + 1;
-+ u64 cur;
-+ int ret = 0;
-+
-+ ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
-+ IS_ALIGNED(len, fs_info->sectorsize));
-+
-+ folios = kzalloc_objs(struct folio *, nr_pages, GFP_NOFS);
-+ if (!folios)
-+ return -ENOMEM;
-+
-+ cur = start;
-+ for (int i = 0; cur < start + len && i < nr_pages; i++) {
-+ folios[i] = defrag_prepare_one_folio(inode, cur >> PAGE_SHIFT);
-+ if (IS_ERR(folios[i])) {
-+ ret = PTR_ERR(folios[i]);
-+ folios[i] = NULL;
-+ goto free_folios;
-+ }
-+ cur = folio_next_pos(folios[i]);
-+ }
-+ for (int i = 0; i < nr_pages && folios[i]; i++)
-+ folio_wait_writeback(folios[i]);
-+
-+ ASSERT(folios[0]);
-+ btrfs_lock_extent(&inode->io_tree, folio_pos(folios[0]), cur - 1,
-+ &cached_state);
-+ /* Still fully mapped to the recorded location? */
-+ em = btrfs_get_extent(inode, NULL, start, len);
-+ if (IS_ERR(em)) {
-+ ret = PTR_ERR(em);
-+ goto unlock_extent;
-+ }
-+ if (em->disk_bytenr >= EXTENT_MAP_LAST_BYTE ||
-+ (em->flags & EXTENT_FLAG_PREALLOC) ||
-+ btrfs_extent_map_compression(em) != BTRFS_COMPRESS_NONE ||
-+ em->start > start ||
-+ em->start + em->len < start + len ||
-+ btrfs_extent_map_block_start(em) + (start - em->start) !=
-+ disk_bytenr) {
-+ btrfs_free_extent_map(em);
-+ goto unlock_extent;
-+ }
-+ btrfs_free_extent_map(em);
-+
-+ /*
-+ * We hold the folio locks and the extent lock, so a flushing
-+ * (ticketed) reservation can deadlock: satisfying the ticket needs
-+ * delalloc writeback -- or a transaction commit, which with
-+ * flushoncommit waits for that writeback -- and writeback of this
-+ * range blocks in __folio_lock on the folios held here. Reserve
-+ * with NO_FLUSH; carrying is optional, so on ENOSPC the tail just
-+ * stays in its old stripe (see btrfs_carry_log_tail).
-+ */
-+ ret = btrfs_check_data_free_space(inode, &data_reserved, start, len,
-+ true);
-+ if (ret < 0)
-+ goto unlock_extent;
-+ ret = btrfs_delalloc_reserve_metadata(inode, len, len, true);
-+ if (ret < 0) {
-+ btrfs_free_reserved_data_space(inode, data_reserved, start,
-+ len);
-+ extent_changeset_free(data_reserved);
-+ goto unlock_extent;
-+ }
-+ btrfs_clear_extent_bit(&inode->io_tree, start, start + len - 1,
-+ EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
-+ EXTENT_DEFRAG, &cached_state);
-+ btrfs_set_extent_bit(&inode->io_tree, start, start + len - 1,
-+ EXTENT_DELALLOC, &cached_state);
-+ for (int i = 0; i < nr_pages && folios[i]; i++) {
-+ struct folio *folio = folios[i];
-+
-+ if (start >= folio_next_pos(folio) ||
-+ start + len <= folio_pos(folio))
-+ continue;
-+ btrfs_folio_clamp_set_dirty(fs_info, folio, start, len);
-+ }
-+ btrfs_delalloc_release_extents(inode, len);
-+ extent_changeset_free(data_reserved);
-+unlock_extent:
-+ btrfs_unlock_extent(&inode->io_tree, folio_pos(folios[0]), cur - 1,
-+ &cached_state);
-+free_folios:
-+ for (int i = 0; i < nr_pages; i++) {
-+ if (!folios[i])
-+ break;
-+ folio_unlock(folios[i]);
-+ folio_put(folios[i]);
-+ }
-+ kfree(folios);
-+ return ret;
-+}
-+
-+/*
-+ * Consume the inode's carry table (see struct btrfs_log_carry): re-dirty
-+ * every recorded range so the caller's upcoming writeback carries them
-+ * into the inode's current private stripe run. Called at fsync entry
-+ * with the inode locked; takes log_mutex only to detach the table, so
-+ * the logging side never records into a half-consumed list. All
-+ * failures are soft: an uncarried range just leaves its old stripe to
-+ * free the slow way.
-+ */
-+void btrfs_carry_log_tail(struct btrfs_inode *inode)
-+{
-+ struct btrfs_log_carry *copy;
-+
-+ if (!btrfs_test_opt(inode->root->fs_info, STRIPE_ALLOC))
-+ return;
-+ if (!READ_ONCE(inode->log_carry))
-+ return;
-+ copy = kmalloc(sizeof(*copy), GFP_NOFS);
-+ if (!copy)
-+ return;
-+ mutex_lock(&inode->log_mutex);
-+ if (!inode->log_carry || !inode->log_carry->nr_ranges) {
-+ mutex_unlock(&inode->log_mutex);
-+ kfree(copy);
-+ return;
-+ }
-+ memcpy(copy, inode->log_carry, sizeof(*copy));
-+ inode->log_carry->nr_ranges = 0;
-+ mutex_unlock(&inode->log_mutex);
-+
-+ for (int i = 0; i < copy->nr_ranges; i++)
-+ carry_one_range(inode, copy->range[i].start,
-+ copy->range[i].len,
-+ copy->range[i].disk_bytenr);
-+ kfree(copy);
-+}
-+
- static int defrag_one_cluster(struct btrfs_inode *inode,
- struct file_ra_state *ra,
- u64 start, u32 len, u32 extent_thresh,
-diff --git a/fs/btrfs/defrag.h b/fs/btrfs/defrag.h
-index a7f917a38dbfb..0b2a124151893 100644
---- a/fs/btrfs/defrag.h
-+++ b/fs/btrfs/defrag.h
-@@ -16,6 +16,7 @@ struct btrfs_ioctl_defrag_range_args;
- int btrfs_defrag_file(struct btrfs_inode *inode, struct file_ra_state *ra,
- struct btrfs_ioctl_defrag_range_args *range,
- u64 newer_than, unsigned long max_to_defrag);
-+void btrfs_carry_log_tail(struct btrfs_inode *inode);
- int __init btrfs_auto_defrag_init(void);
- void __cold btrfs_auto_defrag_exit(void);
- void btrfs_add_inode_defrag(struct btrfs_inode *inode, u32 extent_thresh);
-diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
-index 73cec267971ff..d927b559aa327 100644
---- a/fs/btrfs/file.c
-+++ b/fs/btrfs/file.c
-@@ -35,6 +35,7 @@
- #include "extent-tree.h"
- #include "file-item.h"
- #include "ioctl.h"
-+#include "defrag.h"
- #include "file.h"
- #include "super.h"
- #include "print-tree.h"
-@@ -1584,6 +1585,15 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
- else
- btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
-
-+ /*
-+ * Re-dirty the tail ranges recorded at the last log commit so the
-+ * writeback below carries them into the inode's current private
-+ * stripe run, letting the old partial stripe free whole (see
-+ * struct btrfs_log_carry). Purely a space optimization: a range
-+ * that cannot be carried is simply skipped.
-+ */
-+ btrfs_carry_log_tail(inode);
-+
- /*
- * Before we acquired the inode's lock and the mmap lock, someone may
- * have dirtied more pages in the target range. We need to make sure
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index faa45e7231e79..afe0cc331deb8 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -8096,6 +8096,7 @@ struct inode *btrfs_alloc_inode(struct super_block *sb)
- ei->last_reflink_trans = 0;
- ei->last_log_commit = 0;
- ei->log_run_hint = 0;
-+ ei->log_carry = NULL;
-
- spin_lock_init(&ei->lock);
- ei->outstanding_extents = 0;
-@@ -8135,6 +8136,7 @@ struct inode *btrfs_alloc_inode(struct super_block *sb)
- void btrfs_test_destroy_inode(struct inode *inode)
- {
- btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
-+ kfree(BTRFS_I(inode)->log_carry);
- kfree(BTRFS_I(inode)->file_extent_tree);
- kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
- }
-@@ -8142,6 +8144,7 @@ void btrfs_test_destroy_inode(struct inode *inode)
-
- void btrfs_free_inode(struct inode *inode)
- {
-+ kfree(BTRFS_I(inode)->log_carry);
- kfree(BTRFS_I(inode)->file_extent_tree);
- kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
- }
-diff --git a/fs/btrfs/tree-log.c b/fs/btrfs/tree-log.c
-index 6aa8db5b1044e..d902d169680a4 100644
---- a/fs/btrfs/tree-log.c
-+++ b/fs/btrfs/tree-log.c
-@@ -4887,9 +4887,12 @@ static noinline int copy_items(struct btrfs_trans_handle *trans,
- disk_num_bytes =
- btrfs_file_extent_disk_num_bytes(src, extent);
- if (disk_bytenr)
-- btrfs_log_settle_stripes(trans->fs_info,
-- disk_bytenr,
-- disk_num_bytes);
-+ btrfs_log_settle_stripes(inode,
-+ ins_keys[dst_index].offset,
-+ btrfs_file_extent_compression(src, extent) ?
-+ 0 :
-+ btrfs_file_extent_num_bytes(src, extent),
-+ disk_bytenr, disk_num_bytes);
- }
-
- if (skip_csum)
-@@ -5189,8 +5192,10 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
- */
- if (!(em->flags & EXTENT_FLAG_PREALLOC) &&
- em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
-- btrfs_log_settle_stripes(inode->root->fs_info, em->disk_bytenr,
-- em->disk_num_bytes);
-+ btrfs_log_settle_stripes(inode, em->start,
-+ compress_type == BTRFS_COMPRESS_NONE ?
-+ em->len : 0,
-+ em->disk_bytenr, em->disk_num_bytes);
-
- if (compress_type != BTRFS_COMPRESS_NONE) {
- btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start);
---
-2.47.3
-
--- /dev/null
+From 406db25e00c5ace70157c961876b333ff0ff9752 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:46 -0400
+Subject: [RFC PATCH 15/85] btrfs: stripe_alloc: pessimistic data reservation
+ margin
+To: linux-btrfs@vger.kernel.org
+
+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).
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 6 ++++
+ fs/btrfs/btrfs_inode.h | 3 ++
+ fs/btrfs/delalloc-space.c | 45 ++++++++++++++++++++++--
+ fs/btrfs/delalloc-space.h | 3 +-
+ fs/btrfs/direct-io.c | 9 ++++-
+ fs/btrfs/extent-tree.c | 68 ++++++++++++++++++++++++++++++++++++-
+ fs/btrfs/extent-tree.h | 8 +++++
+ fs/btrfs/file.c | 9 +++--
+ fs/btrfs/free-space-cache.c | 38 +++++++++++++++++++++
+ fs/btrfs/fs.h | 8 +++++
+ fs/btrfs/inode.c | 4 ++-
+ fs/btrfs/space-info.c | 66 +++++++++++++++++++++++++++++++++--
+ fs/btrfs/space-info.h | 14 ++++++++
+ fs/btrfs/sysfs.c | 4 +++
+ 14 files changed, 274 insertions(+), 11 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index d5a1f6f2070b2..4aa943fc23100 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1476,6 +1476,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);
+ }
+ }
+diff --git a/fs/btrfs/btrfs_inode.h b/fs/btrfs/btrfs_inode.h
+index a3aab18d60337..663e925b14300 100644
+--- a/fs/btrfs/btrfs_inode.h
++++ b/fs/btrfs/btrfs_inode.h
+@@ -423,6 +423,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)
+ {
+@@ -430,6 +432,7 @@ static inline void btrfs_mod_outstanding_extents(struct btrfs_inode *inode,
+ inode->outstanding_extents += mod;
+ trace_btrfs_inode_mod_outstanding_extents(inode->root, btrfs_ino(inode),
+ mod, inode->outstanding_extents);
++ btrfs_stripe_margin_mod(inode, mod);
+ }
+
+ /*
+diff --git a/fs/btrfs/delalloc-space.c b/fs/btrfs/delalloc-space.c
+index 77781852e4178..a68847832a5fc 100644
+--- a/fs/btrfs/delalloc-space.c
++++ b/fs/btrfs/delalloc-space.c
+@@ -140,10 +140,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 */
+@@ -154,13 +155,42 @@ int btrfs_check_data_free_space(struct btrfs_inode *inode,
+ if (noflush)
+ flush = BTRFS_RESERVE_NO_FLUSH;
+
+- 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;
+@@ -170,6 +200,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.
+@@ -493,12 +530,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);
+diff --git a/fs/btrfs/delalloc-space.h b/fs/btrfs/delalloc-space.h
+index 6119c0d3f883c..c464cf0a88d9b 100644
+--- a/fs/btrfs/delalloc-space.h
++++ b/fs/btrfs/delalloc-space.h
+@@ -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,
+diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c
+index 8bdfae5ebe694..65c82476c53f4 100644
+--- a/fs/btrfs/direct-io.c
++++ b/fs/btrfs/direct-io.c
+@@ -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 @@ static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
+ 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,
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index dea9af5b7845a..7e1750dcd9f5c 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4207,6 +4207,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)
+@@ -4214,6 +4252,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;
+@@ -4256,6 +4295,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;
+
+@@ -4265,6 +4305,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;
+@@ -4274,7 +4315,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;
+@@ -4286,6 +4327,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;
+@@ -5014,6 +5056,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);
+@@ -5050,6 +5093,7 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ 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) {
+@@ -5063,6 +5107,18 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ 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;
+@@ -5074,6 +5130,16 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ 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;
+diff --git a/fs/btrfs/extent-tree.h b/fs/btrfs/extent-tree.h
+index a75eb49437030..45a4a7e38d810 100644
+--- a/fs/btrfs/extent-tree.h
++++ b/fs/btrfs/extent-tree.h
+@@ -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;
+
+diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
+index 89d71cec371d6..4d1cedc3ecb7c 100644
+--- a/fs/btrfs/file.c
++++ b/fs/btrfs/file.c
+@@ -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,
+@@ -1854,6 +1857,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;
+@@ -1882,7 +1886,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;
+
+@@ -1902,6 +1906,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,
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 391a50a4dd0b7..d6102dba8acf1 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1493,6 +1493,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)
+ {
+@@ -1509,6 +1546,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);
+ }
+
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index d0198cfe1c850..6c82782a8a7f5 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -916,6 +916,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;
+diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
+index 3190191b41d6d..d27cc1155adf9 100644
+--- a/fs/btrfs/inode.c
++++ b/fs/btrfs/inode.c
+@@ -5099,6 +5099,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);
+@@ -5151,7 +5152,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;
+
+@@ -5165,6 +5166,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,
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index d5a84fa97462c..5e7ee4321e8c2 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -16,6 +16,7 @@
+ #include "extent-tree.h"
+ #include "zoned.h"
+ #include "delayed-inode.h"
++#include "btrfs_inode.h"
+
+ /*
+ * HOW DOES SPACE RESERVATION WORK
+@@ -386,6 +387,18 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
+
+ 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) ||
+@@ -409,6 +422,53 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
+ 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)
+ {
+@@ -652,10 +712,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,
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index 83b56c20d5250..b53458d573aec 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -164,6 +164,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
+@@ -324,10 +334,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_block_group *block_group);
+ void btrfs_update_space_info_chunk_size(struct btrfs_space_info *space_info,
+ u64 chunk_size);
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 6d21fd7963115..7957754d80852 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -817,6 +817,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);
+@@ -947,6 +949,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),
+--
+2.47.3
+
--- /dev/null
+From c53ebde40f2c1d2e7ff3320305c45c77e825b408 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:47 -0400
+Subject: [RFC PATCH 16/85] btrfs: stripe_alloc: claim fully-free stripes that
+ span free space entries
+To: linux-btrfs@vger.kernel.org
+
+The claim fast path searches single entries, so a fully-free full
+stripe whose free space spans an entry boundary -- an extent entry
+adjoining a bitmap, or two neighbouring bitmap windows -- was
+unclaimable. stripe_unusable accounting is entry-blind and counts
+exactly those stripes as claimable, so admission reserves data against
+them; at writeback the claim finds nothing, cow_file_range() gets
+-ENOSPC, and the already-dirtied pages are dropped. full_stripe_len
+is not a power of two, so stripe boundaries drift through the fixed
+128M bitmap windows and a straddling stripe is a certainty near full,
+not a corner case.
+
+Observed live at the raid6 fill edge (rolling-failure, then isolated
+by fill-edge-debug with enospc_debug): two 384K stripes, each
+straddling a bitmap window boundary, held the space_info accounting
+786432 bytes above what the claim could reach, and every writeback
+allocation against that phantom margin failed -ENOSPC while ~991MB of
+genuinely trapped free space sat in the cache. The reservation margin
+cannot absorb this: the gap is per straddling stripe, not per
+outstanding extent.
+
+Add an entry-blind slow path: one offset-ordered walk accumulating
+contiguous free coverage across entry boundaries, and a piecewise
+removal that runs in the same tree_lock critical section as the find,
+so a racing claimer cannot see a half-removed run. The fast path is
+unchanged and still serves the common case; the slow path runs only
+after it fails, which is the near-full case where a stranded stripe
+matters most.
+
+A bitmap piece of a split run is taken only to the end of the set bits
+that start at it, so that an extent entry starting inside the same bitmap
+window is found and removed as the next piece. A self-test covers that
+layout.
+
+On a large aged filesystem (85 TiB, mostly legacy data, heavily fragmented
+free space) the slow path walked the whole group for every small
+allocation and found nothing, at 100% CPU in the delalloc workers. So a
+failed exhaustive scan is remembered: bg->max_claimable_run is an upper
+bound learned from the scans ((u64)-1 unknown, 0 after a scan proved no
+claimable run), claims fail in O(1) while it is below one full stripe or
+the group's free space is, and adding free space (frees, unpins, stripe
+run returns, and a cluster returning its entries) resets it. It is only
+set and trusted once the group is fully cached, since cache loading links
+entries without the reset.
+
+When a claim splits one extent entry, the entry keeps the tail and the
+head is linked back with a spare entry allocated before ctl->tree_lock is
+taken, so a failed allocation cannot lose it from the cache; without a
+spare it is added after the lock as before.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 1 +
+ fs/btrfs/block-group.h | 12 ++
+ fs/btrfs/free-space-cache.c | 277 ++++++++++++++++++++++++++++--
+ fs/btrfs/tests/free-space-tests.c | 27 +++
+ 4 files changed, 305 insertions(+), 12 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 4aa943fc23100..2745fe155291d 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -3685,6 +3685,7 @@ static struct btrfs_block_group *btrfs_create_block_group(
+
+ cache->fs_info = fs_info;
+ cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
++ cache->max_claimable_run = (u64)-1;
+
+ cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
+
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 883f6c1746862..fa0294ac0cf1a 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -268,6 +268,18 @@ struct btrfs_block_group {
+ * free_space_ctl->tree_lock and space_info->lock.
+ */
+ u64 stripe_unusable;
++ /*
++ * Upper bound on the longest run btrfs_claim_free_stripe_run() can
++ * find, learned from actual scans: (u64)-1 means unknown, 0 means an
++ * exhaustive scan proved there is no claimable run. Claims fail in
++ * O(1) while the bound is below one full stripe; adding free space
++ * resets it to unknown. Unlike stripe_claimable (an accounting
++ * estimate), this caches what the scan itself proved, so it does not
++ * depend on stripe_claimable being exact. Protected by
++ * free_space_ctl->tree_lock; only meaningful once the block group is
++ * fully cached.
++ */
++ u64 max_claimable_run;
+ bool stripe_unusable_ready;
+
+ /*
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index d6102dba8acf1..2a60ab06618c8 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1384,6 +1384,12 @@ static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
+
+ spin_lock(&ctl->tree_lock);
+
++ /*
++ * New free space may merge into a claimable stripe run; forget any
++ * cached "no claimable run" verdict (see btrfs_claim_free_stripe_run()).
++ */
++ block_group->max_claimable_run = (u64)-1;
++
+ if (try_merge_free_space(ctl, info, true))
+ goto link;
+
+@@ -1770,6 +1776,8 @@ static void __btrfs_return_cluster_to_free_space(
+ cluster->block_group = NULL;
+ cluster->window_start = 0;
+ list_del_init(&cluster->block_group_list);
++ /* As for any free space added back; see __btrfs_add_free_space(). */
++ block_group->max_claimable_run = (u64)-1;
+
+ node = rb_first(&cluster->root);
+ while (node) {
+@@ -2216,21 +2224,209 @@ static bool find_stripe_run_in_bitmap(struct btrfs_free_space_ctl *ctl,
+ }
+
+ /*
+- * Claim a contiguous run of fully-free full stripes.
++ * Entry-blind complement to the by-size fast path in
++ * btrfs_claim_free_stripe_run(): walk the aligned stripe grid in
++ * address order, accumulating contiguous free coverage
++ * with point lookups, looking for a run of fully-free full stripes no
++ * single entry contains.
+ *
+- * On success the run is removed from the free space cache and the caller owns
+- * [*start, *start + *len) exclusively until it either allocates from it or
+- * returns the unused remainder with btrfs_add_free_space().
++ * Address order is the point. Walking the entry tree does not visit
++ * free space in address order: a bitmap entry sorts at its window base
++ * while its set-bit runs extend to the window end, so extent entries
++ * inside the window sort after the bitmap but describe lower addresses.
++ * A coverage accumulator fed by an entry walk breaks exactly at the
++ * bitmap window boundary -- which is where the stripes this path exists
++ * to find live.
+ *
+- * want_bytes must be a full_stripe_len multiple and is a maximum; the
+- * smallest successful claim is a single full stripe. A fully-free stripe
+- * split across two free space entries (e.g. an extent entry adjoining a
+- * bitmap) is not found: adjacent extent entries merge on insert, but
+- * extent/bitmap neighbours do not. This errs toward missing a claimable
+- * stripe, never toward claiming a non-free byte.
++ * ctl->tree_lock must be held.
++ */
++static bool find_free_stripe_run_slow(struct btrfs_block_group *block_group,
++ u64 want_bytes, u64 *run_start,
++ u64 *run_len)
++{
++ struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
++ const u32 unit = block_group->fs_info->sectorsize;
++ const u64 fsl = block_group->full_stripe_len;
++ const u64 bg_end = block_group->start + block_group->length;
++ u64 cand = stripe_run_align(block_group, block_group->start);
++
++ lockdep_assert_held(&ctl->tree_lock);
++
++ while (cand + fsl <= bg_end) {
++ u64 covered = 0;
++
++ /* Accumulate contiguous free coverage upward from cand. */
++ while (covered < want_bytes) {
++ const u64 off = cand + covered;
++ struct btrfs_free_space *info;
++ u64 piece = 0;
++
++ if (off >= bg_end)
++ break;
++ info = tree_search_offset(ctl, off, 0, 0);
++ if (info && !info->bitmap) {
++ piece = info->offset + info->bytes - off;
++ } else {
++ info = tree_search_offset(ctl,
++ offset_to_bitmap(ctl, off), 1, 0);
++ if (info) {
++ unsigned long bit =
++ div64_u64(off - info->offset, unit);
++ unsigned long zero;
++
++ if (test_bit(bit, info->bitmap)) {
++ zero = find_next_zero_bit(
++ info->bitmap,
++ BITS_PER_BITMAP,
++ bit);
++ piece = (u64)(zero - bit) * unit;
++ }
++ }
++ }
++ if (!piece)
++ break;
++ covered += piece;
++ }
++
++ while (covered >= fsl) {
++ u64 tlen = min(want_bytes,
++ div64_u64(covered, fsl) * fsl);
++
++ if (btrfs_stripe_run_range_usable(block_group, cand,
++ &tlen)) {
++ *run_start = cand;
++ *run_len = tlen;
++ return true;
++ }
++ /* Overlaps a live run; try the next stripe. */
++ cand += fsl;
++ covered -= fsl;
++ }
++ /*
++ * The byte at cand + covered is not free, so no stripe
++ * containing it can be claimed: restart at the first
++ * stripe boundary past it.
++ */
++ cand = stripe_run_align(block_group, cand + covered + unit);
++ }
++ return false;
++}
++
++/*
++ * Remove the fully-free run [start, start + len) found by
++ * find_free_stripe_run_slow() from the free space cache, piece by piece
++ * across the entries covering it, without ever dropping ctl->tree_lock:
++ * the find and the removal form one critical section, so a racing
++ * claimer can never see (and double-claim) a half-removed run. @spare
++ * is a caller-allocated entry for the at-most-one split of an extent
++ * entry the run is strictly inside of; returns true if it was consumed.
+ *
+- * Returns 0 on success, -ENOSPC if no aligned fully-free stripe is present
+- * in this block group.
++ * ctl->tree_lock must be held.
++ */
++static bool claim_stripe_run_pieces(struct btrfs_block_group *block_group,
++ u64 start, u64 len,
++ struct btrfs_free_space *spare)
++{
++ struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
++ struct btrfs_discard_ctl *discard_ctl =
++ &block_group->fs_info->discard_ctl;
++ const u32 unit = block_group->fs_info->sectorsize;
++ bool spare_used = false;
++ u64 off = start;
++ u64 remaining = len;
++
++ lockdep_assert_held(&ctl->tree_lock);
++
++ while (remaining) {
++ struct btrfs_free_space *info;
++ u64 piece;
++
++ info = tree_search_offset(ctl, off, 0, 0);
++ if (!info)
++ info = tree_search_offset(ctl,
++ offset_to_bitmap(ctl, off), 1, 0);
++ if (WARN_ON(!info))
++ break;
++
++ if (info->bitmap) {
++ const unsigned long bit =
++ offset_to_bit(info->offset, unit, off);
++ const unsigned long zero =
++ find_next_zero_bit(info->bitmap,
++ BITS_PER_BITMAP, bit);
++
++ /*
++ * Only the set bits from @off: the run may go on in
++ * an extent entry inside this bitmap's window.
++ */
++ piece = min(remaining, (u64)(zero - bit) * unit);
++ if (WARN_ON(!piece))
++ break;
++ if (!btrfs_free_space_trimmed(info))
++ atomic64_add(piece,
++ &discard_ctl->discard_bytes_saved);
++ bitmap_clear_bits(ctl, info, off, piece, true);
++ if (!info->bytes)
++ free_bitmap(ctl, info);
++ } else {
++ const u64 e_end = info->offset + info->bytes;
++ int ret2;
++
++ piece = min(remaining, e_end - off);
++ if (!btrfs_free_space_trimmed(info))
++ atomic64_add(piece,
++ &discard_ctl->discard_bytes_saved);
++ unlink_free_space(ctl, info, true);
++ if (off == info->offset && piece == info->bytes) {
++ kmem_cache_free(btrfs_free_space_cachep, info);
++ } else if (off == info->offset) {
++ info->offset += piece;
++ info->bytes -= piece;
++ ret2 = link_free_space(ctl, info);
++ ASSERT(!ret2); /* -EEXIST; Logic error */
++ } else if (off + piece == e_end) {
++ info->bytes = off - info->offset;
++ ret2 = link_free_space(ctl, info);
++ ASSERT(!ret2); /* -EEXIST; Logic error */
++ } else {
++ /*
++ * Strictly inside: split head off, spare
++ * becomes the tail.
++ */
++ ASSERT(!spare_used);
++ spare->offset = off + piece;
++ spare->bytes = e_end - spare->offset;
++ spare->trim_state = info->trim_state;
++ info->bytes = off - info->offset;
++ ret2 = link_free_space(ctl, info);
++ ASSERT(!ret2); /* -EEXIST; Logic error */
++ ret2 = link_free_space(ctl, spare);
++ ASSERT(!ret2); /* -EEXIST; Logic error */
++ spare_used = true;
++ }
++ }
++ off += piece;
++ remaining -= piece;
++ }
++ return spare_used;
++}
++
++/*
++ * Claim a contiguous run of fully free full stripes.
++ *
++ * On success the run is removed from the free space cache and the caller
++ * owns [*start, *start + *len) until it allocates from it or returns the
++ * remainder with btrfs_add_free_space(). @want_bytes is a maximum; the
++ * smallest claim is one full stripe.
++ *
++ * A fully free stripe may span free space entries: extent and bitmap
++ * entries do not merge, and when full_stripe_len is not a power of two,
++ * stripe boundaries drift through the fixed bitmap windows. The slow path
++ * finds such stripes; stripe_claimable counts them, so missing them would
++ * fail writes that admission accepted.
++ *
++ * Returns 0 on success, -ENOSPC if no fully free stripe is present, or
++ * -ENOMEM if the slow path could not allocate.
+ */
+ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ u64 want_bytes, u64 *start, u64 *len)
+@@ -2241,7 +2437,9 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ const u64 fsl = block_group->full_stripe_len;
+ struct btrfs_free_space *entry;
+ struct rb_node *node;
++ struct btrfs_free_space *spare = NULL;
+ enum btrfs_trim_state head_trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
++ bool spare_used = false;
+ u64 head_start = 0;
+ u64 head_len = 0;
+ u64 run_start;
+@@ -2253,8 +2451,32 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ /* Claims are always whole stripes; tolerate an unaligned want_bytes. */
+ want_bytes = div64_u64(want_bytes, fsl) * fsl;
+
++ /*
++ * For the head of a claimed extent entry, or for a run strictly
++ * inside one, so neither has to be added back after the lock is
++ * dropped, where an allocation failure would lose it.
++ */
++ spare = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
++
+ spin_lock(&ctl->tree_lock);
+
++ /*
++ * Fail fast when an earlier exhaustive scan found no claimable run
++ * (max_claimable_run == 0; __btrfs_add_free_space() resets it) or less
++ * than one full stripe is free; otherwise every failed claim rescans a
++ * fragmented group under ctl->tree_lock. Trust the bound only once the
++ * group is cached: cache loading links entries without
++ * __btrfs_add_free_space(), so the reset would be missed.
++ */
++ if (btrfs_block_group_done(block_group) &&
++ (block_group->max_claimable_run < fsl ||
++ ctl->free_space < fsl)) {
++ spin_unlock(&ctl->tree_lock);
++ if (spare)
++ kmem_cache_free(btrfs_free_space_cachep, spare);
++ return -ENOSPC;
++ }
++
+ if (ctl->free_space < fsl)
+ goto out;
+
+@@ -2294,6 +2516,26 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ continue;
+ goto found;
+ }
++
++ /*
++ * No single entry holds a full stripe; look for one whose
++ * free space spans entry boundaries. The spare entry is
++ * for the belt-and-braces case of a run strictly inside
++ * one extent entry, whose removal splits it in two.
++ */
++ spin_unlock(&ctl->tree_lock);
++ spare = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
++ if (!spare)
++ return -ENOMEM;
++ spin_lock(&ctl->tree_lock);
++ if (!find_free_stripe_run_slow(block_group, want_bytes,
++ &run_start, &run_len))
++ goto out;
++ spare_used = claim_stripe_run_pieces(block_group, run_start,
++ run_len, spare);
++ *start = run_start;
++ *len = run_len;
++ ret = 0;
+ goto out;
+
+ found:
+@@ -2320,6 +2562,15 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ } else {
+ kmem_cache_free(btrfs_free_space_cachep, entry);
+ }
++ if (head_len && spare) {
++ spare->offset = head_start;
++ spare->bytes = head_len;
++ spare->trim_state = head_trim_state;
++ ret2 = link_free_space(ctl, spare);
++ ASSERT(!ret2); /* -EEXIST; Logic error */
++ spare_used = true;
++ head_len = 0;
++ }
+ }
+ *start = run_start;
+ *len = run_len;
+@@ -2328,6 +2579,8 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ btrfs_discard_update_discardable(block_group);
+ spin_unlock(&ctl->tree_lock);
+
++ if (spare && !spare_used)
++ kmem_cache_free(btrfs_free_space_cachep, spare);
+ if (!ret)
+ stripe_unusable_mark_dirty(block_group);
+ if (head_len)
+diff --git a/fs/btrfs/tests/free-space-tests.c b/fs/btrfs/tests/free-space-tests.c
+index 1ee9632d7e0b6..4022cadcd9e4c 100644
+--- a/fs/btrfs/tests/free-space-tests.c
++++ b/fs/btrfs/tests/free-space-tests.c
+@@ -1166,6 +1166,33 @@ static int test_stripe_claim(struct btrfs_block_group *cache, u32 sectorsize)
+ goto out;
+ }
+
++ /*
++ * A free stripe split inside one bitmap window: set bits, then an
++ * extent entry. The claim must remove both pieces, and nothing else.
++ */
++ ret = test_add_free_space_entry(cache, 0, fsl / 2, 1);
++ if (ret) {
++ test_err("error adding bitmap entry %d", ret);
++ goto out;
++ }
++ ret = test_add_free_space_entry(cache, fsl / 2, fsl / 2, 0);
++ if (ret) {
++ test_err("error adding extent entry %d", ret);
++ goto out;
++ }
++ ret = btrfs_claim_free_stripe_run(cache, fsl, &start, &len);
++ if (ret || start != 0 || len != fsl) {
++ test_err("bitmap+extent claim wrong: ret %d start %llu len %llu",
++ ret, start, len);
++ ret = -EINVAL;
++ goto out;
++ }
++ ret = check_cache_empty(cache);
++ if (ret) {
++ test_err("bitmap+extent 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);
+--
+2.47.3
+
+++ /dev/null
-From 4125cef50ff22f035dce63a99a06c3bddb8d6250 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:38 -0400
-Subject: [RFC PATCH 016/116] btrfs: stripe_alloc: kick parked rbios before the
- fast fsync's writeback wait
-To: linux-btrfs@vger.kernel.org
-
-The fast fsync path waits for page writeback, which completes only when
-the raid56 layer writes the data -- but a partial-stripe rbio parks to
-collect merges until its sync deadline, and on this path nothing unparks
-it before the wait: the stripes are settled only later, in the logging
-itself. The full-sync path does not have this problem because the
-ordered extent wait already flushes parked rbios before sleeping.
-
-All of the fsync's writes are submitted before the wait, so nothing more
-can merge into its stripes; flush the parked rbios covering the attached
-ordered extents instead of sleeping out their deadline. Removes the
-sync park timeout from the fast fsync critical path.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/file.c | 23 +++++++++++++++++++++++
- 1 file changed, 23 insertions(+)
-
-diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
-index d927b559aa327..577d2c0f6b73c 100644
---- a/fs/btrfs/file.c
-+++ b/fs/btrfs/file.c
-@@ -36,6 +36,7 @@
- #include "file-item.h"
- #include "ioctl.h"
- #include "defrag.h"
-+#include "raid56.h"
- #include "file.h"
- #include "super.h"
- #include "print-tree.h"
-@@ -1656,6 +1657,28 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
- * checksums attached to the ordered extents.
- */
- btrfs_get_ordered_extents_for_logging(inode, &ctx.ordered_extents);
-+
-+ /*
-+ * The writeback wait below completes only when the raid56
-+ * layer writes this fsync's data, but a partial-stripe rbio
-+ * parks (collecting merges) until its sync deadline, and on
-+ * this path nothing else unparks it before the wait -- the
-+ * stripes are settled only later, in the logging itself. All
-+ * of this fsync's writes are submitted by now, so nothing
-+ * more can merge; kick the parked rbios covering our ordered
-+ * extents instead of sleeping out their deadline.
-+ */
-+ if (btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
-+ struct btrfs_ordered_extent *tmp_oe;
-+
-+ list_for_each_entry(tmp_oe, &ctx.ordered_extents,
-+ log_list)
-+ if (tmp_oe->disk_num_bytes)
-+ btrfs_flush_parked_rbios(fs_info,
-+ tmp_oe->disk_bytenr,
-+ tmp_oe->disk_num_bytes);
-+ }
-+
- ret = filemap_fdatawait_range(inode->vfs_inode.i_mapping, start, end);
- if (ret)
- goto out_release_extents;
---
-2.47.3
-
+++ /dev/null
-From d751a574bd21ed06cfd5ba7163822ec3c07249e7 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:38 -0400
-Subject: [RFC PATCH 017/116] btrfs: raid56: pad sub-stripe writes to full
- stripes in open runs
-To: linux-btrfs@vger.kernel.org
-
-A sub-stripe write does a full RMW: read every untouched data sector of
-the stripe, recompute parity, write. Under stripe-exclusive allocation
-the read phase is usually pointless: a stripe covered by a live stripe
-run has never been written at or past the run's allocation frontier, so
-the sectors being read contain nothing.
-
-When every data sector the rbio does not cover lies at or past the
-frontier, zero-fill those sectors instead of reading them and write
-them out with the stripe -- the zeros must reach the disk, or the
-parity (computed over them) would not match what scrub reads back. The
-partial write becomes one full-stripe write: no read phase, one parity
-pass. A frontier that grows during the attempt is safe: the newer
-allocation's write serializes behind this rbio's stripe lock and lands
-over the zeros. If any uncovered sector is below the frontier (already
-allocated to someone else), fall back to the normal RMW.
-
-Together with kicking parked rbios before the fast fsync's writeback
-wait, this removes both stalls the raid56 layer added to fsync under
-stripe_alloc: the park deadline and the RMW read round trip.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 43 ++++++++++++++++++
- fs/btrfs/block-group.h | 3 ++
- fs/btrfs/raid56.c | 100 ++++++++++++++++++++++++++++++++++++++++-
- 3 files changed, 144 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index be8aa2fc103f8..2e5bb7491363a 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -919,6 +919,49 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- return true;
- }
-
-+/*
-+ * For the raid56 pad-to-full optimization: a sub-stripe write into a
-+ * stripe covered by a live stripe run may zero-fill (instead of read) any
-+ * sector at or past the run's allocation frontier, because such sectors
-+ * have never been written in the run's lifetime and, once the run closes,
-+ * its stripe's tail cannot be reallocated while the stripe holds live
-+ * data. Returns true and sets *pad_from to the frontier when the stripe
-+ * at [stripe_start, stripe_start + stripe_len) has a paddable tail. The
-+ * frontier can grow right after this returns; that is safe, because the
-+ * later allocation's write serializes behind the caller's stripe lock
-+ * and overwrites the zeros.
-+ */
-+bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
-+ u64 stripe_start, u64 stripe_len,
-+ u64 *pad_from)
-+{
-+ struct btrfs_block_group *bg;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ bool ret = false;
-+
-+ if (list_empty_careful(&fs_info->open_stripe_bgs))
-+ return false;
-+ bg = btrfs_lookup_block_group(fs_info, stripe_start);
-+ if (!bg)
-+ return false;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (stripe_start < run->start || stripe_start >= run->end)
-+ continue;
-+ if (run->offset > stripe_start &&
-+ run->offset < stripe_start + stripe_len) {
-+ *pad_from = run->offset;
-+ ret = true;
-+ }
-+ break;
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ btrfs_put_block_group(bg);
-+ return ret;
-+}
-+
- /* No open or draining run covers @bytenr any more. */
- static bool stripe_log_range_settled(struct btrfs_block_group *bg, u64 bytenr)
- {
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 0edfafab20eb4..32b114fa4fede 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -415,6 +415,9 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
- bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- u64 run_start, u64 *run_len);
-+bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
-+ u64 stripe_start, u64 stripe_len,
-+ u64 *pad_from);
- void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- u64 file_len, u64 bytenr, u64 num_bytes);
- int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 279c15cf229e8..30c664babecd3 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -45,6 +45,16 @@
- */
- #define RBIO_PARKED_BIT 4
-
-+/*
-+ * Set when a partial write rbio's uncovered data sectors were zero-filled
-+ * instead of read (they lie at or past the covering stripe run's
-+ * allocation frontier and have never been written). The write path then
-+ * writes them out with the stripe -- parity must match the disk, or
-+ * scrub would flag the never-written sectors -- turning the partial
-+ * write into a full-stripe write with no read phase.
-+ */
-+#define RBIO_PADDED_BIT 5
-+
- #define RBIO_CACHE_SIZE 1024
-
- /*
-@@ -1737,7 +1747,12 @@ static int rmw_assemble_write_bios(struct btrfs_raid_bio *rbio,
- continue;
-
- if (stripe < rbio->nr_data) {
-- paddrs = sector_paddrs_in_rbio(rbio, stripe, sectornr, 1);
-+ /*
-+ * A padded rbio writes its zero-filled stripe sectors
-+ * too, so parity matches the disk (see RBIO_PADDED_BIT).
-+ */
-+ paddrs = sector_paddrs_in_rbio(rbio, stripe, sectornr,
-+ !test_bit(RBIO_PADDED_BIT, &rbio->flags));
- if (paddrs == NULL)
- continue;
- } else {
-@@ -2694,6 +2709,73 @@ static void submit_write_bios(struct btrfs_raid_bio *rbio,
- }
- }
-
-+/*
-+ * Try to avoid the RMW read phase of a sub-stripe write by zero-filling
-+ * the uncovered data sectors. Legal only when every uncovered sector
-+ * lies at or past its stripe run's allocation frontier -- never written
-+ * in the run's lifetime, and unreachable by other allocations while this
-+ * stripe holds live data (see btrfs_stripe_run_pad_start()). A frontier
-+ * that grows under us is safe: the newer allocation's write serializes
-+ * behind this rbio's stripe lock and lands over the zeros.
-+ */
-+static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ const u64 stripe_start = rbio->bioc->full_stripe_logical;
-+ const u32 sectorsize = fs_info->sectorsize;
-+ const u64 stripe_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
-+ u64 pad_from;
-+ int i;
-+
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return false;
-+ if (!btrfs_stripe_run_pad_start(fs_info, stripe_start, stripe_len,
-+ &pad_from))
-+ return false;
-+
-+ /* Populate bio_paddrs so covered sectors are visible below. */
-+ index_rbio_pages(rbio);
-+
-+ /* Every data sector this rbio does not cover must be paddable. */
-+ for (i = 0; i < rbio->nr_data * rbio->stripe_nsectors; i++) {
-+ const int stripe_nr = i / rbio->stripe_nsectors;
-+ const int sectornr = i % rbio->stripe_nsectors;
-+ u64 logical = stripe_start + stripe_nr * BTRFS_STRIPE_LEN +
-+ (u64)sectornr * sectorsize;
-+
-+ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
-+ continue;
-+ if (logical < pad_from)
-+ return false;
-+ }
-+
-+ if (alloc_rbio_data_pages(rbio) < 0)
-+ return false;
-+
-+ for (i = 0; i < rbio->nr_data * rbio->stripe_nsectors; i++) {
-+ const int stripe_nr = i / rbio->stripe_nsectors;
-+ const int sectornr = i % rbio->stripe_nsectors;
-+ int step;
-+
-+ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
-+ continue;
-+ for (step = 0; step < rbio->sector_nsteps; step++) {
-+ phys_addr_t paddr = rbio_stripe_paddr(rbio, stripe_nr,
-+ sectornr, step);
-+ void *kaddr = kmap_local_paddr(paddr);
-+
-+ memset(kaddr, 0, min_t(u32, sectorsize, PAGE_SIZE));
-+ kunmap_local(kaddr);
-+ }
-+ set_bit(i, rbio->stripe_uptodate_bitmap);
-+ }
-+
-+ set_bit(RBIO_PADDED_BIT, &rbio->flags);
-+ /* The whole stripe goes out: every vertical position is written. */
-+ bitmap_set(&rbio->dbitmap, 0, rbio->stripe_nsectors);
-+ return true;
-+}
-+
- /*
- * To determine if we need to read any sector from the disk.
- * Should only be utilized in RMW path, to skip cached rbio.
-@@ -2744,8 +2826,22 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- /*
- * Either full stripe write, or we have every data sector already
- * cached, can go to write path immediately.
-+ *
-+ * Padding must win over the cache: a stolen cached rbio can carry
-+ * all-uptodate pages from the stripe's PREVIOUS life -- before its
-+ * extents were freed and the stripe was re-claimed -- and letting
-+ * those pages skip the pad path bakes the cache's memory of dead
-+ * data into fresh parity while only the bio sectors reach disk.
-+ * If any on-disk column then diverges from that memory (device
-+ * corruption, or simply free-space columns nobody rewrote), the
-+ * stripe is latently unreconstructible. A paddable rbio instead
-+ * zero-fills and WRITES every uncovered column, making the stripe
-+ * self-consistent on disk regardless of what the cache remembered;
-+ * the claimed-stripe invariant (a stripe write depends on nothing
-+ * on disk) requires this ordering.
- */
-- if (!rbio_is_full(rbio) && need_read_stripe_sectors(rbio)) {
-+ if (!rbio_is_full(rbio) && !rmw_try_pad_full(rbio) &&
-+ need_read_stripe_sectors(rbio)) {
- /*
- * Now we're doing sub-stripe write, also need all data stripes
- * to do the full RMW.
---
-2.47.3
-
--- /dev/null
+From 59646fb2be214b885116d4fc5277664960250167 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:47 -0400
+Subject: [RFC PATCH 17/85] btrfs: stripe_alloc: warn when raid56 metadata is
+ not covered
+To: linux-btrfs@vger.kernel.org
+
+stripe_alloc closes the write hole for raid56 data. It does nothing for
+raid56 metadata, which keeps read-modify-write and keeps the hole, and
+on a mixed-block-group filesystem it now does nothing at all. A user
+who enables stripe_alloc on -d raid5 -m raid5 has every reason to
+believe the filesystem is covered, and finds out otherwise only after a
+crash on a degraded array -- with metadata damage, which is worse than
+the data damage they were protecting against.
+
+Say it once at mount, after the block groups are read, so the message
+reflects what is actually on disk rather than what was asked for. A
+warning, not an error: the data guarantee is real and worth having on
+its own, and a filesystem can be converted to raid1c3/raid1c4 metadata
+without unmounting.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 23 +++++++++++++++++++++++
+ 1 file changed, 23 insertions(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 2745fe155291d..a2e7e8667b15e 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1067,6 +1067,28 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
+ }
+ }
+
++/*
++ * stripe_alloc covers raid56 *data* block groups only. A filesystem whose
++ * metadata is also raid56 keeps the write hole there. The data guarantee is
++ * easy to read as a filesystem-wide one, so say once, when the policy turns
++ * on, what is not covered. That is btrfs_enable_stripe_alloc(): at mount the
++ * property applies after the block groups are read, so a report from
++ * btrfs_read_block_groups() would find the flag still clear. (Mixed block
++ * groups cannot get here: the property refuses them.)
++ */
++static void warn_stripe_alloc_uncovered(struct btrfs_fs_info *info)
++{
++ const u64 meta_bits = info->avail_metadata_alloc_bits |
++ info->avail_system_alloc_bits;
++
++ if (!btrfs_test_opt(info, STRIPE_ALLOC))
++ return;
++
++ if (meta_bits & BTRFS_BLOCK_GROUP_RAID56_MASK)
++ btrfs_warn(info,
++"stripe_alloc does not cover raid56 metadata: the write hole remains for metadata, consider converting it to raid1c3/raid1c4");
++}
++
+ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ {
+ int ret;
+@@ -1077,6 +1099,7 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ if (ret)
+ return ret;
+ btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
++ warn_stripe_alloc_uncovered(fs_info);
+ /*
+ * Arm stripe_unusable accounting for raid56 data groups whose caches
+ * loaded before the policy was enabled: block groups are read before
+--
+2.47.3
+
+++ /dev/null
-From 56f960dce657f0f9a18ba36bc984d1d967365e67 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:39 -0400
-Subject: [RFC PATCH 018/116] btrfs: stripe_alloc: isolate nodatacow and
- preallocated extents by stripe
-To: linux-btrfs@vger.kernel.org
-
-Preallocated extents and nodatacow files' extents are candidates for
-write-in-place, which reintroduces the raid56 write hole for every
-stripe such a write touches: the RMW recomputes parity that also covers
-whatever else shares the stripe. Before write-in-place can be
-re-enabled for them (a later change; stripe_alloc still forces COW
-today), their placement must guarantee the blast radius: such an extent
-must never share a stripe with any other file's data.
-
-Steer them into private per-inode stripe runs of a new NOCOW class,
-reusing the log-active inode machinery: runs owned by one inode, never
-in the shared band slots, found by owner-and-class lookup. Successive
-allocations of the same file pack sequentially into the file's own
-stripes; different files, and the datacow/relocation/log classes, never
-share a stripe with them. A preallocation signals itself through a new
-btrfs_reserve_extent() parameter; nodatacow files are recognized by the
-inode flag. Placement remains best effort: when no fully-free stripes
-are left for a private run the allocation falls back to the shared
-runs, which is safe -- an extent that lands in a shared stripe simply
-stays force-COWed when write-in-place arrives.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 6 ++--
- fs/btrfs/block-group.h | 10 +++++++
- fs/btrfs/direct-io.c | 2 +-
- fs/btrfs/extent-tree.c | 63 +++++++++++++++++++++++++++---------------
- fs/btrfs/extent-tree.h | 12 +++++---
- fs/btrfs/inode.c | 12 ++++----
- fs/btrfs/relocation.c | 5 ++--
- 7 files changed, 72 insertions(+), 38 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 2e5bb7491363a..490a2bd401c72 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -793,6 +793,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- * this block group can satisfy the allocation, or -ENOMEM.
- */
- int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
-+ enum btrfs_stripe_run_class class,
- u64 num_bytes, u64 *ret_offset,
- u64 *available)
- {
-@@ -812,8 +813,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (run->class != BTRFS_STRIPE_RUN_LOG || run->owner != ino ||
-- !run->open)
-+ if (run->class != class || run->owner != ino || !run->open)
- continue;
- if (num_bytes <= run->end - run->offset) {
- *ret_offset = run->offset;
-@@ -865,7 +865,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
- goto out;
- }
- new_run->bg = bg;
-- new_run->class = BTRFS_STRIPE_RUN_LOG;
-+ new_run->class = class;
- new_run->owner = ino;
- new_run->start = start;
- new_run->end = start + len;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 32b114fa4fede..568c07929c578 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -37,6 +37,15 @@ enum btrfs_stripe_run_class {
- * own stripes.
- */
- BTRFS_STRIPE_RUN_LOG,
-+ /*
-+ * Private per-inode runs for nodatacow files' extents and
-+ * preallocated extents. These extents are candidates for future
-+ * write-in-place (which reintroduces the write hole for the stripes
-+ * it touches), so they must never share a stripe with any other
-+ * file's data: per-inode scoping confines a future in-place write's
-+ * blast radius to the owning file alone.
-+ */
-+ BTRFS_STRIPE_RUN_NOCOW,
- BTRFS_STRIPE_RUN_NR_CLASSES,
- };
-
-@@ -399,6 +408,7 @@ 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,
-+ enum btrfs_stripe_run_class class,
- u64 num_bytes, u64 *ret_offset,
- u64 *available);
- void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
-diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c
-index 8bdfae5ebe694..dc9db2234be66 100644
---- a/fs/btrfs/direct-io.c
-+++ b/fs/btrfs/direct-io.c
-@@ -186,7 +186,7 @@ static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
- alloc_hint = btrfs_get_extent_allocation_hint(inode, start, len);
- again:
- ret = btrfs_reserve_extent(root, inode, len, len, fs_info->sectorsize,
-- 0, alloc_hint, &ins, true, true);
-+ 0, alloc_hint, &ins, true, true, false);
- if (ret == -EAGAIN) {
- ASSERT(btrfs_is_zoned(fs_info));
- wait_on_bit_io(&inode->root->fs_info->flags, BTRFS_FS_NEED_ZONE_FINISH,
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index e1b6c8a0cdf96..8aeed1040f14f 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4243,22 +4243,25 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- return 1;
-
- /*
-- * A log-active inode allocates from its own private LOG-class run so
-- * its log commits settle only its own stripes. If this block group
-- * has no fully-free stripes left for a private run, fall through to
-- * the shared runs: the data is then placed exactly as before 3b.1
-- * and the log-commit settling keeps it safe, just less cheaply.
-+ * Steered allocations come from the inode's own private run of the
-+ * requested class: a log-active inode's log commits then settle only
-+ * its own stripes, and nocow/prealloc extents never share a stripe
-+ * with another file's data. If this block group has no fully-free
-+ * stripes left for a private run, fall through to the shared runs --
-+ * safe in both cases: log-commit settling covers any placement, and
-+ * a nocow/prealloc extent that lands in a shared stripe simply stays
-+ * force-COWed.
- */
-- if (ffe_ctl->for_log_inode) {
-- struct btrfs_inode *log_inode = ffe_ctl->for_log_inode;
-+ if (ffe_ctl->steer_inode) {
-+ struct btrfs_inode *steer_inode = ffe_ctl->steer_inode;
-
- ret = btrfs_alloc_from_inode_stripe_run(block_group,
-- btrfs_ino(log_inode), ffe_ctl->num_bytes,
-- &offset, &available);
-+ btrfs_ino(steer_inode), ffe_ctl->steer_class,
-+ ffe_ctl->num_bytes, &offset, &available);
- if (ret == -ENOMEM)
- return ret;
- if (!ret) {
-- WRITE_ONCE(log_inode->log_run_hint, offset);
-+ WRITE_ONCE(steer_inode->log_run_hint, offset);
- ffe_ctl->found_offset = offset;
- ffe_ctl->search_start = offset;
- return 0;
-@@ -4993,7 +4996,8 @@ static noinline int find_free_extent(struct btrfs_root *root,
- int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- u64 ram_bytes, u64 num_bytes, u64 min_alloc_size,
- u64 empty_size, u64 hint_byte,
-- struct btrfs_key *ins, bool is_data, bool delalloc)
-+ struct btrfs_key *ins, bool is_data, bool delalloc,
-+ bool for_prealloc)
- {
- struct btrfs_fs_info *fs_info = root->fs_info;
- struct find_free_extent_ctl ffe_ctl = {};
-@@ -5002,22 +5006,34 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- int ret;
- bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
- bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
-- struct btrfs_inode *for_log_inode = NULL;
-+ struct btrfs_inode *steer_inode = NULL;
-+ enum btrfs_stripe_run_class steer_class = BTRFS_STRIPE_RUN_COW;
-
- /*
-- * Steer a log-active inode's datacow data into its private LOG-class
-- * stripe run, seeded with the run's location as the search hint; see
-- * BTRFS_INODE_LOG_ALLOC. Purely placement: any allocation that
-+ * 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.
- */
- if (inode && is_data && !for_data_reloc &&
-- btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
-- test_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags)) {
-- u64 log_hint = READ_ONCE(inode->log_run_hint);
-+ btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
-+ if (for_prealloc || (inode->flags & BTRFS_INODE_NODATACOW)) {
-+ steer_inode = inode;
-+ steer_class = BTRFS_STRIPE_RUN_NOCOW;
-+ } else if (test_bit(BTRFS_INODE_LOG_ALLOC,
-+ &inode->runtime_flags)) {
-+ steer_inode = inode;
-+ steer_class = BTRFS_STRIPE_RUN_LOG;
-+ }
-+ if (steer_inode) {
-+ u64 run_hint = READ_ONCE(inode->log_run_hint);
-
-- for_log_inode = inode;
-- if (log_hint)
-- hint_byte = log_hint;
-+ if (run_hint)
-+ hint_byte = run_hint;
-+ }
- }
-
- flags = get_alloc_profile_by_root(root, is_data);
-@@ -5033,7 +5049,8 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- ffe_ctl.hint_byte = hint_byte;
- ffe_ctl.for_treelog = for_treelog;
- ffe_ctl.for_data_reloc = for_data_reloc;
-- ffe_ctl.for_log_inode = for_log_inode;
-+ ffe_ctl.steer_inode = steer_inode;
-+ ffe_ctl.steer_class = steer_class;
-
- ret = find_free_extent(root, ins, &ffe_ctl);
- if (!ret && !is_data) {
-@@ -5538,7 +5555,7 @@ struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
- return ERR_CAST(block_rsv);
-
- ret = btrfs_reserve_extent(root, NULL, blocksize, blocksize, blocksize,
-- empty_size, hint, &ins, false, false);
-+ empty_size, hint, &ins, false, false, false);
- if (ret)
- goto out_unuse;
-
-diff --git a/fs/btrfs/extent-tree.h b/fs/btrfs/extent-tree.h
-index a75eb49437030..13096c06fe61d 100644
---- a/fs/btrfs/extent-tree.h
-+++ b/fs/btrfs/extent-tree.h
-@@ -50,10 +50,13 @@ struct find_free_extent_ctl {
- bool for_data_reloc;
-
- /*
-- * Data allocation for a log-active inode under stripe-exclusive
-- * allocation: steer it into the inode's private LOG-class stripe run.
-+ * Data allocation to steer into a private per-inode stripe run under
-+ * stripe-exclusive allocation (LOG class for log-active inodes,
-+ * NOCOW class for nodatacow files' and preallocated extents), with
-+ * the class to use.
- */
-- struct btrfs_inode *for_log_inode;
-+ struct btrfs_inode *steer_inode;
-+ enum btrfs_stripe_run_class steer_class;
-
- /*
- * Set to true if we're retrying the allocation on this block group
-@@ -144,7 +147,8 @@ int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
- int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- u64 ram_bytes, u64 num_bytes,
- u64 min_alloc_size, u64 empty_size, u64 hint_byte,
-- struct btrfs_key *ins, bool is_data, bool delalloc);
-+ struct btrfs_key *ins, bool is_data, bool delalloc,
-+ bool for_prealloc);
- int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
- struct extent_buffer *buf, bool full_backref);
- int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index afe0cc331deb8..0aaa5a568ba71 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -1072,7 +1072,7 @@ static void submit_one_async_extent(struct async_chunk *async_chunk,
- compressed_size = async_extent->cb->bbio.bio.bi_iter.bi_size;
- ret = btrfs_reserve_extent(root, inode, async_extent->ram_size,
- compressed_size, compressed_size,
-- 0, *alloc_hint, &ins, true, true);
-+ 0, *alloc_hint, &ins, true, true, false);
- if (ret) {
- /*
- * We can't reserve contiguous space for the compressed size.
-@@ -1218,7 +1218,7 @@ static int cow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
-
- ret = btrfs_reserve_extent(root, inode, num_bytes, num_bytes,
- min_alloc_size, 0, alloc_hint, ins, true,
-- true);
-+ true, false);
- if (ret < 0) {
- *ret_alloc_size = cur_len;
- return ret;
-@@ -9260,8 +9260,9 @@ int btrfs_prealloc_file_range(struct inode *inode, int mode,
- * sized chunks.
- */
- cur_bytes = min(cur_bytes, last_alloc);
-- ret = btrfs_reserve_extent(root, NULL, cur_bytes, cur_bytes,
-- min_size, 0, *alloc_hint, &ins, true, false);
-+ ret = btrfs_reserve_extent(root, BTRFS_I(inode), cur_bytes,
-+ cur_bytes, min_size, 0, *alloc_hint, &ins,
-+ true, false, true);
- if (ret)
- break;
- /*
-@@ -10098,7 +10099,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);
-+ disk_num_bytes, 0, 0, &ins, true, true,
-+ false);
- if (ret)
- goto out_delalloc_release;
- extent_reserved = true;
-diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
-index a41f57559ee74..03b9834b57223 100644
---- a/fs/btrfs/relocation.c
-+++ b/fs/btrfs/relocation.c
-@@ -4286,7 +4286,7 @@ static int move_existing_remap(struct btrfs_fs_info *fs_info,
- min_size = fs_info->nodesize;
-
- ret = btrfs_reserve_extent(fs_info->fs_root, NULL, length, length,
-- min_size, 0, 0, &ins, is_data, false);
-+ min_size, 0, 0, &ins, is_data, false, false);
- if (unlikely(ret)) {
- spin_lock(&sinfo->lock);
- btrfs_space_info_update_bytes_may_use(sinfo, -length);
-@@ -5115,7 +5115,8 @@ static int do_remap_reloc_trans(struct btrfs_fs_info *fs_info,
- * rest of it the next time round.
- */
- ret = btrfs_reserve_extent(fs_info->fs_root, NULL, remap_length,
-- remap_length, min_size, 0, 0, &ins, is_data, false);
-+ remap_length, min_size, 0, 0, &ins, is_data,
-+ false, false);
- if (ret) {
- spin_lock(&sinfo->lock);
- btrfs_space_info_update_bytes_may_use(sinfo, -remap_length);
---
-2.47.3
-
--- /dev/null
+From 4d1558d6fa3ff13a54ef69beecb2ededd8816d3b Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:48 -0400
+Subject: [RFC PATCH 18/85] btrfs: stripe_alloc: report read-modify-write of
+ uncovered stripes
+To: linux-btrfs@vger.kernel.org
+
+The mount-time warning says which block groups stripe_alloc does not
+cover. It cannot say whether anything is actually landing there, and on
+a filesystem with raid56 metadata that is the interesting question: every
+sub-stripe write to an uncovered stripe is a write hole window, where
+parity and data reach the disk separately and a crash in between leaves
+the stripe unreconstructible.
+
+Report it from the one place that knows the write is going out as a
+read-modify-write rather than as a full or padded stripe. Rate limited,
+because a raid56-metadata filesystem does this continuously and the point
+is to make the exposure visible rather than to fill the log. (A
+meta_rmw counter in stripe_park_stats, to read the rate off without
+grepping dmesg, is debug code and is added in the debug subtopic.)
+
+Silent when stripe_alloc is off: there the whole filesystem works this
+way and the user has asked for nothing else.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/raid56.c | 25 +++++++++++++++++++++++++
+ 1 file changed, 25 insertions(+)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index a9fac8fc28e4f..2b54bb70f6d2f 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -2766,6 +2766,27 @@ static bool need_read_stripe_sectors(struct btrfs_raid_bio *rbio)
+ return false;
+ }
+
++/*
++ * Count and audit a metadata or system read-modify-write
++ * (audit_uncovered_rmw()), and warn if it lands in a raid56 group that
++ * stripe_meta does not cover. Silent when stripe_alloc is off.
++ */
++static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return;
++ /* Data groups are btrfs_is_stripe_alloc_bg()'s. */
++ if ((rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA) &&
++ !(rbio->bioc->map_type & BTRFS_BLOCK_GROUP_METADATA))
++ return;
++
++ btrfs_warn_rl(fs_info,
++"read-modify-write of full stripe %llu: this block group is not covered by stripe_alloc, the raid56 write hole applies to it",
++ rbio->bioc->full_stripe_logical);
++}
++
+ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ {
+ struct bio_list bio_list;
+@@ -2811,6 +2832,10 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ goto out;
+ }
+
++ /* Still a sub-stripe write: this stripe is being modified in place. */
++ if (!rbio_is_full(rbio) && !test_bit(RBIO_PADDED_BIT, &rbio->flags))
++ report_uncovered_rmw(rbio);
++
+ /*
+ * At this stage we're not allowed to add any new bios to the
+ * bio list any more, anyone else that wants to change this stripe
+--
+2.47.3
+
+++ /dev/null
-From bd29e332429ed54addde7e66642710d851633b10 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:40 -0400
-Subject: [RFC PATCH 019/116] btrfs: stripe_alloc: allow-rmw policy, and
- write-in-place for isolated nocow extents
-To: linux-btrfs@vger.kernel.org
-
-Re-enable write-in-place for nodatacow files and preallocated extents
-under stripe-exclusive allocation, with the understood caveat that the
-write hole cannot be prevented for data that opts out of COW: an
-in-place write RMWs its stripe's parity, so a degraded crash can tear
-the stripe. What CAN be guaranteed is the blast radius: in-place is
-permitted only for extents whose full stripes are isolated to the
-writing inode, so such a crash can tear only the writing file's own
-data -- the nodatacow contract, no worse.
-
-The gate is per extent, decided where nocow eligibility is already
-checked: fast path, the stripe belongs to one of the inode's own
-NOCOW-class runs (which only ever held its extents); slow path, the
-committed extent tree proves sole ownership (single plain data ref,
-count 1, matching root and objectid; anything shared, foreign or
-metadata fails). The fully-free claim rule keeps uncommitted foreign
-extents out of partially used stripes, so the committed tree is
-authoritative. Extents that fail -- anything allocated before stripe
-isolation existed, extents shared through reflink or snapshots,
-relocated extents -- simply stay force-COWed, and because their rewrite
-is steered into the inode's private NOCOW run, the next overwrite of
-the same data passes: legacy nocow files migrate themselves to
-isolation in one COW generation, with no tool and no flag day.
-
-Log-commit settling skips NOCOW-class runs: nodatacow data gets no
-fsync survival guarantee (its own later in-place writes can always
-tear it), so closing the run would trap its tail for nothing. The
-write-hole debug checker skips groups that hosted NOCOW-class runs,
-like relocation-used groups, since isolated in-place writes land in
-stripes whose runs have drained.
-
-The interface is a word-list policy naming the cases in which
-stripe_alloc may permit the legacy unsafe RMW, each independently:
-
- nodatacow in-place writes for nodatacow files' extents
- prealloc in-place writes into preallocated extents
- fsync waive the close-at-log-commit guarantee: no settling, no
- per-inode LOG steering, no carry-forward; logged stripes
- may be extended and RMWed as before those patches
-
-It is "allow_rmw", not "allow_overwrite": the fsync case overwrites
-nothing, but all three permit read-modify-write of stripes that a
-degraded crash can then tear. The nodatacow and prealloc cases require
-the per-extent stripe isolation above (the blast radius stays confined
-to the writing file); fsync restores the 3a-era exposure where a
-degraded crash may cost just-fsynced data, detectably, in exchange for
-none of the log-commit costs.
-
-The policy is persistent as the btrfs.stripe_alloc_allow_rmw property
-on the top-level root directory, following stripe_alloc's precedent
-(applied when the root inode loads during mount, before any user IO),
-Words are separated by comma, space or colon. Everything defaults off: plain stripe_alloc keeps
-forcing COW and keeps the full fsync guarantee.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 272 ++++++++++++++++++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 14 +++
- fs/btrfs/defrag.c | 3 +
- fs/btrfs/extent-tree.c | 3 +
- fs/btrfs/file.c | 2 +
- fs/btrfs/fs.h | 23 ++++
- fs/btrfs/inode.c | 11 +-
- fs/btrfs/props.c | 42 +++++++
- 8 files changed, 368 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 490a2bd401c72..88fcd964b7036 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -919,6 +919,247 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- return true;
- }
-
-+/*
-+ * Parse a stripe_alloc_allow_rmw word list ("nodatacow",
-+ * "prealloc", "fsync") into its mask. Words are separated by comma,
-+ * space or colon; the mount option form must use colon, since mount
-+ * itself splits options at commas. An empty value yields an empty
-+ * mask. Returns -EINVAL on any unknown word. Shared by the mount
-+ * option and the filesystem property.
-+ */
-+int btrfs_parse_stripe_rmw(const char *value, size_t len, u32 *mask)
-+{
-+ u32 m = 0;
-+ size_t i = 0;
-+
-+ while (i < len) {
-+ size_t j = i;
-+
-+ while (j < len && value[j] != ',' && value[j] != ' ' &&
-+ value[j] != ':')
-+ j++;
-+ if (j - i == strlen("nodatacow") &&
-+ !strncmp(value + i, "nodatacow", j - i))
-+ m |= BTRFS_STRIPE_RMW_NODATACOW;
-+ else if (j - i == strlen("prealloc") &&
-+ !strncmp(value + i, "prealloc", j - i))
-+ m |= BTRFS_STRIPE_RMW_PREALLOC;
-+ else if (j - i == strlen("fsync") &&
-+ !strncmp(value + i, "fsync", j - i))
-+ m |= BTRFS_STRIPE_RMW_FSYNC;
-+ else if (j != i)
-+ return -EINVAL;
-+ i = j + 1;
-+ }
-+ *mask = m;
-+ return 0;
-+}
-+
-+void btrfs_show_stripe_rmw(struct seq_file *seq, u32 mask)
-+{
-+ const char *sep = "";
-+
-+ if (mask & BTRFS_STRIPE_RMW_NODATACOW) {
-+ seq_printf(seq, "%snodatacow", sep);
-+ sep = ":";
-+ }
-+ if (mask & BTRFS_STRIPE_RMW_PREALLOC) {
-+ seq_printf(seq, "%sprealloc", sep);
-+ sep = ":";
-+ }
-+ if (mask & BTRFS_STRIPE_RMW_FSYNC)
-+ seq_printf(seq, "%sfsync", sep);
-+}
-+
-+/*
-+ * Does every committed extent in [start, start + len) belong solely to
-+ * @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.
-+ */
-+static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
-+ u64 root_id, u64 ino, u64 start, u64 len)
-+{
-+ struct btrfs_root *extent_root = btrfs_extent_root(fs_info, start);
-+ struct btrfs_path *path;
-+ struct btrfs_key key;
-+ bool ret = true;
-+ int err;
-+
-+ if (!extent_root)
-+ return false;
-+ path = btrfs_alloc_path();
-+ if (!path)
-+ return false;
-+
-+ key.objectid = start;
-+ key.type = BTRFS_EXTENT_ITEM_KEY;
-+ key.offset = 0;
-+ err = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
-+ if (err < 0) {
-+ ret = false;
-+ goto out;
-+ }
-+ /* An extent starting before @start may still overlap it. */
-+ err = btrfs_previous_extent_item(extent_root, path, 0);
-+ if (err < 0) {
-+ ret = false;
-+ goto out;
-+ }
-+ if (err > 0) {
-+ btrfs_release_path(path);
-+ key.objectid = start;
-+ key.type = BTRFS_EXTENT_ITEM_KEY;
-+ key.offset = 0;
-+ err = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
-+ if (err < 0) {
-+ ret = false;
-+ goto out;
-+ }
-+ }
-+
-+ while (true) {
-+ struct extent_buffer *leaf = path->nodes[0];
-+ int slot = path->slots[0];
-+ struct btrfs_extent_item *ei;
-+ struct btrfs_extent_inline_ref *iref;
-+ struct btrfs_extent_data_ref *dref;
-+ int type;
-+
-+ if (slot >= btrfs_header_nritems(leaf)) {
-+ err = btrfs_next_leaf(extent_root, path);
-+ if (err < 0) {
-+ ret = false;
-+ goto out;
-+ }
-+ if (err > 0)
-+ break;
-+ continue;
-+ }
-+ btrfs_item_key_to_cpu(leaf, &key, slot);
-+ if (key.objectid >= start + len)
-+ break;
-+ if (key.type == BTRFS_METADATA_ITEM_KEY) {
-+ /*
-+ * key.offset is the level, not a length; a tree
-+ * block spans nodesize bytes. One from before the
-+ * range (e.g. where the pre-range positioning landed
-+ * on a metadata block group's last item) is harmless.
-+ */
-+ if (key.objectid + fs_info->nodesize > start) {
-+ ret = false;
-+ goto out;
-+ }
-+ path->slots[0]++;
-+ continue;
-+ }
-+ if (key.type != BTRFS_EXTENT_ITEM_KEY ||
-+ key.objectid + key.offset <= start) {
-+ path->slots[0]++;
-+ continue;
-+ }
-+
-+ ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
-+ if (btrfs_extent_refs(leaf, ei) != 1 ||
-+ !(btrfs_extent_flags(leaf, ei) & BTRFS_EXTENT_FLAG_DATA)) {
-+ ret = false;
-+ goto out;
-+ }
-+ iref = (struct btrfs_extent_inline_ref *)(ei + 1);
-+ type = btrfs_get_extent_inline_ref_type(leaf, iref,
-+ BTRFS_REF_TYPE_DATA);
-+ if (type != BTRFS_EXTENT_DATA_REF_KEY) {
-+ ret = false;
-+ goto out;
-+ }
-+ dref = (struct btrfs_extent_data_ref *)(&iref->offset);
-+ if (btrfs_extent_data_ref_root(leaf, dref) != root_id ||
-+ btrfs_extent_data_ref_objectid(leaf, dref) != ino ||
-+ btrfs_extent_data_ref_count(leaf, dref) != 1) {
-+ ret = false;
-+ goto out;
-+ }
-+ path->slots[0]++;
-+ }
-+out:
-+ btrfs_free_path(path);
-+ return ret;
-+}
-+
-+/*
-+ * May [start, start + num_bytes) be written in place under
-+ * stripe-exclusive allocation? Only when the stripe_alloc_nocow policy
-+ * is enabled and every full stripe the range touches is isolated to
-+ * @inode: an in-place write RMWs the stripe's parity, so a degraded
-+ * crash can tear every extent sharing the stripe -- isolation confines
-+ * that blast radius to the writing file, which opted out of COW
-+ * protection. Fast path: the stripe belongs to one of the inode's own
-+ * NOCOW-class runs (such stripes have only ever held its extents).
-+ * Slow path: the committed extent tree proves sole ownership. Extents
-+ * that fail simply stay force-COWed -- and their rewrite is steered
-+ * into the inode's private NOCOW run, so the next overwrite of the same
-+ * data passes.
-+ */
-+bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
-+ u64 num_bytes, u32 which)
-+{
-+ struct btrfs_fs_info *fs_info = inode->root->fs_info;
-+ struct btrfs_block_group *bg;
-+ const u64 root_id = btrfs_root_id(inode->root);
-+ const u64 ino = btrfs_ino(inode);
-+ u64 fsl;
-+ u64 cur;
-+ u64 end;
-+ bool ret = true;
-+
-+ if (!(btrfs_stripe_allow_rmw(fs_info) & which))
-+ return false;
-+ bg = btrfs_lookup_block_group(fs_info, start);
-+ if (!bg)
-+ return false;
-+ if (!btrfs_is_stripe_alloc_bg(bg)) {
-+ /* Not a raid56 data group: nothing forces COW here anyway. */
-+ btrfs_put_block_group(bg);
-+ return true;
-+ }
-+
-+ fsl = bg->full_stripe_len;
-+ cur = bg->start + round_down(start - bg->start, fsl);
-+ end = start + num_bytes;
-+ while (cur < end) {
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ int verdict = 0; /* 0 = unknown, 1 = ok, -1 = foreign */
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (cur < run->start || cur >= run->end)
-+ continue;
-+ if (run->class == BTRFS_STRIPE_RUN_NOCOW &&
-+ run->owner == ino)
-+ verdict = 1;
-+ else
-+ verdict = -1;
-+ break;
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+
-+ if (verdict == 0 &&
-+ !stripe_extents_owned_by(fs_info, root_id, ino, cur, fsl))
-+ verdict = -1;
-+ if (verdict < 0) {
-+ ret = false;
-+ break;
-+ }
-+ cur += fsl;
-+ }
-+ btrfs_put_block_group(bg);
-+ return ret;
-+}
-+
- /*
- * For the raid56 pad-to-full optimization: a sub-stripe write into a
- * stripe covered by a live stripe run may zero-fill (instead of read) any
-@@ -1070,6 +1311,13 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- u64 ps_start = 0;
- u64 ps_len = 0;
-
-+ /*
-+ * The fsync overwrite policy waives the log-window guarantee:
-+ * logged stripes may be extended and RMWed like before the
-+ * close-at-log-commit machinery existed.
-+ */
-+ if (btrfs_stripe_allow_rmw(fs_info) & BTRFS_STRIPE_RMW_FSYNC)
-+ return;
- if (list_empty_careful(&fs_info->open_stripe_bgs))
- return;
- bg = btrfs_lookup_block_group(fs_info, bytenr);
-@@ -1082,6 +1330,14 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
-
- if (bytenr < run->start || bytenr >= run->offset)
- continue;
-+ /*
-+ * A nodatacow file's logged extents get no fsync survival
-+ * guarantee -- the file's own later in-place writes can
-+ * always tear them -- so closing its run would trap the
-+ * tail for nothing.
-+ */
-+ if (run->class == BTRFS_STRIPE_RUN_NOCOW)
-+ break;
- flush_start = run->start;
- flush_len = run->end - run->start;
- /*
-@@ -1248,6 +1504,17 @@ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
- * writes are the bulk of stripe_alloc's read-modify-writes.
- */
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
-+{
-+ return btrfs_stripe_open_run_class(fs_info, logical, NULL);
-+}
-+
-+/*
-+ * Like btrfs_stripe_in_open_run(), also reporting the covering run's
-+ * class: the raid56 parking gate treats NOCOW-class runs specially
-+ * (sync writes into them never park; see rbio_try_park()).
-+ */
-+bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
-+ enum btrfs_stripe_run_class *class)
- {
- struct btrfs_block_group *bg;
- struct btrfs_open_stripe_run *run;
-@@ -1260,6 +1527,8 @@ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
- if (logical >= run->start && logical < run->end) {
-+ if (class)
-+ *class = run->class;
- ret = true;
- break;
- }
-@@ -1622,7 +1891,8 @@ void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
- if (!bg)
- return;
- if (!btrfs_is_stripe_alloc_bg(bg) ||
-- test_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED, &bg->runtime_flags))
-+ test_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED, &bg->runtime_flags) ||
-+ test_bit(BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED, &bg->runtime_flags))
- goto out;
- fsl = bg->full_stripe_len;
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 568c07929c578..412039daf6b8f 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -138,6 +138,14 @@ enum btrfs_block_group_flags {
- * counter must be rescanned at commit (stripe_alloc only).
- */
- BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY,
-+ /*
-+ * The group has hosted NOCOW-class stripe runs. With the
-+ * stripe_alloc_nocow policy, isolated nodatacow/prealloc extents
-+ * are legitimately overwritten in place after their runs drain, so
-+ * the write-hole debug check skips such groups (sticky, debug
-+ * only), like relocation above.
-+ */
-+ BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED,
- };
-
- enum btrfs_caching_type {
-@@ -423,11 +431,17 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
- void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
-+bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
-+ enum btrfs_stripe_run_class *class);
- bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- u64 run_start, u64 *run_len);
- bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- u64 stripe_start, u64 stripe_len,
- u64 *pad_from);
-+bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
-+ u64 num_bytes, u32 which);
-+int btrfs_parse_stripe_rmw(const char *value, size_t len, u32 *mask);
-+void btrfs_show_stripe_rmw(struct seq_file *seq, u32 mask);
- void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- u64 file_len, u64 bytenr, u64 num_bytes);
- int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
-diff --git a/fs/btrfs/defrag.c b/fs/btrfs/defrag.c
-index d383a5abe7e2b..918a82f6b9035 100644
---- a/fs/btrfs/defrag.c
-+++ b/fs/btrfs/defrag.c
-@@ -1392,6 +1392,9 @@ void btrfs_carry_log_tail(struct btrfs_inode *inode)
-
- if (!btrfs_test_opt(inode->root->fs_info, STRIPE_ALLOC))
- return;
-+ if (btrfs_stripe_allow_rmw(inode->root->fs_info) &
-+ BTRFS_STRIPE_RMW_FSYNC)
-+ return;
- if (!READ_ONCE(inode->log_carry))
- return;
- copy = kmalloc(sizeof(*copy), GFP_NOFS);
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 8aeed1040f14f..3d148310cecee 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4261,6 +4261,9 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- if (ret == -ENOMEM)
- return ret;
- if (!ret) {
-+ if (ffe_ctl->steer_class == BTRFS_STRIPE_RUN_NOCOW)
-+ set_bit(BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED,
-+ &block_group->runtime_flags);
- WRITE_ONCE(steer_inode->log_run_hint, offset);
- ffe_ctl->found_offset = offset;
- ffe_ctl->search_start = offset;
-diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
-index 577d2c0f6b73c..94eedf224daa8 100644
---- a/fs/btrfs/file.c
-+++ b/fs/btrfs/file.c
-@@ -1554,6 +1554,8 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
- * one fsync is taken as a signal that more will follow.
- */
- if (btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
-+ !(btrfs_stripe_allow_rmw(fs_info) &
-+ BTRFS_STRIPE_RMW_FSYNC) &&
- !test_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags))
- set_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags);
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index b085e198f23da..d126b9fab9349 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -283,6 +283,18 @@ enum {
- BTRFS_MOUNT_STRIPE_ALLOC = (1ULL << 34),
- };
-
-+/*
-+ * Cases in which stripe_alloc may permit the legacy unsafe RMW-in-place
-+ * (the write hole returns for the stripes such a write touches, confined
-+ * as each case's machinery allows). Set from the
-+ * btrfs.stripe_alloc_allow_rmw property.
-+ */
-+enum {
-+ BTRFS_STRIPE_RMW_NODATACOW = (1U << 0),
-+ BTRFS_STRIPE_RMW_PREALLOC = (1U << 1),
-+ BTRFS_STRIPE_RMW_FSYNC = (1U << 2),
-+};
-+
- /* These mount options require a full read-only fs, no new transaction is allowed. */
- #define BTRFS_MOUNT_FULL_RO_MASK \
- (BTRFS_MOUNT_NOLOGREPLAY | \
-@@ -792,6 +804,9 @@ struct btrfs_fs_info {
-
- u32 data_chunk_allocations;
- u32 metadata_ratio;
-+ /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
-+ u32 stripe_rmw_opt;
-+ u32 stripe_rmw_prop;
-
- /* Private scrub information */
- struct mutex scrub_lock;
-@@ -1204,6 +1219,14 @@ static inline int btrfs_need_cleaner_sleep(const struct btrfs_fs_info *fs_info)
- btrfs_fs_closing(fs_info);
- }
-
-+static inline u32 btrfs_stripe_allow_rmw(const struct btrfs_fs_info *fs_info)
-+{
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return 0;
-+ return READ_ONCE(fs_info->stripe_rmw_opt) |
-+ READ_ONCE(fs_info->stripe_rmw_prop);
-+}
-+
- static inline void btrfs_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
- {
- clear_and_wake_up_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags);
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index 0aaa5a568ba71..7a9cc1ba095c6 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -1877,9 +1877,18 @@ static int can_nocow_file_extent(struct btrfs_path *path,
- * data relocation inode is exempt: its preallocated extents live in
- * relocation-class stripe runs that never share stripes with other
- * data, and relocation depends on its writes landing in place.
-+ * With the stripe_alloc_nocow policy, an extent whose stripes are
-+ * isolated to this inode may be written in place after all: the
-+ * write hole it reintroduces can tear only the writing file's own
-+ * data, which is the nodatacow/prealloc contract.
- */
- if (!btrfs_is_data_reloc_root(root) &&
-- btrfs_stripe_alloc_forces_cow(root->fs_info, io_start))
-+ btrfs_stripe_alloc_forces_cow(root->fs_info, io_start) &&
-+ !btrfs_stripe_nocow_writable(inode, io_start,
-+ args->file_extent.num_bytes,
-+ extent_type == BTRFS_FILE_EXTENT_PREALLOC ?
-+ BTRFS_STRIPE_RMW_PREALLOC :
-+ BTRFS_STRIPE_RMW_NODATACOW))
- goto out;
-
- /*
-diff --git a/fs/btrfs/props.c b/fs/btrfs/props.c
-index 311c07cef6771..a09cc9481a696 100644
---- a/fs/btrfs/props.c
-+++ b/fs/btrfs/props.c
-@@ -422,6 +422,40 @@ static const char *prop_stripe_alloc_extract(const struct btrfs_inode *inode)
- return NULL;
- }
-
-+static int prop_stripe_rmw_validate(const struct btrfs_inode *inode,
-+ const char *value, size_t len)
-+{
-+ u32 mask;
-+
-+ if (!prop_stripe_alloc_scope_ok(inode))
-+ return -EINVAL;
-+ if (!value || len == 0)
-+ return 0;
-+ return btrfs_parse_stripe_rmw(value, len, &mask);
-+}
-+
-+static int prop_stripe_rmw_apply(struct btrfs_inode *inode,
-+ const char *value, size_t len)
-+{
-+ struct btrfs_fs_info *fs_info = inode->root->fs_info;
-+ u32 mask = 0;
-+
-+ /* Ignore stray copies; only the top-level root carries policy. */
-+ if (!prop_stripe_alloc_scope_ok(inode))
-+ return 0;
-+ if (value && len &&
-+ btrfs_parse_stripe_rmw(value, len, &mask))
-+ return -EINVAL;
-+ WRITE_ONCE(fs_info->stripe_rmw_prop, mask);
-+ return 0;
-+}
-+
-+static const char *prop_stripe_rmw_extract(const struct btrfs_inode *inode)
-+{
-+ /* Not inheritable; nothing regenerates the value from inode state. */
-+ return NULL;
-+}
-+
- static bool prop_stripe_alloc_ignore(const struct btrfs_inode *inode)
- {
- return false;
-@@ -458,6 +492,14 @@ static struct prop_handler prop_handlers[] = {
- .ignore = prop_stripe_alloc_ignore,
- .inheritable = 0
- },
-+ {
-+ .xattr_name = XATTR_BTRFS_PREFIX "stripe_alloc_allow_rmw",
-+ .validate = prop_stripe_rmw_validate,
-+ .apply = prop_stripe_rmw_apply,
-+ .extract = prop_stripe_rmw_extract,
-+ .ignore = prop_stripe_alloc_ignore,
-+ .inheritable = 0
-+ },
- };
-
- int btrfs_inode_inherit_props(struct btrfs_trans_handle *trans,
---
-2.47.3
-
--- /dev/null
+From 387b1af89ded50a341b2da77ee25fa3809e10ea1 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:50 -0400
+Subject: [RFC PATCH 19/85] btrfs: stripe_alloc: tunable park deadlines, and
+ say why padding declined
+To: linux-btrfs@vger.kernel.org
+
+The deadline constants are meant to be judged "from measurements rather
+than taste", but they are compile-time, so every data point costs a kernel
+build and a reboot. Measuring a buffered fill -- dd, no fsync, so nothing
+kicks the park and the backstop is the only exit -- found 1861 of 3984
+parks expiring at the 100ms deadline, which is precisely the no-waiter case
+the constant exists for and the one with no numbers behind it.
+
+Expose both deadlines as writable sysfs files, clamped to 60s because a
+parked rbio holds its stripe lock, with 0 disabling parking for that class
+(useful as an experiment in itself):
+
+ /sys/fs/btrfs/<uuid>/stripe_park_timeout_ms (default 100)
+ /sys/fs/btrfs/<uuid>/stripe_park_sync_timeout_ms (default 3)
+
+Add the counters the stats file cannot supply. rmw_reads counts only
+parked writes that still had to read, so it cannot answer "does this
+workload read-modify-write at all"; data_rmw counts every data RMW, which
+with allow_rmw empty on a covered block group is the number the
+stripe-exclusive claim is about, and it should be zero.
+
+And record why padding refused, because the reasons are different defects:
+the rest of the stripe is allocated and its data has not arrived yet
+(wait longer, or kick when the frontier advances); no open run covers the
+stripe, so the run closed before its own write went down; or the frontier
+never reached the stripe at all. Attributing them turns "some RMW
+remains" into a specific thing to fix.
+
+No behaviour change at the defaults.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 22 ++++++++++++++++++++--
+ fs/btrfs/disk-io.c | 2 ++
+ fs/btrfs/fs.h | 32 ++++++++++++++++++++++++++++++++
+ fs/btrfs/raid56.c | 28 ++++++++++++++++++++--------
+ fs/btrfs/sysfs.c | 37 +++++++++++++++++++++++++++++++++++++
+ 5 files changed, 111 insertions(+), 10 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index a2e7e8667b15e..a0c4bf74a4e42 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -975,14 +975,19 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ {
+ struct btrfs_block_group *bg;
+ struct btrfs_open_stripe_run *run;
++ atomic64_t *decline = NULL;
+ unsigned long flags;
+ bool ret = false;
+
+- if (list_empty_careful(&fs_info->open_stripe_bgs))
++ if (list_empty_careful(&fs_info->open_stripe_bgs)) {
++ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
+ return false;
++ }
+ bg = btrfs_lookup_block_group(fs_info, stripe_start);
+- if (!bg)
++ if (!bg) {
++ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
+ return false;
++ }
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+@@ -992,10 +997,23 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ run->offset < stripe_start + stripe_len) {
+ *pad_from = run->offset;
+ ret = true;
++ } else if (run->offset >= stripe_start + stripe_len) {
++ /*
++ * The frontier is past this stripe: every sector of
++ * it is allocated, so there is nothing dead to pad
++ * and the write is waiting on a neighbour's data.
++ */
++ decline = &fs_info->stripe_park_stats.pad_decline_live;
++ } else {
++ /* The frontier has not reached the stripe at all. */
++ decline = &fs_info->stripe_park_stats.pad_decline_unallocated;
+ }
+ break;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ if (!ret)
++ atomic64_inc(decline ? decline :
++ &fs_info->stripe_park_stats.pad_decline_no_run);
+ btrfs_put_block_group(bg);
+ return ret;
+ }
+diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
+index 28f360e84f110..0b23e576ed4ed 100644
+--- a/fs/btrfs/disk-io.c
++++ b/fs/btrfs/disk-io.c
+@@ -2805,6 +2805,8 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
+ INIT_LIST_HEAD(&fs_info->delalloc_roots);
+ INIT_LIST_HEAD(&fs_info->caching_block_groups);
+ INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
++ fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
++ fs_info->stripe_park_sync_timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
+ spin_lock_init(&fs_info->open_stripe_lock);
+ spin_lock_init(&fs_info->delalloc_root_lock);
+ spin_lock_init(&fs_info->trans_lock);
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 6c82782a8a7f5..9386ec918b530 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -500,6 +500,17 @@ struct btrfs_delayed_root {
+ struct btrfs_free_space_ctl;
+ struct btrfs_free_space;
+
++/*
++ * Default park deadlines, ms (sysfs stripe_park_{,sync_}timeout_ms). Sync
++ * writes (REQ_SYNC) have a waiter blocked on them, so their deadline is
++ * just long enough for the rest of one writeback pass over the stripe to
++ * merge in.
++ */
++#define BTRFS_RBIO_PARK_TIMEOUT_MS 100
++#define BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS 3
++/* Refuse absurd deadlines: a parked rbio holds its stripe lock. */
++#define BTRFS_RBIO_PARK_TIMEOUT_MS_MAX 60000
++
+ struct btrfs_fs_info {
+ u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
+ unsigned long flags;
+@@ -805,7 +816,28 @@ struct btrfs_fs_info {
+ atomic64_t kicked;
+ atomic64_t rmw_reads;
+ atomic64_t padded;
++ /*
++ * Data read-modify-writes in a covered block group, parked or
++ * not; zero with allow_rmw empty. rmw_reads counts only the
++ * parked ones.
++ */
++ atomic64_t data_rmw;
++ /*
++ * Why padding declined: live (the rest of the stripe is
++ * allocated and not yet written), no_run (no open run covers
++ * the stripe), unallocated (the run's frontier has not reached
++ * the stripe).
++ */
++ atomic64_t pad_decline_live;
++ atomic64_t pad_decline_no_run;
++ atomic64_t pad_decline_unallocated;
+ } stripe_park_stats;
++ /*
++ * Park deadlines, ms (sysfs); 0 disables parking for that class. See
++ * rbio_try_park().
++ */
++ u32 stripe_park_timeout_ms;
++ u32 stripe_park_sync_timeout_ms;
+
+ /* Private scrub information */
+ struct mutex scrub_lock;
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 2b54bb70f6d2f..b92712b13294b 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -67,8 +67,6 @@
+
+ #define RBIO_CACHE_SIZE 1024
+
+-#define BTRFS_RBIO_PARK_TIMEOUT_MS 100
+-#define BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS 3
+ /* Scan period of the park timer while anything is parked. */
+ #define BTRFS_RBIO_PARK_SCAN_MS 3
+
+@@ -735,16 +733,22 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ {
+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
+ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
+- unsigned int timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
++ const unsigned int sync_timeout_ms =
++ READ_ONCE(fs_info->stripe_park_sync_timeout_ms);
++ unsigned int timeout_ms = READ_ONCE(fs_info->stripe_park_timeout_ms);
+
+ if (!btrfs_stripe_in_open_run(fs_info, rbio->bioc->full_stripe_logical))
+ return false;
+
+ spin_lock(&rbio->bio_list_lock);
+ if (rbio_has_sync_bio(rbio))
+- timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
++ timeout_ms = sync_timeout_ms;
+ spin_unlock(&rbio->bio_list_lock);
+
++ /* A zeroed deadline disables parking for that class outright. */
++ if (timeout_ms == 0)
++ return false;
++
+ /*
+ * A sync rbio whose submission batch was already merged by its
+ * unplug callback has nothing more coming from its submitter; the
+@@ -754,7 +758,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ * path kicks it as soon as they have all been submitted.)
+ */
+ if (test_bit(RBIO_BATCH_DONE_BIT, &rbio->flags) &&
+- timeout_ms == BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS)
++ timeout_ms == sync_timeout_ms)
+ return false;
+
+ spin_lock(&table->parked_lock);
+@@ -1023,7 +1027,8 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
+ struct btrfs_stripe_hash_table *table =
+ cur->bioc->fs_info->stripe_hash_table;
+ unsigned long dl = jiffies +
+- msecs_to_jiffies(BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS);
++ msecs_to_jiffies(READ_ONCE(cur->bioc->fs_info->
++ stripe_park_sync_timeout_ms));
+
+ spin_lock(&table->parked_lock);
+ if (test_bit(RBIO_PARKED_BIT,
+@@ -2813,10 +2818,17 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ */
+ if (!rbio_is_full(rbio) && !rmw_try_pad_full(rbio) &&
+ need_read_stripe_sectors(rbio)) {
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++
++ /*
++ * Every data read-modify-write, parked or not. With
++ * allow_rmw empty and a covered block group this is the
++ * count that should be zero.
++ */
++ atomic64_inc(&fs_info->stripe_park_stats.data_rmw);
+ /* A parked-then-flushed write that still had to read. */
+ if (test_bit(RBIO_WAS_PARKED_BIT, &rbio->flags))
+- atomic64_inc(&rbio->bioc->fs_info->
+- stripe_park_stats.rmw_reads);
++ atomic64_inc(&fs_info->stripe_park_stats.rmw_reads);
+ /*
+ * Now we're doing sub-stripe write, also need all data stripes
+ * to do the full RMW.
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 7957754d80852..763eaff035e93 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1137,6 +1137,41 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ }
+ BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
+
++/*
++ * Park deadlines, ms; 0 disables parking for that class. See
++ * rbio_try_park().
++ */
++#define BTRFS_PARK_TIMEOUT_ATTR(_name, _field) \
++static ssize_t btrfs_##_name##_show(struct kobject *kobj, \
++ struct kobj_attribute *a, char *buf)\
++{ \
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj); \
++ \
++ return sysfs_emit(buf, "%u\n", READ_ONCE(fs_info->_field)); \
++} \
++static ssize_t btrfs_##_name##_store(struct kobject *kobj, \
++ struct kobj_attribute *a, \
++ const char *buf, size_t len) \
++{ \
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj); \
++ unsigned int val; \
++ int ret; \
++ \
++ ret = kstrtouint(buf, 10, &val); \
++ if (ret) \
++ return ret; \
++ if (val > BTRFS_RBIO_PARK_TIMEOUT_MS_MAX) \
++ return -EINVAL; \
++ WRITE_ONCE(fs_info->_field, val); \
++ return len; \
++} \
++BTRFS_ATTR_RW(, _name, btrfs_##_name##_show, btrfs_##_name##_store)
++
++BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
++BTRFS_PARK_TIMEOUT_ATTR(stripe_park_sync_timeout_ms, stripe_park_sync_timeout_ms);
++
++
++
+ static ssize_t btrfs_clone_alignment_show(struct kobject *kobj,
+ struct kobj_attribute *a, char *buf)
+ {
+@@ -1504,6 +1539,8 @@ static const struct attribute *btrfs_attrs[] = {
+ BTRFS_ATTR_PTR(, bg_reclaim_threshold),
+ BTRFS_ATTR_PTR(, commit_stats),
+ BTRFS_ATTR_PTR(, stripe_park_stats),
++ BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
++ BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
+ BTRFS_ATTR_PTR(, temp_fsid),
+ NULL,
+ };
+--
+2.47.3
+
+++ /dev/null
-From efce6f5f7eaa8a46e982e2b61d0acddec70c5f6a Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:41 -0400
-Subject: [RFC PATCH 020/116] btrfs: stripe_alloc: persist nocow runs across
- commits and remounts
-To: linux-btrfs@vger.kernel.org
-
-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.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 217 +++++++++++++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 9 +-
- fs/btrfs/extent-tree.c | 8 +-
- fs/btrfs/free-space-cache.c | 62 +++++++++++
- fs/btrfs/free-space-cache.h | 2 +
- fs/btrfs/inode.c | 1 +
- 6 files changed, 289 insertions(+), 10 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 88fcd964b7036..c7b21de26540e 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -487,6 +487,12 @@ void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
- * group has no runs left.
- */
-
-+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;
-@@ -792,13 +798,15 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- * 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;
-@@ -835,6 +843,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 +
-+ 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);
-@@ -848,6 +899,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
- goto out;
- }
-
-+install:
- /* See the installation comment in btrfs_alloc_from_open_stripe(). */
- spin_lock(&fs_info->open_stripe_lock);
- if (list_empty(&bg->open_stripe_bg_list)) {
-@@ -979,9 +1031,28 @@ void btrfs_show_stripe_rmw(struct seq_file *seq, u32 mask)
- * 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.
-+ *
-+ * @nowait must be set by callers that hold space_info->groups_sem, i.e.
-+ * anything reached from find_free_extent(). Blocking on an extent tree
-+ * lock there is a deadlock: 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 the
-+ * cycle. Both sides only read groups_sem, but it is an rw_semaphore and
-+ * block group add/remove take it for write, so a queued writer between the
-+ * two readers is enough. Reported by lockdep on a plain fallocate:
-+ *
-+ * rlock(&space_info->groups_sem) lock(btrfs-extent-01)
-+ * lock(&space_info->groups_sem)
-+ * rlock(btrfs-extent-01)
-+ *
-+ * With @nowait the search try-locks and returns -EAGAIN instead, which
-+ * lands in the error paths below as "not provably ours" -- the safe
-+ * answer, since every caller treats false as a reason to decline an
-+ * optimisation rather than as a fact about the extents.
- */
- 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;
-@@ -994,6 +1065,15 @@ 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 legal here (btrfs_search_slot()
-+ * asserts nowait is never combined with cow). It is honoured by the
-+ * whole walk below: search_slot try-locks the root node,
-+ * btrfs_previous_extent_item() reaches search_slot via
-+ * btrfs_prev_leaf(), and btrfs_next_leaf() passes time_seq 0 so its
-+ * ASSERT(!path->nowait) does not apply.
-+ */
-+ path->nowait = nowait;
-
- key.objectid = start;
- key.type = BTRFS_EXTENT_ITEM_KEY;
-@@ -1082,6 +1162,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:
-@@ -1147,8 +1229,15 @@ 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.
-+ */
- 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, false))
- verdict = -1;
- if (verdict < 0) {
- ret = false;
-@@ -1278,6 +1367,110 @@ static void log_carry_record(struct btrfs_inode *inode, u64 file_start,
- carry->nr_ranges++;
- }
-
-+/*
-+ * 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;
-+}
-+
-+/*
-+ * 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);
-+}
-+
- /*
- * A log commit is about to make the extent at [bytenr, bytenr + num_bytes)
- * durable. Once the log super lands, no later write may extend or RMW the
-@@ -1657,6 +1850,17 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
-
- if (!run->open || run->open_seq >= seq)
- continue;
-+ /*
-+ * A nodatacow inode's private run survives transaction
-+ * commits: its stripes hold only that inode's expendable
-+ * (write-hole-waived) data, so invariant I2 has nothing to
-+ * protect there, and closing would burn a stripe per commit
-+ * for a slowly appended nocow file. Forced quiescing
-+ * (read-only, removal, unmount: seq == U64_MAX) still closes
-+ * them, as does the owning inode's eviction.
-+ */
-+ if (run->class == BTRFS_STRIPE_RUN_NOCOW && seq != U64_MAX)
-+ continue;
- 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)
-@@ -1694,6 +1898,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->class == BTRFS_STRIPE_RUN_NOCOW && seq != U64_MAX)
-+ continue;
- if (run->open_seq < seq) {
- ret = false;
- break;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 412039daf6b8f..29cbf6f225329 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -415,10 +415,13 @@ 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);
-+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_done_run(struct btrfs_open_stripe_run *run,
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 3d148310cecee..dedee06848e24 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4256,8 +4256,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,
-+ ffe_ctl->num_bytes, ffe_ctl->hint_byte,
-+ &offset, &available);
- if (ret == -ENOMEM)
- return ret;
- if (!ret) {
-@@ -5036,6 +5037,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);
- }
- }
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 4a1db014b19b0..118fced160032 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2167,6 +2167,68 @@ static bool find_stripe_run_in_bitmap(struct btrfs_free_space_ctl *ctl,
- * Returns 0 on success, -ENOSPC if no aligned fully-free stripe is present
- * in this block group.
- */
-+/*
-+ * 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:
-+ * nothing else can consume free space inside a partially used stripe of a
-+ * stripe_alloc block group (allocations come only from claimed runs, and
-+ * runs claim only fully-free stripes), so the verify-then-remove sequence
-+ * cannot race with another consumer -- except a concurrent re-adoption by
-+ * the same inode, which this function's recount safely turns into one
-+ * winner and one -ENOSPC.
-+ */
-+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;
-+ u64 found = 0;
-+ struct rb_node *n;
-+
-+ 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);
-+ }
-+ spin_unlock(&ctl->tree_lock);
-+
-+ if (found != len)
-+ return -ENOSPC;
-+ return btrfs_remove_free_space(block_group, start, len);
-+}
-+
- int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- u64 want_bytes, u64 *start, u64 *len)
- {
-diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
-index 6bee1e7a7913c..1cff596a4900d 100644
---- a/fs/btrfs/free-space-cache.h
-+++ b/fs/btrfs/free-space-cache.h
-@@ -111,6 +111,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);
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index 7a9cc1ba095c6..d243e078435b5 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -5669,6 +5669,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 &&
---
-2.47.3
-
--- /dev/null
+From b7418073639203b116bc9ee2e125879e4cab1733 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:51 -0400
+Subject: [RFC PATCH 20/85] btrfs: stripe_alloc: trace why padding declined, at
+ the moment it declined
+To: linux-btrfs@vger.kernel.org
+
+The counters say how often padding refused and broadly why, but not what
+the run looked like when it happened, and reconstructing that from the
+extent tree afterwards cannot distinguish "the stripe was already
+allocated when this write arrived" from "it was allocated shortly after".
+Those want different fixes, so record the decision where it is made.
+
+Also count the second refusal, which had no counter at all: the oracle can
+allow padding and the sector walk still refuse, because a sector below the
+frontier is not covered by this write. That is the case where another
+allocation shares the stripe and its data is not in this rbio -- a
+different thing from the oracle finding the whole stripe allocated.
+
+The tracepoint carries the stripe, how much of it this write covers, the
+refusal reason, and the run's start/end/frontier/inflight, so a trace says
+directly whether the frontier had already run past the stripe when the
+write showed up.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 19 +++++++++++++++-
+ fs/btrfs/block-group.h | 23 ++++++++++++++++++-
+ fs/btrfs/fs.h | 6 +++++
+ fs/btrfs/raid56.c | 41 +++++++++++++++++++++++++++++----
+ include/trace/events/btrfs.h | 44 ++++++++++++++++++++++++++++++++++++
+ 5 files changed, 126 insertions(+), 7 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index a0c4bf74a4e42..c9efd4b522f3a 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -971,7 +971,8 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ */
+ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ u64 stripe_start, u64 stripe_len,
+- u64 *pad_from)
++ u64 *pad_from,
++ struct btrfs_stripe_pad_info *info)
+ {
+ struct btrfs_block_group *bg;
+ struct btrfs_open_stripe_run *run;
+@@ -979,6 +980,11 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ unsigned long flags;
+ bool ret = false;
+
++ if (info) {
++ memset(info, 0, sizeof(*info));
++ info->reason = BTRFS_STRIPE_PAD_NO_RUN;
++ }
++
+ if (list_empty_careful(&fs_info->open_stripe_bgs)) {
+ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
+ return false;
+@@ -993,6 +999,13 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+ if (stripe_start < run->start || stripe_start >= run->end)
+ continue;
++ if (info) {
++ info->run_start = run->start;
++ info->run_end = run->end;
++ info->run_offset = run->offset;
++ info->inflight_bytes = run->inflight_bytes;
++ info->reason = BTRFS_STRIPE_PAD_OK;
++ }
+ if (run->offset > stripe_start &&
+ run->offset < stripe_start + stripe_len) {
+ *pad_from = run->offset;
+@@ -1004,9 +1017,13 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ * and the write is waiting on a neighbour's data.
+ */
+ decline = &fs_info->stripe_park_stats.pad_decline_live;
++ if (info)
++ info->reason = BTRFS_STRIPE_PAD_LIVE;
+ } else {
+ /* The frontier has not reached the stripe at all. */
+ decline = &fs_info->stripe_park_stats.pad_decline_unallocated;
++ if (info)
++ info->reason = BTRFS_STRIPE_PAD_UNALLOCATED;
+ }
+ break;
+ }
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index fa0294ac0cf1a..4a14f24d4919b 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -429,9 +429,30 @@ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
+ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
+ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ u64 run_start, u64 *run_len);
++/*
++ * Why padding could or could not proceed, and the run state it was decided
++ * against, for the pad-decline trace.
++ */
++enum btrfs_stripe_pad_reason {
++ BTRFS_STRIPE_PAD_OK = 0,
++ BTRFS_STRIPE_PAD_NO_RUN, /* no open run covers the stripe */
++ BTRFS_STRIPE_PAD_LIVE, /* frontier past the stripe: all allocated */
++ BTRFS_STRIPE_PAD_UNALLOCATED, /* frontier has not reached the stripe */
++ BTRFS_STRIPE_PAD_UNCOVERED, /* a sector below the frontier is not covered */
++};
++
++struct btrfs_stripe_pad_info {
++ u64 run_start;
++ u64 run_end;
++ u64 run_offset; /* the allocation frontier */
++ u64 inflight_bytes;
++ u8 reason;
++};
++
+ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ u64 stripe_start, u64 stripe_len,
+- u64 *pad_from);
++ u64 *pad_from,
++ struct btrfs_stripe_pad_info *info);
+ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
+ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
+ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 9386ec918b530..1790cd2563b02 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -831,6 +831,12 @@ struct btrfs_fs_info {
+ atomic64_t pad_decline_live;
+ atomic64_t pad_decline_no_run;
+ atomic64_t pad_decline_unallocated;
++ /*
++ * Oracle allowed padding, but a sector below the frontier is
++ * not covered by this write: another allocation shares the
++ * stripe.
++ */
++ atomic64_t pad_decline_uncovered;
+ } stripe_park_stats;
+ /*
+ * Park deadlines, ms (sysfs); 0 disables parking for that class. See
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index b92712b13294b..e54f73cb641f4 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -2688,20 +2688,40 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ const u64 stripe_start = rbio->bioc->full_stripe_logical;
+ const u32 sectorsize = fs_info->sectorsize;
+ const u64 stripe_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
+- u64 pad_from;
++ struct btrfs_stripe_pad_info info;
++ const u32 total = rbio->nr_data * rbio->stripe_nsectors;
++ u64 pad_from = 0;
++ u32 covered = 0;
+ int i;
+
+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
+ return false;
+ if (!btrfs_stripe_run_pad_start(fs_info, stripe_start, stripe_len,
+- &pad_from))
++ &pad_from, &info)) {
++ trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
++ stripe_len, pad_from, 0, total,
++ info.run_start, info.run_end,
++ info.run_offset,
++ info.inflight_bytes,
++ info.reason);
+ return false;
++ }
+
+ /* Populate bio_paddrs so covered sectors are visible below. */
+ index_rbio_pages(rbio);
+
+- /* Every data sector this rbio does not cover must be paddable. */
+- for (i = 0; i < rbio->nr_data * rbio->stripe_nsectors; i++) {
++ /*
++ * Every data sector this rbio does not cover must be paddable. A
++ * sector below the frontier is allocated to someone else and this
++ * write does not carry its data, so padding would destroy it: that
++ * is a distinct refusal from the oracle's, and it is the one that
++ * says another writer's allocation shares this stripe.
++ */
++ for (i = 0; i < total; i++)
++ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
++ covered++;
++
++ for (i = 0; i < total; i++) {
+ const int stripe_nr = i / rbio->stripe_nsectors;
+ const int sectornr = i % rbio->stripe_nsectors;
+ u64 logical = stripe_start + stripe_nr * BTRFS_STRIPE_LEN +
+@@ -2709,8 +2729,19 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+
+ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
+ continue;
+- if (logical < pad_from)
++ if (logical < pad_from) {
++ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_uncovered);
++ info.reason = BTRFS_STRIPE_PAD_UNCOVERED;
++ trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
++ stripe_len, pad_from,
++ covered, total,
++ info.run_start,
++ info.run_end,
++ info.run_offset,
++ info.inflight_bytes,
++ info.reason);
+ return false;
++ }
+ }
+
+ if (alloc_rbio_data_pages(rbio) < 0)
+diff --git a/include/trace/events/btrfs.h b/include/trace/events/btrfs.h
+index e1af4dd8287ce..db541d70e9640 100644
+--- a/include/trace/events/btrfs.h
++++ b/include/trace/events/btrfs.h
+@@ -3299,6 +3299,50 @@ DEFINE_EVENT(btrfs__space_info_update, update_bytes_stripe_unusable,
+ TP_ARGS(fs_info, sinfo, old, diff)
+ );
+
++TRACE_EVENT(btrfs_stripe_pad_decline,
++
++ TP_PROTO(const struct btrfs_fs_info *fs_info, u64 full_stripe,
++ u64 stripe_len, u64 pad_from, u32 covered, u32 total,
++ u64 run_start, u64 run_end, u64 run_offset, u64 inflight,
++ u8 reason),
++
++ TP_ARGS(fs_info, full_stripe, stripe_len, pad_from, covered, total,
++ run_start, run_end, run_offset, inflight, reason),
++
++ TP_STRUCT__entry_btrfs(
++ __field( u64, full_stripe )
++ __field( u64, stripe_len )
++ __field( u64, pad_from )
++ __field( u64, run_start )
++ __field( u64, run_end )
++ __field( u64, run_offset )
++ __field( u64, inflight )
++ __field( u32, covered )
++ __field( u32, total )
++ __field( u8, reason )
++ ),
++
++ TP_fast_assign_btrfs(fs_info,
++ __entry->full_stripe = full_stripe;
++ __entry->stripe_len = stripe_len;
++ __entry->pad_from = pad_from;
++ __entry->run_start = run_start;
++ __entry->run_end = run_end;
++ __entry->run_offset = run_offset;
++ __entry->inflight = inflight;
++ __entry->covered = covered;
++ __entry->total = total;
++ __entry->reason = reason;
++ ),
++
++ TP_printk_btrfs(
++"full_stripe=%llu len=%llu covered=%u/%u reason=%u pad_from=%llu run=[%llu,%llu) frontier=%llu inflight=%llu",
++ __entry->full_stripe, __entry->stripe_len,
++ __entry->covered, __entry->total, __entry->reason,
++ __entry->pad_from, __entry->run_start, __entry->run_end,
++ __entry->run_offset, __entry->inflight)
++);
++
+ DECLARE_EVENT_CLASS(btrfs_raid56_bio,
+
+ TP_PROTO(const struct btrfs_raid_bio *rbio,
+--
+2.47.3
+
+++ /dev/null
-From ddcf7587cde779f7f02de4e59be48768ad92b0fc Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:42 -0400
-Subject: [RFC PATCH 021/116] btrfs: raid56: do not park sync writes into nocow
- runs
-To: linux-btrfs@vger.kernel.org
-
-An in-place overwrite of a nodatacow file under stripe_alloc parked
-like any partial write, but with a waiter behind it and nothing worth
-merging: in-place overwrites arrive one fsync at a time, and unlike
-the datacow fsync path nothing kicks the parked rbio before the page
-writeback wait, so every fsync ate the full sync park deadline.
-Measured against stock nodatacow on the same rig, that deadline was
-the bulk of a ~3.7ms per-fsync regression. Skip parking for sync
-writes whose stripe belongs to a NOCOW-class run; async writeback
-still parks and merges there.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/raid56.c | 16 +++++++++++++++-
- 1 file changed, 15 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 30c664babecd3..eeeef54635e60 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -784,8 +784,11 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
- struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
- unsigned int timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
-+ enum btrfs_stripe_run_class class;
-
-- if (!btrfs_stripe_in_open_run(fs_info, rbio->bioc->full_stripe_logical))
-+ if (!btrfs_stripe_open_run_class(fs_info,
-+ rbio->bioc->full_stripe_logical,
-+ &class))
- return false;
-
- spin_lock(&rbio->bio_list_lock);
-@@ -793,6 +796,17 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
- spin_unlock(&rbio->bio_list_lock);
-
-+ /*
-+ * A sync write into a nodatacow inode's private run has a waiter
-+ * behind it and nothing worth waiting to merge with: in-place
-+ * overwrites arrive one fsync at a time, and the plain (unparked)
-+ * write path is what stock nodatacow latency looks like. Park only
-+ * async writeback there.
-+ */
-+ if (class == BTRFS_STRIPE_RUN_NOCOW &&
-+ timeout_ms == BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS)
-+ return false;
-+
- spin_lock(&table->parked_lock);
- set_bit(RBIO_PARKED_BIT, &rbio->flags);
- rbio->park_deadline = jiffies + msecs_to_jiffies(timeout_ms);
---
-2.47.3
-
--- /dev/null
+From 6820ba5fd5d604cec20c20bd0d632ddc9337b2d7 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:52 -0400
+Subject: [RFC PATCH 21/85] btrfs: stripe_alloc: complete parked writes on
+ allocation coverage, not clocks
+To: linux-btrfs@vger.kernel.org
+
+A parked partial-stripe write goes down its RMW path when its deadline
+expires or a retirement flush kicks it, even when every byte it is
+missing below the run's frontier belongs to an allocation whose data IO
+is already in flight -- allocation happens at writeback submission, and
+the commit's retirement drain waits for exactly those arrivals. Timing
+out such a park buys nothing and costs a stripe read plus a second write
+of the same stripe: measured on an 8-device raid5 buffered fill, the
+100ms deadline turns ~2200 parked stripes per 2GB into read-modify-
+writes (pad_decline_live), and stretching the clock 20x recovers only
+14% -- the clock is the wrong instrument.
+
+Replace the clock with a coverage test. A parked rbio is ready when its
+gathered bios cover everything the covering run has allocated inside its
+stripe (btrfs_stripe_run_alloc_ceiling); the remainder lies at or past
+the frontier, so the existing pad turns it into a single full-stripe
+write with no read phase. Merges check readiness as they land, the park
+timer holds unready parks instead of expiring them, and run-retirement
+flushes leave unready parks parked: the retirement has already closed
+the run (freezing the allocated prefix) and its drain waits on the very
+arrivals that will complete them. Waiter-driven flushes (fsync's
+pre-writeback kick, ordered-extent waits) and sync parks keep today's
+forced behaviour: a blocked waiter's latency beats a saved stripe read.
+
+A stuck cap (10x the park deadline) bounds the wait when an arrival can
+never come: a writeback error abandoned the allocation, or the stripe
+was already written once by a forced sync park. Such parks are forced
+down the old path and counted.
+
+New sysfs stripe_park_stats counters: unparked_ready (parks completed by
+the coverage test) and stuck (parks forced at the cap).
+
+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 | 41 +++++++++++++++-
+ fs/btrfs/block-group.h | 2 +
+ fs/btrfs/file.c | 3 +-
+ fs/btrfs/fs.h | 12 +++++
+ fs/btrfs/ordered-data.c | 2 +-
+ fs/btrfs/raid56.c | 101 ++++++++++++++++++++++++++++++++++++----
+ fs/btrfs/raid56.h | 4 +-
+ fs/btrfs/sysfs.c | 4 ++
+ 8 files changed, 155 insertions(+), 14 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index c9efd4b522f3a..4da736937cae8 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -969,6 +969,43 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ * later allocation's write serializes behind the caller's stripe lock
+ * and overwrites the zeros.
+ */
++/*
++ * How far has the covering run allocated into this stripe? Returns the
++ * exclusive end of the allocated prefix, clamped to the stripe, or U64_MAX
++ * when no run covers the stripe (nothing left to wait for; the caller
++ * proceeds as if the stripe were fully allocated and fully arrived).
++ * A partial write below the returned ceiling is waiting on neighbours whose
++ * data IO is already in flight -- allocation happens at writeback submission
++ * and the run's inflight accounting makes the commit wait for it -- so a
++ * parked rbio covering [stripe_start, ceiling) can complete (padding the
++ * dead tail), and one that does not should keep waiting for merges.
++ */
++u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
++ u64 stripe_start, u64 stripe_len)
++{
++ struct btrfs_block_group *bg;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ u64 ceiling = U64_MAX;
++
++ if (list_empty_careful(&fs_info->open_stripe_bgs))
++ return U64_MAX;
++ bg = btrfs_lookup_block_group(fs_info, stripe_start);
++ if (!bg)
++ return U64_MAX;
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (stripe_start < run->start || stripe_start >= run->end)
++ continue;
++ ceiling = clamp(run->offset, stripe_start,
++ stripe_start + stripe_len);
++ break;
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ btrfs_put_block_group(bg);
++ return ceiling;
++}
++
+ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ u64 stripe_start, u64 stripe_len,
+ u64 *pad_from,
+@@ -1372,7 +1409,7 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
+
+ close_block_group_stripe_runs(bg, U64_MAX);
+ /* Parked partial-stripe rbios hold the very bios the wait drains. */
+- btrfs_flush_parked_rbios(bg->fs_info, bg->start, bg->length);
++ btrfs_flush_parked_rbios(fs_info, bg->start, bg->length, false);
+ wait_var_event(&bg->open_stripe_runs,
+ bg_open_stripes_settled(bg, U64_MAX) ||
+ BTRFS_FS_ERROR(fs_info));
+@@ -1442,7 +1479,7 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
+ * A racing park that saw its run still open lands after this flush
+ * and is bounded by the park timer, not by us.
+ */
+- btrfs_flush_parked_rbios(fs_info, 0, U64_MAX);
++ btrfs_flush_parked_rbios(fs_info, 0, U64_MAX, false);
+
+ while (!list_empty(&retire_list)) {
+ bg = list_first_entry(&retire_list, struct btrfs_block_group,
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 4a14f24d4919b..a93483a270d67 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -449,6 +449,8 @@ struct btrfs_stripe_pad_info {
+ u8 reason;
+ };
+
++u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
++ u64 stripe_start, u64 stripe_len);
+ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ u64 stripe_start, u64 stripe_len,
+ u64 *pad_from,
+diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
+index 4d1cedc3ecb7c..9cbed3978a392 100644
+--- a/fs/btrfs/file.c
++++ b/fs/btrfs/file.c
+@@ -1669,7 +1669,8 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
+ if (tmp_oe->disk_num_bytes)
+ btrfs_flush_parked_rbios(fs_info,
+ tmp_oe->disk_bytenr,
+- tmp_oe->disk_num_bytes);
++ tmp_oe->disk_num_bytes,
++ true);
+ }
+
+ ret = filemap_fdatawait_range(inode->vfs_inode.i_mapping, start, end);
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 1790cd2563b02..bbb03936df650 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -812,8 +812,20 @@ struct btrfs_fs_info {
+ atomic64_t parked;
+ atomic64_t merged_bytes;
+ atomic64_t filled;
++ /*
++ * Parks released because their write covers everything the
++ * run has allocated in the stripe -- the rest is dead space
++ * the pad fills; nothing was worth waiting for.
++ */
++ atomic64_t unparked_ready;
+ atomic64_t expired;
+ atomic64_t kicked;
++ /*
++ * Parks forced down past the stuck cap while still missing
++ * allocated neighbours: an arrival never came (writeback
++ * error, or a stripe written twice by a forced sync park).
++ */
++ atomic64_t stuck;
+ atomic64_t rmw_reads;
+ atomic64_t padded;
+ /*
+diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
+index 44122090fe4f4..e0dccad6f22a9 100644
+--- a/fs/btrfs/ordered-data.c
++++ b/fs/btrfs/ordered-data.c
+@@ -938,7 +938,7 @@ void btrfs_start_ordered_extent_nowriteback(struct btrfs_ordered_extent *entry,
+ !test_bit(BTRFS_ORDERED_COMPLETE, &entry->flags)) {
+ btrfs_flush_parked_rbios(inode->root->fs_info,
+ entry->disk_bytenr,
+- entry->disk_num_bytes);
++ entry->disk_num_bytes, true);
+ if (wait_event_timeout(entry->wait,
+ test_bit(BTRFS_ORDERED_COMPLETE,
+ &entry->flags),
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index e54f73cb641f4..da8abb516afb8 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -65,6 +65,13 @@
+ /* Set at park time and never cleared: this rbio once parked (stats). */
+ #define RBIO_WAS_PARKED_BIT 7
+
++/*
++ * Set when a parked rbio carries (or merged) a REQ_SYNC bio: a waiter
++ * is blocked on it, so deadlines stay authoritative and neither the
++ * timer nor a flush may hold it back to wait for neighbours.
++ */
++#define RBIO_SYNC_PARK_BIT 8
++
+ #define RBIO_CACHE_SIZE 1024
+
+ /* Scan period of the park timer while anything is parked. */
+@@ -544,7 +551,7 @@ void btrfs_stop_parked_rbios(struct btrfs_fs_info *fs_info)
+ if (!table || !fs_info->rmw_workers)
+ return;
+ for (int i = 0; i < 3 && !list_empty_careful(&table->parked); i++) {
+- btrfs_flush_parked_rbios(fs_info, 0, U64_MAX);
++ btrfs_flush_parked_rbios(fs_info, 0, U64_MAX, true);
+ flush_workqueue(fs_info->rmw_workers);
+ }
+ cancel_delayed_work_sync(&table->parked_work);
+@@ -723,6 +730,29 @@ static bool rbio_has_sync_bio(struct btrfs_raid_bio *rbio)
+ return false;
+ }
+
++/*
++ * A parked rbio is ready to go down when its gathered bios cover every
++ * byte the covering run has allocated in its stripe: the remainder lies
++ * at or past the frontier and the pad turns it into a full-stripe write.
++ * Anything less is waiting on an allocated neighbour whose data IO is
++ * already in flight, so waiting is bounded and reading (RMW) is waste.
++ * bio_list_bytes is read unlocked: merges only grow it, and a stale low
++ * value just delays readiness by one scan tick.
++ */
++static bool parked_rbio_ready(struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ const u64 stripe_start = rbio->bioc->full_stripe_logical;
++ const u64 stripe_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
++ u64 ceiling;
++
++ ceiling = btrfs_stripe_run_alloc_ceiling(fs_info, stripe_start,
++ stripe_len);
++ if (ceiling == U64_MAX)
++ return true;
++ return READ_ONCE(rbio->bio_list_bytes) >= ceiling - stripe_start;
++}
++
+ /*
+ * Park a partial write rbio that owns its stripe lock, if its stripe is
+ * covered by an open stripe run. Returns true if the rbio was parked (or
+@@ -764,7 +794,11 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ spin_lock(&table->parked_lock);
+ set_bit(RBIO_PARKED_BIT, &rbio->flags);
+ set_bit(RBIO_WAS_PARKED_BIT, &rbio->flags);
++ if (timeout_ms == sync_timeout_ms)
++ set_bit(RBIO_SYNC_PARK_BIT, &rbio->flags);
+ rbio->park_deadline = jiffies + msecs_to_jiffies(timeout_ms);
++ rbio->park_stuck_deadline = jiffies +
++ msecs_to_jiffies(timeout_ms * 10);
+ /*
+ * Take a reference of our own before publishing: once parked_lock is
+ * dropped, a flusher can unpark this rbio and run it to completion,
+@@ -809,7 +843,8 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ * write. Callers may hold the stripe hash and bio_list locks; parked_lock
+ * nests inside both.
+ */
+-static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
++static void unpark_ready_rbio(struct btrfs_raid_bio *rbio,
++ atomic64_t *counter)
+ {
+ struct btrfs_stripe_hash_table *table =
+ rbio->bioc->fs_info->stripe_hash_table;
+@@ -821,7 +856,7 @@ static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
+ }
+ rbio_unpark_locked(rbio);
+ spin_unlock(&table->parked_lock);
+- atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.filled);
++ atomic64_inc(counter);
+ start_async_work(rbio, rmw_rbio_work_locked);
+ }
+
+@@ -831,7 +866,7 @@ static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
+ * ordered-extent waiters, and the park timer.
+ */
+ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
+- u64 num_bytes)
++ u64 num_bytes, bool force)
+ {
+ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
+ struct btrfs_raid_bio *rbio;
+@@ -848,6 +883,17 @@ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
+ if (rbio_start + rbio_len <= start ||
+ (num_bytes != U64_MAX && rbio_start >= start + num_bytes))
+ continue;
++ /*
++ * A run-retirement flush precedes the commit's IO drain,
++ * which waits for the very arrivals this rbio is missing:
++ * leave it parked and the arrivals will complete it (the
++ * run is closed, so its allocated prefix is frozen). Only
++ * waiter-driven flushes (fsync, ordered-extent waits) force
++ * an incomplete stripe down, and sync parks always go.
++ */
++ if (!force && !test_bit(RBIO_SYNC_PARK_BIT, &rbio->flags) &&
++ !parked_rbio_ready(rbio))
++ continue;
+ rbio_unpark_locked(rbio);
+ list_add_tail(&rbio->parked_node, &flush);
+ }
+@@ -878,14 +924,35 @@ static void parked_rbios_timeout_work(struct work_struct *work)
+ rearm = true;
+ continue;
+ }
++ /*
++ * Past the deadline but still missing allocated
++ * neighbours: their data IO is in flight, so expiring
++ * now would read (RMW) what a short wait merges for
++ * free. Hold the park up to the stuck cap -- the cap
++ * only fires when an arrival never comes (writeback
++ * error, or a stripe already written once by a forced
++ * sync park).
++ */
++ if (!test_bit(RBIO_SYNC_PARK_BIT, &rbio->flags) &&
++ time_before(jiffies, rbio->park_stuck_deadline) &&
++ !parked_rbio_ready(rbio)) {
++ rearm = true;
++ continue;
++ }
+ rbio_unpark_locked(rbio);
+ list_add_tail(&rbio->parked_node, &flush);
+ }
+ spin_unlock(&table->parked_lock);
+
+ list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
++ struct btrfs_fs_info *ffs = rbio->bioc->fs_info;
++
+ list_del_init(&rbio->parked_node);
+- atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.expired);
++ if (!test_bit(RBIO_SYNC_PARK_BIT, &rbio->flags) &&
++ time_after_eq(jiffies, rbio->park_stuck_deadline))
++ atomic64_inc(&ffs->stripe_park_stats.stuck);
++ else
++ atomic64_inc(&ffs->stripe_park_stats.expired);
+ start_async_work(rbio, rmw_rbio_work_locked);
+ }
+ if (rearm)
+@@ -1020,9 +1087,21 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
+ * this stripe.
+ */
+ if (test_bit(RBIO_PARKED_BIT, &cur->flags)) {
++ struct btrfs_fs_info *cfs =
++ cur->bioc->fs_info;
++
+ if (cur->bio_list_bytes ==
+ cur->nr_data * cur->bioc->stripe_len) {
+- unpark_full_rbio(cur);
++ unpark_ready_rbio(cur,
++ &cfs->stripe_park_stats.filled);
++ } else if (parked_rbio_ready(cur)) {
++ /*
++ * This merge completed the allocated
++ * prefix; the rest of the stripe is
++ * dead space the pad fills.
++ */
++ unpark_ready_rbio(cur,
++ &cfs->stripe_park_stats.unparked_ready);
+ } else if (sync) {
+ struct btrfs_stripe_hash_table *table =
+ cur->bioc->fs_info->stripe_hash_table;
+@@ -1032,9 +1111,13 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
+
+ spin_lock(&table->parked_lock);
+ if (test_bit(RBIO_PARKED_BIT,
+- &cur->flags) &&
+- time_before(dl, cur->park_deadline))
+- cur->park_deadline = dl;
++ &cur->flags)) {
++ set_bit(RBIO_SYNC_PARK_BIT,
++ &cur->flags);
++ if (time_before(dl,
++ cur->park_deadline))
++ cur->park_deadline = dl;
++ }
+ spin_unlock(&table->parked_lock);
+ }
+ }
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index 1dc9608587ff7..e7ccc20365bf7 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -138,6 +138,8 @@ struct btrfs_raid_bio {
+ */
+ struct list_head parked_node;
+ unsigned long park_deadline;
++ /* Hard cap on completion-waiting (see parked_rbio_ready()). */
++ unsigned long park_stuck_deadline;
+
+ /* Flags that tell us if it is safe to merge with this bio. */
+ unsigned long flags;
+@@ -292,7 +294,7 @@ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
+ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
+ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
+ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
+- u64 num_bytes);
++ u64 num_bytes, bool force);
+ void btrfs_stop_parked_rbios(struct btrfs_fs_info *fs_info);
+
+ #endif
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 763eaff035e93..276617501ee05 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1123,15 +1123,19 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "parked %lld\n"
+ "merged_bytes %lld\n"
+ "filled %lld\n"
++ "unparked_ready %lld\n"
+ "kicked %lld\n"
+ "expired %lld\n"
++ "stuck %lld\n"
+ "padded %lld\n"
+ "rmw_reads %lld\n",
+ atomic64_read(&fs_info->stripe_park_stats.parked),
+ atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
+ atomic64_read(&fs_info->stripe_park_stats.filled),
++ atomic64_read(&fs_info->stripe_park_stats.unparked_ready),
+ atomic64_read(&fs_info->stripe_park_stats.kicked),
+ atomic64_read(&fs_info->stripe_park_stats.expired),
++ atomic64_read(&fs_info->stripe_park_stats.stuck),
+ atomic64_read(&fs_info->stripe_park_stats.padded),
+ atomic64_read(&fs_info->stripe_park_stats.rmw_reads));
+ }
+--
+2.47.3
+
+++ /dev/null
-From 9218820fa26e920552140a8015c978c674b13bb6 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:43 -0400
-Subject: [RFC PATCH 022/116] btrfs: raid56: expose parking statistics in sysfs
-To: linux-btrfs@vger.kernel.org
-
-/sys/fs/btrfs/<uuid>/stripe_park_stats reports lifetime counters for
-the parking machinery: rbios parked, bytes merged into parked rbios,
-and how each park ended (filled to a full stripe, kicked by a waiter or
-a settle/retire flush, or expired at its deadline), plus how many
-flushed writes were padded to full stripes versus still needing the
-RMW read phase. The filled/kicked/expired split shows directly whether
-the deadlines are sized right for a given system -- expired parks that
-later reappear as rmw_reads are the batching the window failed to
-capture -- so any future retuning (or an adaptive deadline) can argue
-from measurements instead of taste.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/fs.h | 14 ++++++++++++++
- fs/btrfs/raid56.c | 16 ++++++++++++++++
- fs/btrfs/sysfs.c | 24 ++++++++++++++++++++++++
- 3 files changed, 54 insertions(+)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index d126b9fab9349..fab55620af0e9 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -804,6 +804,20 @@ struct btrfs_fs_info {
-
- u32 data_chunk_allocations;
- u32 metadata_ratio;
-+
-+ /*
-+ * raid56 parking observability (see rbio_try_park()): lifetime
-+ * counters exposed through sysfs stripe_park_stats.
-+ */
-+ struct {
-+ atomic64_t parked;
-+ atomic64_t merged_bytes;
-+ atomic64_t filled;
-+ atomic64_t expired;
-+ atomic64_t kicked;
-+ atomic64_t rmw_reads;
-+ atomic64_t padded;
-+ } stripe_park_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
- u32 stripe_rmw_prop;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index eeeef54635e60..4f3968313f501 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -55,6 +55,9 @@
- */
- #define RBIO_PADDED_BIT 5
-
-+/* Set at park time and never cleared: this rbio once parked (stats). */
-+#define RBIO_WAS_PARKED_BIT 7
-+
- #define RBIO_CACHE_SIZE 1024
-
- /*
-@@ -498,6 +501,9 @@ static void steal_rbio(struct btrfs_raid_bio *src, struct btrfs_raid_bio *dest)
- static void merge_rbio(struct btrfs_raid_bio *dest,
- struct btrfs_raid_bio *victim)
- {
-+ if (test_bit(RBIO_PARKED_BIT, &dest->flags))
-+ atomic64_add(victim->bio_list_bytes,
-+ &dest->bioc->fs_info->stripe_park_stats.merged_bytes);
- bio_list_merge_init(&dest->bio_list, &victim->bio_list);
- dest->bio_list_bytes += victim->bio_list_bytes;
- /* Also inherit the bitmaps from @victim. */
-@@ -809,6 +815,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
-
- spin_lock(&table->parked_lock);
- set_bit(RBIO_PARKED_BIT, &rbio->flags);
-+ set_bit(RBIO_WAS_PARKED_BIT, &rbio->flags);
- rbio->park_deadline = jiffies + msecs_to_jiffies(timeout_ms);
- /*
- * Take a reference of our own before publishing. The moment
-@@ -827,6 +834,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- refcount_inc(&rbio->refs);
- list_add_tail(&rbio->parked_node, &table->parked);
- spin_unlock(&table->parked_lock);
-+ atomic64_inc(&fs_info->stripe_park_stats.parked);
- queue_delayed_work(system_percpu_wq, &table->parked_work,
- msecs_to_jiffies(BTRFS_RBIO_PARK_SCAN_MS));
-
-@@ -872,6 +880,7 @@ static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
- }
- rbio_unpark_locked(rbio);
- spin_unlock(&table->parked_lock);
-+ atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.filled);
- start_async_work(rbio, rmw_rbio_work_locked);
- }
-
-@@ -905,6 +914,7 @@ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
-
- list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
- list_del_init(&rbio->parked_node);
-+ atomic64_inc(&fs_info->stripe_park_stats.kicked);
- start_async_work(rbio, rmw_rbio_work_locked);
- }
- }
-@@ -934,6 +944,7 @@ static void parked_rbios_timeout_work(struct work_struct *work)
-
- list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
- list_del_init(&rbio->parked_node);
-+ atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.expired);
- start_async_work(rbio, rmw_rbio_work_locked);
- }
- if (rearm)
-@@ -2787,6 +2798,7 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- set_bit(RBIO_PADDED_BIT, &rbio->flags);
- /* The whole stripe goes out: every vertical position is written. */
- bitmap_set(&rbio->dbitmap, 0, rbio->stripe_nsectors);
-+ atomic64_inc(&fs_info->stripe_park_stats.padded);
- return true;
- }
-
-@@ -2856,6 +2868,10 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- */
- if (!rbio_is_full(rbio) && !rmw_try_pad_full(rbio) &&
- need_read_stripe_sectors(rbio)) {
-+ /* A parked-then-flushed write that still had to read. */
-+ if (test_bit(RBIO_WAS_PARKED_BIT, &rbio->flags))
-+ atomic64_inc(&rbio->bioc->fs_info->
-+ stripe_park_stats.rmw_reads);
- /*
- * Now we're doing sub-stripe write, also need all data stripes
- * to do the full RMW.
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 357c669e6ea15..a36754036846b 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1109,6 +1109,29 @@ static ssize_t btrfs_commit_stats_store(struct kobject *kobj,
- }
- BTRFS_ATTR_RW(, commit_stats, btrfs_commit_stats_show, btrfs_commit_stats_store);
-
-+static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
-+ struct kobj_attribute *a, char *buf)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+
-+ return sysfs_emit(buf,
-+ "parked %lld\n"
-+ "merged_bytes %lld\n"
-+ "filled %lld\n"
-+ "kicked %lld\n"
-+ "expired %lld\n"
-+ "padded %lld\n"
-+ "rmw_reads %lld\n",
-+ atomic64_read(&fs_info->stripe_park_stats.parked),
-+ atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
-+ atomic64_read(&fs_info->stripe_park_stats.filled),
-+ atomic64_read(&fs_info->stripe_park_stats.kicked),
-+ atomic64_read(&fs_info->stripe_park_stats.expired),
-+ atomic64_read(&fs_info->stripe_park_stats.padded),
-+ atomic64_read(&fs_info->stripe_park_stats.rmw_reads));
-+}
-+BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
-+
- static ssize_t btrfs_clone_alignment_show(struct kobject *kobj,
- struct kobj_attribute *a, char *buf)
- {
-@@ -1475,6 +1498,7 @@ static const struct attribute *btrfs_attrs[] = {
- BTRFS_ATTR_PTR(, read_policy),
- BTRFS_ATTR_PTR(, bg_reclaim_threshold),
- BTRFS_ATTR_PTR(, commit_stats),
-+ BTRFS_ATTR_PTR(, stripe_park_stats),
- BTRFS_ATTR_PTR(, temp_fsid),
- NULL,
- };
---
-2.47.3
-
--- /dev/null
+From ac7145c02402d97f770bed05d22d3fa320599eaf Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:53 -0400
+Subject: [RFC PATCH 22/85] btrfs: stripe_alloc: track per-sector liveness and
+ pad from the map
+To: linux-btrfs@vger.kernel.org
+
+Padding used to ask where the run's allocation frontier was, which
+cannot see an allocation abandoned below it -- a reservation released, an
+allocation the finder discarded, an extent freed before its write was
+ever issued. Runs now carry a bit per sector, set at allocation and
+cleared by the new btrfs_open_stripe_write_abandoned() report, and
+padding fills exactly the sectors that are dead: this replaces
+btrfs_stripe_run_pad_start() with btrfs_stripe_run_pad_mask(). The map
+is sized once, with headroom for frontier growth, because the growth
+path holds the run lock where nothing may sleep; a run that would
+outgrow its map stops growing instead. A closed run's final stripe
+overhangs its shrunk end by construction, and those sectors -- the
+returned tail, unclaimable while the stripe holds live data -- are dead
+and paddable too.
+
+The abandonment report is what closes a writeback ENOSPC race the
+fsync-heavy near-full workload hits: an allocation undone without a
+report left phantom inflight bytes and phantom-live sectors, and
+reservations admitted against that state failed at writeback
+(cow_file_range -28) where stock refuses the write() up front. With
+the report in place the same workload shows zero writeback failures at
+every reservation margin setting, including margin disabled.
+
+Claiming also learns an O(1) fast fail: the by-size index walk is
+extracted into find_free_stripe_run(), stopping at the first entry whose
+largest contiguous free run cannot hold a full stripe -- near-full, where
+free space degenerates into many sub-stripe holes, this replaces a scan
+of the whole tree on every allocation.
+
+Moved out of the stripe_meta patch, which needs all of this for tree
+blocks but introduced it tangled with the metadata machinery; data wants
+it on its own.
+
+A parked rbio does not wait for sectors whose write will never come: a
+sector the liveness map has as dead is not counted as missing.
+
+The O(1) fast fail extends to the failed-scan bound: claims stop at once
+in a group whose last exhaustive scan proved there is no claimable run,
+until free space is added.
+
+With padding decided by the liveness map, the LIVE and UNALLOCATED pad
+refusal reasons, which only the frontier oracle produced, go; padding now
+declines only for NO_RUN and UNCOVERED.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 262 ++++++++++++++++++++++++++++++------
+ fs/btrfs/block-group.h | 11 +-
+ fs/btrfs/extent-tree.c | 8 +-
+ fs/btrfs/free-space-cache.c | 161 +++++++++++++---------
+ fs/btrfs/raid56.c | 64 ++++-----
+ 5 files changed, 365 insertions(+), 141 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 4da736937cae8..7d94bafac685c 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -495,6 +495,14 @@ struct btrfs_open_stripe_run {
+ u64 owner; /* LOG class: btrfs_ino of the owner */
+ enum btrfs_stripe_run_class class;
+ bool open; /* accepting allocations */
++ /*
++ * One bit per sector of the run, set while the sector holds an
++ * allocation someone still intends to write. Padding uses it to find
++ * dead sectors below the frontier (allocations abandoned before they
++ * were written), which are as safe to zero-fill as space above it.
++ */
++ unsigned long *live;
++ u32 live_nbits; /* sectors @live covers; caps growth */
+ };
+
+ static bool open_stripe_run_drained(const struct btrfs_open_stripe_run *run)
+@@ -521,12 +529,72 @@ static int stripe_run_band(const struct btrfs_block_group *bg, u64 remaining)
+ return band;
+ }
+
++/*
++ * Growth headroom for a run's liveness map, in full stripes.
++ *
++ * The map is sized once and never reallocated, because the only place a run
++ * grows -- the growable frontier in btrfs_alloc_from_open_stripe() -- holds
++ * bg->stripe_run_lock with interrupts disabled, where nothing may sleep.
++ * Sizing it beyond the run's initial span is what lets that path work at
++ * all; a run that would outgrow its map stops growing instead, and the
++ * allocation opens a fresh run.
++ */
++#define BTRFS_STRIPE_RUN_LIVE_STRIPES 32
++
++/*
++ * Allocate a run's liveness map. Must be called before taking
++ * bg->stripe_run_lock: this sleeps. Sets *nbits to what the map covers.
++ */
++static unsigned long *alloc_run_live_map(struct btrfs_block_group *bg,
++ u64 run_len, u32 *nbits)
++{
++ const u64 span = max_t(u64, run_len,
++ (u64)BTRFS_STRIPE_RUN_LIVE_STRIPES *
++ bg->full_stripe_len);
++ unsigned long *map;
++
++ *nbits = span >> bg->fs_info->sectorsize_bits;
++ map = bitmap_zalloc(*nbits, GFP_NOFS);
++ if (!map)
++ *nbits = 0;
++ return map;
++}
++
++/* Mark [start, start+len) live (allocated) or dead (abandoned). */
++static void run_live_set(struct btrfs_open_stripe_run *run, u64 start, u64 len,
++ bool live)
++{
++ const u32 bits = run->bg->fs_info->sectorsize_bits;
++ u32 first, nr;
++
++ if (!run->live || !run->live_nbits || start < run->start)
++ return;
++ first = (start - run->start) >> bits;
++ nr = len >> bits;
++ /*
++ * Growth is capped at the map size, so this should be unreachable. If
++ * it happens, retire the map: btrfs_stripe_run_pad_mask() then declines
++ * the run, and the write falls back to read-modify-write instead of
++ * zero-filling a sector that may be live.
++ */
++ if (unlikely(first + nr > run->live_nbits)) {
++ WARN_ON_ONCE(1);
++ run->live_nbits = 0;
++ return;
++ }
++ if (live)
++ bitmap_set(run->live, first, nr);
++ else
++ bitmap_clear(run->live, first, nr);
++}
++
+ /* 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)
+ {
+ ASSERT(open_stripe_run_drained(run));
+ list_del(&run->list);
++ bitmap_free(run->live);
+ kfree(run);
+ wake_up_var(&bg->open_stripe_runs);
+ }
+@@ -676,6 +744,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ }
+ if (run) {
+ *ret_offset = run->offset;
++ run_live_set(run, run->offset, num_bytes, true);
+ run->offset += num_bytes;
+ run->inflight_bytes += num_bytes;
+ bg->stripe_open_remainder -= num_bytes;
+@@ -691,7 +760,8 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+
+- new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
++ /* Zeroed, so the error paths can free ->live and ->written. */
++ new_run = kzalloc(sizeof(*new_run), GFP_NOFS);
+ if (!new_run)
+ return -ENOMEM;
+
+@@ -712,6 +782,9 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ goto out;
+ }
+
++ /* Sleeps, so it has to happen before the locks below. */
++ new_run->live = alloc_run_live_map(bg, len, &new_run->live_nbits);
++
+ /*
+ * Install under fs_info->open_stripe_lock so that the block group
+ * membership, the retire sequence read and the run installation are
+@@ -755,9 +828,24 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+
+ if (!r || r->end != start)
+ continue;
++ /*
++ * Only grow as far as the run's liveness map reaches; it
++ * cannot be reallocated here (see alloc_run_live_map()).
++ * Beyond that, leave the run alone and open a new one.
++ */
++ if (((start + len - r->start) >> fs_info->sectorsize_bits) >
++ r->live_nbits)
++ continue;
+ ASSERT(r->open);
+ bg->open_stripe[class][band] = NULL;
+ *ret_offset = r->offset;
++ /*
++ * Mark the handed-out bytes live before anything can consult
++ * the map: this allocation begins at the old tail, usually
++ * mid-stripe, and a sector the map calls dead is a sector a
++ * neighbour's padded write may zero-fill.
++ */
++ run_live_set(r, r->offset, num_bytes, true);
+ r->end = start + len;
+ r->offset += num_bytes;
+ r->inflight_bytes += num_bytes;
+@@ -784,6 +872,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ new_run->inflight_bytes = num_bytes;
+ new_run->open_seq = fs_info->stripe_retire_seq;
+ new_run->open = (new_run->offset != new_run->end);
++ run_live_set(new_run, start, num_bytes, true);
+ list_add_tail(&new_run->list, &bg->open_stripe_runs);
+ bg->stripe_open_remainder += new_run->end - new_run->offset;
+ /*
+@@ -803,6 +892,9 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ new_run = NULL;
+ ret = 0;
+ out:
++ /* Unused on every path that did not install it, including errors. */
++ if (new_run)
++ bitmap_free(new_run->live);
+ kfree(new_run);
+ return ret;
+ }
+@@ -849,6 +941,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ continue;
+ if (num_bytes <= run->end - run->offset) {
+ *ret_offset = run->offset;
++ run_live_set(run, run->offset, num_bytes, true);
+ run->offset += num_bytes;
+ run->inflight_bytes += num_bytes;
+ bg->stripe_open_remainder -= num_bytes;
+@@ -867,7 +960,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ stripe_open_remainder_sync(bg);
+ }
+
+- new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
++ /* Zeroed, so the error paths can free ->live and ->written. */
++ new_run = kzalloc(sizeof(*new_run), GFP_NOFS);
+ if (!new_run)
+ return -ENOMEM;
+
+@@ -884,6 +978,9 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ goto out;
+ }
+
++ /* Sleeps, so it has to happen before the locks below. */
++ new_run->live = alloc_run_live_map(bg, len, &new_run->live_nbits);
++
+ /* See the installation comment in btrfs_alloc_from_open_stripe(). */
+ spin_lock(&fs_info->open_stripe_lock);
+ if (list_empty(&bg->open_stripe_bg_list)) {
+@@ -909,6 +1006,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ new_run->inflight_bytes = num_bytes;
+ new_run->open_seq = fs_info->stripe_retire_seq;
+ new_run->open = (new_run->offset != new_run->end);
++ run_live_set(new_run, start, num_bytes, true);
+ list_add_tail(&new_run->list, &bg->open_stripe_runs);
+ bg->stripe_open_remainder += new_run->end - new_run->offset;
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+@@ -919,6 +1017,9 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ new_run = NULL;
+ ret = 0;
+ out:
++ /* Unused on every path that did not install it, including errors. */
++ if (new_run)
++ bitmap_free(new_run->live);
+ kfree(new_run);
+ return ret;
+ }
+@@ -958,17 +1059,30 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ }
+
+ /*
+- * For the raid56 pad-to-full optimization: a sub-stripe write into a
+- * stripe covered by a live stripe run may zero-fill (instead of read) any
+- * sector at or past the run's allocation frontier, because such sectors
+- * have never been written in the run's lifetime and, once the run closes,
+- * its stripe's tail cannot be reallocated while the stripe holds live
+- * data. Returns true and sets *pad_from to the frontier when the stripe
+- * at [stripe_start, stripe_start + stripe_len) has a paddable tail. The
+- * frontier can grow right after this returns; that is safe, because the
+- * later allocation's write serializes behind the caller's stripe lock
+- * and overwrites the zeros.
++ * Lower an allocation ceiling to the end of the last live sector at or above
++ * @floor. Sectors between it and the frontier were allocated and abandoned:
++ * they never get a bio, so a parked rbio counting on them would leave only
++ * when kicked or at its park deadline. Caller holds bg->stripe_run_lock.
+ */
++static u64 run_live_ceiling(const struct btrfs_open_stripe_run *run, u64 floor,
++ u64 ceiling)
++{
++ const u32 bits = run->bg->fs_info->sectorsize_bits;
++ u32 first;
++ u32 i;
++
++ if (!run->live || !run->live_nbits || floor < run->start ||
++ ceiling <= floor)
++ return ceiling;
++ first = (floor - run->start) >> bits;
++ i = (ceiling - run->start) >> bits;
++ if (i > run->live_nbits)
++ return ceiling;
++ while (i > first && !test_bit(i - 1, run->live))
++ i--;
++ return run->start + ((u64)i << bits);
++}
++
+ /*
+ * How far has the covering run allocated into this stripe? Returns the
+ * exclusive end of the allocated prefix, clamped to the stripe, or U64_MAX
+@@ -999,6 +1113,7 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
+ continue;
+ ceiling = clamp(run->offset, stripe_start,
+ stripe_start + stripe_len);
++ ceiling = run_live_ceiling(run, stripe_start, ceiling);
+ break;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+@@ -1006,14 +1121,37 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
+ return ceiling;
+ }
+
+-bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+- u64 stripe_start, u64 stripe_len,
+- u64 *pad_from,
+- struct btrfs_stripe_pad_info *info)
++/*
++ * Which sectors of this stripe may be padded?
++ *
++ * Fills @dead with one bit per sector of the stripe, set where the sector
++ * holds nothing anyone intends to write: space the run has not handed out
++ * yet, and space it handed out but got back before the write was issued.
++ * A caller may zero-fill exactly those and write the whole stripe.
++ *
++ * Returns false if no run covers the stripe, in which case nothing may be
++ * padded: without a run there is no claim of exclusivity, and an uncovered
++ * sector may hold committed data.
++ *
++ * This replaces asking where the run's frontier is. The frontier answers
++ * "what has never been allocated", which misses allocations that were
++ * abandoned below it -- a tree block COWed twice in one transaction, a
++ * reservation released, an allocation the finder discarded. Those leave
++ * holes that are equally safe to pad, and skipping them is the difference
++ * between padding most partial stripes and padding all of them.
++ *
++ * @info, when non-NULL, reports the covering run's state at the moment of
++ * the decision, for the pad-decline trace: a later extent-tree dump cannot
++ * reconstruct where the frontier was when the write arrived.
++ */
++bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
++ u64 stripe_len, unsigned long *dead,
++ struct btrfs_stripe_pad_info *info)
+ {
++ const u32 bits = fs_info->sectorsize_bits;
++ const u32 nsectors = stripe_len >> bits;
+ struct btrfs_block_group *bg;
+ struct btrfs_open_stripe_run *run;
+- atomic64_t *decline = NULL;
+ unsigned long flags;
+ bool ret = false;
+
+@@ -1034,6 +1172,8 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ u32 first;
++
+ if (stripe_start < run->start || stripe_start >= run->end)
+ continue;
+ if (info) {
+@@ -1041,37 +1181,48 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+ info->run_end = run->end;
+ info->run_offset = run->offset;
+ info->inflight_bytes = run->inflight_bytes;
+- info->reason = BTRFS_STRIPE_PAD_OK;
+- }
+- if (run->offset > stripe_start &&
+- run->offset < stripe_start + stripe_len) {
+- *pad_from = run->offset;
+- ret = true;
+- } else if (run->offset >= stripe_start + stripe_len) {
+- /*
+- * The frontier is past this stripe: every sector of
+- * it is allocated, so there is nothing dead to pad
+- * and the write is waiting on a neighbour's data.
+- */
+- decline = &fs_info->stripe_park_stats.pad_decline_live;
+- if (info)
+- info->reason = BTRFS_STRIPE_PAD_LIVE;
+- } else {
+- /* The frontier has not reached the stripe at all. */
+- decline = &fs_info->stripe_park_stats.pad_decline_unallocated;
+- if (info)
+- info->reason = BTRFS_STRIPE_PAD_UNALLOCATED;
+ }
++ if (!run->live || !run->live_nbits)
++ break;
++ /*
++ * The stripe must lie inside the run's span. A closed run
++ * has shrunk its end to the frontier, so its final stripe
++ * overhangs: the sectors past end are the returned tail,
++ * sub-stripe free space nothing can claim while the stripe
++ * holds live data. They were never allocated, their live
++ * bits are clear, and they are exactly what a kicked park
++ * needs to pad. An open run's end is stripe aligned, so
++ * overhang there means a stripe the run does not own.
++ */
++ if (stripe_start + stripe_len > run->end && run->open)
++ break;
++
++ first = (stripe_start - run->start) >> bits;
++ /*
++ * And wholly inside the map. Declining here costs a
++ * read-modify-write; reading past the map would be a lie about
++ * which sectors are dead, and padding acts on that by
++ * overwriting them.
++ */
++ if (first + nsectors > run->live_nbits)
++ break;
++ bitmap_zero(dead, nsectors);
++ for (u32 i = 0; i < nsectors; i++)
++ if (!test_bit(first + i, run->live))
++ set_bit(i, dead);
++ if (info)
++ info->reason = BTRFS_STRIPE_PAD_OK;
++ ret = true;
+ break;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ if (!ret)
+- atomic64_inc(decline ? decline :
+- &fs_info->stripe_park_stats.pad_decline_no_run);
++ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
+ btrfs_put_block_group(bg);
+ return ret;
+ }
+
++
+ /*
+ * Can stripe-exclusive allocation be enabled on this filesystem? Called for
+ * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
+@@ -1231,6 +1382,39 @@ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
+ return ret;
+ }
+
++/*
++ * Report bytes that will never be written: an allocation released before
++ * its write was issued. Same accounting as a completion, plus the sectors
++ * go dead so a later partial write to their stripe can pad over them
++ * instead of falling back to read-modify-write.
++ */
++void btrfs_open_stripe_write_abandoned(struct btrfs_block_group *bg, u64 start,
++ u64 num_bytes)
++{
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (start >= run->start && start < run->offset) {
++ ASSERT(start + num_bytes <= run->offset);
++ ASSERT(run->inflight_bytes >= num_bytes);
++ run_live_set(run, start, num_bytes, false);
++ run->inflight_bytes -= num_bytes;
++ if (open_stripe_run_drained(run))
++ free_open_stripe_run(bg, run);
++ break;
++ }
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++}
++
++/*
++ * Report completed IO for an allocation from any stripe run. Every
++ * allocated byte must be reported exactly once, here or through
++ * btrfs_open_stripe_write_abandoned(), in any number of pieces (e.g. after
++ * ordered extent splits).
++ */
+ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+ u64 num_bytes)
+ {
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index a93483a270d67..bfc98126daeeb 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -416,6 +416,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ u64 *available);
+ 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,
++ u64 num_bytes);
+ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+ u64 num_bytes);
+ void btrfs_open_stripe_write_done_bytenr(struct btrfs_fs_info *fs_info,
+@@ -436,8 +438,6 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ enum btrfs_stripe_pad_reason {
+ BTRFS_STRIPE_PAD_OK = 0,
+ BTRFS_STRIPE_PAD_NO_RUN, /* no open run covers the stripe */
+- BTRFS_STRIPE_PAD_LIVE, /* frontier past the stripe: all allocated */
+- BTRFS_STRIPE_PAD_UNALLOCATED, /* frontier has not reached the stripe */
+ BTRFS_STRIPE_PAD_UNCOVERED, /* a sector below the frontier is not covered */
+ };
+
+@@ -451,10 +451,9 @@ struct btrfs_stripe_pad_info {
+
+ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
+ u64 stripe_start, u64 stripe_len);
+-bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
+- u64 stripe_start, u64 stripe_len,
+- u64 *pad_from,
+- struct btrfs_stripe_pad_info *info);
++bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
++ u64 stripe_len, unsigned long *dead,
++ struct btrfs_stripe_pad_info *info);
+ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
+ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
+ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 7e1750dcd9f5c..a5baba0f27db0 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4348,8 +4348,9 @@ static void undo_stripe_allocation(struct btrfs_block_group *block_group,
+ struct find_free_extent_ctl *ffe_ctl)
+ {
+ if (btrfs_is_stripe_alloc_bg(block_group))
+- btrfs_open_stripe_write_done(block_group, ffe_ctl->found_offset,
+- ffe_ctl->num_bytes);
++ btrfs_open_stripe_write_abandoned(block_group,
++ ffe_ctl->found_offset,
++ ffe_ctl->num_bytes);
+ }
+
+ static int do_allocation(struct btrfs_block_group *block_group,
+@@ -5165,7 +5166,7 @@ static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
+ * (or teardown) already reported these bytes.
+ */
+ if (!stripe_reported)
+- btrfs_open_stripe_write_done(cache, start, len);
++ btrfs_open_stripe_write_abandoned(cache, start, len);
+
+ btrfs_add_free_space(cache, start, len);
+ btrfs_free_reserved_bytes(cache, len, is_delalloc);
+@@ -5630,6 +5631,7 @@ struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
+ ret = PTR_ERR(buf);
+ goto out_free_reserved;
+ }
++
+ owning_root = btrfs_header_owner(buf);
+
+ if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 2a60ab06618c8..074e1c1a1e5da 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -2224,9 +2224,70 @@ static bool find_stripe_run_in_bitmap(struct btrfs_free_space_ctl *ctl,
+ }
+
+ /*
+- * Entry-blind complement to the by-size fast path in
+- * btrfs_claim_free_stripe_run(): walk the aligned stripe grid in
+- * address order, accumulating contiguous free coverage
++ * Find a fully free, stripe-aligned run of up to @want_bytes.
++ *
++ * Returns the free space entry containing it with @run_start and @run_len
++ * describing the run, or NULL if there is none. The caller decides what to
++ * do with it: claiming it for a stripe run, or handing it to a cluster.
++ *
++ * Walks the by-size index (largest max contiguous free run first) rather
++ * than the by-offset index. An entry whose largest contiguous free run is
++ * smaller than a full stripe cannot contain a fully-free stripe, and every
++ * following entry is no larger, so we stop at the first such entry.
++ * Near-full, where the free space degenerates into many sub-stripe holes,
++ * this is an O(1) fast fail instead of a scan of the whole free space tree
++ * on every allocation.
++ *
++ * ctl->tree_lock must be held.
++ */
++static struct btrfs_free_space *find_free_stripe_run(
++ struct btrfs_block_group *block_group,
++ u64 want_bytes, u64 *run_start,
++ u64 *run_len)
++{
++ struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
++ const u64 fsl = block_group->full_stripe_len;
++ struct btrfs_free_space *entry;
++ struct rb_node *node;
++
++ lockdep_assert_held(&ctl->tree_lock);
++
++ if (ctl->free_space < fsl)
++ return NULL;
++
++ for (node = rb_first_cached(&ctl->free_space_bytes); node;
++ node = rb_next(node)) {
++ entry = rb_entry(node, struct btrfs_free_space, bytes_index);
++
++ if (get_max_extent_size(entry) < fsl)
++ break;
++
++ if (entry->bitmap) {
++ if (find_stripe_run_in_bitmap(ctl, entry, want_bytes,
++ run_start, run_len) &&
++ btrfs_stripe_run_range_usable(block_group,
++ *run_start, run_len))
++ return entry;
++ continue;
++ }
++
++ *run_start = stripe_run_align(block_group, entry->offset);
++ if (*run_start + fsl > entry->offset + entry->bytes)
++ continue;
++ *run_len = min(want_bytes,
++ div64_u64(entry->offset + entry->bytes - *run_start,
++ fsl) * fsl);
++ if (!btrfs_stripe_run_range_usable(block_group, *run_start,
++ run_len))
++ continue;
++ return entry;
++ }
++ return NULL;
++}
++
++/*
++ * Entry-blind complement to find_free_stripe_run(): walk the aligned
++ * stripe grid in address order, accumulating contiguous free coverage
+ * with point lookups, looking for a run of fully-free full stripes no
+ * single entry contains.
+ *
+@@ -2436,7 +2497,6 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ &block_group->fs_info->discard_ctl;
+ const u64 fsl = block_group->full_stripe_len;
+ struct btrfs_free_space *entry;
+- struct rb_node *node;
+ struct btrfs_free_space *spare = NULL;
+ enum btrfs_trim_state head_trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
+ bool spare_used = false;
+@@ -2477,68 +2537,42 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ return -ENOSPC;
+ }
+
+- if (ctl->free_space < fsl)
+- goto out;
+-
+- /*
+- * Walk the by-size index (largest max contiguous free run first)
+- * rather than the by-offset index. An entry whose largest contiguous
+- * free run is smaller than a full stripe cannot contain a fully-free
+- * stripe, and every following entry is no larger, so we stop at the
+- * first such entry. Near-full, where the free space degenerates into
+- * many sub-stripe holes, this is an O(1) fast fail instead of a scan
+- * of the whole free space tree on every allocation.
+- */
+- for (node = rb_first_cached(&ctl->free_space_bytes); node;
+- node = rb_next(node)) {
+- entry = rb_entry(node, struct btrfs_free_space, bytes_index);
+-
+- if (get_max_extent_size(entry) < fsl)
+- break;
+-
+- if (entry->bitmap) {
+- if (find_stripe_run_in_bitmap(ctl, entry, want_bytes,
+- &run_start, &run_len) &&
+- btrfs_stripe_run_range_usable(block_group,
+- run_start, &run_len))
+- goto found;
+- continue;
++ entry = find_free_stripe_run(block_group, want_bytes, &run_start, &run_len);
++ if (!entry) {
++ /*
++ * No single entry holds a full stripe; look for one whose
++ * free space spans entry boundaries. The spare entry is
++ * for the belt-and-braces case of a run strictly inside
++ * one extent entry, whose removal splits it in two.
++ */
++ if (!spare) {
++ spin_unlock(&ctl->tree_lock);
++ spare = kmem_cache_zalloc(btrfs_free_space_cachep,
++ GFP_NOFS);
++ if (!spare)
++ return -ENOMEM;
++ spin_lock(&ctl->tree_lock);
+ }
+-
+- run_start = stripe_run_align(block_group, entry->offset);
+- if (run_start + fsl > entry->offset + entry->bytes)
+- continue;
+- run_len = min(want_bytes,
+- div64_u64(entry->offset + entry->bytes - run_start,
+- fsl) * fsl);
+- if (!btrfs_stripe_run_range_usable(block_group, run_start,
+- &run_len))
+- continue;
+- goto found;
+- }
+-
+- /*
+- * No single entry holds a full stripe; look for one whose
+- * free space spans entry boundaries. The spare entry is
+- * for the belt-and-braces case of a run strictly inside
+- * one extent entry, whose removal splits it in two.
+- */
+- spin_unlock(&ctl->tree_lock);
+- spare = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
+- if (!spare)
+- return -ENOMEM;
+- spin_lock(&ctl->tree_lock);
+- if (!find_free_stripe_run_slow(block_group, want_bytes,
+- &run_start, &run_len))
++ if (!find_free_stripe_run_slow(block_group, want_bytes,
++ &run_start, &run_len)) {
++ /*
++ * The exhaustive scan found no claimable run at all
++ * (the slow path accepts any run of at least one full
++ * stripe). Cache that verdict so subsequent claims
++ * fail in O(1) until free space is added.
++ */
++ if (btrfs_block_group_done(block_group))
++ block_group->max_claimable_run = 0;
++ goto out;
++ }
++ spare_used = claim_stripe_run_pieces(block_group, run_start,
++ run_len, spare);
++ *start = run_start;
++ *len = run_len;
++ ret = 0;
+ goto out;
+- spare_used = claim_stripe_run_pieces(block_group, run_start,
+- run_len, spare);
+- *start = run_start;
+- *len = run_len;
+- ret = 0;
+- goto out;
++ }
+
+-found:
+ if (!btrfs_free_space_trimmed(entry))
+ atomic64_add(run_len, &discard_ctl->discard_bytes_saved);
+
+@@ -2589,6 +2623,7 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ return ret;
+ }
+
++
+ /*
+ * given a cluster, put all of its extents back into the free space
+ * cache. If a block group is passed, this function will only free
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index da8abb516afb8..a9068fca6b240 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -2175,6 +2175,7 @@ void raid56_parity_write(struct bio *bio, struct btrfs_io_context *bioc)
+ rbio->operation = BTRFS_RBIO_WRITE;
+ rbio_add_bio(rbio, bio);
+
++
+ /*
+ * Don't plug on full rbios, just get them out the door
+ * as quickly as we can
+@@ -2757,75 +2758,78 @@ static void submit_write_bios(struct btrfs_raid_bio *rbio,
+ }
+
+ /*
+- * Try to avoid the RMW read phase of a sub-stripe write by zero-filling
+- * the uncovered data sectors. Legal only when every uncovered sector
+- * lies at or past its stripe run's allocation frontier -- never written
+- * in the run's lifetime, and unreachable by other allocations while this
+- * stripe holds live data (see btrfs_stripe_run_pad_start()). A frontier
+- * that grows under us is safe: the newer allocation's write serializes
+- * behind this rbio's stripe lock and lands over the zeros.
++ * Try to avoid the RMW read phase of a sub-stripe write by zero-filling the
++ * uncovered data sectors. Legal only where the stripe's run says a sector
++ * is dead: never allocated, handed back, or allocated with its write still
++ * to come. That write, like any allocation the run makes after this check,
++ * serializes behind this rbio's stripe lock and lands over the zeros.
+ */
+ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ {
+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
+ const u64 stripe_start = rbio->bioc->full_stripe_logical;
+- const u32 sectorsize = fs_info->sectorsize;
+ const u64 stripe_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
++ const u32 sectorsize = fs_info->sectorsize;
++ const u32 nsectors = rbio->nr_data * rbio->stripe_nsectors;
+ struct btrfs_stripe_pad_info info;
+- const u32 total = rbio->nr_data * rbio->stripe_nsectors;
+- u64 pad_from = 0;
++ unsigned long *dead;
+ u32 covered = 0;
++ bool ok = false;
+ int i;
+
+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
+ return false;
+- if (!btrfs_stripe_run_pad_start(fs_info, stripe_start, stripe_len,
+- &pad_from, &info)) {
++
++ dead = bitmap_zalloc(nsectors, GFP_NOFS);
++ if (!dead)
++ return false;
++ if (!btrfs_stripe_run_pad_mask(fs_info, stripe_start, stripe_len, dead,
++ &info)) {
+ trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
+- stripe_len, pad_from, 0, total,
++ stripe_len, 0, 0, nsectors,
+ info.run_start, info.run_end,
+ info.run_offset,
+ info.inflight_bytes,
+ info.reason);
+- return false;
++ goto out;
+ }
+
+ /* Populate bio_paddrs so covered sectors are visible below. */
+ index_rbio_pages(rbio);
+
++ for (i = 0; i < nsectors; i++)
++ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
++ covered++;
++
+ /*
+- * Every data sector this rbio does not cover must be paddable. A
+- * sector below the frontier is allocated to someone else and this
++ * Every data sector this rbio does not cover must be dead. A live
++ * uncovered sector belongs to another writer's allocation and this
+ * write does not carry its data, so padding would destroy it: that
+ * is a distinct refusal from the oracle's, and it is the one that
+ * says another writer's allocation shares this stripe.
+ */
+- for (i = 0; i < total; i++)
+- if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
+- covered++;
+-
+- for (i = 0; i < total; i++) {
+- const int stripe_nr = i / rbio->stripe_nsectors;
+- const int sectornr = i % rbio->stripe_nsectors;
+- u64 logical = stripe_start + stripe_nr * BTRFS_STRIPE_LEN +
+- (u64)sectornr * sectorsize;
+-
++ for (i = 0; i < nsectors; i++) {
+ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
+ continue;
+- if (logical < pad_from) {
++ if (!test_bit(i, dead)) {
+ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_uncovered);
+ info.reason = BTRFS_STRIPE_PAD_UNCOVERED;
+ trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
+- stripe_len, pad_from,
+- covered, total,
++ stripe_len, 0, covered,
++ nsectors,
+ info.run_start,
+ info.run_end,
+ info.run_offset,
+ info.inflight_bytes,
+ info.reason);
+- return false;
++ goto out;
+ }
+ }
++ ok = true;
++out:
++ bitmap_free(dead);
++ if (!ok)
++ return false;
+
+ if (alloc_rbio_data_pages(rbio) < 0)
+ return false;
+--
+2.47.3
+
+++ /dev/null
-From f5b0c9d155f96d732d35de297cafc368c6240d40 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:44 -0400
-Subject: [RFC PATCH 023/116] btrfs: raid56: skip parking for sync rbios
- finished by their unplug batch
-To: linux-btrfs@vger.kernel.org
-
-Parking exists to widen the merge window, and for plugged submissions
-the unplug callback is the natural end of that window from the
-submitter's side: once raid_unplug() has sorted and merged the batch,
-nothing more is coming from it. A sync rbio parked after that point --
-a sync(2) or WB_SYNC_ALL sweep, whose whole flush shares one plug --
-has a waiter behind it and can only sit out the sync deadline. Mark
-rbios leaving an unplug batch and let sync ones skip parking.
-
-Unplugged sync submissions (the fsync flush) still park: their sibling
-bios arrive one by one and merge into the parked rbio, and the fsync
-path kicks it as soon as they have all been submitted, so parking there
-is the merge mechanism and the deadline already never fires.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/raid56.c | 25 ++++++++++++++++++++++++-
- 1 file changed, 24 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 4f3968313f501..850011c8b5555 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -55,6 +55,14 @@
- */
- #define RBIO_PADDED_BIT 5
-
-+/*
-+ * Set when an unplug callback finished merging this rbio's submission
-+ * batch: the submitter has no more bios coming. A sync rbio past this
-+ * point gains nothing from parking (its own batch is fully merged and a
-+ * waiter is behind it), so it skips straight to the write.
-+ */
-+#define RBIO_BATCH_DONE_BIT 6
-+
- /* Set at park time and never cleared: this rbio once parked (stats). */
- #define RBIO_WAS_PARKED_BIT 7
-
-@@ -813,6 +821,18 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- timeout_ms == BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS)
- return false;
-
-+ /*
-+ * A sync rbio whose submission batch was already merged by its
-+ * unplug callback has nothing more coming from its submitter; the
-+ * only thing parking can add is its deadline. (Unplugged sync
-+ * submissions -- the fsync flush -- still park: their sibling bios
-+ * arrive one by one and merge into the parked rbio, and the fsync
-+ * path kicks it as soon as they have all been submitted.)
-+ */
-+ if (test_bit(RBIO_BATCH_DONE_BIT, &rbio->flags) &&
-+ timeout_ms == BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS)
-+ return false;
-+
- spin_lock(&table->parked_lock);
- set_bit(RBIO_PARKED_BIT, &rbio->flags);
- set_bit(RBIO_WAS_PARKED_BIT, &rbio->flags);
-@@ -2095,12 +2115,15 @@ static void raid_unplug(struct blk_plug_cb *cb, bool from_schedule)
- free_raid_bio(cur);
- continue;
- }
-+ set_bit(RBIO_BATCH_DONE_BIT, &last->flags);
- start_async_work(last, rmw_rbio_work);
- }
- last = cur;
- }
-- if (last)
-+ if (last) {
-+ set_bit(RBIO_BATCH_DONE_BIT, &last->flags);
- start_async_work(last, rmw_rbio_work);
-+ }
- kfree(plug);
- }
-
---
-2.47.3
-
--- /dev/null
+From d8b93fda68ac47db25b073220c90b369ab09170b Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:54 -0400
+Subject: [RFC PATCH 23/85] btrfs: stripe_alloc: count claimable whole-stripe
+ supply directly
+To: linux-btrfs@vger.kernel.org
+
+Data reservations are admitted against arithmetic -- free space minus
+trapped fragments minus open-run remainders minus a per-extent margin --
+and under sustained near-full churn the arithmetic and the claim rule
+disagree for long enough that admitted buffered writes reach writeback
+with nothing claimable left: measured, ~5.2-5.5k reserved writebacks
+dropped per fsstress churn run, silently for anything not waiting on
+fsync. Stock refuses the same write()s up front. Nothing between
+"durable by fsync" and "refused by write()" is acceptable when an
+operator accident fills the disk.
+
+First step, accounting only: measure the constraint instead of deriving
+it. bg->stripe_claimable counts bytes of fully free whole stripes --
+exactly what btrfs_claim_free_stripe_run() can take, the complement of
+stripe_unusable within each stripe. The commit rescan derives it from
+the same pass that computes trapped bytes (free minus trapped) and is
+the sole upward correction; incremental maintenance under
+ctl->tree_lock only ever DEBITS -- removals round their decrement OUT
+to every touched stripe, claims subtract exactly what they took. The
+counter can therefore only under-count between commits, never
+over-count.
+
+Crediting freed whole stripes incrementally on the add side is
+deliberately not done, having been tried and dropped. Several add
+paths re-add free space that a low-level remove never de-credited --
+the async discard trim (unlink_free_space / bitmap_clear_bits, then
+do_trimming's re-add through __btrfs_add_free_space) and
+btrfs_remove_free_space's middle-split tail re-add -- so crediting on
+add double-counts and drives the counter ABOVE the authoritative scan.
+That is the dangerous direction: once admission gates on this counter,
+an over-count admits reservations against phantom supply that writeback
+then drops, while an under-count is an early, clean write()-time
+ENOSPC. Debit-only makes over-counting structurally impossible,
+whatever a future re-add path forgets to de-credit. (Reproduced with
+compress+autodefrag+discard=async on a legacy-converted raid5
+filesystem, incremental ~= 2x scanned; credit_return attribution
+confirmed the phantom entered through do_trimming's re-add, not the
+open-stripe allocator returns.)
+
+A WARN_RATELIMIT at the rescan catches the dangerous direction anyway
+(incremental above scanned), which under a debit-only rule means a
+missed consumption site, and localizes it; the clamp to the scanned
+value keeps every rescan authoritative regardless. Rate limited rather
+than _ONCE because such a gap recurs on every commit, and reporting
+only the first hit hides that it is ongoing.
+
+The space_info aggregate bytes_stripe_claimable follows the
+stripe_unusable pattern (incremental between commits, re-totaled from
+armed groups at the rescan), shows in the ENOSPC dump and in sysfs.
+No admission change yet; that comes once the counter proves accurate
+under the fill, churn, balance and reclaim suites. The by-size
+fast-fail in the claim keeps its early exit: the point of measuring is
+to make such inputs trustworthy, not to search harder around them.
+
+Data block groups only for now; raid56 metadata and mixed block groups
+join when the data counter has settled.
+
+A trim takes a free range out of the tree, drops tree_lock for the
+discard and adds the range back, and a rescan in that window would find
+fewer claimable stripes than the incremental count (seen as "incremental
+stripe_claimable ... above scanned" with discard=async). Each step
+changes exactly the stripes the range belongs to, so the unlink debits
+every one of them that was claimable (wholly free, not inside a live run:
+the scan's rule) and the re-add credits every one that is claimable now,
+in the tree_lock section that unlinks or links the range. Rounding
+instead would over-debit a stripe per trimmed sub-stripe hole, and async
+discard trims thousands after a delete. The wholly-free test falls back
+to the bitmap lookup at offset_to_bitmap() as the other callers do, since
+an extent entry starting inside a bitmap's window hides the bitmap from a
+non-fuzzy search.
+
+The nocow tail claim, btrfs_claim_stripe_tail(), now counts and removes
+the tail in one ctl->tree_lock section, with claim_stripe_run_pieces()
+doing the removal as for any claimed run, and fails with -ENOSPC unless
+the whole tail is in the cache, debiting the
+claimable count for what it removes in the same lock section. It counted under the lock and then
+called btrfs_remove_free_space(), which returns 0 when the range is not
+in the cache at all: two allocations for the same inode (two direct
+writers, writeback racing fallocate) or a trim holding an entry out could
+both "remove" the same tail and hand out the same extent. A self-test
+claims the same tail twice.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 31 ++++-
+ fs/btrfs/block-group.h | 10 ++
+ fs/btrfs/free-space-cache.c | 220 ++++++++++++++++++++++++++++++++---
+ fs/btrfs/space-info.c | 3 +-
+ fs/btrfs/space-info.h | 5 +
+ fs/btrfs/sysfs.c | 2 +
+ include/trace/events/btrfs.h | 8 ++
+ 7 files changed, 264 insertions(+), 15 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 7d94bafac685c..d3534b6257f48 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1058,6 +1058,30 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ return true;
+ }
+
++/*
++ * Is the full stripe at @stripe inside a live run's range, i.e. stranded by
++ * the rule of btrfs_stripe_run_stranded_stripes()? Caller holds
++ * ctl->tree_lock.
++ */
++bool btrfs_stripe_run_strands(struct btrfs_block_group *bg, u64 stripe)
++{
++ const u64 fsl = bg->full_stripe_len;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ bool ret = false;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (run->end > run->start &&
++ stripe < run->end && stripe + fsl > run->start) {
++ ret = true;
++ break;
++ }
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ return ret;
++}
++
+ /*
+ * Lower an allocation ceiling to the end of the last live sector at or above
+ * @floor. Sectors between it and the frontier were allocated and abandoned:
+@@ -1716,6 +1740,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;
+ int raid;
+
+ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
+@@ -1747,14 +1772,18 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ * groups are excluded; their free space is already
+ * accounted as read-only.
+ */
+- if (READ_ONCE(bg->stripe_unusable_ready))
++ if (READ_ONCE(bg->stripe_unusable_ready)) {
+ total += READ_ONCE(bg->stripe_unusable);
++ total_claimable +=
++ READ_ONCE(bg->stripe_claimable);
++ }
+ }
+ }
+ up_read(&sinfo->groups_sem);
+
+ spin_lock(&sinfo->lock);
+ sinfo->bytes_stripe_unusable = total;
++ sinfo->bytes_stripe_claimable = total_claimable;
+ /*
+ * The rescan usually lowers the counter (mid-transaction
+ * incremental adds overcount conservatively); admission
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index bfc98126daeeb..b114e1ded4966 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -268,6 +268,15 @@ struct btrfs_block_group {
+ * free_space_ctl->tree_lock and space_info->lock.
+ */
+ u64 stripe_unusable;
++ /*
++ * Directly measured claimable supply: bytes of fully free, aligned
++ * whole stripes in the free space cache -- exactly what
++ * btrfs_claim_free_stripe_run() can take. Maintained incrementally
++ * under ctl->tree_lock by rules meant to err only low (early
++ * write()-time ENOSPC); the commit rescan corrects it, and warns if
++ * it was ever high.
++ */
++ u64 stripe_claimable;
+ /*
+ * Upper bound on the longest run btrfs_claim_free_stripe_run() can
+ * find, learned from actual scans: (u64)-1 means unknown, 0 means an
+@@ -429,6 +438,7 @@ void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
+ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
+ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
+ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
++bool btrfs_stripe_run_strands(struct btrfs_block_group *bg, u64 stripe);
+ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ u64 run_start, u64 *run_len);
+ /*
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 074e1c1a1e5da..23bcb799266cf 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1360,9 +1360,15 @@ static void steal_from_bitmap(struct btrfs_free_space_ctl *ctl,
+ }
+ }
+
+-static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
+- u64 offset, u64 bytes,
+- enum btrfs_trim_state trim_state)
++static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta);
++static u64 stripe_touched_bytes(const struct btrfs_block_group *bg,
++ u64 bytenr, u64 size);
++static void stripe_trim_claimable(struct btrfs_block_group *bg, u64 bytenr,
++ u64 size, bool out);
++
++static int add_free_space(struct btrfs_block_group *block_group,
++ u64 offset, u64 bytes,
++ enum btrfs_trim_state trim_state, bool trim_return)
+ {
+ struct btrfs_fs_info *fs_info = block_group->fs_info;
+ struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
+@@ -1420,6 +1426,18 @@ static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
+ if (ret)
+ kmem_cache_free(btrfs_free_space_cachep, info);
+ out:
++ /*
++ * Adding free space never credits stripe_claimable: some add paths
++ * re-add space that was never debited (the tail of
++ * btrfs_remove_free_space()'s middle split), and crediting would
++ * count it twice. The counter may only err low (an early ENOSPC); an
++ * over-count admits reservations writeback cannot place. The commit
++ * rescan is the only upward correction -- except for a trim's return,
++ * whose range was debited when the trim took it out (see
++ * stripe_trim_claimable()).
++ */
++ if (!ret && trim_return)
++ stripe_trim_claimable(block_group, offset, bytes, false);
+ btrfs_discard_update_discardable(block_group);
+ spin_unlock(&ctl->tree_lock);
+
+@@ -1436,6 +1454,13 @@ static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
+ return ret;
+ }
+
++static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
++ u64 offset, u64 bytes,
++ enum btrfs_trim_state trim_state)
++{
++ return add_free_space(block_group, offset, bytes, trim_state, false);
++}
++
+ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
+ u64 bytenr, u64 size, bool used)
+ {
+@@ -1499,6 +1524,133 @@ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
+
+ static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
+
++/*
++ * Debit the claimable whole-stripe supply for claims and removals. Returned
++ * free space is never credited here (see add_free_space()), save a trim's
++ * return (stripe_trim_claimable()); the commit rescan restores it. Caller
++ * holds ctl->tree_lock.
++ */
++static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta)
++{
++ struct btrfs_space_info *sinfo = bg->space_info;
++
++ if (!READ_ONCE(bg->stripe_unusable_ready) || !delta)
++ return;
++ if (delta < 0 && bg->stripe_claimable < (u64)-delta)
++ delta = -(s64)bg->stripe_claimable;
++ if (!delta)
++ return;
++ bg->stripe_claimable += delta;
++ if (!sinfo)
++ return;
++ spin_lock(&sinfo->lock);
++ if (delta < 0 && sinfo->bytes_stripe_claimable < (u64)-delta)
++ sinfo->bytes_stripe_claimable = 0;
++ else
++ btrfs_space_info_update_bytes_stripe_claimable(sinfo, delta);
++ spin_unlock(&sinfo->lock);
++}
++
++/* The whole-stripe span [bytenr, bytenr + size) touches at all. */
++static u64 stripe_touched_bytes(const struct btrfs_block_group *bg,
++ u64 bytenr, u64 size)
++{
++ const u64 fsl = bg->full_stripe_len;
++ const u64 rel = bytenr - bg->start;
++ const u64 astart = div64_u64(rel, fsl) * fsl;
++ const u64 aend = div64_u64(rel + size + fsl - 1, fsl) * fsl;
++
++ return aend - astart;
++}
++
++/* Is all of [start, end) free? Caller holds ctl->tree_lock. */
++static bool stripe_range_free(struct btrfs_free_space_ctl *ctl,
++ u64 start, u64 end)
++{
++ const u32 unit = ctl->block_group->fs_info->sectorsize;
++ u64 pos = start;
++
++ while (pos < end) {
++ struct btrfs_free_space *e = tree_search_offset(ctl, pos, 0, 0);
++ unsigned long bit;
++
++ /*
++ * An extent entry that starts inside a bitmap's window and
++ * ends before pos hides that bitmap from the search above;
++ * look it up by its own offset, as btrfs_remove_free_space()
++ * does.
++ */
++ if (!e)
++ e = tree_search_offset(ctl, offset_to_bitmap(ctl, pos),
++ 1, 0);
++ if (!e)
++ return false;
++ if (!e->bitmap) {
++ /* An extent entry returned here covers pos. */
++ pos = e->offset + e->bytes;
++ continue;
++ }
++ bit = div_u64(pos - e->offset, unit);
++ if (!test_bit(bit, e->bitmap))
++ return false;
++ pos = e->offset + (u64)find_next_zero_bit(e->bitmap,
++ BITS_PER_BITMAP, bit) * unit;
++ }
++ return true;
++}
++
++/*
++ * The claimable stripes that [bytenr, bytenr + size) belongs to, counting
++ * the range itself as free: by the scan's rule (stripe_unusable_scan()),
++ * every stripe that is wholly free and not inside a live stripe run.
++ * Caller holds ctl->tree_lock; stripe_run_lock nests inside it.
++ */
++static u64 stripe_claimable_with_range(struct btrfs_block_group *bg,
++ u64 bytenr, u64 size)
++{
++ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ const u64 fsl = bg->full_stripe_len;
++ const u64 end = bytenr + size;
++ const u64 bg_end = btrfs_block_group_end(bg);
++ u64 whole = 0;
++ u64 s;
++
++ for (s = bg->start + div64_u64(bytenr - bg->start, fsl) * fsl;
++ s < end && s + fsl <= bg_end; s += fsl) {
++ if (s < bytenr && !stripe_range_free(ctl, s, bytenr))
++ continue;
++ if (s + fsl > end && !stripe_range_free(ctl, end, s + fsl))
++ continue;
++ if (!btrfs_stripe_run_strands(bg, s))
++ whole += fsl;
++ }
++ return whole;
++}
++
++/*
++ * A trim takes a free range out of the tree for the length of its discard
++ * (trim_no_bitmap(), trim_bitmaps()) and do_trimming() adds it back. A
++ * rescan in between scans a tree without the range, so the incremental
++ * count must not include it either. Each step changes exactly the stripes
++ * the range belongs to: taking it out (@out) makes every one of them that
++ * was claimable unclaimable, and adding it back makes claimable every one
++ * that is claimable now. Debit and credit those, in the tree_lock section
++ * that unlinks or links the range, so the count stays as exact as it was.
++ * Caller holds ctl->tree_lock; for @out, the range is already unlinked.
++ */
++static void stripe_trim_claimable(struct btrfs_block_group *bg, u64 bytenr,
++ u64 size, bool out)
++{
++ s64 delta;
++
++ if (!btrfs_is_stripe_alloc_bg(bg))
++ return;
++ if (!READ_ONCE(bg->stripe_unusable_ready) || !size)
++ return;
++ delta = stripe_claimable_with_range(bg, bytenr, size);
++ stripe_claimable_mod(bg, out ? -delta : delta);
++}
++
+ /*
+ * 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
+@@ -1617,6 +1769,19 @@ int btrfs_remove_free_space(struct btrfs_block_group *block_group,
+
+ spin_lock(&ctl->tree_lock);
+
++ /*
++ * The removed bytes leave free space; every whole stripe the range
++ * touches may lose wholeness (a boundary fragment removal breaks a
++ * fully free stripe as surely as an interior one empties it).
++ * Rounding the decrement OUT to touched stripes errs claimable-low.
++ * The trapped counter is deliberately not decremented for removed
++ * fragments: leaving it high is the safe direction, and the rescan
++ * settles both.
++ */
++ if (btrfs_is_stripe_alloc_bg(block_group))
++ stripe_claimable_mod(block_group,
++ -(s64)stripe_touched_bytes(block_group, offset, bytes));
++
+ again:
+ ret = 0;
+ if (!bytes)
+@@ -2057,7 +2222,7 @@ static void stripe_return_clusters(struct btrfs_block_group *bg)
+ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
+ {
+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
+- u64 trapped, nstripes;
++ u64 trapped, claimable, nstripes;
+ u32 *freep;
+
+ if (!btrfs_is_stripe_alloc_bg(bg))
+@@ -2079,14 +2244,19 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
+ }
+ trapped = stripe_unusable_scan(bg, freep, nstripes);
+ bg->stripe_unusable = trapped;
++ /* Every free byte is claimable or trapped; the scan split them. */
++ bg->stripe_claimable = ctl->free_space - trapped;
++ claimable = bg->stripe_claimable;
+ bg->stripe_unusable_ready = true;
+ spin_unlock(&ctl->tree_lock);
+ kvfree(freep);
+
+- if (trapped) {
++ if (trapped || claimable) {
+ spin_lock(&bg->space_info->lock);
+ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
+ trapped);
++ btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
++ claimable);
+ spin_unlock(&bg->space_info->lock);
+ }
+ }
+@@ -2103,6 +2273,7 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+ {
+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
+ u64 trapped;
++ u64 claimable;
+
+ if (!btrfs_is_stripe_alloc_bg(bg))
+ return;
+@@ -2113,13 +2284,17 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+ return;
+ }
+ trapped = bg->stripe_unusable;
++ claimable = bg->stripe_claimable;
++ bg->stripe_claimable = 0;
+ bg->stripe_unusable_ready = false;
+ spin_unlock(&ctl->tree_lock);
+
+- if (trapped) {
++ if (trapped || claimable) {
+ spin_lock(&bg->space_info->lock);
+ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
+ -(s64)trapped);
++ btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
++ -(s64)claimable);
+ spin_unlock(&bg->space_info->lock);
+ }
+ }
+@@ -2148,8 +2323,23 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
+
+ stripe_return_clusters(bg);
+ spin_lock(&ctl->tree_lock);
+- if (bg->stripe_unusable_ready) /* skip if disarmed (read-only) */
++ if (bg->stripe_unusable_ready) { /* skip if disarmed (read-only) */
++ u64 scanned;
++
+ bg->stripe_unusable = stripe_unusable_scan(bg, freep, nstripes);
++ scanned = ctl->free_space - bg->stripe_unusable;
++ /*
++ * The incremental rules may only under-count claimable
++ * supply; more than the scan finds means a missed debit,
++ * which admits reservations writeback cannot honor. Rate
++ * limited, not _ONCE, because such a gap recurs every commit.
++ * The assignment below keeps the rescan authoritative.
++ */
++ WARN_RATELIMIT(bg->stripe_claimable > scanned,
++ "bg %llu incremental stripe_claimable %llu above scanned %llu",
++ bg->start, bg->stripe_claimable, scanned);
++ bg->stripe_claimable = scanned;
++ }
+ spin_unlock(&ctl->tree_lock);
+ kvfree(freep);
+ /*
+@@ -2567,6 +2757,7 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ }
+ spare_used = claim_stripe_run_pieces(block_group, run_start,
+ run_len, spare);
++ stripe_claimable_mod(block_group, -(s64)run_len);
+ *start = run_start;
+ *len = run_len;
+ ret = 0;
+@@ -2606,6 +2797,7 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
+ head_len = 0;
+ }
+ }
++ stripe_claimable_mod(block_group, -(s64)run_len);
+ *start = run_start;
+ *len = run_len;
+ ret = 0;
+@@ -3161,13 +3353,12 @@ static int do_trimming(struct btrfs_block_group *block_group,
+ }
+
+ if (reserved_start < start)
+- __btrfs_add_free_space(block_group, reserved_start,
+- start - reserved_start,
+- reserved_trim_state);
++ add_free_space(block_group, reserved_start,
++ start - reserved_start, reserved_trim_state, true);
+ if (end < reserved_end)
+- __btrfs_add_free_space(block_group, end, reserved_end - end,
+- reserved_trim_state);
+- __btrfs_add_free_space(block_group, start, bytes, trim_state);
++ add_free_space(block_group, end, reserved_end - end,
++ reserved_trim_state, true);
++ add_free_space(block_group, start, bytes, trim_state, true);
+
+ if (!bg_ro) {
+ spin_lock(&space_info->lock);
+@@ -3265,6 +3456,8 @@ static int trim_no_bitmap(struct btrfs_block_group *block_group,
+ unlink_free_space(ctl, entry, true);
+ kmem_cache_free(btrfs_free_space_cachep, entry);
+ }
++ stripe_trim_claimable(block_group, extent_start, extent_bytes,
++ true);
+
+ spin_unlock(&ctl->tree_lock);
+
+@@ -3483,6 +3676,7 @@ static int trim_bitmaps(struct btrfs_block_group *block_group,
+ bitmap_clear_bits(ctl, entry, start, bytes, true);
+ if (entry->bytes == 0)
+ free_bitmap(ctl, entry);
++ stripe_trim_claimable(block_group, start, bytes, true);
+
+ spin_unlock(&ctl->tree_lock);
+
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index 5e7ee4321e8c2..561c118a4749e 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -712,11 +712,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 stripe_unusable=%llu stripe_open=%llu stripe_margin=%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 stripe_claimable=%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_stripe_unusable, info->bytes_stripe_open,
++ info->bytes_stripe_claimable,
+ info->bytes_stripe_margin);
+ }
+
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index b53458d573aec..0d2d55580d13b 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -156,6 +156,10 @@ struct btrfs_space_info {
+ stripes stranded behind live runs.
+ Counted as used, and subtracted in
+ statfs. */
++ u64 bytes_stripe_claimable; /* sum of armed groups' directly
++ measured claimable whole-stripe
++ bytes; see stripe_claimable in
++ struct btrfs_block_group */
+ u64 bytes_stripe_open; /* sum of open stripe runs' unallocated
+ remainders. Claimed out of the free
+ space cache but not yet allocated;
+@@ -324,6 +328,7 @@ DECLARE_SPACE_INFO_UPDATE(bytes_may_use, "space_info");
+ DECLARE_SPACE_INFO_UPDATE(bytes_pinned, "pinned");
+ DECLARE_SPACE_INFO_UPDATE(bytes_zone_unusable, "zone_unusable");
+ DECLARE_SPACE_INFO_UPDATE(bytes_stripe_unusable, "stripe_unusable");
++DECLARE_SPACE_INFO_UPDATE(bytes_stripe_claimable, "stripe_claimable");
+
+ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
+ bool may_use_included)
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 276617501ee05..c4170be7524ee 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -817,6 +817,7 @@ 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_claimable);
+ SPACE_INFO_ATTR(bytes_stripe_open);
+ SPACE_INFO_ATTR(bytes_stripe_margin);
+ SPACE_INFO_ATTR(disk_used);
+@@ -949,6 +950,7 @@ 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_claimable),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_open),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_margin),
+ BTRFS_ATTR_PTR(space_info, disk_used),
+diff --git a/include/trace/events/btrfs.h b/include/trace/events/btrfs.h
+index db541d70e9640..e95f1b3a8a0c5 100644
+--- a/include/trace/events/btrfs.h
++++ b/include/trace/events/btrfs.h
+@@ -3299,6 +3299,14 @@ DEFINE_EVENT(btrfs__space_info_update, update_bytes_stripe_unusable,
+ TP_ARGS(fs_info, sinfo, old, diff)
+ );
+
++DEFINE_EVENT(btrfs__space_info_update, update_bytes_stripe_claimable,
++
++ TP_PROTO(const struct btrfs_fs_info *fs_info,
++ const struct btrfs_space_info *sinfo, u64 old, s64 diff),
++
++ TP_ARGS(fs_info, sinfo, old, diff)
++);
++
+ TRACE_EVENT(btrfs_stripe_pad_decline,
+
+ TP_PROTO(const struct btrfs_fs_info *fs_info, u64 full_stripe,
+--
+2.47.3
+
--- /dev/null
+From d5cf72426bd3a1acbbf21e2f210ac5e87cb8f7a4 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:55 -0400
+Subject: [RFC PATCH 24/85] btrfs: raid56: adaptive park deadline from the
+ parked-rbio backlog
+To: linux-btrfs@vger.kernel.org
+
+Full-stripe batching parks a sub-stripe write's rbio for a deadline so the
+writes that fill the rest of its stripe can merge into it, turning a
+read-modify-write into one full-stripe write. The deadline is a fixed
+per-filesystem value. It is long enough to catch those merges, but at a
+small-file fill to ENOSPC -- where a run's stripes never fill because each
+file's neighbours land in the next file's stripe rather than this one --
+every partial write waits the deadline out, and then its 10x stuck cap, on
+an arrival that never comes before padding to a full stripe and going down.
+Lowering the deadline globally fixes that fill but throws away the merges
+the deadline exists to catch on ordinary moderate writes.
+
+Feed the deadline back from the parking machinery's own backlog instead of
+guessing at the workload. Track stripe_parked_now, the number of
+currently-parked rbios, incremented as a partial write parks and
+decremented as it unparks. When it runs ahead of the stripe_park_congestion
+knob (0 disables it, the default), a new async partial write takes the short
+sync deadline through the existing sync-park path rather than the full one.
+This is negative feedback: the shorter deadline drains the backlog, so once
+it falls back below the knob later writes regain the full deadline and full-
+stripe batching. No space-state estimate is needed -- a small-file flood
+builds the backlog directly, while a large sequential fill (already full
+stripes, never parked) and a moderate steady stream do not.
+
+Measured on an eight-device raid5. A small-file balance-reclaim soak that
+times out at the default deadline completes at a congestion of 4; on a
+throttled moderate stream, where the backlog stays low, a congestion of 32
+never trips, keeps the full deadline, and merges three times as much with
+38% fewer RMW reads as the same filesystem under a flat 3ms deadline. The
+gauge and a congestion_short counter join the stripe_park_stats sysfs file
+so the knob can be set from measurement. Off by default, and no data-path
+change: a shortened park still pads or reads exactly as it would have, only
+sooner.
+
+Assisted-by: Claude:claude-opus-4-8
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/fs.h | 5 +++++
+ fs/btrfs/raid56.c | 21 +++++++++++++++++++++
+ fs/btrfs/sysfs.c | 2 ++
+ 3 files changed, 28 insertions(+)
+
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index bbb03936df650..89bd82093ea84 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -849,6 +849,7 @@ struct btrfs_fs_info {
+ * stripe.
+ */
+ atomic64_t pad_decline_uncovered;
++ atomic64_t congestion_short;
+ } stripe_park_stats;
+ /*
+ * Park deadlines, ms (sysfs); 0 disables parking for that class. See
+@@ -856,6 +857,10 @@ struct btrfs_fs_info {
+ */
+ u32 stripe_park_timeout_ms;
+ u32 stripe_park_sync_timeout_ms;
++ /* Parked-rbio backlog above which parks go short; 0 = off. */
++ u32 stripe_park_congestion;
++ /* Live count of currently-parked rbios (the backlog gauge). */
++ atomic_t stripe_parked_now;
+
+ /* Private scrub information */
+ struct mutex scrub_lock;
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index a9068fca6b240..f27215f8a4017 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -717,6 +717,7 @@ static void rbio_unpark_locked(struct btrfs_raid_bio *rbio)
+ {
+ list_del_init(&rbio->parked_node);
+ clear_bit(RBIO_PARKED_BIT, &rbio->flags);
++ atomic_dec(&rbio->bioc->fs_info->stripe_parked_now);
+ }
+
+ /* Does any bio gathered in @rbio carry a sync hint (a blocked waiter)? */
+@@ -791,6 +792,25 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ timeout_ms == sync_timeout_ms)
+ return false;
+
++ /*
++ * Park-congestion feedback: when more rbios are parked than
++ * stripe_park_congestion allows (0 = off), merges are not arriving fast
++ * enough to clear the backlog, so give this write the short sync
++ * deadline (which also skips the stuck cap). Once the backlog drains
++ * below the knob, new writes get the full deadline again.
++ */
++ {
++ unsigned int congestion =
++ READ_ONCE(fs_info->stripe_park_congestion);
++
++ if (timeout_ms != sync_timeout_ms && sync_timeout_ms != 0 &&
++ congestion &&
++ atomic_read(&fs_info->stripe_parked_now) > (int)congestion) {
++ timeout_ms = sync_timeout_ms;
++ atomic64_inc(&fs_info->stripe_park_stats.congestion_short);
++ }
++ }
++
+ spin_lock(&table->parked_lock);
+ set_bit(RBIO_PARKED_BIT, &rbio->flags);
+ set_bit(RBIO_WAS_PARKED_BIT, &rbio->flags);
+@@ -808,6 +828,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ */
+ refcount_inc(&rbio->refs);
+ list_add_tail(&rbio->parked_node, &table->parked);
++ atomic_inc(&fs_info->stripe_parked_now);
+ spin_unlock(&table->parked_lock);
+ atomic64_inc(&fs_info->stripe_park_stats.parked);
+ queue_delayed_work(system_percpu_wq, &table->parked_work,
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index c4170be7524ee..7825318e2d07e 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1175,6 +1175,7 @@ BTRFS_ATTR_RW(, _name, btrfs_##_name##_show, btrfs_##_name##_store)
+
+ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
+ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_sync_timeout_ms, stripe_park_sync_timeout_ms);
++BTRFS_PARK_TIMEOUT_ATTR(stripe_park_congestion, stripe_park_congestion);
+
+
+
+@@ -1547,6 +1548,7 @@ static const struct attribute *btrfs_attrs[] = {
+ BTRFS_ATTR_PTR(, stripe_park_stats),
+ BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
+ BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
++ BTRFS_ATTR_PTR(, stripe_park_congestion),
+ BTRFS_ATTR_PTR(, temp_fsid),
+ NULL,
+ };
+--
+2.47.3
+
+++ /dev/null
-From 70f17f325b3784e23a50958d3a80c500bffe3759 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:45 -0400
-Subject: [RFC PATCH 024/116] btrfs: stripe_alloc: count open stripe run
- remainders against data reservations
-To: linux-btrfs@vger.kernel.org
-
-Close the remaining reservation-vs-allocation windows the commit-time
-stripe_unusable rescan cannot see:
-
-- bytes_stripe_open (new): the sum of open runs' unallocated
- remainders, maintained per block group under stripe_run_lock at
- every open/alloc/grow/close, synced into the space_info after each
- mutation, and counted in btrfs_space_info_used(). Claimed bytes are
- invisible to the free space cache and will either be allocated or
- become trapped tails at close, so reservations must not be admitted
- against them.
-
-A closed run's returned tail is still only counted as trapped by the
-commit-time rescan, so reservations can race the retire-to-rescan window
-inside a commit and be admitted against freshly trapped tails. The next
-patch closes that window from the free space cache side, where every
-returning range is seen and no call site can be missed.
-
-Measured on the fill-to-ENOSPC rolling test before this change (with
-only the bytes_stripe_unusable accounting): tree 'b' still lost 3.3%
-(8532 blocks) and tree 'c' 30% (62371 blocks) to silent writeback
-allocation failure as trapping compounded.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 56 ++++++++++++++++++++++++++++++++++++++++--
- fs/btrfs/block-group.h | 8 ++++++
- fs/btrfs/space-info.h | 18 +++++++++++---
- 3 files changed, 76 insertions(+), 6 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index c7b21de26540e..31b420a979943 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -557,11 +557,46 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
- *tail_start = run->offset;
- tail_len = run->end - run->offset;
- run->end = run->offset;
-+ bg->stripe_open_remainder -= tail_len;
- if (open_stripe_run_drained(run))
- free_open_stripe_run(bg, run);
- return tail_len;
- }
-
-+/*
-+ * Fold this block group's open-run remainder delta into the space_info
-+ * counter that reservations see. Bytes inside an open run are invisible
-+ * to the free space cache (the claim removed them) and will either be
-+ * allocated or become trapped tails when the run closes, so the data
-+ * reservation path must not admit writes against them: a reservation
-+ * that cannot allocate at writeback time discards the pages silently.
-+ * Called after every remainder mutation. Compute and apply are one
-+ * critical section (sinfo->lock nests inside stripe_run_lock): applied
-+ * out of order, a negative delta could overtake the positive it was
-+ * computed against and transiently underflow the space_info sum.
-+ */
-+static void stripe_open_remainder_sync(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_space_info *sinfo = bg->space_info;
-+ unsigned long flags;
-+ s64 delta;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ delta = (s64)(bg->stripe_open_remainder - bg->stripe_open_reported);
-+ bg->stripe_open_reported = bg->stripe_open_remainder;
-+ if (delta && sinfo) {
-+ spin_lock(&sinfo->lock);
-+ if (delta < 0 && sinfo->bytes_stripe_open < (u64)-delta) {
-+ WARN_ON_ONCE(1);
-+ sinfo->bytes_stripe_open = 0;
-+ } else {
-+ sinfo->bytes_stripe_open += delta;
-+ }
-+ spin_unlock(&sinfo->lock);
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+}
-+
- /*
- * Install @run (not currently in any band slot) into its remaining-space band.
- * If a run already occupies that band, keep whichever has more remaining -- it
-@@ -652,6 +687,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- *ret_offset = run->offset;
- run->offset += num_bytes;
- run->inflight_bytes += num_bytes;
-+ bg->stripe_open_remainder -= num_bytes;
- if (run->offset == run->end)
- run->open = false; /* full; drains then is freed */
- else
-@@ -659,6 +695,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- if (tail_len)
- btrfs_add_free_space(bg, tail_start, tail_len);
-+ stripe_open_remainder_sync(bg);
- return 0;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-@@ -740,6 +777,8 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- r->end = start + len;
- r->offset += num_bytes;
- r->inflight_bytes += num_bytes;
-+ bg->stripe_open_remainder += len;
-+ bg->stripe_open_remainder -= num_bytes;
- if (r->offset == r->end)
- r->open = false; /* full; drains then is freed */
- else
-@@ -748,6 +787,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- spin_unlock(&fs_info->open_stripe_lock);
- if (tail_len)
- btrfs_add_free_space(bg, tail_start, tail_len);
-+ stripe_open_remainder_sync(bg);
- ret = 0;
- goto out; /* frees the unused new_run */
- }
-@@ -761,6 +801,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- new_run->open_seq = fs_info->stripe_retire_seq;
- new_run->open = (new_run->offset != new_run->end);
- list_add_tail(&new_run->list, &bg->open_stripe_runs);
-+ bg->stripe_open_remainder += new_run->end - new_run->offset;
- /*
- * Place the new run in its remaining-space band, closing whichever run
- * loses a band collision (the last, fuller opener wins). Other bands'
-@@ -773,6 +814,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
-
- if (tail_len)
- btrfs_add_free_space(bg, tail_start, tail_len);
-+ stripe_open_remainder_sync(bg);
- *ret_offset = start;
- new_run = NULL;
- ret = 0;
-@@ -827,17 +869,21 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- *ret_offset = run->offset;
- run->offset += num_bytes;
- run->inflight_bytes += num_bytes;
-+ bg->stripe_open_remainder -= num_bytes;
- if (run->offset == run->end)
- run->open = false; /* full; drains, is freed */
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ stripe_open_remainder_sync(bg);
- return 0;
- }
- tail_len = close_open_stripe_run(bg, run, &tail_start);
- break;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-- if (tail_len)
-+ if (tail_len) {
- btrfs_add_free_space(bg, tail_start, tail_len);
-+ stripe_open_remainder_sync(bg);
-+ }
-
- new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
- if (!new_run)
-@@ -926,9 +972,11 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- new_run->open_seq = fs_info->stripe_retire_seq;
- new_run->open = (new_run->offset != new_run->end);
- list_add_tail(&new_run->list, &bg->open_stripe_runs);
-+ bg->stripe_open_remainder += new_run->end - new_run->offset;
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- spin_unlock(&fs_info->open_stripe_lock);
-
-+ stripe_open_remainder_sync(bg);
- *ret_offset = start;
- new_run = NULL;
- ret = 0;
-@@ -1464,6 +1512,7 @@ void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
- btrfs_get_block_group(bg);
- spin_unlock(&fs_info->open_stripe_lock);
- btrfs_add_free_space(bg, tail_start, tail_len);
-+ stripe_open_remainder_sync(bg);
- btrfs_put_block_group(bg);
- goto restart;
- }
-@@ -1562,8 +1611,10 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- log_carry_record(inode, file_start, file_len, bytenr, num_bytes,
- ps_start, ps_len);
-
-- if (tail_len)
-+ if (tail_len) {
- btrfs_add_free_space(bg, tail_start, tail_len);
-+ stripe_open_remainder_sync(bg);
-+ }
- if (flush_len) {
- btrfs_flush_parked_rbios(fs_info, flush_start, flush_len);
- wait_var_event(&bg->open_stripe_runs,
-@@ -1875,6 +1926,7 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- if (tail_len)
- btrfs_add_free_space(bg, tail_start, tail_len);
-+ stripe_open_remainder_sync(bg);
- goto restart;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 29cbf6f225329..590d62f59f9b9 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -265,6 +265,14 @@ struct btrfs_block_group {
- struct list_head open_stripe_runs;
- struct btrfs_open_stripe_run
- *open_stripe[BTRFS_STRIPE_RUN_NR_CLASSES][BTRFS_STRIPE_RUN_NR_BANDS];
-+ /*
-+ * Sum of the open runs' unallocated remainders (end - offset), and
-+ * the portion of it already folded into the space_info's
-+ * bytes_stripe_open. Both under stripe_run_lock; synced by
-+ * stripe_open_remainder_sync() after every mutation.
-+ */
-+ u64 stripe_open_remainder;
-+ u64 stripe_open_reported;
- /*
- * Membership in fs_info->open_stripe_bgs, protected by
- * fs_info->open_stripe_lock; holds a block group reference.
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 51098227f9171..44d7014b697f8 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -153,9 +153,19 @@ struct btrfs_space_info {
- u64 bytes_stripe_unusable; /* total free bytes trapped in partially
- filled stripes of stripe_alloc block
- groups; free but not allocatable until
-- the whole stripe frees. Informational
-- only (subtracted in statfs); NOT part
-- of btrfs_space_info_used(). */
-+ the whole stripe frees. Counted in
-+ btrfs_space_info_used() so reservations
-+ cannot admit writes against it, and
-+ subtracted in statfs (from a different
-+ base -- the free space cache walk). */
-+ u64 bytes_stripe_open; /* sum of open stripe runs' unallocated
-+ remainders. Claimed out of the free
-+ space cache but not yet allocated;
-+ will either be allocated or become
-+ trapped tails when the runs close, so
-+ reservations must not count on it
-+ either. Synced from the block groups'
-+ stripe_open_remainder. */
-
- u64 max_extent_size; /* This will hold the maximum extent size of
- the space info if we had an ENOSPC in the
-@@ -298,7 +308,7 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
- return s_info->bytes_used + s_info->bytes_reserved +
- s_info->bytes_pinned + s_info->bytes_readonly +
- s_info->bytes_zone_unusable +
-- s_info->bytes_stripe_unusable +
-+ s_info->bytes_stripe_unusable + s_info->bytes_stripe_open +
- (may_use_included ? s_info->bytes_may_use : 0);
- }
-
---
-2.47.3
-
--- /dev/null
+From 961fd368e3fbfa54791cc92b36e3305cfd29ea95 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:56 -0400
+Subject: [RFC PATCH 25/85] btrfs: stripe_alloc: gate data admission on
+ claimable whole-stripe supply
+To: linux-btrfs@vger.kernel.org
+
+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).
+
+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 | 46 ++++++-
+ fs/btrfs/delalloc-space.c | 20 ++-
+ fs/btrfs/delalloc-space.h | 2 +
+ fs/btrfs/extent-tree.c | 12 +-
+ fs/btrfs/file.c | 17 ++-
+ fs/btrfs/free-space-cache.c | 8 ++
+ fs/btrfs/fs.h | 14 ++
+ fs/btrfs/inode.c | 7 +-
+ fs/btrfs/relocation.c | 7 +-
+ fs/btrfs/space-info.c | 259 ++++++++++++++++++++++++++++++++++--
+ fs/btrfs/space-info.h | 17 +++
+ 11 files changed, 387 insertions(+), 22 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index d3534b6257f48..66d0550af7be6 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1741,6 +1741,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))
+@@ -1776,6 +1777,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);
+ }
+ }
+ }
+@@ -1784,6 +1788,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
+@@ -1825,10 +1830,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);
++ }
+ }
+
+ /*
+@@ -1852,6 +1866,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);
+ }
+@@ -2892,6 +2911,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
+diff --git a/fs/btrfs/delalloc-space.c b/fs/btrfs/delalloc-space.c
+index a68847832a5fc..d09bf6aa43352 100644
+--- a/fs/btrfs/delalloc-space.c
++++ b/fs/btrfs/delalloc-space.c
+@@ -124,18 +124,34 @@ 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);
+
+ 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,
+@@ -175,7 +191,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)
+diff --git a/fs/btrfs/delalloc-space.h b/fs/btrfs/delalloc-space.h
+index c464cf0a88d9b..37860ced7a723 100644
+--- a/fs/btrfs/delalloc-space.h
++++ b/fs/btrfs/delalloc-space.h
+@@ -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);
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index a5baba0f27db0..549b62828f4d8 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4251,6 +4251,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;
+@@ -4267,8 +4268,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 !=
+@@ -4285,6 +4288,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;
+
+diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
+index 9cbed3978a392..7d1f84afe6cf3 100644
+--- a/fs/btrfs/file.c
++++ b/fs/btrfs/file.c
+@@ -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.
+@@ -2940,6 +2941,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,
+@@ -3065,8 +3067,9 @@ static int btrfs_zero_range(struct inode *inode,
+ 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;
+@@ -3083,6 +3086,8 @@ static int btrfs_zero_range(struct inode *inode,
+ 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 */
+@@ -3093,6 +3098,7 @@ static int btrfs_zero_range(struct inode *inode,
+ }
+ 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);
+@@ -3119,6 +3125,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;
+@@ -3243,8 +3250,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;
+ }
+@@ -3279,6 +3287,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;
+
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 23bcb799266cf..e87902bf993ef 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1548,6 +1548,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);
+ }
+
+@@ -2295,6 +2301,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);
+ }
+ }
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 89bd82093ea84..a069482d73257 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -511,6 +511,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;
+@@ -978,6 +981,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;
+diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
+index d27cc1155adf9..1f2a1677aa10a 100644
+--- a/fs/btrfs/inode.c
++++ b/fs/btrfs/inode.c
+@@ -9952,6 +9952,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;
+
+@@ -10093,7 +10094,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);
+@@ -10121,6 +10123,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;
+@@ -10169,6 +10173,7 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
+ 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.
+diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
+index a41f57559ee74..763e066595ea3 100644
+--- a/fs/btrfs/relocation.c
++++ b/fs/btrfs/relocation.c
+@@ -2798,6 +2798,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),
+@@ -2815,8 +2816,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;
+
+@@ -2841,6 +2843,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,
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index 561c118a4749e..6a8f76f763883 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -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;
+@@ -446,6 +458,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) {
+@@ -468,6 +486,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)
+@@ -640,6 +693,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.
+@@ -662,9 +814,13 @@ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info)
+ 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;
+@@ -1750,6 +1906,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);
+@@ -1827,8 +1984,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);
+ }
+
+ /*
+@@ -1845,8 +2007,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;
+@@ -1870,7 +2033,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;
+@@ -1895,8 +2059,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;
+ }
+
+@@ -1927,6 +2095,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();
+
+@@ -1974,7 +2145,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;
+ }
+
+ /*
+@@ -1997,7 +2171,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;
+
+@@ -2010,6 +2184,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.
+ *
+@@ -2020,20 +2216,61 @@ 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_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);
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index 0d2d55580d13b..fadf817652d3e 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -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_ALL,
+
+ /*
+@@ -156,6 +164,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
+@@ -347,6 +360,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_block_group *block_group);
+ void btrfs_update_space_info_chunk_size(struct btrfs_space_info *space_info,
+ u64 chunk_size);
+@@ -372,6 +388,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);
+--
+2.47.3
+
+++ /dev/null
-From eecce5dd3ebd561dc1e7888d98ef8c38e3012a2f Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:46 -0400
-Subject: [RFC PATCH 025/116] btrfs: stripe_alloc: pessimistic data reservation
- margin
-To: linux-btrfs@vger.kernel.org
-
-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 kept a whole-stripe multiple
- (rounddown; the width is not a power of two), so at most one piece
- per delalloc extent can strand a tail -- the margin pre-paid
- exactly one.
-
-- 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).
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 6 +++
- fs/btrfs/btrfs_inode.h | 3 ++
- fs/btrfs/defrag.c | 4 +-
- fs/btrfs/delalloc-space.c | 50 +++++++++++++++++++++++--
- fs/btrfs/delalloc-space.h | 3 +-
- fs/btrfs/direct-io.c | 9 ++++-
- fs/btrfs/extent-tree.c | 26 +++++++++++++
- fs/btrfs/file.c | 9 ++++-
- fs/btrfs/free-space-cache.c | 46 +++++++++++++++++++++++
- fs/btrfs/fs.h | 8 ++++
- fs/btrfs/inode.c | 4 +-
- fs/btrfs/space-info.c | 73 ++++++++++++++++++++++++++++++++++++-
- fs/btrfs/space-info.h | 14 +++++++
- fs/btrfs/sysfs.c | 4 ++
- 14 files changed, 248 insertions(+), 11 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 31b420a979943..29473031c9226 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2095,6 +2095,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);
- }
- }
-diff --git a/fs/btrfs/btrfs_inode.h b/fs/btrfs/btrfs_inode.h
-index 00fd4e6e668d6..fc0421de26bf4 100644
---- a/fs/btrfs/btrfs_inode.h
-+++ b/fs/btrfs/btrfs_inode.h
-@@ -460,6 +460,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)
- {
-@@ -467,6 +469,7 @@ static inline void btrfs_mod_outstanding_extents(struct btrfs_inode *inode,
- inode->outstanding_extents += mod;
- trace_btrfs_inode_mod_outstanding_extents(inode->root, btrfs_ino(inode),
- mod, inode->outstanding_extents);
-+ btrfs_stripe_margin_mod(inode, mod);
- }
-
- /*
-diff --git a/fs/btrfs/defrag.c b/fs/btrfs/defrag.c
-index 918a82f6b9035..5d319df6524d8 100644
---- a/fs/btrfs/defrag.c
-+++ b/fs/btrfs/defrag.c
-@@ -1285,6 +1285,7 @@ static int carry_one_range(struct btrfs_inode *inode, u64 start, u64 len,
- const unsigned int nr_pages = ((start + len - 1) >> PAGE_SHIFT) -
- (start >> PAGE_SHIFT) + 1;
- u64 cur;
-+ u64 held = 0;
- int ret = 0;
-
- ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
-@@ -1338,10 +1339,11 @@ static int carry_one_range(struct btrfs_inode *inode, u64 start, u64 len,
- * stays in its old stripe (see btrfs_carry_log_tail).
- */
- ret = btrfs_check_data_free_space(inode, &data_reserved, start, len,
-- true);
-+ true, &held);
- if (ret < 0)
- goto unlock_extent;
- ret = btrfs_delalloc_reserve_metadata(inode, len, len, true);
-+ btrfs_release_data_margin_probe(inode, held);
- if (ret < 0) {
- btrfs_free_reserved_data_space(inode, data_reserved, start,
- len);
-diff --git a/fs/btrfs/delalloc-space.c b/fs/btrfs/delalloc-space.c
-index 77781852e4178..8aa5d113ccac8 100644
---- a/fs/btrfs/delalloc-space.c
-+++ b/fs/btrfs/delalloc-space.c
-@@ -140,10 +140,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 */
-@@ -154,13 +155,47 @@ int btrfs_check_data_free_space(struct btrfs_inode *inode,
- if (noflush)
- flush = BTRFS_RESERVE_NO_FLUSH;
-
-- ret = btrfs_reserve_data_bytes(data_sinfo_for_inode(inode), len, flush);
-+ /*
-+ * stripe_alloc: probe for the pessimistic reservation margin on top
-+ * of the bytes themselves, so the ticketed flush below has to
-+ * produce enough claimable whole stripes to cover this write's
-+ * worst case, and a writer that cannot be covered gets an honest
-+ * ENOSPC here rather than a dropped writeback later. The margin is
-+ * then re-charged into bytes_stripe_margin by the metadata reservation
-+ * (btrfs_mod_outstanding_extents()), which carries it until writeback.
-+ * A caller that passes @stripe_held keeps the probe's margin in
-+ * bytes_may_use until then and releases it with
-+ * btrfs_release_data_margin_probe() after its metadata reservation:
-+ * released here, the gap between the two let concurrent writers be
-+ * admitted into each other's margin at the fill edge, and their
-+ * writebacks then found no stripe. Without @stripe_held (callers
-+ * that take no metadata reservation) 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;
-@@ -170,6 +205,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.
-@@ -493,12 +535,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);
-diff --git a/fs/btrfs/delalloc-space.h b/fs/btrfs/delalloc-space.h
-index 6119c0d3f883c..c464cf0a88d9b 100644
---- a/fs/btrfs/delalloc-space.h
-+++ b/fs/btrfs/delalloc-space.h
-@@ -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,
-diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c
-index dc9db2234be66..68234efb70547 100644
---- a/fs/btrfs/direct-io.c
-+++ b/fs/btrfs/direct-io.c
-@@ -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 @@ static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
- 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,
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index dedee06848e24..c2ba4abf0ec8c 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -5067,6 +5067,22 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- num_bytes = min(num_bytes >> 1, ins->offset);
- num_bytes = round_down(num_bytes,
- fs_info->sectorsize);
-+ /*
-+ * 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.
-+ */
-+ if (is_data && btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
-+ const u64 unit =
-+ READ_ONCE(fs_info->stripe_margin_unit);
-+
-+ /* Not a power of two: rounddown(), not round_down(). */
-+ if (unit && num_bytes > unit)
-+ num_bytes = rounddown(num_bytes, unit);
-+ }
- num_bytes = max(num_bytes, min_alloc_size);
- ram_bytes = num_bytes;
- if (num_bytes == min_alloc_size)
-@@ -5082,6 +5098,16 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- 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;
-diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
-index 94eedf224daa8..dce4880737eb3 100644
---- a/fs/btrfs/file.c
-+++ b/fs/btrfs/file.c
-@@ -1105,9 +1105,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;
-
-@@ -1132,6 +1134,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,
-@@ -1866,6 +1869,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;
-@@ -1894,7 +1898,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;
-
-@@ -1914,6 +1918,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,
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 118fced160032..62b8803e63251 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1493,6 +1493,51 @@ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
-
- static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
-
-+/*
-+ * stripe_alloc: count the sub-stripe fragments of a returning free range
-+ * as trapped immediately, without waiting for the commit-time rescan.
-+ *
-+ * The rescan remains the authority, but reservations (which now carry the
-+ * pessimistic per-extent margin) read bytes_stripe_unusable in the middle
-+ * of a transaction, and any mid-transaction return of free space -- an
-+ * unpinned deletion, a same-transaction free, a drained run tail, a freed
-+ * reservation -- otherwise leaves its fragments backing admissions the
-+ * claim rule can never honor. Whole stripes lying fully inside the
-+ * returned range are trivially fully free (hence claimable) and are not
-+ * counted; the partial head and tail fragments are counted trapped even
-+ * though neighbouring free space may complete their stripes. That is a
-+ * bounded overcount in the safe direction (early ENOSPC at admission,
-+ * reconciled by the next rescan), never an undercount.
-+ */
-+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)
- {
-@@ -1509,6 +1554,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);
- }
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index fab55620af0e9..eb05e89bb5a15 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -931,6 +931,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;
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index d243e078435b5..98d376ce99eb8 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -5085,6 +5085,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);
-@@ -5137,7 +5138,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;
-
-@@ -5151,6 +5152,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,
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index d5a84fa97462c..2137d58015412 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -16,6 +16,7 @@
- #include "extent-tree.h"
- #include "zoned.h"
- #include "delayed-inode.h"
-+#include "btrfs_inode.h"
-
- /*
- * HOW DOES SPACE RESERVATION WORK
-@@ -386,6 +387,19 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
-
- factor = btrfs_bg_type_to_factor(block_group->flags);
-
-+ /*
-+ * Track the widest raid56 data full stripe as the unit of the
-+ * stripe_alloc pessimistic reservation margin. Pure geometry;
-+ * whether a margin is actually charged is decided per reservation
-+ * by the mount option.
-+ */
-+ 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) ||
-@@ -409,6 +423,59 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
- up_write(&space_info->groups_sem);
- }
-
-+/*
-+ * stripe_alloc pessimistic reservation margin.
-+ *
-+ * A byte-counted data reservation holds no collateral against the stripe
-+ * claim rule: between admission at write() time and the allocation at
-+ * writeback, every transaction commit closes open stripe runs and traps
-+ * their sub-stripe tails, quietly converting bytes the reservation was
-+ * counting on into bytes_stripe_unusable. The reservation cannot fail at
-+ * that point -- delalloc writeback gets no second chance -- so pre-pay the
-+ * worst case instead: charge one full stripe width for every outstanding
-+ * delalloc extent, and release it when the extent is allocated (or its
-+ * delalloc range dropped). The actual allocation is optimistic -- extents
-+ * pack into shared runs and usually trap nothing -- and the unused margin
-+ * returns the moment the extent completes.
-+ *
-+ * The charge rides btrfs_mod_outstanding_extents(), the same bookkeeping
-+ * that sizes metadata reservations, so it stays exact across delalloc
-+ * merges and splits. Charges are gated on the mount option but releases
-+ * are not (and clamp at zero), so toggling stripe_alloc across a remount
-+ * 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) {
-+ /*
-+ * Option 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)
- {
-@@ -652,10 +719,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,
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 44d7014b697f8..13c24536731c5 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -166,6 +166,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
-@@ -309,10 +319,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_block_group *block_group);
- void btrfs_update_space_info_chunk_size(struct btrfs_space_info *space_info,
- u64 chunk_size);
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index a36754036846b..dc12af3ed39a9 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -818,6 +818,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);
-@@ -947,6 +949,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),
---
-2.47.3
-
+++ /dev/null
-From bd75d78d258e5774fe98c815c3b879113b515f3f Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:47 -0400
-Subject: [RFC PATCH 026/116] btrfs: stripe_alloc: claim fully-free stripes
- that span free space entries
-To: linux-btrfs@vger.kernel.org
-
-The claim fast path searches single entries, so a fully-free full
-stripe whose free space spans an entry boundary -- an extent entry
-adjoining a bitmap, or two neighbouring bitmap windows -- was
-unclaimable. stripe_unusable accounting is entry-blind and counts
-exactly those stripes as claimable, so admission reserves data against
-them; at writeback the claim finds nothing, cow_file_range() gets
--ENOSPC, and the already-dirtied pages are dropped. full_stripe_len
-is not a power of two, so stripe boundaries drift through the fixed
-128M bitmap windows and a straddling stripe is a certainty near full,
-not a corner case.
-
-Observed live at the raid6 fill edge (rolling-failure, then isolated
-by fill-edge-debug with enospc_debug): two 384K stripes, each
-straddling a bitmap window boundary, held the space_info accounting
-786432 bytes above what the claim could reach, and every writeback
-allocation against that phantom margin failed -ENOSPC while ~991MB of
-genuinely trapped free space sat in the cache. The reservation margin
-cannot absorb this: the gap is per straddling stripe, not per
-outstanding extent.
-
-Add an entry-blind slow path: one offset-ordered walk accumulating
-contiguous free coverage across entry boundaries, and a piecewise
-removal that runs in the same tree_lock critical section as the find,
-so a racing claimer cannot see a half-removed run. The fast path is
-unchanged and still serves the common case; the slow path runs only
-after it fails, which is the near-full case where a stranded stripe
-matters most.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/free-space-cache.c | 217 +++++++++++++++++++++++++++++++++++-
- 1 file changed, 212 insertions(+), 5 deletions(-)
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 62b8803e63251..c266c0f35f2f1 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2205,13 +2205,19 @@ static bool find_stripe_run_in_bitmap(struct btrfs_free_space_ctl *ctl,
- *
- * want_bytes must be a full_stripe_len multiple and is a maximum; the
- * smallest successful claim is a single full stripe. A fully-free stripe
-- * split across two free space entries (e.g. an extent entry adjoining a
-- * bitmap) is not found: adjacent extent entries merge on insert, but
-- * extent/bitmap neighbours do not. This errs toward missing a claimable
-- * stripe, never toward claiming a non-free byte.
-+ * split across free space entries (an extent entry adjoining a bitmap, or
-+ * two bitmaps: adjacent extent entries merge on insert, but extent/bitmap
-+ * neighbours and neighbouring bitmap windows do not) is found by the
-+ * entry-blind slow path. It has to be: stripe_unusable accounting is
-+ * entry-blind too, so it admits data reservations against exactly these
-+ * stripes, and a stripe the accounting admits but the claim cannot reach
-+ * becomes a buffered write that fails -ENOSPC at writeback, dropping the
-+ * pages -- full_stripe_len is not a power of two, so stripe boundaries
-+ * drift through the fixed bitmap windows and such stripes are a
-+ * certainty, not a corner case.
- *
- * Returns 0 on success, -ENOSPC if no aligned fully-free stripe is present
-- * in this block group.
-+ * in this block group, -ENOMEM if the slow path could not allocate.
- */
- /*
- * Claim exactly [start, start + len) from the free space cache, failing
-@@ -2275,6 +2281,183 @@ int btrfs_claim_stripe_tail(struct btrfs_block_group *block_group,
- return btrfs_remove_free_space(block_group, start, len);
- }
-
-+/*
-+ * Entry-blind complement to the by-size fast path in
-+ * btrfs_claim_free_stripe_run(): walk the aligned stripe grid in
-+ * address order, accumulating contiguous free coverage
-+ * with point lookups, looking for a run of fully-free full stripes no
-+ * single entry contains.
-+ *
-+ * Address order is the point. Walking the entry tree does not visit
-+ * free space in address order: a bitmap entry sorts at its window base
-+ * while its set-bit runs extend to the window end, so extent entries
-+ * inside the window sort after the bitmap but describe lower addresses.
-+ * A coverage accumulator fed by an entry walk breaks exactly at the
-+ * bitmap window boundary -- which is where the stripes this path exists
-+ * to find live.
-+ *
-+ * ctl->tree_lock must be held.
-+ */
-+static bool find_free_stripe_run_slow(struct btrfs_block_group *block_group,
-+ u64 want_bytes, u64 *run_start,
-+ u64 *run_len)
-+{
-+ struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
-+ const u32 unit = block_group->fs_info->sectorsize;
-+ const u64 fsl = block_group->full_stripe_len;
-+ const u64 bg_end = block_group->start + block_group->length;
-+ u64 cand = stripe_run_align(block_group, block_group->start);
-+
-+ lockdep_assert_held(&ctl->tree_lock);
-+
-+ while (cand + fsl <= bg_end) {
-+ u64 covered = 0;
-+
-+ /* Accumulate contiguous free coverage upward from cand. */
-+ while (covered < want_bytes) {
-+ const u64 off = cand + covered;
-+ struct btrfs_free_space *info;
-+ u64 piece = 0;
-+
-+ if (off >= bg_end)
-+ break;
-+ info = tree_search_offset(ctl, off, 0, 0);
-+ if (info && !info->bitmap) {
-+ piece = info->offset + info->bytes - off;
-+ } else {
-+ info = tree_search_offset(ctl,
-+ offset_to_bitmap(ctl, off), 1, 0);
-+ if (info) {
-+ unsigned long bit =
-+ div64_u64(off - info->offset, unit);
-+ unsigned long zero;
-+
-+ if (test_bit(bit, info->bitmap)) {
-+ zero = find_next_zero_bit(
-+ info->bitmap,
-+ BITS_PER_BITMAP,
-+ bit);
-+ piece = (u64)(zero - bit) * unit;
-+ }
-+ }
-+ }
-+ if (!piece)
-+ break;
-+ covered += piece;
-+ }
-+
-+ while (covered >= fsl) {
-+ u64 tlen = min(want_bytes,
-+ div64_u64(covered, fsl) * fsl);
-+
-+ if (btrfs_stripe_run_range_usable(block_group, cand,
-+ &tlen)) {
-+ *run_start = cand;
-+ *run_len = tlen;
-+ return true;
-+ }
-+ /* Overlaps a live run; try the next stripe. */
-+ cand += fsl;
-+ covered -= fsl;
-+ }
-+ /*
-+ * The byte at cand + covered is not free, so no stripe
-+ * containing it can be claimed: restart at the first
-+ * stripe boundary past it.
-+ */
-+ cand = stripe_run_align(block_group, cand + covered + unit);
-+ }
-+ return false;
-+}
-+
-+/*
-+ * Remove the fully-free run [start, start + len) found by
-+ * find_free_stripe_run_slow() from the free space cache, piece by piece
-+ * across the entries covering it, without ever dropping ctl->tree_lock:
-+ * the find and the removal form one critical section, so a racing
-+ * claimer can never see (and double-claim) a half-removed run. @spare
-+ * is a caller-allocated entry for the at-most-one split of an extent
-+ * entry the run is strictly inside of; returns true if it was consumed.
-+ *
-+ * ctl->tree_lock must be held.
-+ */
-+static bool claim_stripe_run_pieces(struct btrfs_block_group *block_group,
-+ u64 start, u64 len,
-+ struct btrfs_free_space *spare)
-+{
-+ struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
-+ struct btrfs_discard_ctl *discard_ctl =
-+ &block_group->fs_info->discard_ctl;
-+ const u32 unit = block_group->fs_info->sectorsize;
-+ bool spare_used = false;
-+ u64 off = start;
-+ u64 remaining = len;
-+
-+ lockdep_assert_held(&ctl->tree_lock);
-+
-+ while (remaining) {
-+ struct btrfs_free_space *info;
-+ u64 piece;
-+
-+ info = tree_search_offset(ctl, off, 0, 0);
-+ if (!info)
-+ info = tree_search_offset(ctl,
-+ offset_to_bitmap(ctl, off), 1, 0);
-+ if (WARN_ON(!info))
-+ break;
-+
-+ if (info->bitmap) {
-+ const u64 b_end = info->offset +
-+ (u64)BITS_PER_BITMAP * unit;
-+
-+ piece = min(remaining, b_end - off);
-+ if (!btrfs_free_space_trimmed(info))
-+ atomic64_add(piece,
-+ &discard_ctl->discard_bytes_saved);
-+ bitmap_clear_bits(ctl, info, off, piece, true);
-+ if (!info->bytes)
-+ free_bitmap(ctl, info);
-+ } else {
-+ const u64 e_end = info->offset + info->bytes;
-+ int ret2;
-+
-+ piece = min(remaining, e_end - off);
-+ if (!btrfs_free_space_trimmed(info))
-+ atomic64_add(piece,
-+ &discard_ctl->discard_bytes_saved);
-+ unlink_free_space(ctl, info, true);
-+ if (off == info->offset && piece == info->bytes) {
-+ kmem_cache_free(btrfs_free_space_cachep, info);
-+ } else if (off == info->offset) {
-+ info->offset += piece;
-+ info->bytes -= piece;
-+ ret2 = link_free_space(ctl, info);
-+ ASSERT(!ret2); /* -EEXIST; Logic error */
-+ } else if (off + piece == e_end) {
-+ info->bytes = off - info->offset;
-+ ret2 = link_free_space(ctl, info);
-+ ASSERT(!ret2); /* -EEXIST; Logic error */
-+ } else {
-+ /* Strictly inside: split head off, spare
-+ * becomes the tail. */
-+ ASSERT(!spare_used);
-+ spare->offset = off + piece;
-+ spare->bytes = e_end - spare->offset;
-+ spare->trim_state = info->trim_state;
-+ info->bytes = off - info->offset;
-+ ret2 = link_free_space(ctl, info);
-+ ASSERT(!ret2); /* -EEXIST; Logic error */
-+ ret2 = link_free_space(ctl, spare);
-+ ASSERT(!ret2); /* -EEXIST; Logic error */
-+ spare_used = true;
-+ }
-+ }
-+ off += piece;
-+ remaining -= piece;
-+ }
-+ return spare_used;
-+}
-+
- int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- u64 want_bytes, u64 *start, u64 *len)
- {
-@@ -2284,7 +2467,9 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- const u64 fsl = block_group->full_stripe_len;
- struct btrfs_free_space *entry;
- struct rb_node *node;
-+ struct btrfs_free_space *spare = NULL;
- enum btrfs_trim_state head_trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
-+ bool spare_used = false;
- u64 head_start = 0;
- u64 head_len = 0;
- u64 run_start;
-@@ -2337,6 +2522,26 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- continue;
- goto found;
- }
-+
-+ /*
-+ * No single entry holds a full stripe; look for one whose
-+ * free space spans entry boundaries. The spare entry is
-+ * for the belt-and-braces case of a run strictly inside
-+ * one extent entry, whose removal splits it in two.
-+ */
-+ spin_unlock(&ctl->tree_lock);
-+ spare = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
-+ if (!spare)
-+ return -ENOMEM;
-+ spin_lock(&ctl->tree_lock);
-+ if (!find_free_stripe_run_slow(block_group, want_bytes,
-+ &run_start, &run_len))
-+ goto out;
-+ spare_used = claim_stripe_run_pieces(block_group, run_start,
-+ run_len, spare);
-+ *start = run_start;
-+ *len = run_len;
-+ ret = 0;
- goto out;
-
- found:
-@@ -2371,6 +2576,8 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- btrfs_discard_update_discardable(block_group);
- spin_unlock(&ctl->tree_lock);
-
-+ if (spare && !spare_used)
-+ kmem_cache_free(btrfs_free_space_cachep, spare);
- if (!ret)
- stripe_unusable_mark_dirty(block_group);
- if (head_len)
---
-2.47.3
-
--- /dev/null
+From 77979a1e01f45f2e6b9651e1c4ec9aba3388680d Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:16 -0400
+Subject: [RFC PATCH 26/85] btrfs: stripe_alloc: show per-group trapped bytes
+ in the space info dump
+To: linux-btrfs@vger.kernel.org
+
+btrfs_dump_space_info() prints each block group's available bytes, and
+under stripe_alloc those include the free space trapped in partly used
+stripes, which no allocation can use until the group is reclaimed
+(stripe_unusable). An ENOSPC dump then shows space in the groups that
+cannot be had.
+
+Print stripe_unusable next to zone_unusable and leave it out of the
+available bytes. A group whose trapped bytes have not been counted yet
+(stripe_unusable_ready not set) prints 0 and the old available figure.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/space-info.c | 6 +++++-
+ 1 file changed, 5 insertions(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index 6a8f76f763883..b109a640050df 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -900,11 +900,15 @@ void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
+
+ spin_lock(&cache->lock);
+ avail = btrfs_block_group_available_space(cache);
++ if (READ_ONCE(cache->stripe_unusable_ready))
++ avail -= min(avail, READ_ONCE(cache->stripe_unusable));
+ btrfs_info(fs_info,
+-"block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %llu delalloc %llu super %llu zone_unusable (%llu bytes available) %s",
++"block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %llu delalloc %llu super %llu zone_unusable %llu stripe_unusable (%llu bytes available) %s",
+ cache->start, cache->length, cache->used, cache->pinned,
+ cache->reserved, cache->delalloc_bytes,
+ cache->bytes_super, cache->zone_unusable,
++ READ_ONCE(cache->stripe_unusable_ready) ?
++ READ_ONCE(cache->stripe_unusable) : 0,
+ avail, cache->ro ? "[readonly]" : "");
+ spin_unlock(&cache->lock);
+ btrfs_dump_free_space(cache, bytes);
+--
+2.47.3
+
--- /dev/null
+From ab3d1172e1ef05b4aaec29389ca173379fab47b6 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:19 -0400
+Subject: [RFC PATCH 27/85] btrfs: stripe_alloc: count whole stripes stranded
+ behind live runs as trapped
+To: linux-btrfs@vger.kernel.org
+
+The data admission gate admits a reservation while the whole-stripe
+supply, bytes_stripe_claimable, covers it, and the per-commit scan
+measures that supply as the block group's wholly free full stripes.
+But a wholly free stripe inside a live stripe run's range cannot be
+claimed: btrfs_stripe_run_range_usable() rejects any claim overlapping
+a run object, because a second run over the same range would make the
+range-to-run lookups ambiguous. The run was claimed over the stripe,
+the extents allocated there were freed again, and the run has not been
+freed yet. For a COW run that window closes at the next commit; a
+nodatacow inode's private run deliberately survives commits and lives
+until the inode is evicted.
+
+On a raid56 filesystem filled to ENOSPC by fsstress (thousands of
+fallocated files, so thousands of cached inodes each holding a private
+NOCOW run) a live walk of the free space cache showed the accounting
+exact -- the wholly free stripes summed to bytes_stripe_claimable to the
+byte -- and 99% of them inside the ranges of open NOCOW runs with no
+inflight IO: 22.8 MiB of 22.8 MiB behind 387 runs in one group, 73.4 MiB
+of 73.4 MiB behind 976 runs in another. Every claim failed in O(1) on
+the "no claimable run" verdict, every write() admitted against the 99 MiB
+of phantom supply failed at writeback, and the data was dropped ("data
+writeback allocation ... returned ENOSPC despite reservation margin"),
+about 100,000 delalloc ranges per run of the degraded acceptance suite
+where the stock allocator drops none.
+
+Have the scan take such stripes out of the claimable supply: count them
+in stripe_unusable, which btrfs_space_info_used() already charges so the
+gate cannot admit against them, and record them separately as
+stripe_stranded so that btrfs_stripe_bg_wants_reclaim() does not ask
+relocation to recover space that comes back by itself. When a run is
+freed, mark its group for rescan so the next commit credits the stripes
+back. The space_info total is exposed as bytes_stripe_stranded in sysfs
+and in the space info dump.
+
+This makes the gate honest -- write() gets the ENOSPC instead of
+writeback dropping the data -- but does not return the stranded space
+while the runs live; that is the run lifecycle's business.
+
+The space_info totals are kept equal to the sum of the armed groups:
+claim, arm, disarm and rescan update a group's value and the total
+together under sinfo->lock, and the commit scan sums the groups under
+sinfo->lock while it holds groups_sem. Reading the groups unlocked and
+assigning the totals later lost or doubled updates made in between, and a
+group made read-only could have its whole claimable supply counted again
+until the next commit, admitting writes that writeback could not place.
+The scan does not restore the stripe_meta margin and reserve when
+stripe_alloc was disabled after it started.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 86 +++++++++++++++++++++++++++++++------
+ fs/btrfs/block-group.h | 12 ++++++
+ fs/btrfs/free-space-cache.c | 76 +++++++++++++++++++-------------
+ fs/btrfs/space-info.h | 5 +++
+ fs/btrfs/sysfs.c | 2 +
+ 5 files changed, 137 insertions(+), 44 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 66d0550af7be6..087a3fa1e3fc8 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -596,6 +596,14 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
+ list_del(&run->list);
+ bitmap_free(run->live);
+ kfree(run);
++ /*
++ * Wholly free stripes inside this run's range were counted as trapped
++ * by the last stripe_unusable scan (btrfs_stripe_run_stranded_stripes());
++ * with the run gone they are claimable again, so have the next commit
++ * rescan the group and credit them back.
++ */
++ if (READ_ONCE(bg->stripe_unusable_ready))
++ set_bit(BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY, &bg->runtime_flags);
+ wake_up_var(&bg->open_stripe_runs);
+ }
+
+@@ -1058,6 +1066,42 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ return true;
+ }
+
++/*
++ * For the stripe_unusable scan: whole free stripes inside a live run's
++ * range cannot be claimed while the run exists
++ * (btrfs_stripe_run_range_usable()), so they must not count as claimable
++ * or the admission gate would admit writes that cannot be placed. Clear
++ * them from @freep and return their total; free_open_stripe_run() marks the
++ * group for rescan so they are credited back when the run goes. Caller
++ * holds ctl->tree_lock; stripe_run_lock nests inside it.
++ */
++u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
++ u64 nstripes)
++{
++ const u64 fsl = bg->full_stripe_len;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ u64 stranded = 0;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ u64 idx, last;
++
++ if (run->end <= run->start)
++ continue;
++ idx = div64_u64(run->start - bg->start, fsl);
++ last = div64_u64(run->end - 1 - bg->start, fsl);
++ for (; idx <= last && idx < nstripes; idx++) {
++ if (freep[idx] != fsl)
++ continue;
++ freep[idx] = 0;
++ stranded += fsl;
++ }
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ return stranded;
++}
++
+ /*
+ * Is the full stripe at @stripe inside a live run's range, i.e. stranded by
+ * the rule of btrfs_stripe_run_stranded_stripes()? Caller holds
+@@ -1742,6 +1786,7 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ u64 total = 0;
+ u64 total_claimable = 0;
+ u64 total_claimable_reloc = 0;
++ u64 total_stranded = 0;
+ int raid;
+
+ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
+@@ -1766,29 +1811,44 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ */
+ if (force || dirty)
+ btrfs_block_group_rescan_stripe_unusable(bg);
+- /*
+- * Sum the authoritative per-group values into the
+- * space_info total so it cannot drift from repeated
+- * arm/disarm/rescan deltas. Disarmed (read-only)
+- * groups are excluded; their free space is already
+- * accounted as read-only.
+- */
+- if (READ_ONCE(bg->stripe_unusable_ready)) {
+- total += READ_ONCE(bg->stripe_unusable);
+- total_claimable +=
+- READ_ONCE(bg->stripe_claimable);
++ }
++ }
++
++ /*
++ * Sum the authoritative per-group values into the space_info
++ * total so it cannot drift from repeated arm/disarm/rescan
++ * deltas. Disarmed (read-only) groups are excluded; their
++ * free space is already accounted as read-only. Every update
++ * of a group's values also updates the total under
++ * sinfo->lock, so summing under it gives totals that match
++ * the groups: claims, arms and disarms that race with the
++ * scan are neither lost nor counted twice.
++ */
++ spin_lock(&sinfo->lock);
++ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
++ struct btrfs_block_group *bg;
++
++ if (!(btrfs_raid_array[raid].bg_flag &
++ BTRFS_BLOCK_GROUP_RAID56_MASK))
++ continue;
++ list_for_each_entry(bg, &sinfo->block_groups[raid],
++ list) {
++ if (bg->stripe_unusable_ready) {
++ total += bg->stripe_unusable;
++ total_stranded += READ_ONCE(bg->stripe_stranded);
++ total_claimable += bg->stripe_claimable;
+ if (bg->start == READ_ONCE(fs_info->data_reloc_bg))
+ total_claimable_reloc +=
+- READ_ONCE(bg->stripe_claimable);
++ bg->stripe_claimable;
+ }
+ }
+ }
+ up_read(&sinfo->groups_sem);
+
+- spin_lock(&sinfo->lock);
+ sinfo->bytes_stripe_unusable = total;
+ sinfo->bytes_stripe_claimable = total_claimable;
+ sinfo->bytes_stripe_claimable_reloc = total_claimable_reloc;
++ sinfo->bytes_stripe_stranded = total_stranded;
+ /*
+ * The rescan usually lowers the counter (mid-transaction
+ * incremental adds overcount conservatively); admission
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index b114e1ded4966..b40feebcdecbc 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -268,6 +268,16 @@ struct btrfs_block_group {
+ * free_space_ctl->tree_lock and space_info->lock.
+ */
+ u64 stripe_unusable;
++ /*
++ * The part of stripe_unusable that is wholly free stripes lying inside
++ * live stripe-run ranges (stripe_alloc): the run was claimed over them,
++ * the extents allocated there were freed again, and the run object
++ * still exists, so btrfs_stripe_run_range_usable() refuses to claim
++ * them. Trapped for admission, but they come back by themselves when
++ * the run is freed, so reclaim leaves them out. Set by the same scan,
++ * under the same lock.
++ */
++ u64 stripe_stranded;
+ /*
+ * Directly measured claimable supply: bytes of fully free, aligned
+ * whole stripes in the free space cache -- exactly what
+@@ -438,6 +448,8 @@ void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
+ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
+ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
+ bool btrfs_stripe_in_open_run(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);
+ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ u64 run_start, u64 *run_len);
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index e87902bf993ef..8b7f241b0cd91 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1529,6 +1529,10 @@ static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
+ * free space is never credited here (see add_free_space()), save a trim's
+ * return (stripe_trim_claimable()); the commit rescan restores it. Caller
+ * holds ctl->tree_lock.
++ *
++ * The group's value and the space_info total change in one sinfo->lock
++ * section, as everywhere else, so that btrfs_scan_stripe_unusable(), which
++ * sums the groups under that lock, never sees one without the other.
+ */
+ static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta)
+ {
+@@ -1536,14 +1540,16 @@ static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta)
+
+ if (!READ_ONCE(bg->stripe_unusable_ready) || !delta)
+ return;
++ if (!sinfo) {
++ if (delta < 0 && bg->stripe_claimable < (u64)-delta)
++ delta = -(s64)bg->stripe_claimable;
++ bg->stripe_claimable += delta;
++ return;
++ }
++ spin_lock(&sinfo->lock);
+ if (delta < 0 && bg->stripe_claimable < (u64)-delta)
+ delta = -(s64)bg->stripe_claimable;
+- if (!delta)
+- return;
+ bg->stripe_claimable += delta;
+- if (!sinfo)
+- return;
+- spin_lock(&sinfo->lock);
+ if (delta < 0 && sinfo->bytes_stripe_claimable < (u64)-delta)
+ sinfo->bytes_stripe_claimable = 0;
+ else
+@@ -2188,6 +2194,13 @@ static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
+ "stripe_unusable_scan counted=%llu != free_space=%llu",
+ counted, ctl->free_space);
+
++ /*
++ * Whole stripes stranded behind live stripe runs are free but not
++ * claimable until their run is freed: trapped, like a partial stripe's
++ * free bytes, so the admission gate does not admit writes against them.
++ */
++ bg->stripe_stranded = btrfs_stripe_run_stranded_stripes(bg, freep, nstripes);
++ trapped = bg->stripe_stranded;
+ for (i = 0; i < nstripes; i++)
+ if (freep[i] && freep[i] < fsl)
+ trapped += freep[i];
+@@ -2249,22 +2262,19 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
+ return;
+ }
+ trapped = stripe_unusable_scan(bg, freep, nstripes);
+- bg->stripe_unusable = trapped;
+ /* Every free byte is claimable or trapped; the scan split them. */
+- bg->stripe_claimable = ctl->free_space - trapped;
+- claimable = bg->stripe_claimable;
++ claimable = ctl->free_space - trapped;
++ /* Group and total together; see stripe_claimable_mod(). */
++ spin_lock(&bg->space_info->lock);
++ bg->stripe_unusable = trapped;
++ bg->stripe_claimable = claimable;
+ bg->stripe_unusable_ready = true;
++ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info, trapped);
++ btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
++ claimable);
++ spin_unlock(&bg->space_info->lock);
+ spin_unlock(&ctl->tree_lock);
+ kvfree(freep);
+-
+- if (trapped || claimable) {
+- spin_lock(&bg->space_info->lock);
+- btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
+- trapped);
+- btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
+- claimable);
+- spin_unlock(&bg->space_info->lock);
+- }
+ }
+
+ /*
+@@ -2289,22 +2299,20 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+ spin_unlock(&ctl->tree_lock);
+ return;
+ }
++ /* Group and total together; see stripe_claimable_mod(). */
++ spin_lock(&bg->space_info->lock);
+ trapped = bg->stripe_unusable;
+ claimable = bg->stripe_claimable;
+ bg->stripe_claimable = 0;
+ bg->stripe_unusable_ready = false;
++ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
++ -(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);
+ spin_unlock(&ctl->tree_lock);
+-
+- if (trapped || claimable) {
+- spin_lock(&bg->space_info->lock);
+- btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
+- -(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);
+- }
+ }
+
+
+@@ -2332,10 +2340,9 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
+ stripe_return_clusters(bg);
+ spin_lock(&ctl->tree_lock);
+ if (bg->stripe_unusable_ready) { /* skip if disarmed (read-only) */
+- u64 scanned;
++ const u64 trapped = stripe_unusable_scan(bg, freep, nstripes);
++ const u64 scanned = ctl->free_space - trapped;
+
+- bg->stripe_unusable = stripe_unusable_scan(bg, freep, nstripes);
+- scanned = ctl->free_space - bg->stripe_unusable;
+ /*
+ * The incremental rules may only under-count claimable
+ * supply; more than the scan finds means a missed debit,
+@@ -2346,7 +2353,14 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
+ WARN_RATELIMIT(bg->stripe_claimable > scanned,
+ "bg %llu incremental stripe_claimable %llu above scanned %llu",
+ bg->start, bg->stripe_claimable, scanned);
++ /*
++ * Under sinfo->lock so btrfs_scan_stripe_unusable() sums
++ * both new values or both old ones.
++ */
++ spin_lock(&bg->space_info->lock);
++ bg->stripe_unusable = trapped;
+ bg->stripe_claimable = scanned;
++ spin_unlock(&bg->space_info->lock);
+ }
+ spin_unlock(&ctl->tree_lock);
+ kvfree(freep);
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index fadf817652d3e..cba0232fa04a3 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -164,6 +164,11 @@ struct btrfs_space_info {
+ stripes stranded behind live runs.
+ Counted as used, and subtracted in
+ statfs. */
++ u64 bytes_stripe_stranded; /* the part of bytes_stripe_unusable that
++ is whole stripes stranded behind live
++ stripe runs (see the block group's
++ stripe_stranded); back to claimable when
++ the runs are freed */
+ u64 bytes_stripe_claimable_reloc; /* the part of bytes_stripe_claimable
+ in the group dedicated to data
+ relocation (fs_info->data_reloc_bg):
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 7825318e2d07e..044b44c580f6e 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -817,6 +817,7 @@ 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_stranded);
+ SPACE_INFO_ATTR(bytes_stripe_claimable);
+ SPACE_INFO_ATTR(bytes_stripe_open);
+ SPACE_INFO_ATTR(bytes_stripe_margin);
+@@ -950,6 +951,7 @@ 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_stranded),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_claimable),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_open),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_margin),
+--
+2.47.3
+
+++ /dev/null
-From 8e25e060df10050ba0d652f78319d7fd1a4a275c Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:47 -0400
-Subject: [RFC PATCH 027/116] btrfs: stripe_alloc: warn when raid56 metadata is
- not covered
-To: linux-btrfs@vger.kernel.org
-
-stripe_alloc closes the write hole for raid56 data. It does nothing for
-raid56 metadata, which keeps read-modify-write and keeps the hole, and
-on a mixed-block-group filesystem it now does nothing at all. A user
-who enables stripe_alloc on -d raid5 -m raid5 has every reason to
-believe the filesystem is covered, and finds out otherwise only after a
-crash on a degraded array -- with metadata damage, which is worse than
-the data damage they were protecting against.
-
-Say it once at mount, after the block groups are read, so the message
-reflects what is actually on disk rather than what was asked for. A
-warning, not an error: the data guarantee is real and worth having on
-its own, and a filesystem can be converted to raid1c3/raid1c4 metadata
-without unmounting.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 23 +++++++++++++++++++++++
- 1 file changed, 23 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 29473031c9226..81eecb45190b8 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1690,6 +1690,28 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
- }
- }
-
-+/*
-+ * stripe_alloc covers raid56 *data* block groups only. A filesystem whose
-+ * metadata is also raid56 keeps the write hole there. The data guarantee is
-+ * easy to read as a filesystem-wide one, so say once, when the policy turns
-+ * on, what is not covered. That is btrfs_enable_stripe_alloc(): at mount the
-+ * property applies after the block groups are read, so a report from
-+ * btrfs_read_block_groups() would find the flag still clear. (Mixed block
-+ * groups cannot get here: the property refuses them.)
-+ */
-+static void warn_stripe_alloc_uncovered(struct btrfs_fs_info *info)
-+{
-+ const u64 meta_bits = info->avail_metadata_alloc_bits |
-+ info->avail_system_alloc_bits;
-+
-+ if (!btrfs_test_opt(info, STRIPE_ALLOC))
-+ return;
-+
-+ if (meta_bits & BTRFS_BLOCK_GROUP_RAID56_MASK)
-+ btrfs_warn(info,
-+"stripe_alloc does not cover raid56 metadata: the write hole remains for metadata, consider converting it to raid1c3/raid1c4");
-+}
-+
- /*
- * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
- * property on the top-level subvolume's root directory. Runs during mount
-@@ -1706,6 +1728,7 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
- if (ret)
- return ret;
- btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
-+ warn_stripe_alloc_uncovered(fs_info);
- /*
- * Arm stripe_unusable accounting for raid56 data groups whose caches
- * loaded before the policy was enabled: block groups are read before
---
-2.47.3
-
--- /dev/null
+From 42a2d55cf0d1a42daf2b0e52b1dbfea8c106ff5d Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:20 -0400
+Subject: [RFC PATCH 28/85] btrfs: stripe_alloc: count nocow run lifecycles and
+ stranded stripes in sysfs
+To: linux-btrfs@vger.kernel.org
+
+Add a stripe_run_stats file beside stripe_park_stats with lifetime
+counters for the paths the previous two patches touched, so a test can
+show that it exercised them rather than merely passed: private NOCOW
+runs opened, claim candidates refused for overlapping a live run, bytes
+of whole stripes the scans found stranded behind live runs, and rescans
+requested by a freed run to credit its stripes back.
+
+A persistent nocow run whose allocations have all been freed is dead: it
+owns no data and only strands the whole stripes in its range (99% of the
+free whole stripes of every read-write group sat inside such runs after an
+fsstress fallocate load). btrfs_stripe_run_note_free(), from
+btrfs_add_free_space(), clears the live bits of freed sectors inside a
+persistent run, and close_block_group_stripe_runs() closes a persistent
+run that handed out space, has nothing in flight and no live bit set, on
+the normal commit path that frees it and marks its group for the rescan.
+A run with any live byte stays open, so a slowly appended nocow file still
+burns no stripe per commit; a run whose map was retired is never taken as
+dead. The free path only clears bits under bg->stripe_run_lock.
+nocow_run_dead_closed counts the closes.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 10 ++++++++--
+ fs/btrfs/fs.h | 11 +++++++++++
+ fs/btrfs/sysfs.c | 18 ++++++++++++++++++
+ 3 files changed, 37 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 087a3fa1e3fc8..ab878c47451d0 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -602,8 +602,10 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
+ * with the run gone they are claimable again, so have the next commit
+ * rescan the group and credit them back.
+ */
+- if (READ_ONCE(bg->stripe_unusable_ready))
++ if (READ_ONCE(bg->stripe_unusable_ready)) {
+ set_bit(BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY, &bg->runtime_flags);
++ atomic64_inc(&bg->fs_info->stripe_run_stats.strand_rescan_marks);
++ }
+ wake_up_var(&bg->open_stripe_runs);
+ }
+
+@@ -1060,8 +1062,10 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
+ len = run->start - run_start;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+- if (len < bg->full_stripe_len)
++ if (len < bg->full_stripe_len) {
++ atomic64_inc(&bg->fs_info->stripe_run_stats.claim_refused_live_run);
+ return false;
++ }
+ *run_len = len;
+ return true;
+ }
+@@ -1099,6 +1103,8 @@ u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
+ }
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ if (stranded)
++ atomic64_add(stranded, &bg->fs_info->stripe_run_stats.strand_scan_bytes);
+ return stranded;
+ }
+
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index a069482d73257..1a028b6b25681 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -854,6 +854,17 @@ struct btrfs_fs_info {
+ atomic64_t pad_decline_uncovered;
+ atomic64_t congestion_short;
+ } stripe_park_stats;
++ /* Stripe run lifecycle counters (sysfs stripe_run_stats). */
++ struct {
++ /* private NOCOW runs opened (they outlive commits) */
++ atomic64_t nocow_run_opened;
++ /* claim candidates refused for overlapping a live run */
++ atomic64_t claim_refused_live_run;
++ /* bytes of whole stripes the scans found stranded behind live runs */
++ atomic64_t strand_scan_bytes;
++ /* rescans requested by a freed run to credit its stripes back */
++ atomic64_t strand_rescan_marks;
++ } stripe_run_stats;
+ /*
+ * Park deadlines, ms (sysfs); 0 disables parking for that class. See
+ * rbio_try_park().
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 044b44c580f6e..a6f318f4b84b0 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1145,6 +1145,23 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ }
+ BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
+
++static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
++ struct kobj_attribute *a, char *buf)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++
++ return sysfs_emit(buf,
++ "nocow_run_opened %lld\n"
++ "claim_refused_live_run %lld\n"
++ "strand_scan_bytes %lld\n"
++ "strand_rescan_marks %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));
++}
++BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
++
+ /*
+ * Park deadlines, ms; 0 disables parking for that class. See
+ * rbio_try_park().
+@@ -1548,6 +1565,7 @@ static const struct attribute *btrfs_attrs[] = {
+ BTRFS_ATTR_PTR(, bg_reclaim_threshold),
+ BTRFS_ATTR_PTR(, commit_stats),
+ BTRFS_ATTR_PTR(, stripe_park_stats),
++ BTRFS_ATTR_PTR(, stripe_run_stats),
+ BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
+ BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
+ BTRFS_ATTR_PTR(, stripe_park_congestion),
+--
+2.47.3
+
+++ /dev/null
-From cf439cf4ee591597df487b491b3b8641d5361f3b Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:48 -0400
-Subject: [RFC PATCH 028/116] btrfs: stripe_alloc: report read-modify-write of
- uncovered stripes
-To: linux-btrfs@vger.kernel.org
-
-The mount-time warning says which block groups stripe_alloc does not
-cover. It cannot say whether anything is actually landing there, and on
-a filesystem with raid56 metadata that is the interesting question: every
-sub-stripe write to an uncovered stripe is a write hole window, where
-parity and data reach the disk separately and a crash in between leaves
-the stripe unreconstructible.
-
-Report it from the one place that knows the write is going out as a
-read-modify-write rather than as a full or padded stripe. Rate limited,
-because a raid56-metadata filesystem does this continuously and the point
-is to make the exposure visible rather than to fill the log, and paired
-with a meta_rmw counter in the existing stripe_park_stats sysfs file so
-the rate can be read off without grepping dmesg.
-
-Silent when stripe_alloc is off: there the whole filesystem works this
-way and the user has asked for nothing else.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/fs.h | 1 +
- fs/btrfs/raid56.c | 41 +++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/sysfs.c | 6 ++++--
- 3 files changed, 46 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index eb05e89bb5a15..c0f174cf5f256 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -817,6 +817,7 @@ struct btrfs_fs_info {
- atomic64_t kicked;
- atomic64_t rmw_reads;
- atomic64_t padded;
-+ atomic64_t meta_rmw;
- } stripe_park_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 850011c8b5555..8248960c7c150 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -2848,6 +2848,43 @@ static bool need_read_stripe_sectors(struct btrfs_raid_bio *rbio)
- return false;
- }
-
-+/*
-+ * Report a sub-stripe write that is going out as a read-modify-write.
-+ *
-+ * With stripe_alloc on, data never gets here: it is either a full stripe or
-+ * padded up to one. Metadata, system chunks and anything in a mixed block
-+ * group are not covered by the allocator, so those still update stripes in
-+ * place -- and every such write is a write hole window, where parity and
-+ * data reach the disk separately and a crash between them leaves the stripe
-+ * unreconstructible. The mount-time warning says the exposure exists; this
-+ * says it is actually happening, and how often.
-+ *
-+ * Rate limited: a raid56-metadata filesystem does this continuously, and
-+ * the point is to make the exposure visible, not to fill the log. Silent
-+ * when stripe_alloc is off, where the entire filesystem works this way and
-+ * the user has asked for nothing else.
-+ */
-+static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return;
-+ /*
-+ * The exact complement of btrfs_is_stripe_alloc_bg(): everything
-+ * that is not data-without-metadata. Note this includes system
-+ * chunks, which carry no METADATA bit but are the chunk tree.
-+ */
-+ if ((rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA) &&
-+ !(rbio->bioc->map_type & BTRFS_BLOCK_GROUP_METADATA))
-+ return;
-+
-+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw);
-+ btrfs_warn_rl(fs_info,
-+"read-modify-write of full stripe %llu: this block group is not covered by stripe_alloc, the raid56 write hole applies to it",
-+ rbio->bioc->full_stripe_logical);
-+}
-+
- static void rmw_rbio(struct btrfs_raid_bio *rbio)
- {
- struct bio_list bio_list;
-@@ -2910,6 +2947,10 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- goto out;
- }
-
-+ /* Still a sub-stripe write: this stripe is being modified in place. */
-+ if (!rbio_is_full(rbio) && !test_bit(RBIO_PADDED_BIT, &rbio->flags))
-+ report_uncovered_rmw(rbio);
-+
- /*
- * At this stage we're not allowed to add any new bios to the
- * bio list any more, anyone else that wants to change this stripe
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index dc12af3ed39a9..106e804b6363e 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1125,14 +1125,16 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "kicked %lld\n"
- "expired %lld\n"
- "padded %lld\n"
-- "rmw_reads %lld\n",
-+ "rmw_reads %lld\n"
-+ "meta_rmw %lld\n",
- atomic64_read(&fs_info->stripe_park_stats.parked),
- atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
- atomic64_read(&fs_info->stripe_park_stats.filled),
- atomic64_read(&fs_info->stripe_park_stats.kicked),
- atomic64_read(&fs_info->stripe_park_stats.expired),
- atomic64_read(&fs_info->stripe_park_stats.padded),
-- atomic64_read(&fs_info->stripe_park_stats.rmw_reads));
-+ atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
-+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw));
- }
- BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
-
---
-2.47.3
-
+++ /dev/null
-From 30d77543640f438ee389f66b5e06fb766dbab2bc Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:49 -0400
-Subject: [RFC PATCH 029/116] btrfs: raid56: say whether a metadata
- read-modify-write is a write hole
-To: linux-btrfs@vger.kernel.org
-
-meta_rmw counts sub-stripe metadata writes, which is a proxy for exposure
-rather than a measurement of it. A stripe modified in place is only a write
-hole if it holds data some completed transaction is relying on; a stripe
-that two writes of the *same* transaction happen to split costs an extra
-read but risks nothing, because a tear loses that whole transaction anyway.
-The counter cannot tell those apart, so it cannot answer the only question
-that matters.
-
-The rbio can. A read-modify-write has already read every column the write
-does not cover, so at the point of the report it is holding the stripe's
-on-disk contents. Walk the uncovered tree block positions and read their
-headers: a block whose bytenr and fsid match belongs there, and its
-generation says which transaction put it there. Compare that against the
-generation of the blocks this write is carrying, taken from the same rbio,
-so a transaction committing concurrently cannot skew the verdict:
-
- meta_rmw_cur the same transaction's own blocks -- a cost
- meta_rmw_old an earlier transaction's -- a write hole
- meta_rmw_free no tree block there at all
-
-System block groups are classified too, not just metadata ones. A system
-chunk carries no METADATA bit, so a flags test excludes it, but it holds
-the chunk tree: the same tree block header, the same generation field, and
-a worse consequence if a degraded crash tears it, since without the chunk
-tree no logical address can be mapped at all. meta_rmw already counted
-system chunks; only the classification skipped them, so their read-modify-
-writes were visible as a rate and never as a verdict. Whether a raid56
-system chunk ever rewrites parity over a committed tree block is therefore
-an open question that this answers by measurement rather than by reasoning
-about how the chunk tree is laid out.
-
-This trusts nothing the allocator says about itself. The stripe runs, the
-liveness map and the drain accounting are all bookkeeping that could be
-wrong in the same way twice; the header in the sector is what a degraded
-read would actually have to reconstruct.
-
-On a 3-device raid5 filesystem with raid5 metadata, 6000 small files with
-periodic syncs and then a third rewritten, plain stripe_alloc reports 249
-sub-stripe metadata writes of which 174 rewrite parity over committed tree
-blocks. Adding stripe_meta leaves 37 sub-stripe writes and none of them.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/fs.h | 9 ++++
- fs/btrfs/raid56.c | 127 ++++++++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/sysfs.c | 10 +++-
- 3 files changed, 144 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index c0f174cf5f256..c5c8e26ea00a4 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -818,6 +818,15 @@ struct btrfs_fs_info {
- atomic64_t rmw_reads;
- atomic64_t padded;
- atomic64_t meta_rmw;
-+ /*
-+ * Breakdown of what a metadata read-modify-write found in the
-+ * columns it did not cover: a tree block of the generation
-+ * being written (a cost), an older one (a write hole), or no
-+ * tree block at all. See audit_uncovered_rmw().
-+ */
-+ atomic64_t meta_rmw_cur;
-+ atomic64_t meta_rmw_old;
-+ atomic64_t meta_rmw_free;
- } stripe_park_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 8248960c7c150..7c15583651fc2 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -2848,6 +2848,132 @@ static bool need_read_stripe_sectors(struct btrfs_raid_bio *rbio)
- return false;
- }
-
-+/*
-+ * Read the header of the tree block at data-stripe sector @i, if there is
-+ * one, from whichever copy of the sector this rbio is holding.
-+ *
-+ * @from_bio picks the source: the caller's pages (what this write is putting
-+ * there) or the stripe pages (what an RMW read found on the disk). Returns
-+ * false when the sector holds no tree block that belongs at this address --
-+ * free space, or the remains of one from a previous life of the stripe.
-+ */
-+static bool rmw_peek_eb_generation(struct btrfs_raid_bio *rbio, u32 i,
-+ bool from_bio, u64 *generation)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ const int stripe_nr = i / rbio->stripe_nsectors;
-+ const int sectornr = i % rbio->stripe_nsectors;
-+ const u64 logical = rbio->bioc->full_stripe_logical +
-+ (u64)stripe_nr * rbio->bioc->stripe_len +
-+ (u64)sectornr * fs_info->sectorsize;
-+ const phys_addr_t *paddrs = from_bio ? rbio->bio_paddrs
-+ : rbio->stripe_paddrs;
-+ struct btrfs_header *hdr;
-+ phys_addr_t paddr;
-+ u64 found_bytenr;
-+ bool bad_fsid;
-+ void *kaddr;
-+
-+ paddr = paddrs[i * rbio->sector_nsteps];
-+ if (paddr == INVALID_PADDR)
-+ return false;
-+ if (!from_bio && !test_bit(i, rbio->stripe_uptodate_bitmap))
-+ return false;
-+
-+ kaddr = kmap_local_paddr(paddr);
-+ hdr = kaddr;
-+ found_bytenr = btrfs_stack_header_bytenr(hdr);
-+ *generation = btrfs_stack_header_generation(hdr);
-+ bad_fsid = memcmp(hdr->fsid, fs_info->fs_devices->metadata_uuid,
-+ BTRFS_FSID_SIZE) != 0;
-+ kunmap_local(kaddr);
-+
-+ return found_bytenr == logical && !bad_fsid;
-+}
-+
-+/*
-+ * Decide whether an uncovered read-modify-write is a write hole or only a
-+ * cost, by looking at what is actually in the stripe.
-+ *
-+ * An RMW has read every column this write does not cover, so the rbio is
-+ * holding the stripe's on-disk contents. Any tree block found there is
-+ * about to have its parity recomputed and rewritten underneath it while its
-+ * own sectors stay put -- the classic torn-stripe window. What decides
-+ * whether that matters is the block's generation:
-+ *
-+ * - equal to the generation of the blocks this write carries, and the block
-+ * belongs to the transaction now in flight. A crash loses that whole
-+ * transaction anyway, so a torn stripe costs nothing that was ever
-+ * committed. This is the residual stripe_meta leaves behind.
-+ *
-+ * - older, and the stripe holds committed metadata. That is a write hole,
-+ * and it means the allocator let a stripe be revisited after the
-+ * transaction that filled it completed.
-+ *
-+ * The comparison is against this rbio's own covered blocks rather than
-+ * fs_info's committed generation so that a transaction committing
-+ * concurrently cannot skew the verdict: both numbers come from the same
-+ * stripe at the same instant.
-+ */
-+static void audit_uncovered_rmw(struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ const u32 sectors_per_tree = fs_info->nodesize >> fs_info->sectorsize_bits;
-+ const u32 nsectors = rbio->nr_data * rbio->stripe_nsectors;
-+ u64 write_gen = 0;
-+
-+ /*
-+ * Tree blocks only, which means metadata block groups and system
-+ * block groups both: a system chunk carries no METADATA bit, but it
-+ * holds the chunk tree, whose blocks have the same header and whose
-+ * loss is worse than any other tree's -- without it nothing maps.
-+ * A mixed block group's sectors need not be tree blocks at all, so
-+ * anything carrying DATA is excluded.
-+ */
-+ if (rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA)
-+ return;
-+ if (!(rbio->bioc->map_type & (BTRFS_BLOCK_GROUP_METADATA |
-+ BTRFS_BLOCK_GROUP_SYSTEM)))
-+ return;
-+
-+ /*
-+ * Both loops read bio_paddrs to tell what this write covers, and the
-+ * paths that reach here do not all populate it (a cached rbio that
-+ * failed to pad never indexes). Idempotent, so just do it.
-+ */
-+ index_rbio_pages(rbio);
-+
-+ /* The generation this write is putting into the stripe. */
-+ for (u32 i = 0; i < nsectors; i += sectors_per_tree) {
-+ u64 gen;
-+
-+ if (rmw_peek_eb_generation(rbio, i, true, &gen))
-+ write_gen = max(write_gen, gen);
-+ }
-+ if (!write_gen)
-+ return;
-+
-+ for (u32 i = 0; i < nsectors; i += sectors_per_tree) {
-+ u64 gen;
-+
-+ /* Covered by this write: it is what we are putting there. */
-+ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
-+ continue;
-+ if (!rmw_peek_eb_generation(rbio, i, false, &gen)) {
-+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_free);
-+ continue;
-+ }
-+ if (gen >= write_gen) {
-+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_cur);
-+ continue;
-+ }
-+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_old);
-+ btrfs_warn_rl(fs_info,
-+"read-modify-write of stripe %llu rewrites parity over committed tree block at generation %llu while writing generation %llu: write hole",
-+ rbio->bioc->full_stripe_logical, gen, write_gen);
-+ }
-+}
-+
- /*
- * Report a sub-stripe write that is going out as a read-modify-write.
- *
-@@ -2880,6 +3006,7 @@ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
- return;
-
- atomic64_inc(&fs_info->stripe_park_stats.meta_rmw);
-+ audit_uncovered_rmw(rbio);
- btrfs_warn_rl(fs_info,
- "read-modify-write of full stripe %llu: this block group is not covered by stripe_alloc, the raid56 write hole applies to it",
- rbio->bioc->full_stripe_logical);
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 106e804b6363e..beabada2eacd7 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1126,7 +1126,10 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "expired %lld\n"
- "padded %lld\n"
- "rmw_reads %lld\n"
-- "meta_rmw %lld\n",
-+ "meta_rmw %lld\n"
-+ "meta_rmw_cur %lld\n"
-+ "meta_rmw_old %lld\n"
-+ "meta_rmw_free %lld\n",
- atomic64_read(&fs_info->stripe_park_stats.parked),
- atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
- atomic64_read(&fs_info->stripe_park_stats.filled),
-@@ -1134,7 +1137,10 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.expired),
- atomic64_read(&fs_info->stripe_park_stats.padded),
- atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
-- atomic64_read(&fs_info->stripe_park_stats.meta_rmw));
-+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
-+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
-+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
-+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free));
- }
- BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
-
---
-2.47.3
-
--- /dev/null
+From a970426e4778810f1fb11a61d9893f9d6867fdd3 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:25 -0400
+Subject: [RFC PATCH 29/85] btrfs: stripe_alloc: say at mount whether the
+ policy is on
+To: linux-btrfs@vger.kernel.org
+
+Nothing announced that stripe-exclusive allocation was on. The
+btrfs.stripe_alloc property applies when btrfs_fill_super() reads the
+root directory's inode and its properties, and btrfs_enable_stripe_alloc()
+prints its line only for a set on a live filesystem, so mounting a
+filesystem whose property was already set said nothing.
+
+An absent line therefore meant "off" and "on" equally well, and the only
+way to answer the question was to look at a live filesystem -- no use
+when the filesystem is someone else's, or when all that is left is a log
+from before a crash. Analysing a lockup from a filesystem whose
+btrfs.stripe_alloc property was set, I read that silence as the policy
+being off and said so, which was wrong.
+
+State it once in btrfs_fill_super(), after the root inode has been read
+so the property has had its say. The property path keeps its own line
+for a set on a live filesystem, where there is no mount to report. At
+mount that line still comes too, so a mount with the property set logs
+the state twice, until "btrfs: stripe_alloc: say at mount whether the
+policy is on (debug part)" later in this series quiets it there: it
+needs the runtime enable worker of the write-hole checker.
+
+Nothing is printed when the policy is off, which keeps the common mount
+quiet and makes the absence of the line mean exactly one thing.
+
+Assisted-by: Claude:claude-fable-5-1
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/super.c | 14 ++++++++++++++
+ 1 file changed, 14 insertions(+)
+
+diff --git a/fs/btrfs/super.c b/fs/btrfs/super.c
+index aa1dd20bb7284..bce3a12032b6a 100644
+--- a/fs/btrfs/super.c
++++ b/fs/btrfs/super.c
+@@ -943,6 +943,18 @@ static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objec
+ return 0;
+ }
+
++/*
++ * Log once at mount whether stripe-exclusive allocation is on: the property
++ * is applied silently while the root directory's inode is read.
++ */
++static void btrfs_emit_stripe_alloc_state(struct btrfs_fs_info *info)
++{
++ if (!btrfs_test_opt(info, STRIPE_ALLOC))
++ return;
++ btrfs_info(info,
++ "using stripe-exclusive allocation for raid56 data (filesystem property)");
++}
++
+ static int btrfs_fill_super(struct super_block *sb,
+ struct btrfs_fs_devices *fs_devices)
+ {
+@@ -983,6 +995,8 @@ static int btrfs_fill_super(struct super_block *sb,
+ goto fail_close;
+ }
+
++ btrfs_emit_stripe_alloc_state(fs_info);
++
+ sb->s_root = d_make_root(&inode->vfs_inode);
+ if (!sb->s_root) {
+ ret = -ENOMEM;
+--
+2.47.3
+
--- /dev/null
+From 1093cc1e885e8804cfc10e1528014a38e29c772c Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 1 Oct 2026 00:57:50 -0400
+Subject: [RFC PATCH 30/85] btrfs: stripe_alloc: keep relocation's stripe runs
+ until relocation ends
+To: linux-btrfs@vger.kernel.org
+
+Relocation preallocates each destination extent and writes the data into
+it later, after the commit that ends relocate_block_group(). Under
+stripe_alloc the preallocation lands in a BTRFS_STRIPE_RUN_RELOC run,
+which drains at once (a preallocation has no IO to report) and is freed
+when that commit closes it. By the time the relocated data is written,
+no run covers its stripes: a write that does not cover a whole stripe
+can neither park to merge with its neighbour nor pad, and goes down as a
+read-modify-write. Relocated extents rarely line up with stripes, so
+that is roughly one RMW per relocated extent: an audited data balance on
+a 4-device raid5 made 2247 of them, every one NO_RUN, every one written
+by the data reloc inode into its own preallocation, and none over
+another owner's committed data (the stripes hold only relocation's own
+orphaned copies) -- harmless, but every one a stripe read.
+
+Keep RELOC runs after they close and drain, as metadata runs already are
+for the same reason, until relocation releases them from
+btrfs_release_data_reloc_bg(), which it calls on its way out (after the
+pointer update, before the next relocation can allocate). A retained
+run that has nothing in flight is not waited for by the commit's drain,
+and any forced quiesce of its block group (read-only, removal, unmount)
+releases it first. While retained, its range stays unclaimable and its
+stripes are relocation's alone, so the writes into them park and merge
+or pad like any other run's.
+
+reloc_run_retained / reloc_run_released in stripe_run_stats count the
+runs kept and released.
+
+The open stripe self-test frees the runs it leaves retained, as unmount
+does.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 65 ++++++++++++++++++++++++++++++++++++++----
+ fs/btrfs/fs.h | 3 ++
+ 2 files changed, 62 insertions(+), 6 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index ab878c47451d0..e9b228c7c0dd5 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -495,6 +495,12 @@ struct btrfs_open_stripe_run {
+ u64 owner; /* LOG class: btrfs_ino of the owner */
+ enum btrfs_stripe_run_class class;
+ bool open; /* accepting allocations */
++ /*
++ * Relocation's run: kept after it closes and drains, until relocation
++ * releases it (btrfs_release_stripe_reloc_runs()). See
++ * run_freed_on_drain().
++ */
++ bool retained;
+ /*
+ * One bit per sector of the run, set while the sector holds an
+ * allocation someone still intends to write. Padding uses it to find
+@@ -627,7 +633,7 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
+ tail_len = run->end - run->offset;
+ run->end = run->offset;
+ bg->stripe_open_remainder -= tail_len;
+- if (open_stripe_run_drained(run))
++ if (open_stripe_run_drained(run) && !run->retained)
+ free_open_stripe_run(bg, run);
+ return tail_len;
+ }
+@@ -875,6 +881,9 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ }
+ new_run->bg = bg;
+ new_run->class = class;
++ new_run->retained = class == BTRFS_STRIPE_RUN_RELOC;
++ if (new_run->retained)
++ atomic64_inc(&fs_info->stripe_run_stats.reloc_run_retained);
+ new_run->owner = 0;
+ new_run->start = start;
+ new_run->end = start + len;
+@@ -1475,7 +1484,7 @@ void btrfs_open_stripe_write_abandoned(struct btrfs_block_group *bg, u64 start,
+ ASSERT(run->inflight_bytes >= num_bytes);
+ run_live_set(run, start, num_bytes, false);
+ run->inflight_bytes -= num_bytes;
+- if (open_stripe_run_drained(run))
++ if (open_stripe_run_drained(run) && !run->retained)
+ free_open_stripe_run(bg, run);
+ break;
+ }
+@@ -1501,7 +1510,7 @@ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+ ASSERT(start + num_bytes <= run->offset);
+ ASSERT(run->inflight_bytes >= num_bytes);
+ run->inflight_bytes -= num_bytes;
+- if (open_stripe_run_drained(run))
++ if (open_stripe_run_drained(run) && !run->retained)
+ free_open_stripe_run(bg, run);
+ break;
+ }
+@@ -1577,7 +1586,7 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ ASSERT(run->inflight_bytes >= num_bytes);
+ run->inflight_bytes -= num_bytes;
+- if (open_stripe_run_drained(run))
++ if (open_stripe_run_drained(run) && !run->retained)
+ free_open_stripe_run(bg, run);
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ }
+@@ -1642,6 +1651,10 @@ 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) {
++ /* Nor are retained relocation runs, once nothing is in flight. */
++ if (run->retained && open_stripe_run_drained(run) &&
++ seq != U64_MAX)
++ continue;
+ if (run->open_seq < seq) {
+ ret = false;
+ break;
+@@ -1651,6 +1664,42 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
+ return ret;
+ }
+
++/*
++ * Stop retaining @bg's relocation runs: free the ones already drained, and
++ * let any still open or in flight be freed when they drain, like any other.
++ */
++static void release_retained_stripe_runs(struct btrfs_block_group *bg)
++{
++ struct btrfs_open_stripe_run *run, *tmp;
++ unsigned long flags;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry_safe(run, tmp, &bg->open_stripe_runs, list) {
++ if (!run->retained)
++ continue;
++ run->retained = false;
++ atomic64_inc(&bg->fs_info->stripe_run_stats.reloc_run_released);
++ if (open_stripe_run_drained(run))
++ free_open_stripe_run(bg, run);
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++}
++
++/*
++ * Relocation is done with its destination stripes: release its retained
++ * runs in every block group (the dedication of btrfs_release_data_reloc_bg()
++ * can have moved between groups during the relocation).
++ */
++static void btrfs_release_stripe_reloc_runs(struct btrfs_fs_info *fs_info)
++{
++ struct btrfs_block_group *bg;
++
++ spin_lock(&fs_info->open_stripe_lock);
++ list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
++ release_retained_stripe_runs(bg);
++ spin_unlock(&fs_info->open_stripe_lock);
++}
++
+ /*
+ * Close and drain all of a block group's stripe runs. The caller must
+ * prevent new allocations first (e.g. the block group is read-only),
+@@ -1665,6 +1714,8 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
+ {
+ struct btrfs_fs_info *fs_info = bg->fs_info;
+
++ /* Nothing may outlive this, relocation's retained runs included. */
++ release_retained_stripe_runs(bg);
+ close_block_group_stripe_runs(bg, U64_MAX);
+ /* Parked partial-stripe rbios hold the very bios the wait drains. */
+ btrfs_flush_parked_rbios(fs_info, bg->start, bg->length, false);
+@@ -1928,10 +1979,10 @@ void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info)
+ spin_unlock(&fs_info->relocation_bg_lock);
+
+ if (!bytenr)
+- return;
++ goto release;
+ bg = btrfs_lookup_block_group(fs_info, bytenr);
+ if (!bg)
+- return;
++ goto release;
+ if (bg->space_info) {
+ spin_lock(&bg->space_info->lock);
+ bg->space_info->bytes_stripe_claimable_reloc = 0;
+@@ -1939,6 +1990,8 @@ void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info)
+ }
+ btrfs_close_bg_open_stripes(bg);
+ btrfs_put_block_group(bg);
++release:
++ btrfs_release_stripe_reloc_runs(fs_info);
+ }
+
+ struct btrfs_caching_control *btrfs_get_caching_control(
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 1a028b6b25681..fbb289ddfb99a 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -864,6 +864,9 @@ 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;
++ /* Relocation runs retained past their drain, and released. */
++ atomic64_t reloc_run_retained;
++ atomic64_t reloc_run_released;
+ } stripe_run_stats;
+ /*
+ * Park deadlines, ms (sysfs); 0 disables parking for that class. See
+--
+2.47.3
+
+++ /dev/null
-From 897917b2d1c3004bd01f804fd778ef3360ee920c Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:50 -0400
-Subject: [RFC PATCH 030/116] btrfs: stripe_alloc: tunable park deadlines, and
- say why padding declined
-To: linux-btrfs@vger.kernel.org
-
-The deadline constants are meant to be judged "from measurements rather
-than taste", but they are compile-time, so every data point costs a kernel
-build and a reboot. Measuring a buffered fill -- dd, no fsync, so nothing
-kicks the park and the backstop is the only exit -- found 1861 of 3984
-parks expiring at the 100ms deadline, which is precisely the no-waiter case
-the constant exists for and the one with no numbers behind it.
-
-Expose both deadlines as writable sysfs files, clamped to 60s because a
-parked rbio holds its stripe lock, with 0 disabling parking for that class
-(useful as an experiment in itself):
-
- /sys/fs/btrfs/<uuid>/stripe_park_timeout_ms (default 100)
- /sys/fs/btrfs/<uuid>/stripe_park_sync_timeout_ms (default 3)
-
-Add the counters the stats file cannot supply. rmw_reads counts only
-parked writes that still had to read, so it cannot answer "does this
-workload read-modify-write at all"; data_rmw counts every data RMW, which
-with allow_rmw empty on a covered block group is the number the
-stripe-exclusive claim is about, and it should be zero.
-
-And record why padding refused, because the reasons are different defects:
-the rest of the stripe is allocated and its data has not arrived yet
-(wait longer, or kick when the frontier advances); no open run covers the
-stripe, so the run closed before its own write went down; or the frontier
-never reached the stripe at all. Attributing them turns "some RMW
-remains" into a specific thing to fix.
-
-No behaviour change at the defaults.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 22 ++++++++++++++++++--
- fs/btrfs/disk-io.c | 2 ++
- fs/btrfs/fs.h | 38 ++++++++++++++++++++++++++++++++++
- fs/btrfs/raid56.c | 30 ++++++++++++++++++---------
- fs/btrfs/sysfs.c | 46 ++++++++++++++++++++++++++++++++++++++++++
- 5 files changed, 127 insertions(+), 11 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 81eecb45190b8..e46ce260f71ad 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1315,14 +1315,19 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- {
- struct btrfs_block_group *bg;
- struct btrfs_open_stripe_run *run;
-+ atomic64_t *decline = NULL;
- unsigned long flags;
- bool ret = false;
-
-- if (list_empty_careful(&fs_info->open_stripe_bgs))
-+ if (list_empty_careful(&fs_info->open_stripe_bgs)) {
-+ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
- return false;
-+ }
- bg = btrfs_lookup_block_group(fs_info, stripe_start);
-- if (!bg)
-+ if (!bg) {
-+ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
- return false;
-+ }
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-@@ -1332,10 +1337,23 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- run->offset < stripe_start + stripe_len) {
- *pad_from = run->offset;
- ret = true;
-+ } else if (run->offset >= stripe_start + stripe_len) {
-+ /*
-+ * The frontier is past this stripe: every sector of
-+ * it is allocated, so there is nothing dead to pad
-+ * and the write is waiting on a neighbour's data.
-+ */
-+ decline = &fs_info->stripe_park_stats.pad_decline_live;
-+ } else {
-+ /* The frontier has not reached the stripe at all. */
-+ decline = &fs_info->stripe_park_stats.pad_decline_unallocated;
- }
- break;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ if (!ret)
-+ atomic64_inc(decline ? decline :
-+ &fs_info->stripe_park_stats.pad_decline_no_run);
- btrfs_put_block_group(bg);
- return ret;
- }
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index 7540f7d9e3de1..5d306267e3f47 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -2804,6 +2804,8 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
- INIT_LIST_HEAD(&fs_info->delalloc_roots);
- INIT_LIST_HEAD(&fs_info->caching_block_groups);
- INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
-+ fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
-+ fs_info->stripe_park_sync_timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
- spin_lock_init(&fs_info->open_stripe_lock);
- spin_lock_init(&fs_info->delalloc_root_lock);
- spin_lock_init(&fs_info->trans_lock);
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index c5c8e26ea00a4..8c0456add9d47 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -512,6 +512,16 @@ struct btrfs_delayed_root {
- struct btrfs_free_space_ctl;
- struct btrfs_free_space;
-
-+/*
-+ * Park deadline defaults, ms. Both are tunable at runtime through
-+ * /sys/fs/btrfs/<uuid>/stripe_park_{,sync_}timeout_ms; the constants here
-+ * are only the initial values.
-+ */
-+#define BTRFS_RBIO_PARK_TIMEOUT_MS 100
-+#define BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS 3
-+/* Refuse absurd deadlines: a parked rbio holds its stripe lock. */
-+#define BTRFS_RBIO_PARK_TIMEOUT_MS_MAX 60000
-+
- struct btrfs_fs_info {
- u8 chunk_tree_uuid[BTRFS_UUID_SIZE];
- unsigned long flags;
-@@ -817,6 +827,26 @@ struct btrfs_fs_info {
- atomic64_t kicked;
- atomic64_t rmw_reads;
- atomic64_t padded;
-+ /*
-+ * Data read-modify-writes on a block group the allocator
-+ * covers. With allow_rmw empty this is the number the
-+ * stripe-exclusive claim is about, and it should be zero;
-+ * rmw_reads counts only the parked ones, so it cannot say
-+ * whether a workload RMWs at all.
-+ */
-+ atomic64_t data_rmw;
-+ /*
-+ * Why padding refused, so "some RMW remains" names a defect
-+ * instead of a symptom. live: the rest of the stripe is
-+ * allocated and its data has not arrived (wait longer, or
-+ * kick when the frontier advances). no_run: no open run
-+ * covers the stripe, so the run closed before its own write
-+ * went down (a lifetime problem). unallocated: the run's
-+ * frontier has not reached the stripe being written at all.
-+ */
-+ atomic64_t pad_decline_live;
-+ atomic64_t pad_decline_no_run;
-+ atomic64_t pad_decline_unallocated;
- atomic64_t meta_rmw;
- /*
- * Breakdown of what a metadata read-modify-write found in the
-@@ -831,6 +861,14 @@ struct btrfs_fs_info {
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
- u32 stripe_rmw_prop;
-+ /*
-+ * Parking deadlines in ms, tunable through sysfs so the constants
-+ * can be swept against a workload instead of rebuilt for each
-+ * data point. 0 disables parking for that class. See
-+ * rbio_try_park().
-+ */
-+ u32 stripe_park_timeout_ms;
-+ u32 stripe_park_sync_timeout_ms;
-
- /* Private scrub information */
- struct mutex scrub_lock;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 7c15583651fc2..d117cf701b807 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -75,8 +75,6 @@
- * enough for the rest of one writeback pass over the same stripe to merge
- * in, short enough to stay invisible in fsync latency.
- */
--#define BTRFS_RBIO_PARK_TIMEOUT_MS 100
--#define BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS 3
- /* Scan period of the park timer while anything is parked. */
- #define BTRFS_RBIO_PARK_SCAN_MS 3
-
-@@ -797,7 +795,9 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- {
- struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
- struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
-- unsigned int timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
-+ const unsigned int sync_timeout_ms =
-+ READ_ONCE(fs_info->stripe_park_sync_timeout_ms);
-+ unsigned int timeout_ms = READ_ONCE(fs_info->stripe_park_timeout_ms);
- enum btrfs_stripe_run_class class;
-
- if (!btrfs_stripe_open_run_class(fs_info,
-@@ -807,9 +807,13 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
-
- spin_lock(&rbio->bio_list_lock);
- if (rbio_has_sync_bio(rbio))
-- timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
-+ timeout_ms = sync_timeout_ms;
- spin_unlock(&rbio->bio_list_lock);
-
-+ /* A zeroed deadline disables parking for that class outright. */
-+ if (timeout_ms == 0)
-+ return false;
-+
- /*
- * A sync write into a nodatacow inode's private run has a waiter
- * behind it and nothing worth waiting to merge with: in-place
-@@ -818,7 +822,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- * async writeback there.
- */
- if (class == BTRFS_STRIPE_RUN_NOCOW &&
-- timeout_ms == BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS)
-+ timeout_ms == sync_timeout_ms)
- return false;
-
- /*
-@@ -830,7 +834,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- * path kicks it as soon as they have all been submitted.)
- */
- if (test_bit(RBIO_BATCH_DONE_BIT, &rbio->flags) &&
-- timeout_ms == BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS)
-+ timeout_ms == sync_timeout_ms)
- return false;
-
- spin_lock(&table->parked_lock);
-@@ -1106,7 +1110,8 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
- struct btrfs_stripe_hash_table *table =
- cur->bioc->fs_info->stripe_hash_table;
- unsigned long dl = jiffies +
-- msecs_to_jiffies(BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS);
-+ msecs_to_jiffies(READ_ONCE(cur->bioc->fs_info->
-+ stripe_park_sync_timeout_ms));
-
- spin_lock(&table->parked_lock);
- if (test_bit(RBIO_PARKED_BIT,
-@@ -3055,10 +3060,17 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- */
- if (!rbio_is_full(rbio) && !rmw_try_pad_full(rbio) &&
- need_read_stripe_sectors(rbio)) {
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+
-+ /*
-+ * Every data read-modify-write, parked or not. With
-+ * allow_rmw empty and a covered block group this is the
-+ * count that should be zero.
-+ */
-+ atomic64_inc(&fs_info->stripe_park_stats.data_rmw);
- /* A parked-then-flushed write that still had to read. */
- if (test_bit(RBIO_WAS_PARKED_BIT, &rbio->flags))
-- atomic64_inc(&rbio->bioc->fs_info->
-- stripe_park_stats.rmw_reads);
-+ atomic64_inc(&fs_info->stripe_park_stats.rmw_reads);
- /*
- * Now we're doing sub-stripe write, also need all data stripes
- * to do the full RMW.
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index beabada2eacd7..fbd5158babd99 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1126,6 +1126,10 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "expired %lld\n"
- "padded %lld\n"
- "rmw_reads %lld\n"
-+ "data_rmw %lld\n"
-+ "pad_decline_live %lld\n"
-+ "pad_decline_no_run %lld\n"
-+ "pad_decline_unallocated %lld\n"
- "meta_rmw %lld\n"
- "meta_rmw_cur %lld\n"
- "meta_rmw_old %lld\n"
-@@ -1137,6 +1141,10 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.expired),
- atomic64_read(&fs_info->stripe_park_stats.padded),
- atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw),
-+ atomic64_read(&fs_info->stripe_park_stats.pad_decline_live),
-+ atomic64_read(&fs_info->stripe_park_stats.pad_decline_no_run),
-+ atomic64_read(&fs_info->stripe_park_stats.pad_decline_unallocated),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
-@@ -1144,6 +1152,42 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- }
- BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
-
-+/*
-+ * Park deadlines, ms. Writable so the constants can be swept against a
-+ * workload rather than rebuilt per data point; 0 disables parking for that
-+ * class. See rbio_try_park().
-+ */
-+#define BTRFS_PARK_TIMEOUT_ATTR(_name, _field) \
-+static ssize_t btrfs_##_name##_show(struct kobject *kobj, \
-+ struct kobj_attribute *a, char *buf)\
-+{ \
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj); \
-+ \
-+ return sysfs_emit(buf, "%u\n", READ_ONCE(fs_info->_field)); \
-+} \
-+static ssize_t btrfs_##_name##_store(struct kobject *kobj, \
-+ struct kobj_attribute *a, \
-+ const char *buf, size_t len) \
-+{ \
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj); \
-+ unsigned int val; \
-+ int ret; \
-+ \
-+ ret = kstrtouint(buf, 10, &val); \
-+ if (ret) \
-+ return ret; \
-+ if (val > BTRFS_RBIO_PARK_TIMEOUT_MS_MAX) \
-+ return -EINVAL; \
-+ WRITE_ONCE(fs_info->_field, val); \
-+ return len; \
-+} \
-+BTRFS_ATTR_RW(, _name, btrfs_##_name##_show, btrfs_##_name##_store)
-+
-+BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
-+BTRFS_PARK_TIMEOUT_ATTR(stripe_park_sync_timeout_ms, stripe_park_sync_timeout_ms);
-+
-+
-+
- static ssize_t btrfs_clone_alignment_show(struct kobject *kobj,
- struct kobj_attribute *a, char *buf)
- {
-@@ -1511,6 +1555,8 @@ static const struct attribute *btrfs_attrs[] = {
- BTRFS_ATTR_PTR(, bg_reclaim_threshold),
- BTRFS_ATTR_PTR(, commit_stats),
- BTRFS_ATTR_PTR(, stripe_park_stats),
-+ BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
-+ BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
- BTRFS_ATTR_PTR(, temp_fsid),
- NULL,
- };
---
-2.47.3
-
--- /dev/null
+From 3f01056e9cf437ba083971c5e9d7abb87546e572 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 1 Oct 2026 12:14:49 -0400
+Subject: [RFC PATCH 31/85] btrfs: stripe_alloc: keep a stripe in the rbio
+ cache until its run has written all of it
+To: linux-btrfs@vger.kernel.org
+
+A stripe run hands out its sectors in order, so a stripe it allocates is
+often written in pieces: a write that ends inside the stripe leaves the
+rest to later writes, and writeback allocates a whole range before any of
+its bios complete, so even a stripe the frontier has already passed can
+still have writes in flight. The later writes cannot pad (the earlier
+sectors are live), so unless the stripe is still in the rbio cache each
+is a read-modify-write that reads the earlier sectors back from the
+devices. Those sectors are not yet covered by the csum tree (their
+ordered extents have not finished), so what the devices return goes into
+the new parity unverified. A device that returns wrong data there
+destroys the earlier write, whose only intact copy at that point may be
+the parity: the strip-fault fixture (a device that returns random bytes
+for one strip per stripe) lost a file exactly this way, with every RMW of
+the run in this same-run class.
+
+The cache already prevents that read when the stripe is still cached: the
+later write steals the earlier write's pages (lock_stripe_add()) and reads
+nothing. But the cache is an LRU that any other stripe's write can push
+such a stripe out of. Pin it instead. Each run gets a written map beside
+its live map, set from each completed raid56 write's covered data sectors
+(rbio_orig_end_io(), before the cache decision in unlock_stripe()).
+cache_rbio() pins an rbio whose stripe is still waiting for writes
+(btrfs_stripe_run_incomplete()): an open run's allocation frontier lies
+inside it -- the rest is not even allocated yet, so every sector
+allocated so far may already be written -- or a run covering it, open,
+closed or kept for relocation, has live sectors there not yet written.
+The prune skips live pins and re-checks each against the runs, so a pin
+ends as soon as the stripe is complete or its run goes away. Nodatacow
+runs are excluded from the written check: they are rewritten in place
+for as long as the inode lives and are never complete. RBIO_PIN_MAX
+bounds the pinned entries; no memory is allocated for this, the stripe's
+pages are only released later. A completed write is marked in the run
+that owns it, by [run->start, run->end): the maps reach past run->end
+(they span at least BTRFS_STRIPE_RUN_LIVE_STRIPES stripes), so a write
+must never be recorded in an earlier run whose map merely overlaps it.
+written_not_live in stripe_park_stats counts completed-write sectors that
+are not live in their run, which should stay near zero.
+
+This removes the read rather than adding a recovery step for it: nothing
+here depends on checksums, sectors without them, or the reconstruction
+path. What remains is a stripe's first partial write, which reads only
+sectors nobody has written yet (traced on the fixture: every remaining
+data RMW read was of that kind). rbio_pinned in stripe_park_stats counts
+the pins.
+
+An ordered extent can end without writing all of its sectors (a write
+error, truncation of folios never submitted, a short direct write, teardown
+of an extent whose IO never started). When it reports to its run, its
+whole range is marked written: no write of those sectors is still coming,
+which is all the pin (and any other waiter on the written map) needs to
+know. Marking them written rather than dead keeps them from being padded,
+so nothing a truncated extent kept is zeroed. Waiters are woken while the
+run lock is held, since the run and its group can be freed once it is
+dropped.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 157 ++++++++++++++++++++++++++++++++++++++--
+ fs/btrfs/block-group.h | 6 +-
+ fs/btrfs/fs.h | 4 +
+ fs/btrfs/ordered-data.c | 3 +-
+ fs/btrfs/raid56.c | 131 ++++++++++++++++++++++++++++++---
+ 5 files changed, 283 insertions(+), 18 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index e9b228c7c0dd5..36e2aff3ee49f 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -508,6 +508,13 @@ struct btrfs_open_stripe_run {
+ * were written), which are as safe to zero-fill as space above it.
+ */
+ unsigned long *live;
++ /*
++ * Sectors of @live whose data has been written (raid56 write
++ * completions, btrfs_stripe_run_mark_written()); same size as @live.
++ * A stripe with live sectors not yet written is still waiting for
++ * writes, and its cached rbio stays pinned (raid56.c, cache_rbio()).
++ */
++ unsigned long *written;
+ u32 live_nbits; /* sectors @live covers; caps growth */
+ };
+
+@@ -601,6 +608,7 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
+ ASSERT(open_stripe_run_drained(run));
+ list_del(&run->list);
+ bitmap_free(run->live);
++ bitmap_free(run->written);
+ kfree(run);
+ /*
+ * Wholly free stripes inside this run's range were counted as trapped
+@@ -800,6 +808,8 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+
+ /* 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 ?
++ bitmap_zalloc(new_run->live_nbits, GFP_NOFS) : NULL;
+
+ /*
+ * Install under fs_info->open_stripe_lock so that the block group
+@@ -912,8 +922,10 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ ret = 0;
+ out:
+ /* Unused on every path that did not install it, including errors. */
+- if (new_run)
++ if (new_run) {
+ bitmap_free(new_run->live);
++ bitmap_free(new_run->written);
++ }
+ kfree(new_run);
+ return ret;
+ }
+@@ -999,6 +1011,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+
+ /* 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 ?
++ bitmap_zalloc(new_run->live_nbits, GFP_NOFS) : NULL;
+
+ /* See the installation comment in btrfs_alloc_from_open_stripe(). */
+ spin_lock(&fs_info->open_stripe_lock);
+@@ -1037,8 +1051,10 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ ret = 0;
+ out:
+ /* Unused on every path that did not install it, including errors. */
+- if (new_run)
++ if (new_run) {
+ bitmap_free(new_run->live);
++ bitmap_free(new_run->written);
++ }
+ kfree(new_run);
+ return ret;
+ }
+@@ -1443,6 +1459,121 @@ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ * the commit drain already waits for and everything above it is dead space
+ * padding may fill.
+ */
++/*
++ * The part of [*start, *start + *len) that @run owns and tracks in its
++ * written map: inside [run->start, run->end) -- the map itself reaches
++ * further (it spans at least BTRFS_STRIPE_RUN_LIVE_STRIPES stripes from
++ * run->start, past run->end into later runs' ranges), so it must never be
++ * consulted outside the run's own range -- and inside the map. Nodatacow
++ * runs keep no written map: they are rewritten in place for as long as the
++ * inode lives and are never complete. Caller holds stripe_run_lock.
++ */
++static bool run_written_range(const struct btrfs_open_stripe_run *run,
++ u64 *start, u64 *len)
++{
++ const u32 bits = run->bg->fs_info->sectorsize_bits;
++ u64 lo, hi;
++
++ if (!run->live || !run->written || !run->live_nbits)
++ return false;
++ lo = max(*start, run->start);
++ hi = min3(*start + *len, run->end,
++ run->start + ((u64)run->live_nbits << bits));
++ if (lo >= hi)
++ return false;
++ *start = lo;
++ *len = hi - lo;
++ return true;
++}
++
++/*
++ * A raid56 write of [start, start + len) has completed: mark it written in
++ * the run that owns it. Sectors that are not live in that run (freed while
++ * the write was in flight, or a bookkeeping bug) are counted in
++ * written_not_live: the pad oracle trusts this map to say which allocated
++ * sectors hold data, so a write it misses could be zeroed.
++ */
++void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
++ u64 len)
++{
++ const u32 bits = fs_info->sectorsize_bits;
++ struct btrfs_block_group *bg;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ u32 not_live = 0;
++
++ if (list_empty_careful(&fs_info->open_stripe_bgs))
++ return;
++ bg = btrfs_lookup_block_group(fs_info, start);
++ if (!bg)
++ return;
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ u64 s = start, l = len;
++ u32 first, nr, i;
++
++ if (!run_written_range(run, &s, &l))
++ continue;
++ first = (s - run->start) >> bits;
++ nr = l >> bits;
++ for (i = first; i < first + nr; i++)
++ if (!test_bit(i, run->live))
++ not_live++;
++ bitmap_set(run->written, first, nr);
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ btrfs_put_block_group(bg);
++ if (not_live)
++ atomic64_add(not_live, &fs_info->stripe_park_stats.written_not_live);
++}
++
++/* Has @run allocated sectors in [start, start + len) it has not yet written? */
++static bool run_unwritten_in(struct btrfs_open_stripe_run *run, u64 start,
++ u64 len)
++{
++ const u32 bits = run->bg->fs_info->sectorsize_bits;
++ u32 first, last, i;
++
++ if (!run_written_range(run, &start, &len))
++ return false;
++ first = (start - run->start) >> bits;
++ last = first + (len >> bits);
++ for (i = first; i < last; i++)
++ if (test_bit(i, run->live) && !test_bit(i, run->written))
++ return true;
++ return false;
++}
++
++bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
++ u64 stripe_start, u64 stripe_len)
++{
++ struct btrfs_block_group *bg;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ bool ret = false;
++
++ if (list_empty_careful(&fs_info->open_stripe_bgs))
++ return false;
++ bg = btrfs_lookup_block_group(fs_info, stripe_start);
++ if (!bg)
++ return false;
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (run->open && run->offset > stripe_start &&
++ run->offset < stripe_start + stripe_len) {
++ ret = true;
++ break;
++ }
++ if (run_unwritten_in(run, stripe_start, stripe_len)) {
++ ret = true;
++ break;
++ }
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ btrfs_put_block_group(bg);
++ return ret;
++}
++
+ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
+ {
+ struct btrfs_block_group *bg;
+@@ -1573,19 +1704,33 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
+
+ /*
+ * Pointer-based variant of btrfs_open_stripe_write_done() for callers that
+- * recorded the run at allocation or ordered extent creation time; safe from
+- * bio end_io context. The run pointer stays valid until the reporter's own
+- * bytes are reported: a run with inflight bytes is never freed.
++ * recorded the run at allocation or ordered extent creation time. The run
++ * pointer stays valid until the reporter's own bytes are reported: a run
++ * with inflight bytes is never freed.
++ *
++ * An ordered extent's data IO is over, whether or not all of it reached the
++ * disk: stop counting it as in flight, and mark its sectors written. A
++ * sector whose write failed or was never issued (truncation, a short direct
++ * write, error teardown) will not be written now. Marking it keeps a log
++ * settle from waiting for it forever, and a written sector is never padded,
++ * so a later partial write to the stripe reads it instead of zeroing it.
+ */
+ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+- u64 num_bytes)
++ u64 start, u64 num_bytes)
+ {
+ struct btrfs_block_group *bg = run->bg;
++ const u32 bits = bg->fs_info->sectorsize_bits;
+ unsigned long flags;
++ u64 s = start;
++ u64 l = num_bytes;
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ ASSERT(run->inflight_bytes >= num_bytes);
+ run->inflight_bytes -= num_bytes;
++ if (run_written_range(run, &s, &l))
++ bitmap_set(run->written, (s - run->start) >> bits, l >> bits);
++ /* Under the lock: the run and the group may be gone after it. */
++ wake_up_var(&bg->open_stripe_runs);
+ if (open_stripe_run_drained(run) && !run->retained)
+ free_open_stripe_run(bg, run);
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index b40feebcdecbc..0abca6e249f44 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -438,7 +438,7 @@ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+ void btrfs_open_stripe_write_abandoned(struct btrfs_block_group *bg, u64 start,
+ u64 num_bytes);
+ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+- u64 num_bytes);
++ u64 start, u64 num_bytes);
+ void btrfs_open_stripe_write_done_bytenr(struct btrfs_fs_info *fs_info,
+ u64 start, u64 num_bytes);
+ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
+@@ -448,6 +448,10 @@ void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
+ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
+ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
+ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
++void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
++ u64 len);
++bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
++ u64 stripe_start, u64 stripe_len);
+ 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);
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index fbb289ddfb99a..58d4eb020e1f2 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -853,6 +853,10 @@ struct btrfs_fs_info {
+ */
+ atomic64_t pad_decline_uncovered;
+ atomic64_t congestion_short;
++ /* Stripes pinned in the rbio cache (rbio_needs_pin()). */
++ atomic64_t rbio_pinned;
++ /* Completed-write sectors not live in their run (should be ~0). */
++ atomic64_t written_not_live;
+ } stripe_park_stats;
+ /* Stripe run lifecycle counters (sysfs stripe_run_stats). */
+ struct {
+diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
+index e0dccad6f22a9..5bd8ff43f9d52 100644
+--- a/fs/btrfs/ordered-data.c
++++ b/fs/btrfs/ordered-data.c
+@@ -414,7 +414,8 @@ static void btrfs_ordered_stripe_write_done(struct btrfs_ordered_extent *ordered
+ if (!run)
+ return;
+ ordered->stripe_run = NULL;
+- btrfs_open_stripe_write_done_run(run, ordered->disk_num_bytes);
++ btrfs_open_stripe_write_done_run(run, ordered->disk_bytenr,
++ ordered->disk_num_bytes);
+ }
+
+ static bool can_finish_ordered_extent(struct btrfs_ordered_extent *ordered,
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index f27215f8a4017..4b8854370ce1b 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -72,6 +72,17 @@
+ */
+ #define RBIO_SYNC_PARK_BIT 8
+
++/*
++ * Set while a cached rbio holds a stripe that its run has not finished
++ * writing: the cache prune skips it, so the run's next write into the stripe
++ * takes the part already written from memory instead of reading it back
++ * from the devices (see rbio_needs_pin()).
++ */
++#define RBIO_PINNED_BIT 9
++
++/* At most this many pinned stripes; normally about one per stripe run. */
++#define RBIO_PIN_MAX 256
++
+ #define RBIO_CACHE_SIZE 1024
+
+ /* Scan period of the park timer while anything is parked. */
+@@ -169,6 +180,8 @@ struct btrfs_stripe_hash_table {
+ struct list_head stripe_cache;
+ spinlock_t cache_lock;
+ int cache_size;
++ /* Cached rbios with RBIO_PINNED_BIT set, live or not. */
++ int nr_pinned;
+ /*
+ * Parked partial write rbios (RBIO_PARKED_BIT), in park order.
+ * parked_lock nests inside the hash and bio_list locks.
+@@ -475,6 +488,8 @@ static void __remove_rbio_from_cache(struct btrfs_raid_bio *rbio)
+ if (test_and_clear_bit(RBIO_CACHE_BIT, &rbio->flags)) {
+ list_del_init(&rbio->stripe_cache);
+ table->cache_size -= 1;
++ if (test_and_clear_bit(RBIO_PINNED_BIT, &rbio->flags))
++ table->nr_pinned -= 1;
+ freeit = true;
+
+ /* if the bio list isn't empty, this rbio is
+@@ -574,6 +589,104 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info)
+ info->stripe_hash_table = NULL;
+ }
+
++/*
++ * A stripe its open run has not finished writing is written more than once:
++ * each write that ends inside the stripe leaves the rest to a later write.
++ * That later write cannot pad (the earlier sectors are live) and would read
++ * them back, folding into parity whatever the devices return before the
++ * csum tree covers those sectors. Keep such a stripe cached instead, so the
++ * later write steals the pages it needs (lock_stripe_add()) and reads
++ * nothing.
++ *
++ * That is the stripe holding the run's allocation frontier, and any stripe
++ * behind it whose allocated sectors are still being written
++ * (btrfs_stripe_run_incomplete()). Each prune re-checks the pin against
++ * the run, and the run's next write into the stripe replaces the entry.
++ */
++static bool rbio_needs_pin(const struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return false;
++ return btrfs_stripe_run_incomplete(fs_info,
++ rbio->bioc->full_stripe_logical,
++ (u64)rbio->nr_data * rbio->bioc->stripe_len);
++}
++
++/* Re-checked at every prune: the pin ends when its run has written it all. */
++static bool rbio_pin_live(const struct btrfs_raid_bio *rbio)
++{
++ return test_bit(RBIO_PINNED_BIT, &rbio->flags) && rbio_needs_pin(rbio);
++}
++
++/*
++ * A write completed: tell the stripe runs which sectors now hold their data,
++ * as contiguous ranges of the data sectors this rbio's bios covered.
++ */
++static void rbio_mark_written(struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ const u32 sectorsize = fs_info->sectorsize;
++ const int nr = rbio->nr_data * rbio->stripe_nsectors;
++ int i, first = -1;
++
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return;
++ for (i = 0; i <= nr; i++) {
++ const bool covered = i < nr && rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR;
++
++ if (covered && first < 0)
++ first = i;
++ if (!covered && first >= 0) {
++ btrfs_stripe_run_mark_written(fs_info,
++ rbio->bioc->full_stripe_logical +
++ (u64)first * sectorsize,
++ (u64)(i - first) * sectorsize);
++ first = -1;
++ }
++ }
++}
++
++/*
++ * Mark @rbio pinned or not; caller holds the cache lock and @rbio is in the
++ * cache.
++ */
++static void rbio_set_pin(struct btrfs_stripe_hash_table *table,
++ struct btrfs_raid_bio *rbio, bool pin)
++{
++ if (pin && table->nr_pinned >= RBIO_PIN_MAX &&
++ !test_bit(RBIO_PINNED_BIT, &rbio->flags))
++ pin = false;
++ if (pin) {
++ if (!test_and_set_bit(RBIO_PINNED_BIT, &rbio->flags))
++ table->nr_pinned += 1;
++ atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.rbio_pinned);
++ } else if (test_and_clear_bit(RBIO_PINNED_BIT, &rbio->flags)) {
++ table->nr_pinned -= 1;
++ }
++}
++
++/*
++ * Evict from the cold end until the cache is within @limit, keeping @rbio
++ * (just cached) and live pins. Caller holds the cache lock.
++ */
++static void rbio_cache_prune(struct btrfs_stripe_hash_table *table,
++ struct btrfs_raid_bio *rbio, unsigned int limit)
++{
++ struct btrfs_raid_bio *found, *tmp;
++
++ list_for_each_entry_safe_reverse(found, tmp, &table->stripe_cache,
++ stripe_cache) {
++ if (table->cache_size <= limit)
++ break;
++ if (found == rbio || rbio_pin_live(found))
++ continue;
++ /* __remove_rbio_from_cache() drops a stale pin's count. */
++ __remove_rbio_from_cache(found);
++ }
++}
++
+ /*
+ * insert an rbio into the stripe cache. It
+ * must have already been prepared by calling
+@@ -588,10 +701,12 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info)
+ static void cache_rbio(struct btrfs_raid_bio *rbio)
+ {
+ struct btrfs_stripe_hash_table *table;
++ bool pin;
+
+ if (!test_bit(RBIO_CACHE_READY_BIT, &rbio->flags))
+ return;
+
++ pin = rbio_needs_pin(rbio);
+ table = rbio->bioc->fs_info->stripe_hash_table;
+
+ spin_lock(&table->cache_lock);
+@@ -607,19 +722,11 @@ static void cache_rbio(struct btrfs_raid_bio *rbio)
+ list_add(&rbio->stripe_cache, &table->stripe_cache);
+ table->cache_size += 1;
+ }
++ rbio_set_pin(table, rbio, pin);
+
+ spin_unlock(&rbio->bio_list_lock);
+
+- if (table->cache_size > RBIO_CACHE_SIZE) {
+- struct btrfs_raid_bio *found;
+-
+- found = list_last_entry(&table->stripe_cache,
+- struct btrfs_raid_bio,
+- stripe_cache);
+-
+- if (found != rbio)
+- __remove_rbio_from_cache(found);
+- }
++ rbio_cache_prune(table, rbio, RBIO_CACHE_SIZE);
+
+ spin_unlock(&table->cache_lock);
+ }
+@@ -1291,6 +1398,10 @@ static void rbio_orig_end_io(struct btrfs_raid_bio *rbio, blk_status_t status)
+ rbio->csum_buf = NULL;
+ rbio->csum_bitmap = NULL;
+
++ /* Before unlock_stripe()'s cache decision: see rbio_needs_pin(). */
++ if (rbio->operation == BTRFS_RBIO_WRITE && status == BLK_STS_OK)
++ rbio_mark_written(rbio);
++
+ /*
+ * Clear the data bitmap, as the rbio may be cached for later usage.
+ * do this before unlock_stripe() so there will be no new bio
+--
+2.47.3
+
+++ /dev/null
-From cae5a5d0a6e9a7a0a1b11229920cdb81b1f81769 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:51 -0400
-Subject: [RFC PATCH 031/116] btrfs: stripe_alloc: trace why padding declined,
- at the moment it declined
-To: linux-btrfs@vger.kernel.org
-
-The counters say how often padding refused and broadly why, but not what
-the run looked like when it happened, and reconstructing that from the
-extent tree afterwards cannot distinguish "the stripe was already
-allocated when this write arrived" from "it was allocated shortly after".
-Those want different fixes, so record the decision where it is made.
-
-Also count the second refusal, which had no counter at all: the oracle can
-allow padding and the sector walk still refuse, because a sector below the
-frontier is not covered by this write. That is the case where another
-allocation shares the stripe and its data is not in this rbio -- a
-different thing from the oracle finding the whole stripe allocated.
-
-The tracepoint carries the stripe, how much of it this write covers, the
-refusal reason, and the run's start/end/frontier/inflight, so a trace says
-directly whether the frontier had already run past the stripe when the
-write showed up.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 19 +++++++++++++++-
- fs/btrfs/block-group.h | 25 +++++++++++++++++++-
- fs/btrfs/fs.h | 4 ++++
- fs/btrfs/raid56.c | 41 +++++++++++++++++++++++++++++----
- fs/btrfs/sysfs.c | 2 ++
- include/trace/events/btrfs.h | 44 ++++++++++++++++++++++++++++++++++++
- 6 files changed, 128 insertions(+), 7 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index e46ce260f71ad..5c3239f41f538 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1311,7 +1311,8 @@ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
- */
- bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- u64 stripe_start, u64 stripe_len,
-- u64 *pad_from)
-+ u64 *pad_from,
-+ struct btrfs_stripe_pad_info *info)
- {
- struct btrfs_block_group *bg;
- struct btrfs_open_stripe_run *run;
-@@ -1319,6 +1320,11 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- unsigned long flags;
- bool ret = false;
-
-+ if (info) {
-+ memset(info, 0, sizeof(*info));
-+ info->reason = BTRFS_STRIPE_PAD_NO_RUN;
-+ }
-+
- if (list_empty_careful(&fs_info->open_stripe_bgs)) {
- atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
- return false;
-@@ -1333,6 +1339,13 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
- if (stripe_start < run->start || stripe_start >= run->end)
- continue;
-+ if (info) {
-+ info->run_start = run->start;
-+ info->run_end = run->end;
-+ info->run_offset = run->offset;
-+ info->inflight_bytes = run->inflight_bytes;
-+ info->reason = BTRFS_STRIPE_PAD_OK;
-+ }
- if (run->offset > stripe_start &&
- run->offset < stripe_start + stripe_len) {
- *pad_from = run->offset;
-@@ -1344,9 +1357,13 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- * and the write is waiting on a neighbour's data.
- */
- decline = &fs_info->stripe_park_stats.pad_decline_live;
-+ if (info)
-+ info->reason = BTRFS_STRIPE_PAD_LIVE;
- } else {
- /* The frontier has not reached the stripe at all. */
- decline = &fs_info->stripe_park_stats.pad_decline_unallocated;
-+ if (info)
-+ info->reason = BTRFS_STRIPE_PAD_UNALLOCATED;
- }
- break;
- }
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 590d62f59f9b9..1d75703ddb0a7 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -446,9 +446,32 @@ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class);
- bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- u64 run_start, u64 *run_len);
-+/*
-+ * Why padding could or could not proceed, and the run state it was decided
-+ * against. Filled at the moment of the decision so a trace can answer
-+ * "where was the frontier when this write arrived", which reconstructing
-+ * the extent tree afterwards cannot.
-+ */
-+enum btrfs_stripe_pad_reason {
-+ BTRFS_STRIPE_PAD_OK = 0,
-+ BTRFS_STRIPE_PAD_NO_RUN, /* no open run covers the stripe */
-+ BTRFS_STRIPE_PAD_LIVE, /* frontier past the stripe: all allocated */
-+ BTRFS_STRIPE_PAD_UNALLOCATED, /* frontier has not reached the stripe */
-+ BTRFS_STRIPE_PAD_UNCOVERED, /* a sector below the frontier is not covered */
-+};
-+
-+struct btrfs_stripe_pad_info {
-+ u64 run_start;
-+ u64 run_end;
-+ u64 run_offset; /* the allocation frontier */
-+ u64 inflight_bytes;
-+ u8 reason;
-+};
-+
- bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- u64 stripe_start, u64 stripe_len,
-- u64 *pad_from);
-+ u64 *pad_from,
-+ struct btrfs_stripe_pad_info *info);
- bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
- u64 num_bytes, u32 which);
- int btrfs_parse_stripe_rmw(const char *value, size_t len, u32 *mask);
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 8c0456add9d47..6dd9e331d89f7 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -847,6 +847,10 @@ struct btrfs_fs_info {
- atomic64_t pad_decline_live;
- atomic64_t pad_decline_no_run;
- atomic64_t pad_decline_unallocated;
-+ /* Oracle allowed padding, but a sector below the
-+ * frontier is not covered by this write: another
-+ * allocation shares the stripe. */
-+ atomic64_t pad_decline_uncovered;
- atomic64_t meta_rmw;
- /*
- * Breakdown of what a metadata read-modify-write found in the
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index d117cf701b807..7f70c0ed81e9f 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -2777,20 +2777,40 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- const u64 stripe_start = rbio->bioc->full_stripe_logical;
- const u32 sectorsize = fs_info->sectorsize;
- const u64 stripe_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
-- u64 pad_from;
-+ struct btrfs_stripe_pad_info info;
-+ const u32 total = rbio->nr_data * rbio->stripe_nsectors;
-+ u64 pad_from = 0;
-+ u32 covered = 0;
- int i;
-
- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
- return false;
- if (!btrfs_stripe_run_pad_start(fs_info, stripe_start, stripe_len,
-- &pad_from))
-+ &pad_from, &info)) {
-+ trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
-+ stripe_len, pad_from, 0, total,
-+ info.run_start, info.run_end,
-+ info.run_offset,
-+ info.inflight_bytes,
-+ info.reason);
- return false;
-+ }
-
- /* Populate bio_paddrs so covered sectors are visible below. */
- index_rbio_pages(rbio);
-
-- /* Every data sector this rbio does not cover must be paddable. */
-- for (i = 0; i < rbio->nr_data * rbio->stripe_nsectors; i++) {
-+ /*
-+ * Every data sector this rbio does not cover must be paddable. A
-+ * sector below the frontier is allocated to someone else and this
-+ * write does not carry its data, so padding would destroy it: that
-+ * is a distinct refusal from the oracle's, and it is the one that
-+ * says another writer's allocation shares this stripe.
-+ */
-+ for (i = 0; i < total; i++)
-+ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
-+ covered++;
-+
-+ for (i = 0; i < total; i++) {
- const int stripe_nr = i / rbio->stripe_nsectors;
- const int sectornr = i % rbio->stripe_nsectors;
- u64 logical = stripe_start + stripe_nr * BTRFS_STRIPE_LEN +
-@@ -2798,8 +2818,19 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
-
- if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
- continue;
-- if (logical < pad_from)
-+ if (logical < pad_from) {
-+ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_uncovered);
-+ info.reason = BTRFS_STRIPE_PAD_UNCOVERED;
-+ trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
-+ stripe_len, pad_from,
-+ covered, total,
-+ info.run_start,
-+ info.run_end,
-+ info.run_offset,
-+ info.inflight_bytes,
-+ info.reason);
- return false;
-+ }
- }
-
- if (alloc_rbio_data_pages(rbio) < 0)
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index fbd5158babd99..4059b8e0974a8 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1130,6 +1130,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "pad_decline_live %lld\n"
- "pad_decline_no_run %lld\n"
- "pad_decline_unallocated %lld\n"
-+ "pad_decline_uncovered %lld\n"
- "meta_rmw %lld\n"
- "meta_rmw_cur %lld\n"
- "meta_rmw_old %lld\n"
-@@ -1145,6 +1146,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.pad_decline_live),
- atomic64_read(&fs_info->stripe_park_stats.pad_decline_no_run),
- atomic64_read(&fs_info->stripe_park_stats.pad_decline_unallocated),
-+ atomic64_read(&fs_info->stripe_park_stats.pad_decline_uncovered),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
-diff --git a/include/trace/events/btrfs.h b/include/trace/events/btrfs.h
-index e1af4dd8287ce..db541d70e9640 100644
---- a/include/trace/events/btrfs.h
-+++ b/include/trace/events/btrfs.h
-@@ -3299,6 +3299,50 @@ DEFINE_EVENT(btrfs__space_info_update, update_bytes_stripe_unusable,
- TP_ARGS(fs_info, sinfo, old, diff)
- );
-
-+TRACE_EVENT(btrfs_stripe_pad_decline,
-+
-+ TP_PROTO(const struct btrfs_fs_info *fs_info, u64 full_stripe,
-+ u64 stripe_len, u64 pad_from, u32 covered, u32 total,
-+ u64 run_start, u64 run_end, u64 run_offset, u64 inflight,
-+ u8 reason),
-+
-+ TP_ARGS(fs_info, full_stripe, stripe_len, pad_from, covered, total,
-+ run_start, run_end, run_offset, inflight, reason),
-+
-+ TP_STRUCT__entry_btrfs(
-+ __field( u64, full_stripe )
-+ __field( u64, stripe_len )
-+ __field( u64, pad_from )
-+ __field( u64, run_start )
-+ __field( u64, run_end )
-+ __field( u64, run_offset )
-+ __field( u64, inflight )
-+ __field( u32, covered )
-+ __field( u32, total )
-+ __field( u8, reason )
-+ ),
-+
-+ TP_fast_assign_btrfs(fs_info,
-+ __entry->full_stripe = full_stripe;
-+ __entry->stripe_len = stripe_len;
-+ __entry->pad_from = pad_from;
-+ __entry->run_start = run_start;
-+ __entry->run_end = run_end;
-+ __entry->run_offset = run_offset;
-+ __entry->inflight = inflight;
-+ __entry->covered = covered;
-+ __entry->total = total;
-+ __entry->reason = reason;
-+ ),
-+
-+ TP_printk_btrfs(
-+"full_stripe=%llu len=%llu covered=%u/%u reason=%u pad_from=%llu run=[%llu,%llu) frontier=%llu inflight=%llu",
-+ __entry->full_stripe, __entry->stripe_len,
-+ __entry->covered, __entry->total, __entry->reason,
-+ __entry->pad_from, __entry->run_start, __entry->run_end,
-+ __entry->run_offset, __entry->inflight)
-+);
-+
- DECLARE_EVENT_CLASS(btrfs_raid56_bio,
-
- TP_PROTO(const struct btrfs_raid_bio *rbio,
---
-2.47.3
-
+++ /dev/null
-From 138ec473477dae46a688181c42319f862d01ec56 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:52 -0400
-Subject: [RFC PATCH 032/116] btrfs: stripe_alloc: complete parked writes on
- allocation coverage, not clocks
-To: linux-btrfs@vger.kernel.org
-
-A parked partial-stripe write goes down its RMW path when its deadline
-expires or a retirement flush kicks it, even when every byte it is
-missing below the run's frontier belongs to an allocation whose data IO
-is already in flight -- allocation happens at writeback submission, and
-the commit's retirement drain waits for exactly those arrivals. Timing
-out such a park buys nothing and costs a stripe read plus a second write
-of the same stripe: measured on an 8-device raid5 buffered fill, the
-100ms deadline turns ~2200 parked stripes per 2GB into read-modify-
-writes (pad_decline_live), and stretching the clock 20x recovers only
-14% -- the clock is the wrong instrument.
-
-Replace the clock with a coverage test. A parked rbio is ready when its
-gathered bios cover everything the covering run has allocated inside its
-stripe (btrfs_stripe_run_alloc_ceiling); the remainder lies at or past
-the frontier, so the existing pad turns it into a single full-stripe
-write with no read phase. Merges check readiness as they land, the park
-timer holds unready parks instead of expiring them, and run-retirement
-flushes leave unready parks parked: the retirement has already closed
-the run (freezing the allocated prefix) and its drain waits on the very
-arrivals that will complete them. Waiter-driven flushes (fsync's
-pre-writeback kick, ordered-extent waits) and sync parks keep today's
-forced behaviour: a blocked waiter's latency beats a saved stripe read.
-
-A stuck cap (10x the park deadline) bounds the wait when an arrival can
-never come: a writeback error abandoned the allocation, or the stripe
-was already written once by a forced sync park. Such parks are forced
-down the old path and counted.
-
-New sysfs stripe_park_stats counters: unparked_ready (parks completed by
-the coverage test) and stuck (parks forced at the cap).
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 43 ++++++++++++++++--
- fs/btrfs/block-group.h | 2 +
- fs/btrfs/file.c | 3 +-
- fs/btrfs/fs.h | 12 +++++
- fs/btrfs/ordered-data.c | 2 +-
- fs/btrfs/raid56.c | 99 +++++++++++++++++++++++++++++++++++++----
- fs/btrfs/raid56.h | 4 +-
- fs/btrfs/sysfs.c | 4 ++
- 8 files changed, 155 insertions(+), 14 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 5c3239f41f538..59b7232c6482e 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1309,6 +1309,43 @@ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
- * later allocation's write serializes behind the caller's stripe lock
- * and overwrites the zeros.
- */
-+/*
-+ * How far has the covering run allocated into this stripe? Returns the
-+ * exclusive end of the allocated prefix, clamped to the stripe, or U64_MAX
-+ * when no run covers the stripe (nothing left to wait for; the caller
-+ * proceeds as if the stripe were fully allocated and fully arrived).
-+ * A partial write below the returned ceiling is waiting on neighbours whose
-+ * data IO is already in flight -- allocation happens at writeback submission
-+ * and the run's inflight accounting makes the commit wait for it -- so a
-+ * parked rbio covering [stripe_start, ceiling) can complete (padding the
-+ * dead tail), and one that does not should keep waiting for merges.
-+ */
-+u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
-+ u64 stripe_start, u64 stripe_len)
-+{
-+ struct btrfs_block_group *bg;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ u64 ceiling = U64_MAX;
-+
-+ if (list_empty_careful(&fs_info->open_stripe_bgs))
-+ return U64_MAX;
-+ bg = btrfs_lookup_block_group(fs_info, stripe_start);
-+ if (!bg)
-+ return U64_MAX;
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (stripe_start < run->start || stripe_start >= run->end)
-+ continue;
-+ ceiling = clamp(run->offset, stripe_start,
-+ stripe_start + stripe_len);
-+ break;
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ btrfs_put_block_group(bg);
-+ return ceiling;
-+}
-+
- bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- u64 stripe_start, u64 stripe_len,
- u64 *pad_from,
-@@ -1651,7 +1688,7 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- stripe_open_remainder_sync(bg);
- }
- if (flush_len) {
-- btrfs_flush_parked_rbios(fs_info, flush_start, flush_len);
-+ btrfs_flush_parked_rbios(fs_info, flush_start, flush_len, false);
- wait_var_event(&bg->open_stripe_runs,
- stripe_log_range_settled(bg, bytenr));
- }
-@@ -2030,7 +2067,7 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
- {
- close_block_group_stripe_runs(bg, U64_MAX);
- /* Parked partial-stripe rbios hold the very bios the wait drains. */
-- btrfs_flush_parked_rbios(bg->fs_info, bg->start, bg->length);
-+ btrfs_flush_parked_rbios(bg->fs_info, bg->start, bg->length, false);
- wait_var_event(&bg->open_stripe_runs,
- bg_open_stripes_settled(bg, U64_MAX));
- }
-@@ -2072,7 +2109,7 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
- * A racing park that saw its run still open lands after this flush
- * and is bounded by the park timer, not by us.
- */
-- btrfs_flush_parked_rbios(fs_info, 0, U64_MAX);
-+ btrfs_flush_parked_rbios(fs_info, 0, U64_MAX, false);
-
- while (!list_empty(&retire_list)) {
- bg = list_first_entry(&retire_list, struct btrfs_block_group,
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 1d75703ddb0a7..46f4ba48bcff8 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -468,6 +468,8 @@ struct btrfs_stripe_pad_info {
- u8 reason;
- };
-
-+u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
-+ u64 stripe_start, u64 stripe_len);
- bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- u64 stripe_start, u64 stripe_len,
- u64 *pad_from,
-diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
-index dce4880737eb3..1cd9cc6f34b87 100644
---- a/fs/btrfs/file.c
-+++ b/fs/btrfs/file.c
-@@ -1681,7 +1681,8 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
- if (tmp_oe->disk_num_bytes)
- btrfs_flush_parked_rbios(fs_info,
- tmp_oe->disk_bytenr,
-- tmp_oe->disk_num_bytes);
-+ tmp_oe->disk_num_bytes,
-+ true);
- }
-
- ret = filemap_fdatawait_range(inode->vfs_inode.i_mapping, start, end);
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 6dd9e331d89f7..cfaf19d7528b3 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -823,8 +823,20 @@ struct btrfs_fs_info {
- atomic64_t parked;
- atomic64_t merged_bytes;
- atomic64_t filled;
-+ /*
-+ * Parks released because their write covers everything the
-+ * run has allocated in the stripe -- the rest is dead space
-+ * the pad fills; nothing was worth waiting for.
-+ */
-+ atomic64_t unparked_ready;
- atomic64_t expired;
- atomic64_t kicked;
-+ /*
-+ * Parks forced down past the stuck cap while still missing
-+ * allocated neighbours: an arrival never came (writeback
-+ * error, or a stripe written twice by a forced sync park).
-+ */
-+ atomic64_t stuck;
- atomic64_t rmw_reads;
- atomic64_t padded;
- /*
-diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
-index e7aeee5c7172d..8e06a4266b3a3 100644
---- a/fs/btrfs/ordered-data.c
-+++ b/fs/btrfs/ordered-data.c
-@@ -937,7 +937,7 @@ void btrfs_start_ordered_extent_nowriteback(struct btrfs_ordered_extent *entry,
- !test_bit(BTRFS_ORDERED_COMPLETE, &entry->flags)) {
- btrfs_flush_parked_rbios(inode->root->fs_info,
- entry->disk_bytenr,
-- entry->disk_num_bytes);
-+ entry->disk_num_bytes, true);
- if (wait_event_timeout(entry->wait,
- test_bit(BTRFS_ORDERED_COMPLETE,
- &entry->flags),
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 7f70c0ed81e9f..370893ab20223 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -66,6 +66,13 @@
- /* Set at park time and never cleared: this rbio once parked (stats). */
- #define RBIO_WAS_PARKED_BIT 7
-
-+/*
-+ * Set when a parked rbio carries (or merged) a REQ_SYNC bio: a waiter
-+ * is blocked on it, so deadlines stay authoritative and neither the
-+ * timer nor a flush may hold it back to wait for neighbours.
-+ */
-+#define RBIO_SYNC_PARK_BIT 8
-+
- #define RBIO_CACHE_SIZE 1024
-
- /*
-@@ -785,6 +792,29 @@ static bool rbio_has_sync_bio(struct btrfs_raid_bio *rbio)
- return false;
- }
-
-+/*
-+ * A parked rbio is ready to go down when its gathered bios cover every
-+ * byte the covering run has allocated in its stripe: the remainder lies
-+ * at or past the frontier and the pad turns it into a full-stripe write.
-+ * Anything less is waiting on an allocated neighbour whose data IO is
-+ * already in flight, so waiting is bounded and reading (RMW) is waste.
-+ * bio_list_bytes is read unlocked: merges only grow it, and a stale low
-+ * value just delays readiness by one scan tick.
-+ */
-+static bool parked_rbio_ready(struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ const u64 stripe_start = rbio->bioc->full_stripe_logical;
-+ const u64 stripe_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
-+ u64 ceiling;
-+
-+ ceiling = btrfs_stripe_run_alloc_ceiling(fs_info, stripe_start,
-+ stripe_len);
-+ if (ceiling == U64_MAX)
-+ return true;
-+ return READ_ONCE(rbio->bio_list_bytes) >= ceiling - stripe_start;
-+}
-+
- /*
- * Park a partial write rbio that owns its stripe lock, if its stripe is
- * covered by an open stripe run. Returns true if the rbio was parked (or
-@@ -840,7 +870,11 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- spin_lock(&table->parked_lock);
- set_bit(RBIO_PARKED_BIT, &rbio->flags);
- set_bit(RBIO_WAS_PARKED_BIT, &rbio->flags);
-+ if (timeout_ms == sync_timeout_ms)
-+ set_bit(RBIO_SYNC_PARK_BIT, &rbio->flags);
- rbio->park_deadline = jiffies + msecs_to_jiffies(timeout_ms);
-+ rbio->park_stuck_deadline = jiffies +
-+ msecs_to_jiffies(timeout_ms * 10);
- /*
- * Take a reference of our own before publishing. The moment
- * parked_lock is dropped this rbio is visible to every flusher, and a
-@@ -892,7 +926,8 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- * write. Callers may hold the stripe hash and bio_list locks; parked_lock
- * nests inside both.
- */
--static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
-+static void unpark_ready_rbio(struct btrfs_raid_bio *rbio,
-+ atomic64_t *counter)
- {
- struct btrfs_stripe_hash_table *table =
- rbio->bioc->fs_info->stripe_hash_table;
-@@ -904,7 +939,7 @@ static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
- }
- rbio_unpark_locked(rbio);
- spin_unlock(&table->parked_lock);
-- atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.filled);
-+ atomic64_inc(counter);
- start_async_work(rbio, rmw_rbio_work_locked);
- }
-
-@@ -914,7 +949,7 @@ static void unpark_full_rbio(struct btrfs_raid_bio *rbio)
- * ordered-extent waiters, and the park timer.
- */
- void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
-- u64 num_bytes)
-+ u64 num_bytes, bool force)
- {
- struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
- struct btrfs_raid_bio *rbio;
-@@ -931,6 +966,17 @@ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
- if (rbio_start + rbio_len <= start ||
- (num_bytes != U64_MAX && rbio_start >= start + num_bytes))
- continue;
-+ /*
-+ * A run-retirement flush precedes the commit's IO drain,
-+ * which waits for the very arrivals this rbio is missing:
-+ * leave it parked and the arrivals will complete it (the
-+ * run is closed, so its allocated prefix is frozen). Only
-+ * waiter-driven flushes (fsync, ordered-extent waits) force
-+ * an incomplete stripe down, and sync parks always go.
-+ */
-+ if (!force && !test_bit(RBIO_SYNC_PARK_BIT, &rbio->flags) &&
-+ !parked_rbio_ready(rbio))
-+ continue;
- rbio_unpark_locked(rbio);
- list_add_tail(&rbio->parked_node, &flush);
- }
-@@ -961,14 +1007,35 @@ static void parked_rbios_timeout_work(struct work_struct *work)
- rearm = true;
- continue;
- }
-+ /*
-+ * Past the deadline but still missing allocated
-+ * neighbours: their data IO is in flight, so expiring
-+ * now would read (RMW) what a short wait merges for
-+ * free. Hold the park up to the stuck cap -- the cap
-+ * only fires when an arrival never comes (writeback
-+ * error, or a stripe already written once by a forced
-+ * sync park).
-+ */
-+ if (!test_bit(RBIO_SYNC_PARK_BIT, &rbio->flags) &&
-+ time_before(jiffies, rbio->park_stuck_deadline) &&
-+ !parked_rbio_ready(rbio)) {
-+ rearm = true;
-+ continue;
-+ }
- rbio_unpark_locked(rbio);
- list_add_tail(&rbio->parked_node, &flush);
- }
- spin_unlock(&table->parked_lock);
-
- list_for_each_entry_safe(rbio, tmp, &flush, parked_node) {
-+ struct btrfs_fs_info *ffs = rbio->bioc->fs_info;
-+
- list_del_init(&rbio->parked_node);
-- atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.expired);
-+ if (!test_bit(RBIO_SYNC_PARK_BIT, &rbio->flags) &&
-+ time_after_eq(jiffies, rbio->park_stuck_deadline))
-+ atomic64_inc(&ffs->stripe_park_stats.stuck);
-+ else
-+ atomic64_inc(&ffs->stripe_park_stats.expired);
- start_async_work(rbio, rmw_rbio_work_locked);
- }
- if (rearm)
-@@ -1103,9 +1170,21 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
- * this stripe.
- */
- if (test_bit(RBIO_PARKED_BIT, &cur->flags)) {
-+ struct btrfs_fs_info *cfs =
-+ cur->bioc->fs_info;
-+
- if (cur->bio_list_bytes ==
- cur->nr_data * cur->bioc->stripe_len) {
-- unpark_full_rbio(cur);
-+ unpark_ready_rbio(cur,
-+ &cfs->stripe_park_stats.filled);
-+ } else if (parked_rbio_ready(cur)) {
-+ /*
-+ * This merge completed the allocated
-+ * prefix; the rest of the stripe is
-+ * dead space the pad fills.
-+ */
-+ unpark_ready_rbio(cur,
-+ &cfs->stripe_park_stats.unparked_ready);
- } else if (sync) {
- struct btrfs_stripe_hash_table *table =
- cur->bioc->fs_info->stripe_hash_table;
-@@ -1115,9 +1194,13 @@ static noinline int lock_stripe_add(struct btrfs_raid_bio *rbio)
-
- spin_lock(&table->parked_lock);
- if (test_bit(RBIO_PARKED_BIT,
-- &cur->flags) &&
-- time_before(dl, cur->park_deadline))
-- cur->park_deadline = dl;
-+ &cur->flags)) {
-+ set_bit(RBIO_SYNC_PARK_BIT,
-+ &cur->flags);
-+ if (time_before(dl,
-+ cur->park_deadline))
-+ cur->park_deadline = dl;
-+ }
- spin_unlock(&table->parked_lock);
- }
- }
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index f5b8d788b1fff..11b843095903e 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -138,6 +138,8 @@ struct btrfs_raid_bio {
- */
- struct list_head parked_node;
- unsigned long park_deadline;
-+ /* Hard cap on completion-waiting (see parked_rbio_ready()). */
-+ unsigned long park_stuck_deadline;
-
- /* Flags that tell us if it is safe to merge with this bio. */
- unsigned long flags;
-@@ -292,6 +294,6 @@ void raid56_parity_cache_data_folios(struct btrfs_raid_bio *rbio,
- int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
-- u64 num_bytes);
-+ u64 num_bytes, bool force);
-
- #endif
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 4059b8e0974a8..25d8c61d72a9e 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1122,8 +1122,10 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "parked %lld\n"
- "merged_bytes %lld\n"
- "filled %lld\n"
-+ "unparked_ready %lld\n"
- "kicked %lld\n"
- "expired %lld\n"
-+ "stuck %lld\n"
- "padded %lld\n"
- "rmw_reads %lld\n"
- "data_rmw %lld\n"
-@@ -1138,8 +1140,10 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.parked),
- atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
- atomic64_read(&fs_info->stripe_park_stats.filled),
-+ atomic64_read(&fs_info->stripe_park_stats.unparked_ready),
- atomic64_read(&fs_info->stripe_park_stats.kicked),
- atomic64_read(&fs_info->stripe_park_stats.expired),
-+ atomic64_read(&fs_info->stripe_park_stats.stuck),
- atomic64_read(&fs_info->stripe_park_stats.padded),
- atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
- atomic64_read(&fs_info->stripe_park_stats.data_rmw),
---
-2.47.3
-
--- /dev/null
+From 7aaa8f1b809d96dec4c7d6efc27bc42289439e50 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Fri, 2 Oct 2026 02:41:44 -0400
+Subject: [RFC PATCH 32/85] btrfs: stripe_alloc: pad a stripe's allocated
+ sectors whose write is still to come
+To: linux-btrfs@vger.kernel.org
+
+A stripe run's first partial write into a stripe cannot pad today: the
+stripe's other sectors are allocated (live) to writes that are still in
+flight, so the pad oracle calls them live and the write goes down as a
+read-modify-write of the whole stripe. With the stripe pin keeping the
+stripe cached for every later write, this first write is the only data RMW
+left in a stripe run (traced on the strip-fault fixture: every remaining
+data RMW read was a first write), and the read it does is of sectors
+nobody has written: it can only fetch garbage into the parity, and on a
+device that returns wrong data it makes that parity disagree with what is
+on the disk.
+
+Use the run's written map: a live sector whose write has not completed
+holds nothing anyone has written, so it is as paddable as a dead one.
+Zeroing it is safe because its write is ordered after this one -- the
+padding write holds the stripe lock, every raid56 write to the stripe
+takes it, and rbio_orig_end_io() records a write's sectors in the written
+map before it unlocks the stripe -- and nothing reads the sector before
+its own write lands, since its extent is not committed until then. That
+write replaces the zeros; it is a sub-stripe write into a stripe written
+before, which the stripe pin serves from the cache.
+
+A live sector that HAS been written still refuses the pad, as before:
+that is now the precise meaning of the UNCOVERED decline. Nodatacow runs
+keep no written map (their extents are rewritten in place for as long as
+the inode lives) and are excluded. padded_unwritten in stripe_park_stats
+counts the pads that zeroed such sectors.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 47 +++++++++++++++++++++++++-----------------
+ fs/btrfs/block-group.h | 1 +
+ fs/btrfs/fs.h | 2 ++
+ fs/btrfs/raid56.c | 24 ++++++++++++++-------
+ fs/btrfs/sysfs.c | 2 ++
+ 5 files changed, 50 insertions(+), 26 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 36e2aff3ee49f..e101654302a7d 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1223,28 +1223,28 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
+ /*
+ * Which sectors of this stripe may be padded?
+ *
+- * Fills @dead with one bit per sector of the stripe, set where the sector
+- * holds nothing anyone intends to write: space the run has not handed out
+- * yet, and space it handed out but got back before the write was issued.
+- * A caller may zero-fill exactly those and write the whole stripe.
++ * Fills @dead with one bit per sector, set where the sector holds nothing
++ * anyone has written: never handed out, handed out and abandoned, or
++ * handed out with the write not yet completed (per the run's written map).
++ * The caller may zero-fill exactly those and write the whole stripe.
++ * @unwritten, when non-NULL, gets the subset that is allocated but
++ * unwritten.
+ *
+- * Returns false if no run covers the stripe, in which case nothing may be
+- * padded: without a run there is no claim of exclusivity, and an uncovered
+- * sector may hold committed data.
++ * Zeroing an allocated sector whose write is still to come is safe: the
++ * caller holds the stripe lock, which every raid56 write to the stripe
++ * takes, so that write lands after the caller's; completed writes are in
++ * the written map before the stripe is unlocked (rbio_orig_end_io()); and
++ * nothing reads the sector before its own write lands, since its extent is
++ * not committed until then. A NOCOW run's written map is not consulted:
++ * its live sectors are rewritten in place, so they may already hold data.
+ *
+- * This replaces asking where the run's frontier is. The frontier answers
+- * "what has never been allocated", which misses allocations that were
+- * abandoned below it -- a tree block COWed twice in one transaction, a
+- * reservation released, an allocation the finder discarded. Those leave
+- * holes that are equally safe to pad, and skipping them is the difference
+- * between padding most partial stripes and padding all of them.
+- *
+- * @info, when non-NULL, reports the covering run's state at the moment of
+- * the decision, for the pad-decline trace: a later extent-tree dump cannot
+- * reconstruct where the frontier was when the write arrived.
++ * Returns false if no run covers the stripe; nothing may be padded then,
++ * since an uncovered sector may hold committed data. @info, when non-NULL,
++ * records the covering run's state for the pad-decline trace.
+ */
+ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ u64 stripe_len, unsigned long *dead,
++ unsigned long *unwritten,
+ struct btrfs_stripe_pad_info *info)
+ {
+ const u32 bits = fs_info->sectorsize_bits;
+@@ -1306,9 +1306,18 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ if (first + nsectors > run->live_nbits)
+ break;
+ bitmap_zero(dead, nsectors);
+- for (u32 i = 0; i < nsectors; i++)
+- if (!test_bit(first + i, run->live))
++ if (unwritten)
++ bitmap_zero(unwritten, nsectors);
++ for (u32 i = 0; i < nsectors; i++) {
++ if (!test_bit(first + i, run->live)) {
++ set_bit(i, dead);
++ } else if (run->written &&
++ !test_bit(first + i, run->written)) {
+ set_bit(i, dead);
++ if (unwritten)
++ set_bit(i, unwritten);
++ }
++ }
+ if (info)
+ info->reason = BTRFS_STRIPE_PAD_OK;
+ ret = true;
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 0abca6e249f44..29d88d9c6c361 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -479,6 +479,7 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
+ u64 stripe_start, u64 stripe_len);
+ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ u64 stripe_len, unsigned long *dead,
++ unsigned long *unwritten,
+ struct btrfs_stripe_pad_info *info);
+ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
+ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 58d4eb020e1f2..0abf7d9f8b661 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -831,6 +831,8 @@ struct btrfs_fs_info {
+ atomic64_t stuck;
+ atomic64_t rmw_reads;
+ atomic64_t padded;
++ /* Pads that zeroed allocated sectors whose write was to come. */
++ atomic64_t padded_unwritten;
+ /*
+ * Data read-modify-writes in a covered block group, parked or
+ * not; zero with allow_rmw empty. rmw_reads counts only the
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 4b8854370ce1b..9245585a371b0 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -2905,7 +2905,9 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ const u32 nsectors = rbio->nr_data * rbio->stripe_nsectors;
+ struct btrfs_stripe_pad_info info;
+ unsigned long *dead;
++ unsigned long *unwritten;
+ u32 covered = 0;
++ u32 nr_unwritten = 0;
+ bool ok = false;
+ int i;
+
+@@ -2913,10 +2915,14 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ return false;
+
+ dead = bitmap_zalloc(nsectors, GFP_NOFS);
+- if (!dead)
++ unwritten = bitmap_zalloc(nsectors, GFP_NOFS);
++ if (!dead || !unwritten) {
++ bitmap_free(dead);
++ bitmap_free(unwritten);
+ return false;
++ }
+ if (!btrfs_stripe_run_pad_mask(fs_info, stripe_start, stripe_len, dead,
+- &info)) {
++ unwritten, &info)) {
+ trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
+ stripe_len, 0, 0, nsectors,
+ info.run_start, info.run_end,
+@@ -2934,11 +2940,10 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ covered++;
+
+ /*
+- * Every data sector this rbio does not cover must be dead. A live
+- * uncovered sector belongs to another writer's allocation and this
+- * write does not carry its data, so padding would destroy it: that
+- * is a distinct refusal from the oracle's, and it is the one that
+- * says another writer's allocation shares this stripe.
++ * Every uncovered sector must be dead per the run. A live uncovered
++ * sector that was already written holds data this write does not
++ * carry, so refuse (UNCOVERED); the stripe pin (rbio_needs_pin())
++ * normally supplies such sectors from the cache, so nothing is read.
+ */
+ for (i = 0; i < nsectors; i++) {
+ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
+@@ -2956,10 +2961,13 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ info.reason);
+ goto out;
+ }
++ if (test_bit(i, unwritten))
++ nr_unwritten++;
+ }
+ ok = true;
+ out:
+ bitmap_free(dead);
++ bitmap_free(unwritten);
+ if (!ok)
+ return false;
+
+@@ -2994,6 +3002,8 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ bitmap_set(&rbio->dbitmap, 0, rbio->stripe_nsectors);
+ spin_unlock(&rbio->bio_list_lock);
+ atomic64_inc(&fs_info->stripe_park_stats.padded);
++ if (nr_unwritten)
++ atomic64_inc(&fs_info->stripe_park_stats.padded_unwritten);
+ return true;
+ }
+
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index a6f318f4b84b0..74eb13bf72c58 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1132,6 +1132,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "expired %lld\n"
+ "stuck %lld\n"
+ "padded %lld\n"
++ "padded_unwritten %lld\n"
+ "rmw_reads %lld\n",
+ atomic64_read(&fs_info->stripe_park_stats.parked),
+ atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
+@@ -1141,6 +1142,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.expired),
+ atomic64_read(&fs_info->stripe_park_stats.stuck),
+ atomic64_read(&fs_info->stripe_park_stats.padded),
++ atomic64_read(&fs_info->stripe_park_stats.padded_unwritten),
+ atomic64_read(&fs_info->stripe_park_stats.rmw_reads));
+ }
+ BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
+--
+2.47.3
+
--- /dev/null
+From 450ed7f4243375fd35744e4305ce5e50f60c1ace Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sun, 4 Oct 2026 12:26:45 -0400
+Subject: [RFC PATCH 33/85] btrfs: stripe_alloc: count refused rbio pins and
+ track rbio cache high water
+To: linux-btrfs@vger.kernel.org
+
+The rbio cache keeps a stripe its run has not finished writing pinned, at
+most RBIO_PIN_MAX (256) of them; the next pin is refused and that stripe
+is cached evictable. If it is evicted before its run's next write into
+it, that write reads back the sectors already written, unverified: the
+case the pin exists to avoid. Nothing counted the refusals, so whether
+the limit is ever reached was unknown.
+
+stripe_park_stats gains:
+ rbio_pin_refused pins refused at RBIO_PIN_MAX (every attempt)
+ rbio_pinned_now pinned rbios now (nr_pinned: what the limit counts)
+ rbio_pinned_live of those, pins still needed: re-checked against the
+ runs at read time, as the prune does. A pin whose run
+ has finished the stripe stays counted until its entry
+ is evicted or cached again.
+ rbio_pinned_hwm high water of pinned rbios since mount
+ rbio_cache_now cached rbios now
+ rbio_cache_hwm high water of cached rbios since mount (above
+ RBIO_CACHE_SIZE only by live pins, which the prune
+ keeps)
+ meta_rmw_reads read-modify-writes of metadata/system stripes that had
+ to read (data_rmw counts these with the data ones).
+ The pin is what keeps a stripe of fsync log blocks
+ cached for the next log commit; a refused pin can bring
+ that read back.
+
+The high water marks are only raised under the cache lock. Reading the
+file walks the cache once under the cache lock (1024 entries at most).
+
+nr_pinned counts a pin until its entry is evicted or cached again, also
+after its run has finished the stripe, so the limit filled with stale pins
+within seconds under any fsync-heavy load (13k-87k refusals a minute)
+while buffered writeback needed 3-14. Two things release pins:
+
+- A sweep, rbio_unpin_stale(), re-checks every pin against its run and
+ clears the stale ones under the cache lock. It runs when a pin is about
+ to be taken with RBIO_PIN_LOW (3/4 of the limit) or more counted, at
+ most once per RBIO_PIN_SWEEP_INTERVAL from that path, and at every
+ commit right after btrfs_retire_open_stripes(), which ends every run.
+- If the pins left after a sweep (all live) are still RBIO_PIN_LOW or
+ more, the transaction kthread is asked to commit now, once per
+ transaction. After the commit a stripe's earlier writes are no longer
+ at risk from a read-back: data checksums are committed and the log
+ blocks are dead.
+
+stripe_park_stats also has rbio_pin_swept and rbio_pin_commit_requests.
+
+Assisted-by: Claude:claude-opus-5-5
+Assisted-by: Claude:claude-fable-5
+---
+ fs/btrfs/fs.h | 19 ++++++
+ fs/btrfs/raid56.c | 136 +++++++++++++++++++++++++++++++++++++++--
+ fs/btrfs/raid56.h | 3 +
+ fs/btrfs/sysfs.c | 25 +++++++-
+ fs/btrfs/transaction.c | 3 +
+ 5 files changed, 180 insertions(+), 6 deletions(-)
+
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 0abf7d9f8b661..015f492b1f5d3 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -857,6 +857,25 @@ struct btrfs_fs_info {
+ atomic64_t congestion_short;
+ /* Stripes pinned in the rbio cache (rbio_needs_pin()). */
+ atomic64_t rbio_pinned;
++ /*
++ * Pins refused because RBIO_PIN_MAX stripes were already
++ * pinned: the stripe was cached evictable instead, and a later
++ * write into it may read back the part already written.
++ */
++ atomic64_t rbio_pin_refused;
++ /* High water since mount of pinned and of all cached rbios. */
++ atomic64_t rbio_pinned_hwm;
++ atomic64_t rbio_cache_hwm;
++ /* Stale pins cleared by a sweep (rbio_unpin_stale()). */
++ atomic64_t rbio_pin_swept;
++ /* Commits requested because live pins ran low. */
++ atomic64_t rbio_pin_commit_requests;
++ /*
++ * Read-modify-writes of metadata or system stripes that had to
++ * read (data_rmw counts them with the data ones): the fsync log
++ * stripes the pin keeps cached read back when it is refused.
++ */
++ atomic64_t meta_rmw_reads;
+ /* Completed-write sectors not live in their run (should be ~0). */
+ atomic64_t written_not_live;
+ } stripe_park_stats;
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 9245585a371b0..3c702231c6f44 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -80,8 +80,20 @@
+ */
+ #define RBIO_PINNED_BIT 9
+
+-/* At most this many pinned stripes; normally about one per stripe run. */
++/*
++ * At most this many pinned stripes: about as many as stripes with writes in
++ * flight, but fsync-heavy work caches a partial stripe on nearly every write.
++ * A pin goes stale when its run finishes the stripe and is only uncounted
++ * when a sweep, an eviction or a re-cache finds it, so pinning past
++ * RBIO_PIN_LOW sweeps first, and if the pins left are still live, asks for a
++ * commit: the commit retires the runs (btrfs_retire_open_stripes(), and
++ * btrfs_retire_meta_stripes() for metadata), which makes their pins
++ * unnecessary, and its sweep releases them.
++ */
+ #define RBIO_PIN_MAX 256
++#define RBIO_PIN_LOW (RBIO_PIN_MAX * 3 / 4)
++/* At most one sweep per this interval from the pin path (commits always sweep). */
++#define RBIO_PIN_SWEEP_INTERVAL (HZ / 20)
+
+ #define RBIO_CACHE_SIZE 1024
+
+@@ -182,6 +194,9 @@ struct btrfs_stripe_hash_table {
+ int cache_size;
+ /* Cached rbios with RBIO_PINNED_BIT set, live or not. */
+ int nr_pinned;
++ /* Last pin sweep, and the generation the last commit request was for. */
++ unsigned long pin_sweep_jiffies;
++ u64 pin_commit_gen;
+ /*
+ * Parked partial write rbios (RBIO_PARKED_BIT), in park order.
+ * parked_lock nests inside the hash and bio_list locks.
+@@ -648,19 +663,31 @@ static void rbio_mark_written(struct btrfs_raid_bio *rbio)
+ }
+ }
+
++static void rbio_stat_hwm(atomic64_t *hwm, int now)
++{
++ /* Only ever raised under the cache lock: no lost update. */
++ if (now > atomic64_read(hwm))
++ atomic64_set(hwm, now);
++}
++
+ /*
+ * Mark @rbio pinned or not; caller holds the cache lock and @rbio is in the
+- * cache.
++ * cache. A pin refused at RBIO_PIN_MAX is counted at every attempt.
+ */
+ static void rbio_set_pin(struct btrfs_stripe_hash_table *table,
+ struct btrfs_raid_bio *rbio, bool pin)
+ {
+ if (pin && table->nr_pinned >= RBIO_PIN_MAX &&
+- !test_bit(RBIO_PINNED_BIT, &rbio->flags))
++ !test_bit(RBIO_PINNED_BIT, &rbio->flags)) {
++ atomic64_inc(&table->fs_info->stripe_park_stats.rbio_pin_refused);
+ pin = false;
++ }
+ if (pin) {
+- if (!test_and_set_bit(RBIO_PINNED_BIT, &rbio->flags))
++ if (!test_and_set_bit(RBIO_PINNED_BIT, &rbio->flags)) {
+ table->nr_pinned += 1;
++ rbio_stat_hwm(&table->fs_info->stripe_park_stats.rbio_pinned_hwm,
++ table->nr_pinned);
++ }
+ atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.rbio_pinned);
+ } else if (test_and_clear_bit(RBIO_PINNED_BIT, &rbio->flags)) {
+ table->nr_pinned -= 1;
+@@ -685,6 +712,102 @@ static void rbio_cache_prune(struct btrfs_stripe_hash_table *table,
+ /* __remove_rbio_from_cache() drops a stale pin's count. */
+ __remove_rbio_from_cache(found);
+ }
++ /* Above the limit only by live pins, which the prune keeps. */
++ rbio_stat_hwm(&table->fs_info->stripe_park_stats.rbio_cache_hwm,
++ table->cache_size);
++}
++
++/*
++ * Clear the pins no longer needed (their run has written all of the stripe,
++ * or is gone). Caller holds the cache lock, the same context the prune
++ * re-checks pins in. Returns how many pins are left: all of them live.
++ */
++static int rbio_unpin_stale(struct btrfs_stripe_hash_table *table)
++{
++ struct btrfs_raid_bio *rbio;
++ int swept = 0;
++
++ table->pin_sweep_jiffies = jiffies;
++ list_for_each_entry(rbio, &table->stripe_cache, stripe_cache) {
++ if (!test_bit(RBIO_PINNED_BIT, &rbio->flags) || rbio_needs_pin(rbio))
++ continue;
++ clear_bit(RBIO_PINNED_BIT, &rbio->flags);
++ table->nr_pinned -= 1;
++ swept++;
++ }
++ if (swept)
++ atomic64_add(swept, &table->fs_info->stripe_park_stats.rbio_pin_swept);
++ return table->nr_pinned;
++}
++
++/*
++ * About to pin with the pins running low: sweep the stale ones, and if the
++ * live ones are still many, ask for a commit (once per transaction), which
++ * ends every run and so every pin. Caller holds the cache lock.
++ */
++static void rbio_pins_low(struct btrfs_stripe_hash_table *table)
++{
++ struct btrfs_fs_info *fs_info = table->fs_info;
++ u64 gen;
++
++ /*
++ * Rate limited: a sweep walks every pin, and only a commit frees live
++ * ones.
++ */
++ if (!time_after(jiffies, table->pin_sweep_jiffies + RBIO_PIN_SWEEP_INTERVAL))
++ return;
++ if (rbio_unpin_stale(table) < RBIO_PIN_LOW)
++ return;
++ gen = btrfs_get_fs_generation(fs_info);
++ if (table->pin_commit_gen == gen)
++ return;
++ table->pin_commit_gen = gen;
++ atomic64_inc(&fs_info->stripe_park_stats.rbio_pin_commit_requests);
++ /* As btrfs_commit_transaction_async(): the kthread commits now. */
++ set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
++ wake_up_process(fs_info->transaction_kthread);
++}
++
++/*
++ * A commit has retired every open stripe run: release the pins that leaves
++ * stale. Pins of runs opened since then are re-checked, not dropped.
++ */
++void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info)
++{
++ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
++
++ if (!table || !btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return;
++ spin_lock(&table->cache_lock);
++ if (table->nr_pinned)
++ rbio_unpin_stale(table);
++ spin_unlock(&table->cache_lock);
++}
++
++/*
++ * Cached and pinned rbios now, for sysfs stripe_park_stats. @live re-checks
++ * each pin against its run, as the prune does: a pin whose run has finished
++ * writing the stripe is still counted in nr_pinned until a sweep, an
++ * eviction or a re-cache finds it.
++ */
++void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
++ int *pinned, int *live)
++{
++ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
++ struct btrfs_raid_bio *rbio;
++
++ *cached = 0;
++ *pinned = 0;
++ *live = 0;
++ if (!table)
++ return;
++ spin_lock(&table->cache_lock);
++ *cached = table->cache_size;
++ *pinned = table->nr_pinned;
++ list_for_each_entry(rbio, &table->stripe_cache, stripe_cache)
++ if (rbio_pin_live(rbio))
++ *live += 1;
++ spin_unlock(&table->cache_lock);
+ }
+
+ /*
+@@ -710,6 +833,9 @@ static void cache_rbio(struct btrfs_raid_bio *rbio)
+ table = rbio->bioc->fs_info->stripe_hash_table;
+
+ spin_lock(&table->cache_lock);
++ if (pin && table->nr_pinned >= RBIO_PIN_LOW &&
++ !test_bit(RBIO_PINNED_BIT, &rbio->flags))
++ rbio_pins_low(table);
+ spin_lock(&rbio->bio_list_lock);
+
+ /* bump our ref if we were not in the list before */
+@@ -3086,6 +3212,8 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ * count that should be zero.
+ */
+ atomic64_inc(&fs_info->stripe_park_stats.data_rmw);
++ if (!(rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA))
++ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_reads);
+ /* A parked-then-flushed write that still had to read. */
+ if (test_bit(RBIO_WAS_PARKED_BIT, &rbio->flags))
+ atomic64_inc(&fs_info->stripe_park_stats.rmw_reads);
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index e7ccc20365bf7..b1913e70a2187 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -296,5 +296,8 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
+ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
+ u64 num_bytes, bool force);
+ void btrfs_stop_parked_rbios(struct btrfs_fs_info *fs_info);
++void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
++ int *pinned, int *live);
++void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info);
+
+ #endif
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 74eb13bf72c58..6997c81febfb2 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -25,6 +25,7 @@
+ #include "misc.h"
+ #include "fs.h"
+ #include "accessors.h"
++#include "raid56.h"
+
+ /*
+ * Structure name Path
+@@ -1122,7 +1123,9 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ struct kobj_attribute *a, char *buf)
+ {
+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++ int cached, pinned, live;
+
++ btrfs_rbio_cache_usage(fs_info, &cached, &pinned, &live);
+ return sysfs_emit(buf,
+ "parked %lld\n"
+ "merged_bytes %lld\n"
+@@ -1133,7 +1136,16 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "stuck %lld\n"
+ "padded %lld\n"
+ "padded_unwritten %lld\n"
+- "rmw_reads %lld\n",
++ "rmw_reads %lld\n"
++ "rbio_pin_refused %lld\n"
++ "rbio_pinned_now %d\n"
++ "rbio_pinned_live %d\n"
++ "rbio_pinned_hwm %lld\n"
++ "rbio_cache_now %d\n"
++ "rbio_cache_hwm %lld\n"
++ "rbio_pin_swept %lld\n"
++ "rbio_pin_commit_requests %lld\n"
++ "meta_rmw_reads %lld\n",
+ atomic64_read(&fs_info->stripe_park_stats.parked),
+ atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
+ atomic64_read(&fs_info->stripe_park_stats.filled),
+@@ -1143,7 +1155,16 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.stuck),
+ atomic64_read(&fs_info->stripe_park_stats.padded),
+ atomic64_read(&fs_info->stripe_park_stats.padded_unwritten),
+- atomic64_read(&fs_info->stripe_park_stats.rmw_reads));
++ atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
++ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_refused),
++ pinned,
++ live,
++ atomic64_read(&fs_info->stripe_park_stats.rbio_pinned_hwm),
++ cached,
++ atomic64_read(&fs_info->stripe_park_stats.rbio_cache_hwm),
++ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_swept),
++ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_commit_requests),
++ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_reads));
+ }
+ BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
+
+diff --git a/fs/btrfs/transaction.c b/fs/btrfs/transaction.c
+index 4f781df772202..6bbcf42121461 100644
+--- a/fs/btrfs/transaction.c
++++ b/fs/btrfs/transaction.c
+@@ -23,6 +23,7 @@
+ #include "dev-replace.h"
+ #include "qgroup.h"
+ #include "block-group.h"
++#include "raid56.h"
+ #include "space-info.h"
+ #include "fs.h"
+ #include "accessors.h"
+@@ -2472,6 +2473,8 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
+ * no-op when no stripe runs exist.
+ */
+ btrfs_retire_open_stripes(fs_info, cur_trans);
++ /* Every run just closed: the rbio cache's pins on them are stale. */
++ btrfs_rbio_unpin_stale(fs_info);
+
+ btrfs_scrub_pause(fs_info);
+ /*
+--
+2.47.3
+
+++ /dev/null
-From b5b297cec9569dd1040ab925a60f6df4bc13c227 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:53 -0400
-Subject: [RFC PATCH 033/116] btrfs: stripe_alloc: track per-sector liveness
- and pad from the map
-To: linux-btrfs@vger.kernel.org
-
-Padding used to ask where the run's allocation frontier was, which
-cannot see an allocation abandoned below it -- a reservation released, an
-allocation the finder discarded, an extent freed before its write was
-ever issued. Runs now carry a bit per sector, set at allocation and
-cleared by the new btrfs_open_stripe_write_abandoned() report, and
-padding fills exactly the sectors that are dead: this replaces
-btrfs_stripe_run_pad_start() with btrfs_stripe_run_pad_mask(). The map
-is sized once, with headroom for frontier growth, because the growth
-path holds the run lock where nothing may sleep; a run that would
-outgrow its map stops growing instead. A closed run's final stripe
-overhangs its shrunk end by construction, and those sectors -- the
-returned tail, unclaimable while the stripe holds live data -- are dead
-and paddable too.
-
-The abandonment report is what closes a writeback ENOSPC race the
-fsync-heavy near-full workload hits: an allocation undone without a
-report left phantom inflight bytes and phantom-live sectors, and
-reservations admitted against that state failed at writeback
-(cow_file_range -28) where stock refuses the write() up front. With
-the report in place the same workload shows zero writeback failures at
-every reservation margin setting, including margin disabled.
-
-Claiming also learns an O(1) fast fail: the by-size index walk is
-extracted into find_free_stripe_run(), stopping at the first entry whose
-largest contiguous free run cannot hold a full stripe -- near-full, where
-free space degenerates into many sub-stripe holes, this replaces a scan
-of the whole tree on every allocation.
-
-Moved out of the stripe_meta patch, which needs all of this for tree
-blocks but introduced it tangled with the metadata machinery; data wants
-it on its own.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 275 ++++++++++++++++++++++++++++++------
- fs/btrfs/block-group.h | 9 +-
- fs/btrfs/extent-tree.c | 8 +-
- fs/btrfs/free-space-cache.c | 149 ++++++++++---------
- fs/btrfs/raid56.c | 61 ++++----
- 5 files changed, 357 insertions(+), 145 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 59b7232c6482e..974ffc73f3b1e 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -504,6 +504,21 @@ struct btrfs_open_stripe_run {
- u64 owner; /* LOG class: btrfs_ino of the owner */
- enum btrfs_stripe_run_class class;
- bool open; /* accepting allocations */
-+ /*
-+ * One bit per sector of the run: set while that sector holds an
-+ * allocation someone still intends to write, clear otherwise.
-+ *
-+ * This is what lets a partial write be padded out to a full stripe.
-+ * The frontier alone cannot answer the question: space above it is
-+ * obviously free, but an allocation below it may have been abandoned
-+ * before it was ever written (a tree block COWed twice in one
-+ * transaction, a reservation released, an allocation the finder
-+ * discarded), leaving a hole that is just as safe to zero-fill.
-+ * Padding needs to know which uncovered sectors are dead, and only
-+ * the run knows -- it handed the space out and took it back.
-+ */
-+ unsigned long *live;
-+ u32 live_nbits; /* sectors @live covers; caps growth */
- };
-
- static bool open_stripe_run_drained(const struct btrfs_open_stripe_run *run)
-@@ -530,12 +545,74 @@ static int stripe_run_band(const struct btrfs_block_group *bg, u64 remaining)
- return band;
- }
-
-+/*
-+ * Growth headroom for a run's liveness map, in full stripes.
-+ *
-+ * The map is sized once and never reallocated, because the only place a run
-+ * grows -- the growable frontier in btrfs_alloc_from_open_stripe() -- holds
-+ * bg->stripe_run_lock with interrupts disabled, where nothing may sleep.
-+ * Sizing it beyond the run's initial span is what lets that path work at
-+ * all; a run that would outgrow its map stops growing instead, and the
-+ * allocation opens a fresh run.
-+ */
-+#define BTRFS_STRIPE_RUN_LIVE_STRIPES 32
-+
-+/*
-+ * Allocate a run's liveness map. Must be called before taking
-+ * bg->stripe_run_lock: this sleeps. Sets *nbits to what the map covers.
-+ */
-+static unsigned long *alloc_run_live_map(struct btrfs_block_group *bg,
-+ u64 run_len, u32 *nbits)
-+{
-+ const u64 span = max_t(u64, run_len,
-+ (u64)BTRFS_STRIPE_RUN_LIVE_STRIPES *
-+ bg->full_stripe_len);
-+ unsigned long *map;
-+
-+ *nbits = span >> bg->fs_info->sectorsize_bits;
-+ map = bitmap_zalloc(*nbits, GFP_NOFS);
-+ if (!map)
-+ *nbits = 0;
-+ return map;
-+}
-+
-+/* Mark [start, start+len) live (allocated) or dead (abandoned). */
-+static void run_live_set(struct btrfs_open_stripe_run *run, u64 start, u64 len,
-+ bool live)
-+{
-+ const u32 bits = run->bg->fs_info->sectorsize_bits;
-+ u32 first, nr;
-+
-+ if (!run->live || !run->live_nbits || start < run->start)
-+ return;
-+ first = (start - run->start) >> bits;
-+ nr = len >> bits;
-+ /*
-+ * Past the end of the map. Growth is capped at what the map covers,
-+ * so this should be unreachable; if it ever happens the map no longer
-+ * describes the run, and padding must not trust it -- zero-filling a
-+ * sector that is really live would destroy data. Retiring the map
-+ * makes btrfs_stripe_run_pad_mask() decline the run, so the write
-+ * degrades to a read-modify-write rather than to corruption.
-+ */
-+ if (unlikely(first + nr > run->live_nbits)) {
-+ WARN_ON_ONCE(1);
-+ run->live_nbits = 0;
-+ return;
-+ }
-+ if (live)
-+ bitmap_set(run->live, first, nr);
-+ else
-+ bitmap_clear(run->live, first, nr);
-+}
-+
- /* 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)
- {
- ASSERT(open_stripe_run_drained(run));
- list_del(&run->list);
-+ bitmap_free(run->live);
- kfree(run);
- wake_up_var(&bg->open_stripe_runs);
- }
-@@ -685,6 +762,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- }
- if (run) {
- *ret_offset = run->offset;
-+ run_live_set(run, run->offset, num_bytes, true);
- run->offset += num_bytes;
- run->inflight_bytes += num_bytes;
- bg->stripe_open_remainder -= num_bytes;
-@@ -700,7 +778,11 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-
-- new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
-+ /*
-+ * Zeroed: the error paths below reach out: before the liveness map is
-+ * allocated and must find a NULL there rather than uninitialised heap.
-+ */
-+ new_run = kzalloc(sizeof(*new_run), GFP_NOFS);
- if (!new_run)
- return -ENOMEM;
-
-@@ -721,6 +803,9 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- goto out;
- }
-
-+ /* Sleeps, so it has to happen before the locks below. */
-+ new_run->live = alloc_run_live_map(bg, len, &new_run->live_nbits);
-+
- /*
- * Install under fs_info->open_stripe_lock so that the block group
- * membership, the retire sequence read and the run installation are
-@@ -771,9 +856,24 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
-
- if (!r || r->end != start)
- continue;
-+ /*
-+ * Only grow as far as the run's liveness map reaches; it
-+ * cannot be reallocated here (see alloc_run_live_map()).
-+ * Beyond that, leave the run alone and open a new one.
-+ */
-+ if (((start + len - r->start) >> fs_info->sectorsize_bits) >
-+ r->live_nbits)
-+ continue;
- ASSERT(r->open);
- bg->open_stripe[class][band] = NULL;
- *ret_offset = r->offset;
-+ /*
-+ * Mark the handed-out bytes live before anything can consult
-+ * the map: this allocation begins at the old tail, usually
-+ * mid-stripe, and a sector the map calls dead is a sector a
-+ * neighbour's padded write may zero-fill.
-+ */
-+ run_live_set(r, r->offset, num_bytes, true);
- r->end = start + len;
- r->offset += num_bytes;
- r->inflight_bytes += num_bytes;
-@@ -800,6 +900,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- new_run->inflight_bytes = num_bytes;
- new_run->open_seq = fs_info->stripe_retire_seq;
- new_run->open = (new_run->offset != new_run->end);
-+ run_live_set(new_run, start, num_bytes, true);
- list_add_tail(&new_run->list, &bg->open_stripe_runs);
- bg->stripe_open_remainder += new_run->end - new_run->offset;
- /*
-@@ -819,6 +920,9 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- new_run = NULL;
- ret = 0;
- out:
-+ /* Unused on every path that did not install it, including errors. */
-+ if (new_run)
-+ bitmap_free(new_run->live);
- kfree(new_run);
- return ret;
- }
-@@ -867,6 +971,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- continue;
- if (num_bytes <= run->end - run->offset) {
- *ret_offset = run->offset;
-+ run_live_set(run, run->offset, num_bytes, true);
- run->offset += num_bytes;
- run->inflight_bytes += num_bytes;
- bg->stripe_open_remainder -= num_bytes;
-@@ -885,7 +990,11 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- stripe_open_remainder_sync(bg);
- }
-
-- new_run = kmalloc(sizeof(*new_run), GFP_NOFS);
-+ /*
-+ * Zeroed: the error paths below reach out: before the liveness map is
-+ * allocated and must find a NULL there rather than uninitialised heap.
-+ */
-+ new_run = kzalloc(sizeof(*new_run), GFP_NOFS);
- if (!new_run)
- return -ENOMEM;
-
-@@ -946,6 +1055,9 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- }
-
- install:
-+ /* Sleeps, so it has to happen before the locks below. */
-+ new_run->live = alloc_run_live_map(bg, len, &new_run->live_nbits);
-+
- /* See the installation comment in btrfs_alloc_from_open_stripe(). */
- spin_lock(&fs_info->open_stripe_lock);
- if (list_empty(&bg->open_stripe_bg_list)) {
-@@ -971,6 +1083,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- new_run->inflight_bytes = num_bytes;
- new_run->open_seq = fs_info->stripe_retire_seq;
- new_run->open = (new_run->offset != new_run->end);
-+ run_live_set(new_run, start, num_bytes, true);
- list_add_tail(&new_run->list, &bg->open_stripe_runs);
- bg->stripe_open_remainder += new_run->end - new_run->offset;
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-@@ -981,6 +1094,9 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- new_run = NULL;
- ret = 0;
- out:
-+ /* Unused on every path that did not install it, including errors. */
-+ if (new_run)
-+ bitmap_free(new_run->live);
- kfree(new_run);
- return ret;
- }
-@@ -1297,18 +1413,6 @@ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
- return ret;
- }
-
--/*
-- * For the raid56 pad-to-full optimization: a sub-stripe write into a
-- * stripe covered by a live stripe run may zero-fill (instead of read) any
-- * sector at or past the run's allocation frontier, because such sectors
-- * have never been written in the run's lifetime and, once the run closes,
-- * its stripe's tail cannot be reallocated while the stripe holds live
-- * data. Returns true and sets *pad_from to the frontier when the stripe
-- * at [stripe_start, stripe_start + stripe_len) has a paddable tail. The
-- * frontier can grow right after this returns; that is safe, because the
-- * later allocation's write serializes behind the caller's stripe lock
-- * and overwrites the zeros.
-- */
- /*
- * How far has the covering run allocated into this stripe? Returns the
- * exclusive end of the allocated prefix, clamped to the stripe, or U64_MAX
-@@ -1346,14 +1450,37 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
- return ceiling;
- }
-
--bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
-- u64 stripe_start, u64 stripe_len,
-- u64 *pad_from,
-- struct btrfs_stripe_pad_info *info)
-+/*
-+ * Which sectors of this stripe may be padded?
-+ *
-+ * Fills @dead with one bit per sector of the stripe, set where the sector
-+ * holds nothing anyone intends to write: space the run has not handed out
-+ * yet, and space it handed out but got back before the write was issued.
-+ * A caller may zero-fill exactly those and write the whole stripe.
-+ *
-+ * Returns false if no run covers the stripe, in which case nothing may be
-+ * padded: without a run there is no claim of exclusivity, and an uncovered
-+ * sector may hold committed data.
-+ *
-+ * This replaces asking where the run's frontier is. The frontier answers
-+ * "what has never been allocated", which misses allocations that were
-+ * abandoned below it -- a tree block COWed twice in one transaction, a
-+ * reservation released, an allocation the finder discarded. Those leave
-+ * holes that are equally safe to pad, and skipping them is the difference
-+ * between padding most partial stripes and padding all of them.
-+ *
-+ * @info, when non-NULL, reports the covering run's state at the moment of
-+ * the decision, for the pad-decline trace: a later extent-tree dump cannot
-+ * reconstruct where the frontier was when the write arrived.
-+ */
-+bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
-+ u64 stripe_len, unsigned long *dead,
-+ struct btrfs_stripe_pad_info *info)
- {
-+ const u32 bits = fs_info->sectorsize_bits;
-+ const u32 nsectors = stripe_len >> bits;
- struct btrfs_block_group *bg;
- struct btrfs_open_stripe_run *run;
-- atomic64_t *decline = NULL;
- unsigned long flags;
- bool ret = false;
-
-@@ -1374,6 +1501,8 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ u32 first;
-+
- if (stripe_start < run->start || stripe_start >= run->end)
- continue;
- if (info) {
-@@ -1381,37 +1510,48 @@ bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
- info->run_end = run->end;
- info->run_offset = run->offset;
- info->inflight_bytes = run->inflight_bytes;
-- info->reason = BTRFS_STRIPE_PAD_OK;
-- }
-- if (run->offset > stripe_start &&
-- run->offset < stripe_start + stripe_len) {
-- *pad_from = run->offset;
-- ret = true;
-- } else if (run->offset >= stripe_start + stripe_len) {
-- /*
-- * The frontier is past this stripe: every sector of
-- * it is allocated, so there is nothing dead to pad
-- * and the write is waiting on a neighbour's data.
-- */
-- decline = &fs_info->stripe_park_stats.pad_decline_live;
-- if (info)
-- info->reason = BTRFS_STRIPE_PAD_LIVE;
-- } else {
-- /* The frontier has not reached the stripe at all. */
-- decline = &fs_info->stripe_park_stats.pad_decline_unallocated;
-- if (info)
-- info->reason = BTRFS_STRIPE_PAD_UNALLOCATED;
- }
-+ if (!run->live || !run->live_nbits)
-+ break;
-+ /*
-+ * The stripe must lie inside the run's span. A closed run
-+ * has shrunk its end to the frontier, so its final stripe
-+ * overhangs: the sectors past end are the returned tail,
-+ * sub-stripe free space nothing can claim while the stripe
-+ * holds live data. They were never allocated, their live
-+ * bits are clear, and they are exactly what a kicked park
-+ * needs to pad. An open run's end is stripe aligned, so
-+ * overhang there means a stripe the run does not own.
-+ */
-+ if (stripe_start + stripe_len > run->end && run->open)
-+ break;
-+
-+ first = (stripe_start - run->start) >> bits;
-+ /*
-+ * And wholly inside the map. Declining here costs a
-+ * read-modify-write; reading past the map would be a lie about
-+ * which sectors are dead, and padding acts on that by
-+ * overwriting them.
-+ */
-+ if (first + nsectors > run->live_nbits)
-+ break;
-+ bitmap_zero(dead, nsectors);
-+ for (u32 i = 0; i < nsectors; i++)
-+ if (!test_bit(first + i, run->live))
-+ set_bit(i, dead);
-+ if (info)
-+ info->reason = BTRFS_STRIPE_PAD_OK;
-+ ret = true;
- break;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- if (!ret)
-- atomic64_inc(decline ? decline :
-- &fs_info->stripe_park_stats.pad_decline_no_run);
-+ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
- btrfs_put_block_group(bg);
- return ret;
- }
-
-+
- /* No open or draining run covers @bytenr any more. */
- static bool stripe_log_range_settled(struct btrfs_block_group *bg, u64 bytenr)
- {
-@@ -1865,12 +2005,26 @@ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- return false;
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (logical >= run->start && logical < run->end) {
-- if (class)
-- *class = run->class;
-- ret = true;
-- break;
-- }
-+ if (logical < run->start || logical >= run->end)
-+ continue;
-+ /*
-+ * A run stops being "open" as soon as it is full, but its
-+ * stripes stay exclusively ours until it drains, and a
-+ * closed run's end has been shrunk to its frontier, so a
-+ * write into it (necessarily below the frontier) still
-+ * matches. Metadata needs the draining window: allocation
-+ * and writeback are separated by the whole transaction.
-+ * Data needs it too: a run closes on exhaustion in the gap
-+ * between allocation and write arrival, and refusing here
-+ * made every run's tail writes unparkable -- the bulk of
-+ * stripe_alloc's read-modify-writes. The commit drain
-+ * waits for exactly these arrivals; parking them is what
-+ * lets the stripe go out whole.
-+ */
-+ if (class)
-+ *class = run->class;
-+ ret = true;
-+ break;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- btrfs_put_block_group(bg);
-@@ -1882,6 +2036,33 @@ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- * btrfs_alloc_from_open_stripe(). Every allocated byte must be reported
- * exactly once, in any number of pieces (e.g. after ordered extent splits).
- */
-+/*
-+ * Report bytes that will never be written: an allocation released before
-+ * its write was issued. Same accounting as a completion, plus the sectors
-+ * go dead so a later partial write to their stripe can pad over them
-+ * instead of falling back to read-modify-write.
-+ */
-+void btrfs_open_stripe_write_abandoned(struct btrfs_block_group *bg, u64 start,
-+ u64 num_bytes)
-+{
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (start >= run->start && start < run->offset) {
-+ ASSERT(start + num_bytes <= run->offset);
-+ ASSERT(run->inflight_bytes >= num_bytes);
-+ run_live_set(run, start, num_bytes, false);
-+ run->inflight_bytes -= num_bytes;
-+ if (open_stripe_run_drained(run))
-+ free_open_stripe_run(bg, run);
-+ break;
-+ }
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+}
-+
- void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
- u64 num_bytes)
- {
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 46f4ba48bcff8..87d807639589d 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -432,6 +432,8 @@ 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,
-+ u64 num_bytes);
- void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
- u64 num_bytes);
- void btrfs_open_stripe_write_done_bytenr(struct btrfs_fs_info *fs_info,
-@@ -470,10 +472,9 @@ struct btrfs_stripe_pad_info {
-
- u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
- u64 stripe_start, u64 stripe_len);
--bool btrfs_stripe_run_pad_start(struct btrfs_fs_info *fs_info,
-- u64 stripe_start, u64 stripe_len,
-- u64 *pad_from,
-- struct btrfs_stripe_pad_info *info);
-+bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
-+ u64 stripe_len, unsigned long *dead,
-+ struct btrfs_stripe_pad_info *info);
- bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
- u64 num_bytes, u32 which);
- int btrfs_parse_stripe_rmw(const char *value, size_t len, u32 *mask);
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index c2ba4abf0ec8c..fc97d1f78119f 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4309,8 +4309,9 @@ static void undo_stripe_allocation(struct btrfs_block_group *block_group,
- struct find_free_extent_ctl *ffe_ctl)
- {
- if (btrfs_is_stripe_alloc_bg(block_group))
-- btrfs_open_stripe_write_done(block_group, ffe_ctl->found_offset,
-- ffe_ctl->num_bytes);
-+ btrfs_open_stripe_write_abandoned(block_group,
-+ ffe_ctl->found_offset,
-+ ffe_ctl->num_bytes);
- }
-
- static int do_allocation(struct btrfs_block_group *block_group,
-@@ -5133,7 +5134,7 @@ static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
- * (or teardown) already reported these bytes.
- */
- if (!stripe_reported)
-- btrfs_open_stripe_write_done(cache, start, len);
-+ btrfs_open_stripe_write_abandoned(cache, start, len);
-
- btrfs_add_free_space(cache, start, len);
- btrfs_free_reserved_bytes(cache, len, is_delalloc);
-@@ -5598,6 +5599,7 @@ struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
- ret = PTR_ERR(buf);
- goto out_free_reserved;
- }
-+
- owning_root = btrfs_header_owner(buf);
-
- if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index c266c0f35f2f1..aabf456b70d97 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2282,9 +2282,70 @@ int btrfs_claim_stripe_tail(struct btrfs_block_group *block_group,
- }
-
- /*
-- * Entry-blind complement to the by-size fast path in
-- * btrfs_claim_free_stripe_run(): walk the aligned stripe grid in
-- * address order, accumulating contiguous free coverage
-+ * Find a fully free, stripe-aligned run of up to @want_bytes.
-+ *
-+ * Returns the free space entry containing it with @run_start and @run_len
-+ * describing the run, or NULL if there is none. The caller decides what to
-+ * do with it: claiming it for a stripe run, or handing it to a cluster.
-+ *
-+ * Walks the by-size index (largest max contiguous free run first) rather
-+ * than the by-offset index. An entry whose largest contiguous free run is
-+ * smaller than a full stripe cannot contain a fully-free stripe, and every
-+ * following entry is no larger, so we stop at the first such entry.
-+ * Near-full, where the free space degenerates into many sub-stripe holes,
-+ * this is an O(1) fast fail instead of a scan of the whole free space tree
-+ * on every allocation.
-+ *
-+ * ctl->tree_lock must be held.
-+ */
-+static struct btrfs_free_space *find_free_stripe_run(
-+ struct btrfs_block_group *block_group,
-+ u64 want_bytes, u64 *run_start,
-+ u64 *run_len)
-+{
-+ struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
-+ const u64 fsl = block_group->full_stripe_len;
-+ struct btrfs_free_space *entry;
-+ struct rb_node *node;
-+
-+ lockdep_assert_held(&ctl->tree_lock);
-+
-+ if (ctl->free_space < fsl)
-+ return NULL;
-+
-+ for (node = rb_first_cached(&ctl->free_space_bytes); node;
-+ node = rb_next(node)) {
-+ entry = rb_entry(node, struct btrfs_free_space, bytes_index);
-+
-+ if (get_max_extent_size(entry) < fsl)
-+ break;
-+
-+ if (entry->bitmap) {
-+ if (find_stripe_run_in_bitmap(ctl, entry, want_bytes,
-+ run_start, run_len) &&
-+ btrfs_stripe_run_range_usable(block_group,
-+ *run_start, run_len))
-+ return entry;
-+ continue;
-+ }
-+
-+ *run_start = stripe_run_align(block_group, entry->offset);
-+ if (*run_start + fsl > entry->offset + entry->bytes)
-+ continue;
-+ *run_len = min(want_bytes,
-+ div64_u64(entry->offset + entry->bytes - *run_start,
-+ fsl) * fsl);
-+ if (!btrfs_stripe_run_range_usable(block_group, *run_start,
-+ run_len))
-+ continue;
-+ return entry;
-+ }
-+ return NULL;
-+}
-+
-+/*
-+ * Entry-blind complement to find_free_stripe_run(): walk the aligned
-+ * stripe grid in address order, accumulating contiguous free coverage
- * with point lookups, looking for a run of fully-free full stripes no
- * single entry contains.
- *
-@@ -2466,7 +2527,6 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- &block_group->fs_info->discard_ctl;
- const u64 fsl = block_group->full_stripe_len;
- struct btrfs_free_space *entry;
-- struct rb_node *node;
- struct btrfs_free_space *spare = NULL;
- enum btrfs_trim_state head_trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
- bool spare_used = false;
-@@ -2483,68 +2543,30 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
-
- spin_lock(&ctl->tree_lock);
-
-- if (ctl->free_space < fsl)
-+ entry = find_free_stripe_run(block_group, want_bytes, &run_start, &run_len);
-+ if (!entry) {
-+ /*
-+ * No single entry holds a full stripe; look for one whose
-+ * free space spans entry boundaries. The spare entry is
-+ * for the belt-and-braces case of a run strictly inside
-+ * one extent entry, whose removal splits it in two.
-+ */
-+ spin_unlock(&ctl->tree_lock);
-+ spare = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
-+ if (!spare)
-+ return -ENOMEM;
-+ spin_lock(&ctl->tree_lock);
-+ if (!find_free_stripe_run_slow(block_group, want_bytes,
-+ &run_start, &run_len))
-+ goto out;
-+ spare_used = claim_stripe_run_pieces(block_group, run_start,
-+ run_len, spare);
-+ *start = run_start;
-+ *len = run_len;
-+ ret = 0;
- goto out;
--
-- /*
-- * Walk the by-size index (largest max contiguous free run first)
-- * rather than the by-offset index. An entry whose largest contiguous
-- * free run is smaller than a full stripe cannot contain a fully-free
-- * stripe, and every following entry is no larger, so we stop at the
-- * first such entry. Near-full, where the free space degenerates into
-- * many sub-stripe holes, this is an O(1) fast fail instead of a scan
-- * of the whole free space tree on every allocation.
-- */
-- for (node = rb_first_cached(&ctl->free_space_bytes); node;
-- node = rb_next(node)) {
-- entry = rb_entry(node, struct btrfs_free_space, bytes_index);
--
-- if (get_max_extent_size(entry) < fsl)
-- break;
--
-- if (entry->bitmap) {
-- if (find_stripe_run_in_bitmap(ctl, entry, want_bytes,
-- &run_start, &run_len) &&
-- btrfs_stripe_run_range_usable(block_group,
-- run_start, &run_len))
-- goto found;
-- continue;
-- }
--
-- run_start = stripe_run_align(block_group, entry->offset);
-- if (run_start + fsl > entry->offset + entry->bytes)
-- continue;
-- run_len = min(want_bytes,
-- div64_u64(entry->offset + entry->bytes - run_start,
-- fsl) * fsl);
-- if (!btrfs_stripe_run_range_usable(block_group, run_start,
-- &run_len))
-- continue;
-- goto found;
- }
-
-- /*
-- * No single entry holds a full stripe; look for one whose
-- * free space spans entry boundaries. The spare entry is
-- * for the belt-and-braces case of a run strictly inside
-- * one extent entry, whose removal splits it in two.
-- */
-- spin_unlock(&ctl->tree_lock);
-- spare = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
-- if (!spare)
-- return -ENOMEM;
-- spin_lock(&ctl->tree_lock);
-- if (!find_free_stripe_run_slow(block_group, want_bytes,
-- &run_start, &run_len))
-- goto out;
-- spare_used = claim_stripe_run_pieces(block_group, run_start,
-- run_len, spare);
-- *start = run_start;
-- *len = run_len;
-- ret = 0;
-- goto out;
--
--found:
- if (!btrfs_free_space_trimmed(entry))
- atomic64_add(run_len, &discard_ctl->discard_bytes_saved);
-
-@@ -2586,6 +2608,7 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- return ret;
- }
-
-+
- /*
- * given a cluster, put all of its extents back into the free space
- * cache. If a block group is passed, this function will only free
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 370893ab20223..92c48cb4578da 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -2262,6 +2262,7 @@ void raid56_parity_write(struct bio *bio, struct btrfs_io_context *bioc)
- rbio->operation = BTRFS_RBIO_WRITE;
- rbio_add_bio(rbio, bio);
-
-+
- /*
- * Don't plug on full rbios, just get them out the door
- * as quickly as we can
-@@ -2847,74 +2848,78 @@ static void submit_write_bios(struct btrfs_raid_bio *rbio,
-
- /*
- * Try to avoid the RMW read phase of a sub-stripe write by zero-filling
-- * the uncovered data sectors. Legal only when every uncovered sector
-- * lies at or past its stripe run's allocation frontier -- never written
-- * in the run's lifetime, and unreachable by other allocations while this
-- * stripe holds live data (see btrfs_stripe_run_pad_start()). A frontier
-- * that grows under us is safe: the newer allocation's write serializes
-+ * the uncovered data sectors. Legal only where the stripe's run says the
-+ * sector holds nothing anyone intends to write -- never allocated, or
-+ * allocated and abandoned before its write was issued. A run that hands
-+ * out more space under us is safe: the newer allocation's write serializes
- * behind this rbio's stripe lock and lands over the zeros.
- */
- static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- {
- struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
- const u64 stripe_start = rbio->bioc->full_stripe_logical;
-- const u32 sectorsize = fs_info->sectorsize;
- const u64 stripe_len = (u64)rbio->nr_data * rbio->bioc->stripe_len;
-+ const u32 sectorsize = fs_info->sectorsize;
-+ const u32 nsectors = rbio->nr_data * rbio->stripe_nsectors;
- struct btrfs_stripe_pad_info info;
-- const u32 total = rbio->nr_data * rbio->stripe_nsectors;
-- u64 pad_from = 0;
-+ unsigned long *dead;
- u32 covered = 0;
-+ bool ok = false;
- int i;
-
- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
- return false;
-- if (!btrfs_stripe_run_pad_start(fs_info, stripe_start, stripe_len,
-- &pad_from, &info)) {
-+
-+ dead = bitmap_zalloc(nsectors, GFP_NOFS);
-+ if (!dead)
-+ return false;
-+ if (!btrfs_stripe_run_pad_mask(fs_info, stripe_start, stripe_len, dead,
-+ &info)) {
- trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
-- stripe_len, pad_from, 0, total,
-+ stripe_len, 0, 0, nsectors,
- info.run_start, info.run_end,
- info.run_offset,
- info.inflight_bytes,
- info.reason);
-- return false;
-+ goto out;
- }
-
- /* Populate bio_paddrs so covered sectors are visible below. */
- index_rbio_pages(rbio);
-
-+ for (i = 0; i < nsectors; i++)
-+ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
-+ covered++;
-+
- /*
-- * Every data sector this rbio does not cover must be paddable. A
-- * sector below the frontier is allocated to someone else and this
-+ * Every data sector this rbio does not cover must be dead. A live
-+ * uncovered sector belongs to another writer's allocation and this
- * write does not carry its data, so padding would destroy it: that
- * is a distinct refusal from the oracle's, and it is the one that
- * says another writer's allocation shares this stripe.
- */
-- for (i = 0; i < total; i++)
-- if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
-- covered++;
--
-- for (i = 0; i < total; i++) {
-- const int stripe_nr = i / rbio->stripe_nsectors;
-- const int sectornr = i % rbio->stripe_nsectors;
-- u64 logical = stripe_start + stripe_nr * BTRFS_STRIPE_LEN +
-- (u64)sectornr * sectorsize;
--
-+ for (i = 0; i < nsectors; i++) {
- if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
- continue;
-- if (logical < pad_from) {
-+ if (!test_bit(i, dead)) {
- atomic64_inc(&fs_info->stripe_park_stats.pad_decline_uncovered);
- info.reason = BTRFS_STRIPE_PAD_UNCOVERED;
- trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
-- stripe_len, pad_from,
-- covered, total,
-+ stripe_len, 0, covered,
-+ nsectors,
- info.run_start,
- info.run_end,
- info.run_offset,
- info.inflight_bytes,
- info.reason);
-- return false;
-+ goto out;
- }
- }
-+ ok = true;
-+out:
-+ bitmap_free(dead);
-+ if (!ok)
-+ return false;
-
- if (alloc_rbio_data_pages(rbio) < 0)
- return false;
---
-2.47.3
-
+++ /dev/null
-From e41a35a9dc376c6b027def1b5cf16607cec0a75f Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:54 -0400
-Subject: [RFC PATCH 034/116] btrfs: stripe_alloc: count claimable whole-stripe
- supply directly
-To: linux-btrfs@vger.kernel.org
-
-Data reservations are admitted against arithmetic -- free space minus
-trapped fragments minus open-run remainders minus a per-extent margin --
-and under sustained near-full churn the arithmetic and the claim rule
-disagree for long enough that admitted buffered writes reach writeback
-with nothing claimable left: measured, ~5.2-5.5k reserved writebacks
-dropped per fsstress churn run, silently for anything not waiting on
-fsync. Stock refuses the same write()s up front. Nothing between
-"durable by fsync" and "refused by write()" is acceptable when an
-operator accident fills the disk.
-
-First step, accounting only: measure the constraint instead of deriving
-it. bg->stripe_claimable counts bytes of fully free whole stripes --
-exactly what btrfs_claim_free_stripe_run() can take, the complement of
-stripe_unusable within each stripe. The commit rescan derives it from
-the same pass that computes trapped bytes (free minus trapped) and is
-the sole upward correction; incremental maintenance under
-ctl->tree_lock only ever DEBITS -- removals round their decrement OUT
-to every touched stripe, claims subtract exactly what they took. The
-counter can therefore only under-count between commits, never
-over-count.
-
-Crediting freed whole stripes incrementally on the add side is
-deliberately not done, having been tried and dropped. Several add
-paths re-add free space that a low-level remove never de-credited --
-the async discard trim (unlink_free_space / bitmap_clear_bits, then
-do_trimming's re-add through __btrfs_add_free_space) and
-btrfs_remove_free_space's middle-split tail re-add -- so crediting on
-add double-counts and drives the counter ABOVE the authoritative scan.
-That is the dangerous direction: once admission gates on this counter,
-an over-count admits reservations against phantom supply that writeback
-then drops, while an under-count is an early, clean write()-time
-ENOSPC. Debit-only makes over-counting structurally impossible,
-whatever a future re-add path forgets to de-credit. (Reproduced with
-compress+autodefrag+discard=async on a legacy-converted raid5
-filesystem, incremental ~= 2x scanned; credit_return attribution
-confirmed the phantom entered through do_trimming's re-add, not the
-open-stripe allocator returns.)
-
-A WARN_RATELIMIT at the rescan catches the dangerous direction anyway
-(incremental above scanned), which under a debit-only rule means a
-missed consumption site, and localizes it; the clamp to the scanned
-value keeps every rescan authoritative regardless. Rate limited rather
-than _ONCE because such a gap recurs on every commit, and reporting
-only the first hit hides that it is ongoing.
-
-The space_info aggregate bytes_stripe_claimable follows the
-stripe_unusable pattern (incremental between commits, re-totaled from
-armed groups at the rescan), shows in the ENOSPC dump and in sysfs.
-No admission change yet; that comes once the counter proves accurate
-under the fill, churn, balance and reclaim suites. The by-size
-fast-fail in the claim keeps its early exit: the point of measuring is
-to make such inputs trustworthy, not to search harder around them.
-
-Data block groups only for now; raid56 metadata and mixed block groups
-join when the data counter has settled.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 7 ++-
- fs/btrfs/block-group.h | 8 +++
- fs/btrfs/free-space-cache.c | 111 +++++++++++++++++++++++++++++++++--
- fs/btrfs/space-info.c | 3 +-
- fs/btrfs/space-info.h | 5 ++
- fs/btrfs/sysfs.c | 2 +
- include/trace/events/btrfs.h | 8 +++
- 7 files changed, 138 insertions(+), 6 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 974ffc73f3b1e..857638d2d506c 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2332,6 +2332,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;
- int raid;
-
- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
-@@ -2363,14 +2364,18 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- * groups are excluded; their free space is already
- * accounted as read-only.
- */
-- if (READ_ONCE(bg->stripe_unusable_ready))
-+ if (READ_ONCE(bg->stripe_unusable_ready)) {
- total += READ_ONCE(bg->stripe_unusable);
-+ total_claimable +=
-+ READ_ONCE(bg->stripe_claimable);
-+ }
- }
- }
- up_read(&sinfo->groups_sem);
-
- spin_lock(&sinfo->lock);
- sinfo->bytes_stripe_unusable = total;
-+ sinfo->bytes_stripe_claimable = total_claimable;
- /*
- * The rescan usually lowers the counter (mid-transaction
- * incremental adds overcount conservatively); admission
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 87d807639589d..4c59b0ba0f217 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -292,6 +292,14 @@ struct btrfs_block_group {
- * (honest f_bavail); the reservation layer is deliberately unchanged.
- */
- u64 stripe_unusable;
-+ /*
-+ * Directly measured claimable supply: bytes of fully free, aligned
-+ * whole stripes in the free space cache -- exactly what
-+ * btrfs_claim_free_stripe_run() can take. Maintained incrementally
-+ * under ctl->tree_lock by rules that only ever err LOW (early
-+ * write()-time ENOSPC), corrected upward by the commit rescan.
-+ */
-+ u64 stripe_claimable;
- bool stripe_unusable_ready;
-
- /*
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index aabf456b70d97..eed6f8b7de197 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1360,6 +1360,10 @@ static void steal_from_bitmap(struct btrfs_free_space_ctl *ctl,
- }
- }
-
-+static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta);
-+static u64 stripe_touched_bytes(const struct btrfs_block_group *bg,
-+ u64 bytenr, u64 size);
-+
- static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
- u64 offset, u64 bytes,
- enum btrfs_trim_state trim_state)
-@@ -1414,6 +1418,19 @@ static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
- if (ret)
- kmem_cache_free(btrfs_free_space_cachep, info);
- out:
-+ /*
-+ * Do NOT incrementally credit newly-freed whole stripes here. Add paths
-+ * re-add space that a low-level remove never de-credited -- the async
-+ * discard trim (unlink_free_space / bitmap_clear_bits + do_trimming's
-+ * re-add) and btrfs_remove_free_space's middle-split tail -- so crediting
-+ * on add double-counts and stripe_claimable drifts ABOVE the authoritative
-+ * scan. That is the dangerous direction: once admission gates on the
-+ * counter, an over-count admits reservations against phantom supply that
-+ * writeback then drops. The incremental rules now only ever DEBIT
-+ * (removes/claims, which err low); the per-commit rescan is the sole
-+ * upward correction, so the counter can only under-count (early, clean
-+ * write()-time ENOSPC) -- never over-count.
-+ */
- btrfs_discard_update_discardable(block_group);
- spin_unlock(&ctl->tree_lock);
-
-@@ -1493,6 +1510,48 @@ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
-
- static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
-
-+/*
-+ * stripe_alloc: keep the directly measured claimable whole-stripe supply
-+ * in step with free space mutations. Positive deltas come from returned
-+ * ranges' interior whole stripes, negative from claims and removals. The
-+ * blind rules only ever err by counting claimable LOW (early write()-time
-+ * ENOSPC, corrected upward by the commit rescan), never HIGH: a
-+ * reservation admitted against phantom supply fails at writeback and
-+ * drops buffered data. Caller holds ctl->tree_lock.
-+ */
-+static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta)
-+{
-+ struct btrfs_space_info *sinfo = bg->space_info;
-+
-+ if (!READ_ONCE(bg->stripe_unusable_ready) || !delta)
-+ return;
-+ if (delta < 0 && bg->stripe_claimable < (u64)-delta)
-+ delta = -(s64)bg->stripe_claimable;
-+ if (!delta)
-+ return;
-+ bg->stripe_claimable += delta;
-+ if (!sinfo)
-+ return;
-+ spin_lock(&sinfo->lock);
-+ if (delta < 0 && sinfo->bytes_stripe_claimable < (u64)-delta)
-+ sinfo->bytes_stripe_claimable = 0;
-+ else
-+ btrfs_space_info_update_bytes_stripe_claimable(sinfo, delta);
-+ spin_unlock(&sinfo->lock);
-+}
-+
-+/* The whole-stripe span [bytenr, bytenr + size) touches at all. */
-+static u64 stripe_touched_bytes(const struct btrfs_block_group *bg,
-+ u64 bytenr, u64 size)
-+{
-+ const u64 fsl = bg->full_stripe_len;
-+ const u64 rel = bytenr - bg->start;
-+ const u64 astart = div64_u64(rel, fsl) * fsl;
-+ const u64 aend = div64_u64(rel + size + fsl - 1, fsl) * fsl;
-+
-+ return aend - astart;
-+}
-+
- /*
- * stripe_alloc: count the sub-stripe fragments of a returning free range
- * as trapped immediately, without waiting for the commit-time rescan.
-@@ -1619,6 +1678,19 @@ int btrfs_remove_free_space(struct btrfs_block_group *block_group,
-
- spin_lock(&ctl->tree_lock);
-
-+ /*
-+ * The removed bytes leave free space; every whole stripe the range
-+ * touches may lose wholeness (a boundary fragment removal breaks a
-+ * fully free stripe as surely as an interior one empties it).
-+ * Rounding the decrement OUT to touched stripes errs claimable-low.
-+ * The trapped counter is deliberately not decremented for removed
-+ * fragments: leaving it high is the safe direction, and the rescan
-+ * settles both.
-+ */
-+ if (btrfs_is_stripe_alloc_bg(block_group))
-+ stripe_claimable_mod(block_group,
-+ -(s64)stripe_touched_bytes(block_group, offset, bytes));
-+
- again:
- ret = 0;
- if (!bytes)
-@@ -2032,7 +2104,7 @@ static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
- void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
- {
- struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-- u64 trapped, nstripes;
-+ u64 trapped, claimable, nstripes;
- u32 *freep;
-
- if (!btrfs_is_stripe_alloc_bg(bg))
-@@ -2053,14 +2125,19 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
- }
- trapped = stripe_unusable_scan(bg, freep, nstripes);
- bg->stripe_unusable = trapped;
-+ /* Every free byte is claimable or trapped; the scan split them. */
-+ bg->stripe_claimable = ctl->free_space - trapped;
-+ claimable = bg->stripe_claimable;
- bg->stripe_unusable_ready = true;
- spin_unlock(&ctl->tree_lock);
- kvfree(freep);
-
-- if (trapped) {
-+ if (trapped || claimable) {
- spin_lock(&bg->space_info->lock);
- btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
- trapped);
-+ btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
-+ claimable);
- spin_unlock(&bg->space_info->lock);
- }
- }
-@@ -2077,6 +2154,7 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
- {
- struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
- u64 trapped;
-+ u64 claimable;
-
- if (!btrfs_is_stripe_alloc_bg(bg))
- return;
-@@ -2087,13 +2165,17 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
- return;
- }
- trapped = bg->stripe_unusable;
-+ claimable = bg->stripe_claimable;
-+ bg->stripe_claimable = 0;
- bg->stripe_unusable_ready = false;
- spin_unlock(&ctl->tree_lock);
-
-- if (trapped) {
-+ if (trapped || claimable) {
- spin_lock(&bg->space_info->lock);
- btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
- -(s64)trapped);
-+ btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
-+ -(s64)claimable);
- spin_unlock(&bg->space_info->lock);
- }
- }
-@@ -2121,8 +2203,27 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
- return;
-
- spin_lock(&ctl->tree_lock);
-- if (bg->stripe_unusable_ready) /* skip if disarmed (read-only) */
-+ if (bg->stripe_unusable_ready) { /* skip if disarmed (read-only) */
-+ u64 scanned;
-+
- bg->stripe_unusable = stripe_unusable_scan(bg, freep, nstripes);
-+ scanned = ctl->free_space - bg->stripe_unusable;
-+ /*
-+ * The incremental rules may only under-count claimable
-+ * supply; counting more than the scan finds means a missed
-+ * consumption site, the direction that admits reservations
-+ * writeback cannot honor. Rate-limited rather than _ONCE: a
-+ * persistent gap -- e.g. a filesystem carrying extents from the
-+ * legacy allocator, a layout the incremental rules were not
-+ * shaped for -- recurs every commit, and hiding all but the
-+ * first hit loses that signal in the field. The clamp below
-+ * keeps each rescan authoritative regardless.
-+ */
-+ WARN_RATELIMIT(bg->stripe_claimable > scanned,
-+ "bg %llu incremental stripe_claimable %llu above scanned %llu",
-+ bg->start, bg->stripe_claimable, scanned);
-+ bg->stripe_claimable = scanned;
-+ }
- spin_unlock(&ctl->tree_lock);
- kvfree(freep);
- /*
-@@ -2561,6 +2662,7 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- goto out;
- spare_used = claim_stripe_run_pieces(block_group, run_start,
- run_len, spare);
-+ stripe_claimable_mod(block_group, -(s64)run_len);
- *start = run_start;
- *len = run_len;
- ret = 0;
-@@ -2591,6 +2693,7 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- kmem_cache_free(btrfs_free_space_cachep, entry);
- }
- }
-+ stripe_claimable_mod(block_group, -(s64)run_len);
- *start = run_start;
- *len = run_len;
- ret = 0;
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 2137d58015412..13e0db4aa1c42 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -719,11 +719,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 stripe_unusable=%llu stripe_open=%llu stripe_margin=%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 stripe_claimable=%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_stripe_unusable, info->bytes_stripe_open,
-+ info->bytes_stripe_claimable,
- info->bytes_stripe_margin);
- }
-
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 13c24536731c5..c8143f39f89b0 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -158,6 +158,10 @@ struct btrfs_space_info {
- cannot admit writes against it, and
- subtracted in statfs (from a different
- base -- the free space cache walk). */
-+ u64 bytes_stripe_claimable; /* sum of armed groups' directly
-+ measured claimable whole-stripe
-+ bytes; see stripe_claimable in
-+ struct btrfs_block_group */
- u64 bytes_stripe_open; /* sum of open stripe runs' unallocated
- remainders. Claimed out of the free
- space cache but not yet allocated;
-@@ -309,6 +313,7 @@ DECLARE_SPACE_INFO_UPDATE(bytes_may_use, "space_info");
- DECLARE_SPACE_INFO_UPDATE(bytes_pinned, "pinned");
- DECLARE_SPACE_INFO_UPDATE(bytes_zone_unusable, "zone_unusable");
- DECLARE_SPACE_INFO_UPDATE(bytes_stripe_unusable, "stripe_unusable");
-+DECLARE_SPACE_INFO_UPDATE(bytes_stripe_claimable, "stripe_claimable");
-
- static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
- bool may_use_included)
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 25d8c61d72a9e..2559c37f8af85 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -818,6 +818,7 @@ 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_claimable);
- SPACE_INFO_ATTR(bytes_stripe_open);
- SPACE_INFO_ATTR(bytes_stripe_margin);
- SPACE_INFO_ATTR(disk_used);
-@@ -949,6 +950,7 @@ 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_claimable),
- BTRFS_ATTR_PTR(space_info, bytes_stripe_open),
- BTRFS_ATTR_PTR(space_info, bytes_stripe_margin),
- BTRFS_ATTR_PTR(space_info, disk_used),
-diff --git a/include/trace/events/btrfs.h b/include/trace/events/btrfs.h
-index db541d70e9640..e95f1b3a8a0c5 100644
---- a/include/trace/events/btrfs.h
-+++ b/include/trace/events/btrfs.h
-@@ -3299,6 +3299,14 @@ DEFINE_EVENT(btrfs__space_info_update, update_bytes_stripe_unusable,
- TP_ARGS(fs_info, sinfo, old, diff)
- );
-
-+DEFINE_EVENT(btrfs__space_info_update, update_bytes_stripe_claimable,
-+
-+ TP_PROTO(const struct btrfs_fs_info *fs_info,
-+ const struct btrfs_space_info *sinfo, u64 old, s64 diff),
-+
-+ TP_ARGS(fs_info, sinfo, old, diff)
-+);
-+
- TRACE_EVENT(btrfs_stripe_pad_decline,
-
- TP_PROTO(const struct btrfs_fs_info *fs_info, u64 full_stripe,
---
-2.47.3
-
--- /dev/null
+From f0c935dc1c822c96b7756632d5820b5e2ff3e3b9 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 10 Oct 2026 00:19:18 -0400
+Subject: [RFC PATCH 34/85] btrfs: stripe_alloc: skip RAID5/6 groups that are
+ mapped as RAID1/RAID1C3
+To: linux-btrfs@vger.kernel.org
+
+Since commit 49ba3a3c0d67 ("btrfs: disguise single-data-RAID56 as
+RAID1/RAID1C3"), a RAID5 chunk with one data stripe (two devices) or a
+RAID6 chunk with one (three devices) keeps its RAID5/6 type on disk, in
+the chunk map's on_disk_type and in the block group's flags, but is
+mapped as RAID1/RAID1C3. Such chunks appear when only two or three
+devices have unallocated space, e.g. on devices of unequal size.
+
+stripe_alloc and stripe_meta decide by the block group's flags, so they
+kept opening stripe runs in these groups. Their IO goes down the
+mirrored path and never reaches raid56, so no write ever marked the
+runs' sectors written: every ordered extent there ended with all its
+sectors unwritten, and the groups paid stripe_alloc's per-allocation run
+bookkeeping for a write hole they do not have. (Nothing was trapped there:
+their full stripe is one sector, since btrfs_full_stripe_len() reads the
+chunk map's type.)
+
+Record at block group creation whether the chunk map's type differs from
+its on_disk_type in this way (BLOCK_GROUP_FLAG_RAID56_MIRRORED), and
+leave such groups to the normal allocator.
+
+Their flags still match the RAID5/6 allocation profile, so writes land in
+them, and with two of five raid6 devices missing every new data chunk is
+one: the admission supply must include them, or every degraded write fails
+with ENOSPC. Each space_info counts the free space of its writable
+single-data-stripe RAID5/6 data groups, following ctl->free_space, which
+every free space change goes through; btrfs_stripe_unmanaged_sync() runs
+when a group joins its space_info and after each read-only transition, and
+the read-only guard treats a counted group's free space as the supply it
+takes away. Groups of other profiles are not counted: a RAID5/6 write
+cannot use them. The full-stripe widths the admission charge is taken
+over leave these groups out, as their full stripe is one sector.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 25 ++++++++++++++----
+ fs/btrfs/block-group.h | 27 ++++++++++++++++++++
+ fs/btrfs/extent-tree.c | 6 +++--
+ fs/btrfs/free-space-cache.c | 51 ++++++++++++++++++++++++++++++++-----
+ fs/btrfs/free-space-cache.h | 1 +
+ fs/btrfs/space-info.c | 41 ++++++++++++++++++++++++++++-
+ fs/btrfs/space-info.h | 6 +++++
+ fs/btrfs/volumes.c | 21 +++++++++++++++
+ fs/btrfs/volumes.h | 1 +
+ 9 files changed, 165 insertions(+), 14 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index e101654302a7d..8b81b73dc193d 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -3193,17 +3193,26 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
+ * 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)) {
++ if (!ret && (READ_ONCE(cache->stripe_unusable_ready) ||
++ test_bit(BLOCK_GROUP_FLAG_UNMANAGED_COUNTED,
++ &cache->runtime_flags)) &&
++ btrfs_test_opt(cache->fs_info, STRIPE_ALLOC) &&
++ READ_ONCE(cache->fs_info->stripe_margin_unit)) {
+ /*
+ * 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.
++ * A group stripe_alloc does not manage supplies its
++ * free space (bytes_unmanaged_free) instead.
+ */
+- const u64 supply = sinfo->bytes_stripe_claimable;
++ const u64 supply = sinfo->bytes_stripe_claimable +
++ atomic64_read(&sinfo->bytes_unmanaged_free);
+ const u64 mine = min(supply,
+- READ_ONCE(cache->stripe_claimable));
++ READ_ONCE(cache->stripe_unusable_ready) ?
++ READ_ONCE(cache->stripe_claimable) :
++ READ_ONCE(cache->free_space_ctl->free_space));
+
+ if (sinfo->bytes_may_use + sinfo->bytes_stripe_margin >
+ supply - mine)
+@@ -3240,8 +3249,10 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
+ * contribution so it is not subtracted twice. Idempotent, so repeated
+ * ro increments are harmless.
+ */
+- if (!ret)
++ if (!ret) {
+ btrfs_block_group_disarm_stripe_unusable(cache);
++ btrfs_stripe_unmanaged_sync(cache);
++ }
+ if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
+ btrfs_info(cache->fs_info,
+ "unable to make block group %llu ro", cache->start);
+@@ -4310,6 +4321,8 @@ static struct btrfs_block_group *btrfs_create_block_group(
+
+ cache->fs_info = fs_info;
+ cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
++ if (btrfs_chunk_raid56_mirrored(fs_info, start))
++ set_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &cache->runtime_flags);
+ cache->max_claimable_run = (u64)-1;
+
+ cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
+@@ -5172,8 +5185,10 @@ void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
+ * the current free space (it may have changed while read-only). The
+ * scan re-adds this group's trapped free space to the space_info total.
+ */
+- if (became_rw)
++ if (became_rw) {
+ btrfs_block_group_init_stripe_unusable(cache);
++ btrfs_stripe_unmanaged_sync(cache);
++ }
+ }
+
+ static int update_block_group_item(struct btrfs_trans_handle *trans,
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 29d88d9c6c361..8b6575c98e0d5 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -123,6 +123,18 @@ enum btrfs_block_group_flags {
+ * counter must be rescanned at commit (stripe_alloc only).
+ */
+ BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY,
++ /*
++ * A RAID5/6 group with a single data stripe, which is mapped as
++ * RAID1/RAID1C3 (its chunk map's type differs from on_disk_type). Its
++ * IO never reaches raid56, so stripe_alloc and stripe_meta skip it.
++ */
++ BLOCK_GROUP_FLAG_RAID56_MIRRORED,
++ /*
++ * This group's free space is in its space_info's
++ * bytes_unmanaged_free (see btrfs_stripe_unmanaged_sync()). Set and
++ * cleared under the free-space ctl's tree_lock.
++ */
++ BLOCK_GROUP_FLAG_UNMANAGED_COUNTED,
+ };
+
+ enum btrfs_caching_type {
+@@ -383,6 +395,21 @@ static inline u64 btrfs_block_group_end(const struct btrfs_block_group *block_gr
+ return (block_group->start + block_group->length);
+ }
+
++/*
++ * A RAID5/6 data group stripe_alloc does not manage because it has a single
++ * data stripe and is mapped as RAID1/RAID1C3. Its flags still match the
++ * RAID5/6 allocation profile, so writes stripe_alloc admits can land there,
++ * and the admission has to count its free space. Groups of other profiles
++ * are left out: a write allocated for a RAID5/6 profile cannot use them.
++ */
++static inline bool btrfs_stripe_bg_unmanaged(const struct btrfs_block_group *bg)
++{
++ return (bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
++ !(bg->flags & BTRFS_BLOCK_GROUP_METADATA) &&
++ (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
++ test_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &bg->runtime_flags);
++}
++
+ static inline bool btrfs_is_block_group_used(const struct btrfs_block_group *bg)
+ {
+ lockdep_assert_held(&bg->lock);
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 549b62828f4d8..56ea5eead8a17 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4197,14 +4197,16 @@ static int do_allocation_zoned(struct btrfs_block_group *block_group,
+ * closes the raid56 write hole; see "Open stripe runs" in block-group.c.
+ * Metadata is covered by btrfs_is_stripe_meta_bg(). Mixed groups are
+ * excluded: stripe_alloc refuses to enable on them
+- * (btrfs_stripe_alloc_check_support()).
++ * (btrfs_stripe_alloc_check_support()). So are groups with a single data
++ * stripe: they are mapped as RAID1/RAID1C3 and have no write hole.
+ */
+ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
+ {
+ return btrfs_test_opt(bg->fs_info, STRIPE_ALLOC) &&
+ (bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
+ !(bg->flags & BTRFS_BLOCK_GROUP_METADATA) &&
+- (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK);
++ (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
++ !test_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &bg->runtime_flags);
+ }
+
+ /*
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 8b7f241b0cd91..5529b86306478 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -550,6 +550,19 @@ tree_search_offset(struct btrfs_free_space_ctl *ctl,
+ return entry;
+ }
+
++/*
++ * Change the group's free-space total, and with it the space_info's
++ * bytes_unmanaged_free while the group is counted there. Under tree_lock.
++ */
++static void free_space_stat_mod(struct btrfs_free_space_ctl *ctl, s64 delta)
++{
++ struct btrfs_block_group *bg = ctl->block_group;
++
++ ctl->free_space += delta;
++ if (bg && test_bit(BLOCK_GROUP_FLAG_UNMANAGED_COUNTED, &bg->runtime_flags))
++ atomic64_add(delta, &bg->space_info->bytes_unmanaged_free);
++}
++
+ static inline void unlink_free_space(struct btrfs_free_space_ctl *ctl,
+ struct btrfs_free_space *info,
+ bool update_stat)
+@@ -566,7 +579,7 @@ static inline void unlink_free_space(struct btrfs_free_space_ctl *ctl,
+ }
+
+ if (update_stat)
+- ctl->free_space -= info->bytes;
++ free_space_stat_mod(ctl, -(s64)info->bytes);
+ }
+
+ static int link_free_space(struct btrfs_free_space_ctl *ctl,
+@@ -588,7 +601,7 @@ static int link_free_space(struct btrfs_free_space_ctl *ctl,
+ ctl->discardable_bytes[BTRFS_STAT_CURR] += info->bytes;
+ }
+
+- ctl->free_space += info->bytes;
++ free_space_stat_mod(ctl, info->bytes);
+ ctl->free_extents++;
+ return ret;
+ }
+@@ -645,7 +658,7 @@ static inline void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
+ }
+
+ if (update_stat)
+- ctl->free_space -= bytes;
++ free_space_stat_mod(ctl, -(s64)bytes);
+ }
+
+ static void btrfs_bitmap_set_bits(struct btrfs_free_space_ctl *ctl,
+@@ -669,7 +682,7 @@ static void btrfs_bitmap_set_bits(struct btrfs_free_space_ctl *ctl,
+ */
+ info->max_extent_size = 0;
+ info->bytes += bytes;
+- ctl->free_space += bytes;
++ free_space_stat_mod(ctl, bytes);
+
+ relink_bitmap_entry(ctl, info);
+
+@@ -1492,7 +1505,7 @@ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
+ to_unusable = size - to_free;
+
+ spin_lock(&ctl->tree_lock);
+- ctl->free_space += to_free;
++ free_space_stat_mod(ctl, to_free);
+ spin_unlock(&ctl->tree_lock);
+ /*
+ * If the block group is read-only, we should account freed space into
+@@ -2232,6 +2245,32 @@ static void stripe_return_clusters(struct btrfs_block_group *bg)
+ spin_unlock(&cluster->refill_lock);
+ }
+
++/*
++ * Count a writable single-data-stripe RAID5/6 data group, which stripe_alloc
++ * does not manage, in its space_info's bytes_unmanaged_free, or stop counting
++ * it once it is read-only. Called when the group joins its space_info and
++ * after every read-only transition; it re-reads ->ro, so of two racing
++ * transitions the later call settles the state.
++ */
++void btrfs_stripe_unmanaged_sync(struct btrfs_block_group *bg)
++{
++ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ bool want;
++
++ if (!btrfs_stripe_bg_unmanaged(bg) || !bg->space_info)
++ return;
++
++ spin_lock(&ctl->tree_lock);
++ want = !READ_ONCE(bg->ro);
++ if (want && !test_and_set_bit(BLOCK_GROUP_FLAG_UNMANAGED_COUNTED,
++ &bg->runtime_flags))
++ atomic64_add(ctl->free_space, &bg->space_info->bytes_unmanaged_free);
++ else if (!want && test_and_clear_bit(BLOCK_GROUP_FLAG_UNMANAGED_COUNTED,
++ &bg->runtime_flags))
++ atomic64_sub(ctl->free_space, &bg->space_info->bytes_unmanaged_free);
++ spin_unlock(&ctl->tree_lock);
++}
++
+ /*
+ * Compute a stripe_alloc block group's initial trapped free space once its
+ * free space cache is loaded, and enable incremental accounting from here on.
+@@ -2988,7 +3027,7 @@ u64 btrfs_alloc_from_cluster(struct btrfs_block_group *block_group,
+ if (!btrfs_free_space_trimmed(entry))
+ atomic64_add(bytes, &discard_ctl->discard_bytes_saved);
+
+- ctl->free_space -= bytes;
++ free_space_stat_mod(ctl, -(s64)bytes);
+ if (!entry->bitmap && !btrfs_free_space_trimmed(entry))
+ ctl->discardable_bytes[BTRFS_STAT_CURR] -= bytes;
+
+diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
+index 6bee1e7a7913c..03a3d91ae04d5 100644
+--- a/fs/btrfs/free-space-cache.h
++++ b/fs/btrfs/free-space-cache.h
+@@ -115,6 +115,7 @@ 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);
+ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
++void btrfs_stripe_unmanaged_sync(struct btrfs_block_group *block_group);
+ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
+ void btrfs_dump_free_space(struct btrfs_block_group *block_group,
+ u64 bytes);
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index b109a640050df..dad4a6467c92e 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -392,6 +392,25 @@ int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
+ return ret;
+ }
+
++/*
++ * Remember a raid56 data full-stripe width for stripe_whole_need(). The
++ * entries are published before the count, so a lockless reader never sees
++ * an unset entry.
++ */
++static void stripe_width_record(struct btrfs_fs_info *fs_info, u64 width)
++{
++ const int nr = fs_info->nr_stripe_widths;
++
++ if (nr > BTRFS_STRIPE_WIDTHS_MAX)
++ return;
++ for (int i = 0; i < nr; i++)
++ if (fs_info->stripe_widths[i] == width)
++ return;
++ if (nr < BTRFS_STRIPE_WIDTHS_MAX)
++ WRITE_ONCE(fs_info->stripe_widths[nr], width);
++ smp_store_release(&fs_info->nr_stripe_widths, nr + 1);
++}
++
+ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
+ {
+ struct btrfs_space_info *space_info = block_group->space_info;
+@@ -412,6 +431,17 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
+ block_group->full_stripe_len);
+
+ spin_lock(&space_info->lock);
++ /*
++ * A RAID5/6 group with one data stripe is mapped as RAID1/RAID1C3 and
++ * its full_stripe_len is a sector: not a stripe width (and not
++ * managed, see btrfs_stripe_bg_unmanaged()).
++ */
++ if ((block_group->flags & BTRFS_BLOCK_GROUP_DATA) &&
++ (block_group->flags & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
++ !test_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED,
++ &block_group->runtime_flags))
++ stripe_width_record(block_group->fs_info,
++ block_group->full_stripe_len);
+
+ if (!(block_group->flags & BTRFS_BLOCK_GROUP_REMAPPED) ||
+ block_group->identity_remap_count != 0) {
+@@ -432,6 +462,8 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
+ down_write(&space_info->groups_sem);
+ list_add_tail(&block_group->list, &space_info->block_groups[index]);
+ up_write(&space_info->groups_sem);
++
++ btrfs_stripe_unmanaged_sync(block_group);
+ }
+
+ /*
+@@ -751,7 +783,14 @@ static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 byte
+ * runs can lose at the next commit.
+ */
+ {
+- u64 supply = space_info->bytes_stripe_claimable;
++ /*
++ * Single-data-stripe RAID5/6 groups, which stripe_alloc does
++ * not manage, take these writes too: count their free space,
++ * or a degraded filesystem, where every new chunk is one,
++ * refuses every write.
++ */
++ u64 supply = space_info->bytes_stripe_claimable +
++ atomic64_read(&space_info->bytes_unmanaged_free);
+ const u64 dedicated = space_info->bytes_stripe_claimable_reloc;
+
+ if (reloc) {
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index cba0232fa04a3..6cdfe66d0d305 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -178,6 +178,12 @@ struct btrfs_space_info {
+ measured claimable whole-stripe
+ bytes; see stripe_claimable in
+ struct btrfs_block_group */
++ atomic64_t bytes_unmanaged_free; /* free bytes in writable
++ single-data-stripe RAID5/6 data
++ groups, which stripe_alloc does not
++ manage (btrfs_stripe_bg_unmanaged());
++ write admission counts them with the
++ claimable stripes */
+ u64 bytes_stripe_open; /* sum of open stripe runs' unallocated
+ remainders. Claimed out of the free
+ space cache but not yet allocated;
+diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
+index ce78a9441c64f..ae2d0a814d63e 100644
+--- a/fs/btrfs/volumes.c
++++ b/fs/btrfs/volumes.c
+@@ -6593,6 +6593,27 @@ unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
+ return len;
+ }
+
++/*
++ * Is the chunk at @logical a RAID5/6 chunk with a single data stripe, mapped
++ * as RAID1/RAID1C3 (see set_real_chunk_type())?
++ */
++bool btrfs_chunk_raid56_mirrored(struct btrfs_fs_info *fs_info, u64 logical)
++{
++ struct btrfs_chunk_map *map;
++ bool ret = false;
++
++ if (!btrfs_fs_incompat(fs_info, RAID56))
++ return false;
++
++ map = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
++ if (!WARN_ON(IS_ERR(map))) {
++ ret = (map->on_disk_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
++ !(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK);
++ btrfs_free_chunk_map(map);
++ }
++ return ret;
++}
++
+ #ifdef CONFIG_BTRFS_EXPERIMENTAL
+ static int btrfs_read_preferred(struct btrfs_chunk_map *map, int first, int num_stripes)
+ {
+diff --git a/fs/btrfs/volumes.h b/fs/btrfs/volumes.h
+index 75b1179776c80..bce6134218f48 100644
+--- a/fs/btrfs/volumes.h
++++ b/fs/btrfs/volumes.h
+@@ -803,6 +803,7 @@ void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev,
+ void btrfs_free_device(struct btrfs_device *device);
+ unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
+ u64 logical);
++bool btrfs_chunk_raid56_mirrored(struct btrfs_fs_info *fs_info, u64 logical);
+ u64 btrfs_calc_dev_extent_size(const struct btrfs_chunk_map *map);
+ int btrfs_nr_parity_stripes(u64 type);
+ int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
+--
+2.47.3
+
+++ /dev/null
-From 4384767186cded93819133007b4b6eaf5117ddf6 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:55 -0400
-Subject: [RFC PATCH 035/116] btrfs: raid56: adaptive park deadline from the
- parked-rbio backlog
-To: linux-btrfs@vger.kernel.org
-
-Full-stripe batching parks a sub-stripe write's rbio for a deadline so the
-writes that fill the rest of its stripe can merge into it, turning a
-read-modify-write into one full-stripe write. The deadline is a fixed
-per-filesystem value. It is long enough to catch those merges, but at a
-small-file fill to ENOSPC -- where a run's stripes never fill because each
-file's neighbours land in the next file's stripe rather than this one --
-every partial write waits the deadline out, and then its 10x stuck cap, on
-an arrival that never comes before padding to a full stripe and going down.
-Lowering the deadline globally fixes that fill but throws away the merges
-the deadline exists to catch on ordinary moderate writes.
-
-Feed the deadline back from the parking machinery's own backlog instead of
-guessing at the workload. Track stripe_parked_now, the number of
-currently-parked rbios, incremented as a partial write parks and
-decremented as it unparks. When it runs ahead of the stripe_park_congestion
-knob (0 disables it, the default), a new async partial write takes the short
-sync deadline through the existing sync-park path rather than the full one.
-This is negative feedback: the shorter deadline drains the backlog, so once
-it falls back below the knob later writes regain the full deadline and full-
-stripe batching. No space-state estimate is needed -- a small-file flood
-builds the backlog directly, while a large sequential fill (already full
-stripes, never parked) and a moderate steady stream do not.
-
-Measured on an eight-device raid5. A small-file balance-reclaim soak that
-times out at the default deadline completes at a congestion of 4; on a
-throttled moderate stream, where the backlog stays low, a congestion of 32
-never trips, keeps the full deadline, and merges three times as much with
-38% fewer RMW reads as the same filesystem under a flat 3ms deadline. The
-gauge and a congestion_short counter join the stripe_park_stats sysfs file
-so the knob can be set from measurement. Off by default, and no data-path
-change: a shortened park still pads or reads exactly as it would have, only
-sooner.
-
-Assisted-by: Claude:claude-opus-4-8
----
- fs/btrfs/fs.h | 5 +++++
- fs/btrfs/raid56.c | 25 +++++++++++++++++++++++++
- fs/btrfs/sysfs.c | 10 ++++++++--
- 3 files changed, 38 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index cfaf19d7528b3..035e0cc80edd8 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -873,6 +873,7 @@ struct btrfs_fs_info {
- atomic64_t meta_rmw_cur;
- atomic64_t meta_rmw_old;
- atomic64_t meta_rmw_free;
-+ atomic64_t congestion_short;
- } stripe_park_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
-@@ -885,6 +886,10 @@ struct btrfs_fs_info {
- */
- u32 stripe_park_timeout_ms;
- u32 stripe_park_sync_timeout_ms;
-+ /* Parked-rbio backlog above which parks go short; 0 = off. */
-+ u32 stripe_park_congestion;
-+ /* Live count of currently-parked rbios (the backlog gauge). */
-+ atomic_t stripe_parked_now;
-
- /* Private scrub information */
- struct mutex scrub_lock;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 92c48cb4578da..8c587dd13965a 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -779,6 +779,7 @@ static void rbio_unpark_locked(struct btrfs_raid_bio *rbio)
- {
- list_del_init(&rbio->parked_node);
- clear_bit(RBIO_PARKED_BIT, &rbio->flags);
-+ atomic_dec(&rbio->bioc->fs_info->stripe_parked_now);
- }
-
- /* Does any bio gathered in @rbio carry a sync hint (a blocked waiter)? */
-@@ -867,6 +868,29 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- timeout_ms == sync_timeout_ms)
- return false;
-
-+ /*
-+ * Park-congestion feedback. stripe_parked_now is the live count of
-+ * parked rbios. When it runs ahead of the stripe_park_congestion knob
-+ * (0 = off) the park machinery is not clearing its backlog -- merges
-+ * are not arriving fast enough, the regime a small-file / partial-write
-+ * fill produces -- so collapse this write's deadline to the short sync
-+ * value (the sync-park path below flushes at it, skipping the stuck
-+ * cap). Negative feedback: the shorter deadline drains the backlog, so
-+ * once it falls back under the knob new writes regain the full deadline
-+ * and full-stripe batching. No space-state assumption.
-+ */
-+ {
-+ unsigned int congestion =
-+ READ_ONCE(fs_info->stripe_park_congestion);
-+
-+ if (timeout_ms != sync_timeout_ms && sync_timeout_ms != 0 &&
-+ congestion &&
-+ atomic_read(&fs_info->stripe_parked_now) > (int)congestion) {
-+ timeout_ms = sync_timeout_ms;
-+ atomic64_inc(&fs_info->stripe_park_stats.congestion_short);
-+ }
-+ }
-+
- spin_lock(&table->parked_lock);
- set_bit(RBIO_PARKED_BIT, &rbio->flags);
- set_bit(RBIO_WAS_PARKED_BIT, &rbio->flags);
-@@ -891,6 +915,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- */
- refcount_inc(&rbio->refs);
- list_add_tail(&rbio->parked_node, &table->parked);
-+ atomic_inc(&fs_info->stripe_parked_now);
- spin_unlock(&table->parked_lock);
- atomic64_inc(&fs_info->stripe_park_stats.parked);
- queue_delayed_work(system_percpu_wq, &table->parked_work,
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 2559c37f8af85..0369a7c04c54f 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1138,7 +1138,9 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "meta_rmw %lld\n"
- "meta_rmw_cur %lld\n"
- "meta_rmw_old %lld\n"
-- "meta_rmw_free %lld\n",
-+ "meta_rmw_free %lld\n"
-+ "congestion_short %lld\n"
-+ "parked_now %d\n",
- atomic64_read(&fs_info->stripe_park_stats.parked),
- atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
- atomic64_read(&fs_info->stripe_park_stats.filled),
-@@ -1156,7 +1158,9 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
-- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free));
-+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free),
-+ atomic64_read(&fs_info->stripe_park_stats.congestion_short),
-+ atomic_read(&fs_info->stripe_parked_now));
- }
- BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
-
-@@ -1193,6 +1197,7 @@ BTRFS_ATTR_RW(, _name, btrfs_##_name##_show, btrfs_##_name##_store)
-
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_sync_timeout_ms, stripe_park_sync_timeout_ms);
-+BTRFS_PARK_TIMEOUT_ATTR(stripe_park_congestion, stripe_park_congestion);
-
-
-
-@@ -1565,6 +1570,7 @@ static const struct attribute *btrfs_attrs[] = {
- BTRFS_ATTR_PTR(, stripe_park_stats),
- BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
- BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
-+ BTRFS_ATTR_PTR(, stripe_park_congestion),
- BTRFS_ATTR_PTR(, temp_fsid),
- NULL,
- };
---
-2.47.3
-
--- /dev/null
+From e8b09057e186e8145de34006de1d726882937c03 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sun, 25 Oct 2026 06:27:49 -0400
+Subject: [RFC PATCH 35/85] btrfs: stripe_alloc: do not count a writeback
+ ENOSPC drop's give-back as supply
+To: linux-btrfs@vger.kernel.org
+
+When buffered writeback fails with ENOSPC under stripe_alloc,
+cow_file_range() drops the range: the folios end writeback unwritten, the
+range's may_use and its margin are released, and the extents it had
+already allocated are freed, so their stripes come back as claimable at
+the next commit's rescan. The data was acknowledged by write(2), so it
+is lost; that is the bug the earlier patches remove at its causes. This
+patch is about what happens next.
+
+The write admission gate ("btrfs: stripe_alloc: gate data admission on
+claimable whole-stripe supply", earlier in this series) sees the
+give-back as supply. The writer blocked on the FLUSH_DATA ticket whose
+flush caused the drop is admitted when the same reclaim pass commits
+(COMMIT_TRANS is one of the data flush states) and the rescan returns
+the dropped extents' stripes. The supply was not enough for the range
+that was just dropped, so the next range fails the same way. With split
+pieces stranding stripes (as they did before "btrfs: stripe_alloc:
+pessimistic data reservation margin", earlier in this series, trimmed
+them to the group's stripes), one writer of 64 MiB got every write(2)
+acknowledged and lost 62.8 MiB in five identical drop cycles of 12.6
+MiB. Stock btrfs releases the same way after a cow_file_range() ENOSPC;
+it just does not expect one, because its data reservation is exact.
+
+Keep a quarantine, bytes_stripe_quarantine, that the gate adds to every
+non-relocation data admission:
+
+- On the drop, add the range length plus one full-stripe unit per extent
+ the range had allocated: each extent claimed at most its length rounded
+ up to its group's full stripe, so this bounds what the drop gives back.
+ The whole stripes covering the range plus one unit would not: in the
+ case above, the range was 13172736 bytes and its first 10747904 were
+ allocated as 448K pieces that each claimed 640K in 320K groups, so the
+ drop gives back about 15.3 MiB of stripes, where need(L) + unit is
+ 13.6 MiB. Capped at the space info's size. Relocation's own drops do not count:
+ its data is never acknowledged to a writer.
+- Release it only by claimable stripes that come back for real: whole
+ stripes completed by extents unpinned at a commit (deletes, overwrites,
+ relocation, compaction), measured with the rescan's own rule, and the
+ claimable of a new group (a new chunk, or a group whose free space only
+ now finished loading). Not a group back from read-only: a failed
+ relocation at the fill edge returns stripes the supply had before, and
+ reclaim's read-only cycling would drain the quarantine. The rescan
+ cannot be used either: it recomputes the total and cannot tell the
+ dropped extents' stripes from real frees.
+- Relocation is not held back by it, since relocation is what frees
+ stripes. It is cleared when stripe_alloc is turned off at runtime, and
+ it is not persistent, so an unmount clears it.
+
+The ticket that waited on the dropping flush now runs out of flush states
+with no new supply and fails with ENOSPC, and so does every later write
+until something is freed. The trade-off: ENOSPC in place of loss of
+acknowledged data, and stripes that were only temporarily held at the
+drop (run tails that a commit returns) stay quarantined until real frees
+or a new group arrive.
+
+The counter is in sysfs (bytes_stripe_quarantine), in the space info
+dump, and in the data writeback ENOSPC line; each drop logs the new total.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 12 +++++-
+ fs/btrfs/extent-tree.c | 13 +++++++
+ fs/btrfs/free-space-cache.c | 19 ++++++++++
+ fs/btrfs/free-space-cache.h | 2 +
+ fs/btrfs/inode.c | 11 ++++++
+ fs/btrfs/space-info.c | 76 +++++++++++++++++++++++++++++++++++++
+ fs/btrfs/space-info.h | 11 ++++++
+ fs/btrfs/sysfs.c | 2 +
+ 8 files changed, 145 insertions(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 8b81b73dc193d..a70a2286acfac 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1379,6 +1379,13 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
+
+ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
+ continue;
++ /* The writeback quarantine is the gate's; it goes with it. */
++ if (!arm && (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)) {
++ spin_lock(&sinfo->lock);
++ sinfo->bytes_stripe_quarantine = 0;
++ btrfs_try_granting_tickets(sinfo);
++ spin_unlock(&sinfo->lock);
++ }
+ down_read(&sinfo->groups_sem);
+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
+ struct btrfs_block_group *bg;
+@@ -2637,8 +2644,10 @@ static noinline void caching_thread(struct btrfs_work *work)
+ * accounting. Nothing until this point counted against
+ * stripe_unusable, so the scan captures the full loaded state.
+ */
+- if (!ret)
++ if (!ret) {
+ btrfs_block_group_init_stripe_unusable(block_group);
++ btrfs_stripe_quarantine_new_group(block_group);
++ }
+
+ #ifdef CONFIG_BTRFS_DEBUG
+ if (btrfs_should_fragment_free_space(block_group)) {
+@@ -5013,6 +5022,7 @@ struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *tran
+
+ /* A freshly created stripe_alloc group starts fully free (0 trapped). */
+ btrfs_block_group_init_stripe_unusable(cache);
++ btrfs_stripe_quarantine_new_group(cache);
+
+ set_avail_alloc_bits(fs_info, type);
+ return cache;
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 56ea5eead8a17..363e50dec88bd 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -2843,6 +2843,7 @@ static int unpin_extent_range(struct btrfs_fs_info *fs_info,
+ u64 empty_cluster = 0;
+
+ while (start <= end) {
++ u64 quarantine_back;
+ u64 len;
+ bool readonly;
+
+@@ -2867,6 +2868,16 @@ static int unpin_extent_range(struct btrfs_fs_info *fs_info,
+
+ if (return_free_space)
+ btrfs_add_free_space(cache, start, len);
++ /*
++ * Whole stripes this free completes are real supply: they pay
++ * back writeback quarantine (stripe_claimable_admit()).
++ */
++ quarantine_back = 0;
++ if (return_free_space &&
++ READ_ONCE(cache->space_info->bytes_stripe_quarantine) &&
++ !READ_ONCE(cache->ro))
++ quarantine_back = btrfs_stripe_claimable_in_range(cache,
++ start, len);
+
+ start += len;
+ total_unpinned += len;
+@@ -2902,6 +2913,8 @@ static int unpin_extent_range(struct btrfs_fs_info *fs_info,
+ } else if (return_free_space) {
+ btrfs_return_free_space(space_info, len);
+ }
++ if (quarantine_back)
++ btrfs_stripe_quarantine_free(space_info, quarantine_back);
+ spin_unlock(&space_info->lock);
+ }
+
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 5529b86306478..76877414bf7fc 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1652,6 +1652,25 @@ static u64 stripe_claimable_with_range(struct btrfs_block_group *bg,
+ return whole;
+ }
+
++/*
++ * The claimable whole stripes that the free range [bytenr, bytenr + size) of
++ * a stripe_alloc data group belongs to, for the writeback quarantine.
++ */
++u64 btrfs_stripe_claimable_in_range(struct btrfs_block_group *bg, u64 bytenr,
++ u64 size)
++{
++ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ u64 whole = 0;
++
++ if (!btrfs_is_stripe_alloc_bg(bg))
++ return 0;
++ spin_lock(&ctl->tree_lock);
++ if (bg->stripe_unusable_ready)
++ whole = stripe_claimable_with_range(bg, bytenr, size);
++ spin_unlock(&ctl->tree_lock);
++ return whole;
++}
++
+ /*
+ * A trim takes a free range out of the tree for the length of its discard
+ * (trim_no_bitmap(), trim_bitmaps()) and do_trimming() adds it back. A
+diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
+index 03a3d91ae04d5..d89127c24f11e 100644
+--- a/fs/btrfs/free-space-cache.h
++++ b/fs/btrfs/free-space-cache.h
+@@ -114,6 +114,8 @@ u64 btrfs_find_space_for_alloc(struct btrfs_block_group *block_group,
+ 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);
++u64 btrfs_stripe_claimable_in_range(struct btrfs_block_group *bg, u64 bytenr,
++ u64 size);
+ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
+ void btrfs_stripe_unmanaged_sync(struct btrfs_block_group *block_group);
+ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
+diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
+index 1f2a1677aa10a..5a36404d62d8f 100644
+--- a/fs/btrfs/inode.c
++++ b/fs/btrfs/inode.c
+@@ -1360,6 +1360,7 @@ static noinline int cow_file_range(struct btrfs_inode *inode,
+ u32 min_alloc_size;
+ u32 blocksize = fs_info->sectorsize;
+ u32 cur_alloc_size = 0;
++ u64 nr_allocated = 0;
+ struct btrfs_key ins;
+ unsigned clear_bits;
+ unsigned long page_ops;
+@@ -1440,6 +1441,7 @@ static noinline int cow_file_range(struct btrfs_inode *inode,
+ }
+ if (ret < 0)
+ goto out_unlock;
++ nr_allocated++;
+
+ /* We should not allocate an extent larger than requested.*/
+ ASSERT(cur_alloc_size <= num_bytes);
+@@ -1507,6 +1509,15 @@ static noinline int cow_file_range(struct btrfs_inode *inode,
+ btrfs_qgroup_free_data(inode, NULL, start + cur_alloc_size,
+ end - start - cur_alloc_size + 1, NULL);
+ }
++ /*
++ * The range is dropped: under stripe_alloc, hold what it gives back
++ * out of write admission. Not for relocation, whose data is never
++ * acknowledged to a writer and whose shortfall must not hold back
++ * user writes.
++ */
++ if (ret == -ENOSPC && !btrfs_is_data_reloc_root(root))
++ btrfs_stripe_quarantine_add(fs_info, end + 1 - orig_start,
++ nr_allocated);
+ btrfs_err(fs_info,
+ "%s failed, root=%llu inode=%llu start=%llu len=%llu cur_offset=%llu cur_alloc_size=%u: %pe",
+ __func__, btrfs_root_id(inode->root),
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index dad4a6467c92e..f5e83f636b56e 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -725,6 +725,69 @@ static void remove_ticket(struct btrfs_space_info *space_info,
+ spin_unlock(&ticket->lock);
+ }
+
++/*
++ * Buffered writeback of @len bytes of delalloc failed with ENOSPC under
++ * stripe_alloc after @nr_extents of its extents were allocated, and the
++ * range is being dropped (cow_file_range()). Quarantine what the drop gives
++ * back: the range's may_use and margin now, and the whole stripes its
++ * allocated extents claimed at the next commit's rescan. Each extent claims
++ * at most its length rounded up to its group's full stripe, so @len plus one
++ * unit per extent bounds both. The quarantine never exceeds the space
++ * info's size.
++ */
++void btrfs_stripe_quarantine_add(struct btrfs_fs_info *fs_info, u64 len,
++ u64 nr_extents)
++{
++ struct btrfs_space_info *sinfo = fs_info->data_sinfo;
++ const u64 unit = READ_ONCE(fs_info->stripe_margin_unit);
++ u64 bytes;
++
++ if (!sinfo || !unit || !btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return;
++ bytes = len + nr_extents * unit;
++ spin_lock(&sinfo->lock);
++ sinfo->bytes_stripe_quarantine = min(sinfo->bytes_stripe_quarantine + bytes,
++ sinfo->total_bytes);
++ bytes = sinfo->bytes_stripe_quarantine;
++ spin_unlock(&sinfo->lock);
++ btrfs_info_rl(fs_info,
++"stripe_alloc: buffered writeback of %llu bytes failed with ENOSPC; %llu bytes held out of write admission until space is freed",
++ len, bytes);
++}
++
++/*
++ * @claimable bytes of whole stripes came back for real: extents freed at a
++ * commit (unpin_extent_range()), or a new group (see below). Release that
++ * much quarantine. Caller holds space_info->lock.
++ */
++void btrfs_stripe_quarantine_free(struct btrfs_space_info *space_info,
++ u64 claimable)
++{
++ lockdep_assert_held(&space_info->lock);
++ space_info->bytes_stripe_quarantine -=
++ min(claimable, space_info->bytes_stripe_quarantine);
++}
++
++/*
++ * A data group just armed for stripe_alloc that the supply did not have
++ * when the quarantined writeback failed: a new chunk, or a group whose free
++ * space only now finished loading. Not a group back from read-only: a
++ * failed relocation at the fill edge returns stripes the supply had before,
++ * and its read-only/read-write cycling would drain the quarantine.
++ */
++void btrfs_stripe_quarantine_new_group(struct btrfs_block_group *bg)
++{
++ struct btrfs_space_info *sinfo = bg->space_info;
++
++ if (!sinfo || !btrfs_is_stripe_alloc_bg(bg) ||
++ !READ_ONCE(sinfo->bytes_stripe_quarantine))
++ return;
++ spin_lock(&sinfo->lock);
++ if (bg->stripe_unusable_ready)
++ btrfs_stripe_quarantine_free(sinfo, bg->stripe_claimable);
++ spin_unlock(&sinfo->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
+@@ -827,6 +890,19 @@ static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 byte
+ * there.
+ */
+ bytes += space_info->bytes_stripe_margin;
++ /*
++ * When buffered writeback fails with ENOSPC, its range is
++ * dropped and gives back its may_use, its margin and, at the
++ * next commit's rescan, the stripes its extents claimed. The
++ * supply that admitted it was not enough, so that give-back
++ * is not supply: counted as supply, it admits the next writes
++ * (the ticket waiting on that very flush first), and their
++ * writeback drops them the same way. Hold it out until real
++ * frees or new groups bring claimable stripes back.
++ * Relocation is what frees them, so it is not held back.
++ */
++ if (!reloc)
++ bytes += space_info->bytes_stripe_quarantine;
+ return space_info->bytes_may_use + bytes <= supply;
+ }
+ }
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index 6cdfe66d0d305..3a8bda4471830 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -202,6 +202,12 @@ struct btrfs_space_info {
+ from under an admitted reservation.
+ Charged and released in lockstep with
+ the inodes' outstanding_extents. */
++ u64 bytes_stripe_quarantine; /* data: what buffered writeback that
++ failed with ENOSPC released, held
++ out of the admission supply until
++ real frees or new groups give
++ claimable stripes back (see
++ btrfs_stripe_quarantine_add()) */
+
+ u64 max_extent_size; /* This will hold the maximum extent size of
+ the space info if we had an ENOSPC in the
+@@ -374,6 +380,11 @@ 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_stripe_quarantine_add(struct btrfs_fs_info *fs_info, u64 len,
++ u64 nr_extents);
++void btrfs_stripe_quarantine_free(struct btrfs_space_info *space_info,
++ u64 claimable);
++void btrfs_stripe_quarantine_new_group(struct btrfs_block_group *bg);
+ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group);
+ void btrfs_update_space_info_chunk_size(struct btrfs_space_info *space_info,
+ u64 chunk_size);
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 6997c81febfb2..17570b99b1a41 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -822,6 +822,7 @@ SPACE_INFO_ATTR(bytes_stripe_stranded);
+ SPACE_INFO_ATTR(bytes_stripe_claimable);
+ SPACE_INFO_ATTR(bytes_stripe_open);
+ SPACE_INFO_ATTR(bytes_stripe_margin);
++SPACE_INFO_ATTR(bytes_stripe_quarantine);
+ SPACE_INFO_ATTR(disk_used);
+ SPACE_INFO_ATTR(disk_total);
+ SPACE_INFO_ATTR(reclaim_count);
+@@ -956,6 +957,7 @@ static struct attribute *space_info_attrs[] = {
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_claimable),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_open),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_margin),
++ BTRFS_ATTR_PTR(space_info, bytes_stripe_quarantine),
+ BTRFS_ATTR_PTR(space_info, disk_used),
+ BTRFS_ATTR_PTR(space_info, disk_total),
+ BTRFS_ATTR_PTR(space_info, bg_reclaim_threshold),
+--
+2.47.3
+
+++ /dev/null
-From 3002a7e4dce8259c68b19a47f454e8996e7c8cbf Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:56 -0400
-Subject: [RFC PATCH 036/116] btrfs: stripe_alloc: gate data admission on
- claimable whole-stripe supply
-To: linux-btrfs@vger.kernel.org
-
-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.
-
-Assisted-by: Claude:claude-opus-4-8
----
- fs/btrfs/space-info.c | 68 +++++++++++++++++++++++++++++++++++++++++--
- 1 file changed, 65 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 13e0db4aa1c42..53a4d3c3decfb 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -647,6 +647,66 @@ static void remove_ticket(struct btrfs_space_info *space_info,
- spin_unlock(&ticket->lock);
- }
-
-+/*
-+ * stripe_alloc DATA admission gate. On a raid56 stripe_alloc DATA space_info a
-+ * write can only be placed crash-safely in a fully-free whole stripe, so admit a
-+ * data reservation only while the whole-stripe supply (bytes_stripe_claimable,
-+ * which errs LOW now that the incremental positive credit is gone) covers all
-+ * outstanding reservations plus this one. This refuses at reservation time --
-+ * before the range becomes delalloc and later parks at writeback with nowhere to
-+ * land -- and makes write() -ENOSPC coincide with statfs f_bavail==0 (both on the
-+ * whole-stripe bound). Non-stripe_alloc / metadata / non-raid56 space_infos are
-+ * unaffected: stripe_margin_unit is 0 unless a raid56 DATA bg exists. Caller
-+ * holds space_info->lock.
-+ *
-+ * Phase 1 is deliberately PESSIMISTIC: it gates on claimable alone, 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 + the
-+ * FLUSH_DATA ticket retry). A later phase adds bytes_stripe_open to the bound to
-+ * match statfs exactly and recover that space.
-+ */
-+static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 bytes)
-+{
-+ 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;
-+ /*
-+ * An allocation of @bytes that opens a run claims
-+ * round_up(bytes, unit) whole stripes. A delalloc write's
-+ * margin (below) covers that for itself, but a
-+ * preallocation holds no margin -- it has no outstanding
-+ * extent -- and was admitted for its byte size alone, so
-+ * each fallocate() short of a stripe took up to a stripe
-+ * more than the gate had charged, out of the supply behind
-+ * writes already admitted: at the fill edge those writes
-+ * then found no stripe and were dropped. Charge the
-+ * roundup. (The excess is not held past admission; a
-+ * preallocation allocates in the same call.)
-+ */
-+ bytes = round_up(bytes, unit);
-+ /*
-+ * Every outstanding data extent holds a whole-stripe margin
-+ * (bytes_stripe_margin) as collateral against the commit that
-+ * closes its open run and traps the tail.
-+ * btrfs_space_info_used() charges that margin against
-+ * total_bytes, but what an admitted write actually draws on is
-+ * the whole-stripe supply: left out of this bound, the stripes
-+ * behind bytes admitted earlier are lost at the next commit, and
-+ * a write that passed admission finds no stripe at writeback
-+ * (ENOSPC despite reservation margin, data dropped). The margin
-+ * is owed to the writers already admitted, so every later
-+ * admission has to respect it -- relocation included: admitted
-+ * without it at the fill edge, relocation consumed the whole
-+ * stripes that small writes' claims then needed, and those
-+ * writes were dropped in bursts that tracked the relocations.
-+ */
-+ bytes += space_info->bytes_stripe_margin;
-+ return space_info->bytes_may_use + bytes <= space_info->bytes_stripe_claimable;
-+}
-+
- /*
- * 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.
-@@ -669,8 +729,9 @@ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info)
- 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)) {
- btrfs_space_info_update_bytes_may_use(space_info, ticket->bytes);
- remove_ticket(space_info, ticket, 0);
- space_info->tickets_id++;
-@@ -1902,7 +1963,8 @@ 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)) {
- btrfs_space_info_update_bytes_may_use(space_info, orig_bytes);
- ret = 0;
- }
---
-2.47.3
-
--- /dev/null
+From c5e7e44d3b410638918e88d8cc9f97918b558c48 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:39 -0400
+Subject: [RFC PATCH 36/85] btrfs: stripe_alloc: isolate nodatacow and
+ preallocated extents by stripe
+To: linux-btrfs@vger.kernel.org
+
+Preallocated extents and nodatacow files' extents are candidates for
+write-in-place, which reintroduces the raid56 write hole for every
+stripe such a write touches: the RMW recomputes parity that also covers
+whatever else shares the stripe. Before write-in-place can be
+re-enabled for them (a later change; stripe_alloc still forces COW
+today), their placement must guarantee the blast radius: such an extent
+must never share a stripe with any other file's data.
+
+Steer them into private per-inode stripe runs of a new NOCOW class,
+reusing the log-active inode machinery: runs owned by one inode, never
+in the shared band slots, found by owner-and-class lookup. Successive
+allocations of the same file pack sequentially into the file's own
+stripes; different files, and the datacow/relocation/log classes, never
+share a stripe with them. A preallocation signals itself through a new
+btrfs_reserve_extent() parameter; nodatacow files are recognized by the
+inode flag. Placement remains best effort: when no fully-free stripes
+are left for a private run the allocation falls back to the shared
+runs, which is safe -- an extent that lands in a shared stripe simply
+stays force-COWed when write-in-place arrives.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 6 ++--
+ fs/btrfs/block-group.h | 10 +++++++
+ fs/btrfs/direct-io.c | 2 +-
+ fs/btrfs/extent-tree.c | 62 ++++++++++++++++++++++++++----------------
+ fs/btrfs/extent-tree.h | 11 +++++---
+ fs/btrfs/inode.c | 12 ++++----
+ fs/btrfs/relocation.c | 5 ++--
+ 7 files changed, 70 insertions(+), 38 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index a70a2286acfac..6826fc3f0ac48 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -948,6 +948,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ * this block group can satisfy the allocation, or -ENOMEM.
+ */
+ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
++ enum btrfs_stripe_run_class class,
+ u64 num_bytes, u64 *ret_offset,
+ u64 *available)
+ {
+@@ -967,8 +968,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+- if (run->class != BTRFS_STRIPE_RUN_LOG || run->owner != ino ||
+- !run->open)
++ if (run->class != class || run->owner != ino || !run->open)
+ continue;
+ if (num_bytes <= run->end - run->offset) {
+ *ret_offset = run->offset;
+@@ -1031,7 +1031,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ goto out;
+ }
+ new_run->bg = bg;
+- new_run->class = BTRFS_STRIPE_RUN_LOG;
++ new_run->class = class;
+ new_run->owner = ino;
+ new_run->start = start;
+ new_run->end = start + len;
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 8b6575c98e0d5..52dfab2a188ca 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -38,6 +38,15 @@ enum btrfs_stripe_run_class {
+ * its own extents.
+ */
+ BTRFS_STRIPE_RUN_LOG,
++ /*
++ * Private per-inode runs for nodatacow files' extents and
++ * preallocated extents. These extents are candidates for future
++ * write-in-place (which reintroduces the write hole for the stripes
++ * it touches), so they must never share a stripe with any other
++ * file's data: per-inode scoping confines a future in-place write's
++ * blast radius to the owning file alone.
++ */
++ BTRFS_STRIPE_RUN_NOCOW,
+ BTRFS_STRIPE_RUN_NR_CLASSES,
+ };
+
+@@ -458,6 +467,7 @@ 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,
++ enum btrfs_stripe_run_class class,
+ u64 num_bytes, u64 *ret_offset,
+ u64 *available);
+ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+diff --git a/fs/btrfs/direct-io.c b/fs/btrfs/direct-io.c
+index 65c82476c53f4..68234efb70547 100644
+--- a/fs/btrfs/direct-io.c
++++ b/fs/btrfs/direct-io.c
+@@ -188,7 +188,7 @@ static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
+ alloc_hint = btrfs_get_extent_allocation_hint(inode, start, len);
+ again:
+ ret = btrfs_reserve_extent(root, inode, len, len, fs_info->sectorsize,
+- 0, alloc_hint, &ins, true, true);
++ 0, alloc_hint, &ins, true, true, false);
+ if (ret == -EAGAIN) {
+ ASSERT(btrfs_is_zoned(fs_info));
+ wait_on_bit_io(&inode->root->fs_info->flags, BTRFS_FS_NEED_ZONE_FINISH,
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 363e50dec88bd..6a1e26eb8278b 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4314,24 +4314,26 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
+ return 1;
+
+ /*
+- * A log-active inode allocates from its own private LOG-class run so
+- * its log commits settle only its own stripes. If this block group
+- * has no fully-free stripes left for a private run, fall through to
+- * the shared runs: the data is then placed exactly as before 3b.1
+- * and the log-commit settling keeps it safe, just less cheaply.
++ * Steered allocations come from a private run of the requested class:
++ * the inode's own, or for LOG-class allocations under a full stripe
++ * with stripe_log_data_shared, the run its subvolume shares for the
++ * current log transaction (stripe_run_owner()). If this block group
++ * has no fully free stripe for such a run, fall through to the shared
++ * runs: log-commit settling covers any placement, and a nocow/prealloc
++ * extent in a shared stripe is simply COWed.
+ */
+ 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;
++ if (ffe_ctl->steer_inode) {
++ struct btrfs_inode *steer_inode = ffe_ctl->steer_inode;
+
+ ret = btrfs_alloc_from_inode_stripe_run(block_group,
+- btrfs_ino(log_inode), ffe_ctl->num_bytes,
+- &offset, &available);
++ btrfs_ino(steer_inode), ffe_ctl->steer_class,
++ ffe_ctl->num_bytes, &offset, &available);
+ if (ret == -ENOMEM)
+ return ret;
+ if (!ret) {
+ stripe_split_taken(ffe_ctl, num_bytes);
+- WRITE_ONCE(log_inode->log_run_hint, offset);
++ WRITE_ONCE(steer_inode->log_run_hint, offset);
+ ffe_ctl->found_offset = offset;
+ ffe_ctl->search_start = offset;
+ return 0;
+@@ -5077,7 +5079,8 @@ static noinline int find_free_extent(struct btrfs_root *root,
+ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ u64 ram_bytes, u64 num_bytes, u64 min_alloc_size,
+ u64 empty_size, u64 hint_byte,
+- struct btrfs_key *ins, bool is_data, bool delalloc)
++ struct btrfs_key *ins, bool is_data, bool delalloc,
++ bool for_prealloc)
+ {
+ struct btrfs_fs_info *fs_info = root->fs_info;
+ struct find_free_extent_ctl ffe_ctl = {};
+@@ -5087,22 +5090,34 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ int ret;
+ bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
+ bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
+- struct btrfs_inode *for_log_inode = NULL;
++ struct btrfs_inode *steer_inode = NULL;
++ enum btrfs_stripe_run_class steer_class = BTRFS_STRIPE_RUN_COW;
+
+ /*
+- * Steer a log-active inode's datacow data into its private LOG-class
+- * stripe run, seeded with the run's location as the search hint; see
+- * BTRFS_INODE_LOG_ALLOC. Purely placement: any allocation that
++ * 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.
+ */
+ if (inode && is_data && !for_data_reloc &&
+- btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
+- test_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags)) {
+- u64 log_hint = READ_ONCE(inode->log_run_hint);
++ btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
++ if (for_prealloc || (inode->flags & BTRFS_INODE_NODATACOW)) {
++ steer_inode = inode;
++ steer_class = BTRFS_STRIPE_RUN_NOCOW;
++ } else if (test_bit(BTRFS_INODE_LOG_ALLOC,
++ &inode->runtime_flags)) {
++ steer_inode = inode;
++ steer_class = BTRFS_STRIPE_RUN_LOG;
++ }
++ if (steer_inode) {
++ u64 run_hint = READ_ONCE(inode->log_run_hint);
+
+- for_log_inode = inode;
+- if (log_hint)
+- hint_byte = log_hint;
++ if (run_hint)
++ hint_byte = run_hint;
++ }
+ }
+
+ flags = get_alloc_profile_by_root(root, is_data);
+@@ -5118,7 +5133,8 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ ffe_ctl.hint_byte = hint_byte;
+ ffe_ctl.for_treelog = for_treelog;
+ ffe_ctl.for_data_reloc = for_data_reloc;
+- ffe_ctl.for_log_inode = for_log_inode;
++ ffe_ctl.steer_inode = steer_inode;
++ ffe_ctl.steer_class = steer_class;
+ ffe_ctl.split_bytes = split_bytes;
+
+ ret = find_free_extent(root, ins, &ffe_ctl);
+@@ -5646,7 +5662,7 @@ struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
+ return ERR_CAST(block_rsv);
+
+ ret = btrfs_reserve_extent(root, NULL, blocksize, blocksize, blocksize,
+- empty_size, hint, &ins, false, false);
++ empty_size, hint, &ins, false, false, false);
+ if (ret)
+ goto out_unuse;
+
+diff --git a/fs/btrfs/extent-tree.h b/fs/btrfs/extent-tree.h
+index 45a4a7e38d810..f650cc79b094d 100644
+--- a/fs/btrfs/extent-tree.h
++++ b/fs/btrfs/extent-tree.h
+@@ -50,10 +50,12 @@ struct find_free_extent_ctl {
+ bool for_data_reloc;
+
+ /*
+- * Data allocation for a log-active inode under stripe-exclusive
+- * allocation: steer it into the inode's private LOG-class stripe run.
++ * Data allocation to steer into a private stripe run (see
++ * stripe_run_owner()), and the run class: NOCOW for nodatacow and
++ * preallocated extents, LOG for log-active inodes.
+ */
+- struct btrfs_inode *for_log_inode;
++ struct btrfs_inode *steer_inode;
++ enum btrfs_stripe_run_class steer_class;
+
+ /*
+ * Set to true if we're retrying the allocation on this block group
+@@ -152,7 +154,8 @@ int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
+ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ u64 ram_bytes, u64 num_bytes,
+ u64 min_alloc_size, u64 empty_size, u64 hint_byte,
+- struct btrfs_key *ins, bool is_data, bool delalloc);
++ struct btrfs_key *ins, bool is_data, bool delalloc,
++ bool for_prealloc);
+ int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
+ struct extent_buffer *buf, bool full_backref);
+ int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
+diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
+index 5a36404d62d8f..56e516441be7e 100644
+--- a/fs/btrfs/inode.c
++++ b/fs/btrfs/inode.c
+@@ -1072,7 +1072,7 @@ static void submit_one_async_extent(struct async_chunk *async_chunk,
+ compressed_size = async_extent->cb->bbio.bio.bi_iter.bi_size;
+ ret = btrfs_reserve_extent(root, inode, async_extent->ram_size,
+ compressed_size, compressed_size,
+- 0, *alloc_hint, &ins, true, true);
++ 0, *alloc_hint, &ins, true, true, false);
+ if (ret) {
+ /*
+ * We can't reserve contiguous space for the compressed size.
+@@ -1218,7 +1218,7 @@ static int cow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
+
+ ret = btrfs_reserve_extent(root, inode, num_bytes, num_bytes,
+ min_alloc_size, 0, alloc_hint, ins, true,
+- true);
++ true, false);
+ if (ret < 0) {
+ *ret_alloc_size = cur_len;
+ return ret;
+@@ -9293,8 +9293,9 @@ int btrfs_prealloc_file_range(struct inode *inode, int mode,
+ * sized chunks.
+ */
+ cur_bytes = min(cur_bytes, last_alloc);
+- ret = btrfs_reserve_extent(root, NULL, cur_bytes, cur_bytes,
+- min_size, 0, *alloc_hint, &ins, true, false);
++ ret = btrfs_reserve_extent(root, BTRFS_I(inode), cur_bytes,
++ cur_bytes, min_size, 0, *alloc_hint, &ins,
++ true, false, true);
+ if (ret)
+ break;
+ /*
+@@ -10133,7 +10134,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);
++ disk_num_bytes, 0, 0, &ins, true, true,
++ false);
+ btrfs_stripe_prealloc_release(fs_info, stripe_held);
+ stripe_held = 0;
+ if (ret)
+diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
+index 763e066595ea3..35240a459e4ed 100644
+--- a/fs/btrfs/relocation.c
++++ b/fs/btrfs/relocation.c
+@@ -4289,7 +4289,7 @@ static int move_existing_remap(struct btrfs_fs_info *fs_info,
+ min_size = fs_info->nodesize;
+
+ ret = btrfs_reserve_extent(fs_info->fs_root, NULL, length, length,
+- min_size, 0, 0, &ins, is_data, false);
++ min_size, 0, 0, &ins, is_data, false, false);
+ if (unlikely(ret)) {
+ spin_lock(&sinfo->lock);
+ btrfs_space_info_update_bytes_may_use(sinfo, -length);
+@@ -5118,7 +5118,8 @@ static int do_remap_reloc_trans(struct btrfs_fs_info *fs_info,
+ * rest of it the next time round.
+ */
+ ret = btrfs_reserve_extent(fs_info->fs_root, NULL, remap_length,
+- remap_length, min_size, 0, 0, &ins, is_data, false);
++ remap_length, min_size, 0, 0, &ins, is_data,
++ false, false);
+ if (ret) {
+ spin_lock(&sinfo->lock);
+ btrfs_space_info_update_bytes_may_use(sinfo, -remap_length);
+--
+2.47.3
+
+++ /dev/null
-From 9cbe3ca82143309b0b8e1fac5f67e131cbff4470 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:57 -0400
-Subject: [RFC PATCH 037/116] btrfs: stripe_alloc: cache a failed stripe run
- scan per block group
-To: linux-btrfs@vger.kernel.org
-
-On a large aged filesystem (85 TiB, mostly legacy pre-stripe_alloc data,
-heavily fragmented free space), the delalloc workers spin at 100% CPU
-while commits crawl at KiB/s. NMI backtraces put the time in
-btrfs_claim_free_stripe_run() called from btrfs_alloc_from_open_stripe()
-for every small compressed extent allocation.
-
-The cost is in find_free_stripe_run_slow(): when the single-entry fast
-path misses (always, on fragmented block groups), the slow path walks
-candidate stripes from the START of the block group, doing an rbtree
-lookup per free-space piece, all under ctl->tree_lock. When the block
-group has no claimable run at all - the common case for block groups
-filled with legacy data - the scan traverses the entire block group,
-returns -ENOSPC, and remembers nothing: the next 4K allocation repeats
-the whole scan. Per-allocation cost is O(block group size) in the
-fragmented worst case, multiplied by every block group find_free_extent
-visits.
-
-The stock allocator avoids exactly this pathology by caching the largest
-extent a failed search saw (max_extent_size); the stripe claim path is a
-new search primitive built beside it and never inherited the idea. The
-per-block-group stripe_claimable counter cannot serve this role: it is a
-commit-scan-granular byte estimate that can err high (block groups where
-the accounting promises claimable bytes but the scan finds no aligned,
-usable run are precisely where the scan storm happens).
-
-Add bg->max_claimable_run, an upper bound learned from the scans
-themselves: (u64)-1 unknown, 0 after an exhaustive scan proved no
-claimable run exists (find_free_stripe_run_slow() accepts any run of at
-least one full stripe, so its failure is that proof). Claims fail in
-O(1) while the bound is below one full stripe, or when total free space
-in the block group is smaller than a full stripe. Adding free space
-resets the bound to unknown in __btrfs_add_free_space(), which covers
-all paths that can create a run: frees, unpins, and stripe run returns.
-The bound is only trusted and only set once the block group is fully
-cached, because cache loading links entries directly and would bypass
-the reset.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 1 +
- fs/btrfs/block-group.h | 12 ++++++++++++
- fs/btrfs/free-space-cache.c | 37 ++++++++++++++++++++++++++++++++++++-
- 3 files changed, 49 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 857638d2d506c..c984b5ffcf465 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -4532,6 +4532,7 @@ static struct btrfs_block_group *btrfs_create_block_group(
-
- cache->fs_info = fs_info;
- cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
-+ cache->max_claimable_run = (u64)-1;
-
- cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
-
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 4c59b0ba0f217..2f3091b848317 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -300,6 +300,18 @@ struct btrfs_block_group {
- * write()-time ENOSPC), corrected upward by the commit rescan.
- */
- u64 stripe_claimable;
-+ /*
-+ * Upper bound on the longest run btrfs_claim_free_stripe_run() can
-+ * find, learned from actual scans: (u64)-1 means unknown, 0 means an
-+ * exhaustive scan proved there is no claimable run. Claims fail in
-+ * O(1) while the bound is below one full stripe; adding free space
-+ * resets it to unknown. Unlike stripe_claimable (an accounting
-+ * estimate), this caches what the scan itself proved, so it stays
-+ * correct even when the accounting errs high. Protected by
-+ * free_space_ctl->tree_lock; only meaningful once the block group is
-+ * fully cached.
-+ */
-+ u64 max_claimable_run;
- bool stripe_unusable_ready;
-
- /*
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index eed6f8b7de197..b9074d21f90f6 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1388,6 +1388,12 @@ static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
-
- spin_lock(&ctl->tree_lock);
-
-+ /*
-+ * New free space may merge into a claimable stripe run; forget any
-+ * cached "no claimable run" verdict (see btrfs_claim_free_stripe_run()).
-+ */
-+ block_group->max_claimable_run = (u64)-1;
-+
- if (try_merge_free_space(ctl, info, true))
- goto link;
-
-@@ -2644,6 +2650,26 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
-
- spin_lock(&ctl->tree_lock);
-
-+ /*
-+ * Fail fast without scanning when a previous exhaustive scan proved
-+ * this block group has no claimable run (max_claimable_run == 0, set
-+ * below): only adding free space can create one, and
-+ * __btrfs_add_free_space() resets the bound when it does. Also skip
-+ * when the total free space cannot possibly hold one full stripe.
-+ * Without this, a fragmented block group costs a full O(size) scan
-+ * under ctl->tree_lock for EVERY failed claim - one per small
-+ * allocation - which starves the delalloc workers at 100% CPU on
-+ * large aged filesystems. Only trust the bound once the block group
-+ * is fully cached: cache loading links entries directly, bypassing
-+ * __btrfs_add_free_space(), so the reset would be missed.
-+ */
-+ if (btrfs_block_group_done(block_group) &&
-+ (block_group->max_claimable_run < fsl ||
-+ ctl->free_space < fsl)) {
-+ spin_unlock(&ctl->tree_lock);
-+ return -ENOSPC;
-+ }
-+
- entry = find_free_stripe_run(block_group, want_bytes, &run_start, &run_len);
- if (!entry) {
- /*
-@@ -2658,8 +2684,17 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- return -ENOMEM;
- spin_lock(&ctl->tree_lock);
- if (!find_free_stripe_run_slow(block_group, want_bytes,
-- &run_start, &run_len))
-+ &run_start, &run_len)) {
-+ /*
-+ * The exhaustive scan found no claimable run at all
-+ * (the slow path accepts any run of at least one full
-+ * stripe). Cache that verdict so subsequent claims
-+ * fail in O(1) until free space is added.
-+ */
-+ if (btrfs_block_group_done(block_group))
-+ block_group->max_claimable_run = 0;
- goto out;
-+ }
- spare_used = claim_stripe_run_pieces(block_group, run_start,
- run_len, spare);
- stripe_claimable_mod(block_group, -(s64)run_len);
---
-2.47.3
-
--- /dev/null
+From a69e33446c5071f8b1ec51725680c0c6018d6b13 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:20 -0400
+Subject: [RFC PATCH 37/85] btrfs: stripe_alloc: count nocow run lifecycles and
+ stranded stripes in sysfs (allow_rmw part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: count nocow run lifecycles and
+stranded stripes in sysfs" (earlier in this series) that need code from
+"btrfs: stripe_alloc: isolate nodatacow and preallocated extents by
+stripe", which comes after it in this series: they are applied here,
+once "btrfs: stripe_alloc: isolate nodatacow and preallocated extents by
+stripe" is in, instead of with the rest of "btrfs: stripe_alloc: count
+nocow run lifecycles and stranded stripes in sysfs".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 2 ++
+ 1 file changed, 2 insertions(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 6826fc3f0ac48..0dfe64dc1ca2d 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1032,6 +1032,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ }
+ new_run->bg = bg;
+ new_run->class = class;
++ if (class == BTRFS_STRIPE_RUN_NOCOW)
++ atomic64_inc(&fs_info->stripe_run_stats.nocow_run_opened);
+ new_run->owner = ino;
+ new_run->start = start;
+ new_run->end = start + len;
+--
+2.47.3
+
--- /dev/null
+From 0d4a5956944659eaf614e92e4457eb4818133dbd Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 1 Oct 2026 12:14:49 -0400
+Subject: [RFC PATCH 38/85] btrfs: stripe_alloc: keep a stripe in the rbio
+ cache until its run has written all of it (allow_rmw part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: keep a stripe in the rbio cache until
+its run has written all of it" (earlier in this series) that need code
+from "btrfs: stripe_alloc: isolate nodatacow and preallocated extents by
+stripe", which comes after it in this series: they are applied here,
+once "btrfs: stripe_alloc: isolate nodatacow and preallocated extents by
+stripe" is in, instead of with the rest of "btrfs: stripe_alloc: keep a
+stripe in the rbio cache until its run has written all of it".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 2 ++
+ 1 file changed, 2 insertions(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 0dfe64dc1ca2d..107377e8cf697 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1492,6 +1492,8 @@ static bool run_written_range(const struct btrfs_open_stripe_run *run,
+ const u32 bits = run->bg->fs_info->sectorsize_bits;
+ u64 lo, hi;
+
++ if (run->class == BTRFS_STRIPE_RUN_NOCOW)
++ return false;
+ if (!run->live || !run->written || !run->live_nbits)
+ return false;
+ lo = max(*start, run->start);
+--
+2.47.3
+
+++ /dev/null
-From dde098ab4e495aebe9bb82a19e2d9ea01b6918e8 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:58 -0400
-Subject: [RFC PATCH 038/116] btrfs: stripe_meta: allocate tree blocks by whole
- stripes
-To: linux-btrfs@vger.kernel.org
-
-Metadata gets the placement rule data already has: tree blocks are handed
-out from runs of fully free stripes, and a stripe is never revisited once
-the transaction that filled it has written it. No separate mount option: the
-chunk profile already decides it. raid56 metadata has the same write hole
-as raid56 data, so it gets the same protection at the same time, and
-metadata on any other profile has no write hole to close -- the policy's
-RAID56_MASK test simply does not match it, so nothing changes there.
-
-It does cost a stranded stripe tail per commit, and a metadata allocation
-that fails aborts the transaction rather than failing one write. Those
-are the price of covering raid56 metadata at all rather than a reason to
-make it opt-in separately: a filesystem unwilling to pay them does not
-want raid56 metadata, and converting it to raid1c3/raid1c4 removes both
-the cost and the write hole.
-
-Only system chunks are left uncovered: btrfs_is_stripe_meta_bg() tests the
-METADATA flag and a system chunk does not carry it, so a raid56 system
-chunk keeps the legacy read-modify-write. The mount-time warning is
-narrowed to say exactly that instead of claiming metadata is uncovered,
-which it no longer is.
-
-The machinery is the data machinery, including the per-sector liveness
-map the previous patch gave it. Metadata needed three things of its own:
-
- - A completion report. A run drains when every byte allocated from it
- has been accounted for, and metadata had no equivalent of ordered
- extent completion, so its runs could never drain -- the deadlock that
- mixed block groups hit. end_bbio_meta_write() now reports, and
- btrfs_open_stripe_write_abandoned() covers a tree block freed before
- it was ever written (COWed twice in one transaction, say).
-
- - A two-phase closure. btrfs_retire_open_stripes() runs before the
- commit writes tree blocks, so it skips metadata runs; they are closed
- and drained afterwards by btrfs_retire_meta_stripes(), once every block
- is on disk. Closing earlier would strand blocks the commit has not
- allocated yet, draining earlier would wait for writes it has not
- issued. Metadata runs are also freed there rather than when their
- counter reaches zero: a stripe's columns can be written by separate
- rbios, and freeing on the first completion leaves the second with no
- run to pad or merge against.
-
- - Whole stripes per writeback pass. The opportunistic writeback passes
- do not know about stripes and will happily write three tree blocks now
- and five later; btrfs_defer_stripe_meta_write() leaves the blocks
- dirty for the commit (or a WB_SYNC_ALL waiter) instead, the same shape
- as the zoned write-pointer deferral.
-
-Two free paths bypass the usual completion reporting and must report the
-block abandoned themselves: btrfs_free_tree_block() can send a
-same-transaction unwritten block through the delayed-ref machinery when
-check_ref_cleanup() finds its ref head already processed, and
-clean_log_buffer() discards unwritten log tree blocks via
-btrfs_pin_reserved_extent() without ever visiting btrfs_free_tree_block().
-Either miss leaves the block counted as inflight forever: the run never
-drains, the block group reference never drops, and unmount asserts. Both
-were found by the dm-log-writes replay matrix, whose crash-recovery mounts
-exercise both paths routinely.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 335 ++++++++++++++++++++++++++++++++++--
- fs/btrfs/block-group.h | 13 ++
- fs/btrfs/extent-tree.c | 72 +++++++-
- fs/btrfs/extent_io.c | 18 ++
- fs/btrfs/free-space-cache.c | 2 +-
- fs/btrfs/raid56.c | 17 ++
- fs/btrfs/transaction.c | 19 ++
- fs/btrfs/tree-log.c | 22 +++
- 8 files changed, 482 insertions(+), 16 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index c984b5ffcf465..d64f882cec24d 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -501,6 +501,7 @@ struct btrfs_open_stripe_run {
- u64 offset; /* next unallocated byte */
- u64 inflight_bytes; /* reserved bytes with data IO pending */
- u64 open_seq; /* fs_info->stripe_retire_seq at open */
-+ u64 transid; /* fs_info->generation at open */
- u64 owner; /* LOG class: btrfs_ino of the owner */
- enum btrfs_stripe_run_class class;
- bool open; /* accepting allocations */
-@@ -521,6 +522,60 @@ struct btrfs_open_stripe_run {
- u32 live_nbits; /* sectors @live covers; caps growth */
- };
-
-+static void btrfs_dump_open_meta_runs(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (run->class != BTRFS_STRIPE_RUN_META)
-+ continue;
-+ btrfs_warn(bg->fs_info,
-+" run %llu..%llu frontier %llu open %d inflight %llu transid %llu",
-+ run->start, run->end, run->offset, run->open,
-+ run->inflight_bytes, run->transid);
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+}
-+
-+static bool bg_has_undrained_meta_runs(struct btrfs_block_group *bg,
-+ u64 transid)
-+{
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ bool ret = false;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (run->class != BTRFS_STRIPE_RUN_META)
-+ continue;
-+ /*
-+ * An open run here belongs to the running transaction: the
-+ * retirer closed every run it is responsible for before its
-+ * wait, so this one was opened while it waited, and drains
-+ * when that transaction's own commit writes its tree blocks.
-+ * Waiting on it would be waiting for writes this commit never
-+ * issued.
-+ */
-+ if (run->open)
-+ continue;
-+ /*
-+ * Likewise a run the running transaction opened and a band
-+ * collision or eviction closed early: its blocks are written,
-+ * and its stripes settled, by that transaction's own commit.
-+ */
-+ if (run->transid > transid)
-+ continue;
-+ if (run->inflight_bytes) {
-+ ret = true;
-+ break;
-+ }
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ return ret;
-+}
-+
- static bool open_stripe_run_drained(const struct btrfs_open_stripe_run *run)
- {
- return !run->open && run->inflight_bytes == 0;
-@@ -606,7 +661,22 @@ static void run_live_set(struct btrfs_open_stripe_run *run, u64 start, u64 len,
- bitmap_clear(run->live, first, nr);
- }
-
--/* Free a drained run. Caller holds bg->stripe_run_lock. */
-+/*
-+ * A drained run may still be needed.
-+ *
-+ * Metadata writeback issues one rbio per contiguous run of tree blocks, so
-+ * a stripe's columns can be submitted separately. If the run were freed as
-+ * soon as its counter hit zero -- which happens when the first column's
-+ * completions arrive -- the second column would find no run covering its
-+ * stripe, and with no run there is nothing to pad against and nothing to
-+ * merge with. Metadata runs are therefore freed by
-+ * btrfs_retire_meta_stripes(), which runs once every tree block is on disk.
-+ */
-+static bool run_freed_on_drain(const struct btrfs_open_stripe_run *run)
-+{
-+ return run->class != BTRFS_STRIPE_RUN_META;
-+}
-+
- static void free_open_stripe_run(struct btrfs_block_group *bg,
- struct btrfs_open_stripe_run *run)
- {
-@@ -617,6 +687,27 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
- wake_up_var(&bg->open_stripe_runs);
- }
-
-+/*
-+ * Report a run's transition to drained. Freeing wakes the retire waiters as
-+ * a side effect of free_open_stripe_run(); a metadata run instead stays
-+ * behind for padding and merging until btrfs_retire_meta_stripes() collects
-+ * it, but that same retirer may already be asleep waiting for exactly this
-+ * drain -- completion reports normally all precede its wait, but a report
-+ * can arrive outside the writeback window (a tree block freed before it was
-+ * written, e.g. an unwritten log tree block). Wake it, or it sleeps out
-+ * its whole timeout.
-+ */
-+static void open_stripe_run_drain_reported(struct btrfs_block_group *bg,
-+ struct btrfs_open_stripe_run *run)
-+{
-+ if (!open_stripe_run_drained(run))
-+ return;
-+ if (run_freed_on_drain(run))
-+ free_open_stripe_run(bg, run);
-+ else
-+ wake_up_var(&bg->open_stripe_runs);
-+}
-+
- /*
- * Close a run: no further allocation may join it, and its unallocated tail
- * must be returned to the free space cache by the caller (after dropping the
-@@ -725,6 +816,10 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- u64 *ret_offset, u64 *available)
- {
- struct btrfs_fs_info *fs_info = bg->fs_info;
-+ const u64 transid = btrfs_get_fs_generation(fs_info);
-+ u64 evict_start[BTRFS_STRIPE_RUN_NR_BANDS];
-+ u64 evict_len[BTRFS_STRIPE_RUN_NR_BANDS];
-+ int nr_evict = 0;
- const u64 fsl = bg->full_stripe_len;
- struct btrfs_open_stripe_run *new_run;
- struct btrfs_open_stripe_run *run;
-@@ -752,6 +847,24 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
-
- if (!r)
- continue;
-+ /*
-+ * Metadata runs are closed after the next transaction is
-+ * already running (btrfs_retire_meta_stripes()), so a slot can
-+ * still hold the previous transaction's run. Joining it would
-+ * put two transactions' tree blocks in the same stripes, and
-+ * the later one's writeback would read-modify-write parity
-+ * over the earlier one's committed blocks: the write hole.
-+ * Close it; its tail returns to the free space cache below.
-+ */
-+ if (class == BTRFS_STRIPE_RUN_META && r->transid != transid) {
-+ bg->open_stripe[class][band] = NULL;
-+ evict_len[nr_evict] =
-+ close_open_stripe_run(bg, r,
-+ &evict_start[nr_evict]);
-+ if (evict_len[nr_evict])
-+ nr_evict++;
-+ continue;
-+ }
- rem = r->end - r->offset;
- if (rem > *available)
- *available = rem;
-@@ -773,10 +886,16 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- if (tail_len)
- btrfs_add_free_space(bg, tail_start, tail_len);
-+ for (int i = 0; i < nr_evict; i++)
-+ btrfs_add_free_space(bg, evict_start[i], evict_len[i]);
- stripe_open_remainder_sync(bg);
- return 0;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ for (int i = 0; i < nr_evict; i++)
-+ btrfs_add_free_space(bg, evict_start[i], evict_len[i]);
-+ if (nr_evict)
-+ stripe_open_remainder_sync(bg);
-
- /*
- * Zeroed: the error paths below reach out: before the liveness map is
-@@ -856,6 +975,9 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
-
- if (!r || r->end != start)
- continue;
-+ /* Never grow another transaction's run (see the scan above). */
-+ if (class == BTRFS_STRIPE_RUN_META && r->transid != transid)
-+ continue;
- /*
- * Only grow as far as the run's liveness map reaches; it
- * cannot be reallocated here (see alloc_run_live_map()).
-@@ -894,6 +1016,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->owner = 0;
-+ new_run->transid = transid;
- new_run->start = start;
- new_run->end = start + len;
- new_run->offset = start + num_bytes;
-@@ -1913,15 +2036,20 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
- */
- static void warn_stripe_alloc_uncovered(struct btrfs_fs_info *info)
- {
-- const u64 meta_bits = info->avail_metadata_alloc_bits |
-- info->avail_system_alloc_bits;
--
- if (!btrfs_test_opt(info, STRIPE_ALLOC))
- return;
-
-- if (meta_bits & BTRFS_BLOCK_GROUP_RAID56_MASK)
-+ /*
-+ * raid56 metadata is covered now that the policy follows the chunk
-+ * profile. System chunks are not: btrfs_is_stripe_meta_bg() tests
-+ * the METADATA flag, and a system chunk does not carry it, so a
-+ * raid56 system chunk keeps the legacy read-modify-write and its
-+ * write hole. They are small and rewritten rarely, but say so
-+ * rather than let the earlier "covered" message imply otherwise.
-+ */
-+ if (info->avail_system_alloc_bits & BTRFS_BLOCK_GROUP_RAID56_MASK)
- btrfs_warn(info,
--"stripe_alloc does not cover raid56 metadata: the write hole remains for metadata, consider converting it to raid1c3/raid1c4");
-+"stripe_alloc does not cover raid56 system chunks: the write hole remains for them, consider converting to raid1c3/raid1c4");
- }
-
- /*
-@@ -2055,8 +2183,7 @@ void btrfs_open_stripe_write_abandoned(struct btrfs_block_group *bg, u64 start,
- ASSERT(run->inflight_bytes >= num_bytes);
- run_live_set(run, start, num_bytes, false);
- run->inflight_bytes -= num_bytes;
-- if (open_stripe_run_drained(run))
-- free_open_stripe_run(bg, run);
-+ open_stripe_run_drain_reported(bg, run);
- break;
- }
- }
-@@ -2075,8 +2202,7 @@ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
- ASSERT(start + num_bytes <= run->offset);
- ASSERT(run->inflight_bytes >= num_bytes);
- run->inflight_bytes -= num_bytes;
-- if (open_stripe_run_drained(run))
-- free_open_stripe_run(bg, run);
-+ open_stripe_run_drain_reported(bg, run);
- break;
- }
- }
-@@ -2151,8 +2277,7 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- ASSERT(run->inflight_bytes >= num_bytes);
- run->inflight_bytes -= num_bytes;
-- if (open_stripe_run_drained(run))
-- free_open_stripe_run(bg, run);
-+ open_stripe_run_drain_reported(bg, run);
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- }
-
-@@ -2188,6 +2313,13 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
- */
- if (run->class == BTRFS_STRIPE_RUN_NOCOW && seq != U64_MAX)
- continue;
-+ /*
-+ * Metadata runs are still being filled at this point in the
-+ * commit and their tree blocks are not written until later;
-+ * btrfs_retire_meta_stripes() closes them once they are.
-+ */
-+ if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
-+ continue;
- 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)
-@@ -2229,6 +2361,9 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
- /* Persistent nocow runs are not part of any commit window. */
- if (run->class == BTRFS_STRIPE_RUN_NOCOW && seq != U64_MAX)
- continue;
-+ /* Metadata drains after tree writeback, not here. */
-+ if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
-+ continue;
- if (run->open_seq < seq) {
- ret = false;
- break;
-@@ -2265,6 +2400,173 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
- * Calls are serialized by the transaction commit; @trans may be NULL for
- * the final cleanup call.
- */
-+/*
-+ * Close and drain the metadata stripe runs, once every tree block this
-+ * transaction allocated has reached the disk.
-+ *
-+ * This is the second half of a two-phase closure. The first half happens
-+ * implicitly: btrfs_retire_open_stripes() runs earlier in the commit and
-+ * skips these runs, so they stay open for allocation right through the
-+ * commit-time tree building that follows it. Here the allocation side is
-+ * finished and the writes are complete, so the runs can be closed and their
-+ * unused tails returned.
-+ *
-+ * Ordering matters in both directions. Closing earlier would strand tree
-+ * blocks the commit has not allocated yet; draining earlier would wait for
-+ * writes the commit has not issued yet, which is precisely the deadlock
-+ * mixed block groups used to hit.
-+ */
-+void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
-+{
-+ struct btrfs_block_group *bg;
-+ LIST_HEAD(retire_list);
-+ unsigned long flags;
-+
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return;
-+
-+ spin_lock(&fs_info->open_stripe_lock);
-+ list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
-+ list_add_tail(&bg->open_stripe_retire_list, &retire_list);
-+ spin_unlock(&fs_info->open_stripe_lock);
-+
-+ while (!list_empty(&retire_list)) {
-+ struct btrfs_open_stripe_run *run;
-+ bool again = true;
-+
-+ bg = list_first_entry(&retire_list, struct btrfs_block_group,
-+ open_stripe_retire_list);
-+ list_del_init(&bg->open_stripe_retire_list);
-+ if (!(bg->flags & BTRFS_BLOCK_GROUP_METADATA))
-+ continue;
-+
-+ while (again) {
-+ u64 tail_start;
-+ u64 tail_len = 0;
-+
-+ again = false;
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (run->class != BTRFS_STRIPE_RUN_META ||
-+ !run->open)
-+ continue;
-+ /*
-+ * The running transaction's runs are not ours
-+ * to close: their tree blocks are written, and
-+ * their stripes settled, by that transaction's
-+ * own commit.
-+ */
-+ if (run->transid > transid)
-+ continue;
-+ for (int band = 0;
-+ band < BTRFS_STRIPE_RUN_NR_BANDS; band++)
-+ if (bg->open_stripe[BTRFS_STRIPE_RUN_META][band] == run)
-+ bg->open_stripe[BTRFS_STRIPE_RUN_META][band] = NULL;
-+ tail_len = close_open_stripe_run(bg, run, &tail_start);
-+ again = true;
-+ break;
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ if (tail_len)
-+ btrfs_add_free_space(bg, tail_start, tail_len);
-+ }
-+ /*
-+ * The closes above shrank the group's open-run remainder;
-+ * fold the delta into the space_info now. While the policy
-+ * is on the next allocation from this group would carry it,
-+ * but after a runtime disable nothing allocates here again
-+ * and the stale remainder holds metadata back for good.
-+ */
-+ stripe_open_remainder_sync(bg);
-+
-+ /*
-+ * Every tree block is on disk, so end_bbio_meta_write() has
-+ * reported all of them and this settles without waiting.
-+ *
-+ * Bounded rather than indefinite on purpose. A run drains
-+ * only when every byte allocated from it has been reported,
-+ * by writeback or by whatever freed the block before it was
-+ * written; a path that frees a tree block without reporting
-+ * would otherwise wedge the commit with no clue as to which
-+ * one. Time out, say so, and carry on: the stripe is then
-+ * left open, which costs space, where hanging costs the
-+ * filesystem.
-+ */
-+ if (!wait_var_event_timeout(&bg->open_stripe_runs,
-+ !bg_has_undrained_meta_runs(bg, transid),
-+ 60 * HZ)) {
-+ btrfs_warn(fs_info,
-+"metadata stripe runs in block group %llu did not drain; a tree block was freed without reporting to its run",
-+ bg->start);
-+ btrfs_dump_open_meta_runs(bg);
-+ }
-+
-+ /* Drained and no longer needed for padding or merging. */
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ while (true) {
-+ struct btrfs_open_stripe_run *next = NULL;
-+
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (run->class == BTRFS_STRIPE_RUN_META &&
-+ open_stripe_run_drained(run)) {
-+ next = run;
-+ break;
-+ }
-+ }
-+ if (!next)
-+ break;
-+ free_open_stripe_run(bg, next);
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ }
-+}
-+
-+/*
-+ * Should this tree block be left dirty for the transaction commit to write?
-+ *
-+ * A stripe filled by one transaction is written in one piece only if all of
-+ * its tree blocks go out in the same writeback pass. The opportunistic
-+ * passes -- memory reclaim, the periodic writeback timer -- do not know
-+ * about stripes and will happily write three tree blocks now and the other
-+ * five later, which turns a full-stripe write into two read-modify-writes.
-+ *
-+ * Zoned mode has the same problem for a different reason (a tree block that
-+ * is not at its zone's write pointer cannot be written yet) and solves it
-+ * the same way: btrfs_check_meta_write_pointer() declines the block and the
-+ * writeback loop leaves it dirty. This declines on stripe grounds instead.
-+ *
-+ * WB_SYNC_ALL is never deferred. That is what keeps this from deadlocking:
-+ * a reclaimer that must have these pages written waits on WB_SYNC_ALL, which
-+ * always proceeds, so dirty metadata pinned in an incomplete stripe can
-+ * always be flushed by the caller who needs the memory. Only the
-+ * best-effort passes are turned away, and turning one away asks for a commit
-+ * rather than leaving the pages for the periodic writeback to find again.
-+ */
-+bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
-+ struct extent_buffer *eb,
-+ const struct writeback_control *wbc)
-+{
-+ struct btrfs_block_group *bg;
-+ bool defer;
-+
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return false;
-+ if (wbc->sync_mode == WB_SYNC_ALL)
-+ return false;
-+
-+ bg = btrfs_lookup_block_group(fs_info, eb->start);
-+ if (!bg)
-+ return false;
-+ defer = btrfs_is_stripe_meta_bg(bg);
-+ btrfs_put_block_group(bg);
-+
-+ if (defer) {
-+ set_bit(BTRFS_FS_NEED_TRANS_COMMIT, &fs_info->flags);
-+ wake_up_process(fs_info->transaction_kthread);
-+ }
-+ return defer;
-+}
-+
- void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
- struct btrfs_transaction *trans)
- {
-@@ -2436,7 +2738,14 @@ void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
- bg = btrfs_lookup_block_group(fs_info, full_stripe_start);
- if (!bg)
- return;
-- if (!btrfs_is_stripe_alloc_bg(bg) ||
-+ /*
-+ * Metadata is checked on the same terms once stripe_meta places it:
-+ * its runs stay open across the commit's tree building but are closed
-+ * and drained before the commit ends, so a tree block write outside
-+ * every live run means a stripe was revisited after the transaction
-+ * that filled it finished -- the same violation as for data.
-+ */
-+ if ((!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg)) ||
- test_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED, &bg->runtime_flags) ||
- test_bit(BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED, &bg->runtime_flags))
- goto out;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 2f3091b848317..bacabac29e351 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -46,6 +46,14 @@ enum btrfs_stripe_run_class {
- * blast radius to the owning file alone.
- */
- BTRFS_STRIPE_RUN_NOCOW,
-+ /*
-+ * Tree blocks. Kept out of the commit-time drain that settles the
-+ * classes above, because metadata writeback happens later in the same
-+ * commit than that drain runs: these are sealed against further
-+ * allocation and drained separately once the tree blocks are on disk
-+ * (see btrfs_retire_meta_stripes()).
-+ */
-+ BTRFS_STRIPE_RUN_META,
- BTRFS_STRIPE_RUN_NR_CLASSES,
- };
-
-@@ -462,8 +470,12 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
- struct btrfs_fs_info *fs_info, u64 bytenr, u64 num_bytes,
- u64 *open_seq);
- void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
-+void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid);
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
-+bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
-+ struct extent_buffer *eb,
-+ const struct writeback_control *wbc);
- bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class);
- bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
-@@ -510,6 +522,7 @@ void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg);
- void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info);
- bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr);
- bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg);
-+bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg);
- void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force);
- #ifdef CONFIG_BTRFS_DEBUG
- void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index fc97d1f78119f..921c2c1956f70 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -3654,6 +3654,24 @@ int btrfs_free_tree_block(struct btrfs_trans_handle *trans,
- if (btrfs_header_generation(buf) != trans->transid)
- return 0;
-
-+ /*
-+ * Last ref to a tree block this transaction allocated and never
-+ * wrote: no writeback completion will ever report it to its stripe
-+ * run. Report it here, before the free paths diverge. When the
-+ * delayed ref head was already processed (truncate and friends run
-+ * delayed refs mid-transaction for throttling) check_ref_cleanup()
-+ * below returns 0 and the free goes through __btrfs_free_extent()
-+ * and the pin/unpin machinery, none of which know about the run --
-+ * the run's inflight count would never drain.
-+ */
-+ if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
-+ bg = btrfs_lookup_block_group(fs_info, buf->start);
-+ if (btrfs_is_stripe_meta_bg(bg))
-+ btrfs_open_stripe_write_abandoned(bg, buf->start,
-+ buf->len);
-+ btrfs_put_block_group(bg);
-+ }
-+
- if (root_id != BTRFS_TREE_LOG_OBJECTID) {
- ret = check_ref_cleanup(trans, buf->start);
- if (!ret)
-@@ -4210,6 +4228,30 @@ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
- (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK);
- }
-
-+/*
-+ * Should this block group allocate tree blocks by whole stripes?
-+ *
-+ * The same rule data follows: only fully free stripes are claimed, and the
-+ * partial stripe left at the end of a commit is padded out rather than
-+ * revisited, so no tree block write ever lands in a stripe holding earlier
-+ * committed data. Not separately gated: the chunk profile already decides
-+ * it. raid56 metadata has the same write hole as raid56 data and gets the
-+ * same protection at the same time; metadata on any other profile has no
-+ * write hole to close, and the RAID56_MASK test below means the policy
-+ * simply does not apply to it. The costs metadata brings -- a stranded
-+ * stripe tail per commit, and an allocation failure that aborts the
-+ * transaction rather than failing one write -- are the price of covering
-+ * raid56 metadata at all, and a filesystem that does not want them wants
-+ * raid1c3/raid1c4 metadata instead, which is the better answer anyway.
-+ */
-+bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg)
-+{
-+ return btrfs_test_opt(bg->fs_info, STRIPE_ALLOC) &&
-+ (bg->flags & BTRFS_BLOCK_GROUP_METADATA) &&
-+ !(bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
-+ (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK);
-+}
-+
- static int do_allocation_stripe(struct btrfs_block_group *block_group,
- struct find_free_extent_ctl *ffe_ctl,
- struct btrfs_block_group **bg_ret)
-@@ -4221,6 +4263,30 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- bool skip = false;
- int ret;
-
-+ /*
-+ * Tree blocks take the same path as data -- whole free stripes, a
-+ * frontier that padding can complete -- in their own class, and none
-+ * of the steering below applies to them: there is no inode to steer
-+ * by, metadata is always COW, and relocation moves tree blocks
-+ * through the normal metadata allocator.
-+ */
-+ if (btrfs_is_stripe_meta_bg(block_group)) {
-+ ret = btrfs_alloc_from_open_stripe(block_group,
-+ ffe_ctl->num_bytes,
-+ BTRFS_STRIPE_RUN_META,
-+ &offset, &available);
-+ if (ret == -ENOMEM)
-+ return ret;
-+ if (ret) {
-+ if (available > ffe_ctl->max_extent_size)
-+ ffe_ctl->max_extent_size = available;
-+ return 1;
-+ }
-+ ffe_ctl->found_offset = offset;
-+ ffe_ctl->search_start = offset;
-+ return 0;
-+ }
-+
- /*
- * Soft dedication of one block group to relocation, mirroring the
- * zoned data_reloc_bg rule: it keeps relocation's prealloc-then-
-@@ -4308,7 +4374,8 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- static void undo_stripe_allocation(struct btrfs_block_group *block_group,
- struct find_free_extent_ctl *ffe_ctl)
- {
-- if (btrfs_is_stripe_alloc_bg(block_group))
-+ if (btrfs_is_stripe_alloc_bg(block_group) ||
-+ btrfs_is_stripe_meta_bg(block_group))
- btrfs_open_stripe_write_abandoned(block_group,
- ffe_ctl->found_offset,
- ffe_ctl->num_bytes);
-@@ -4320,7 +4387,8 @@ static int do_allocation(struct btrfs_block_group *block_group,
- {
- switch (ffe_ctl->policy) {
- case BTRFS_EXTENT_ALLOC_CLUSTERED:
-- if (btrfs_is_stripe_alloc_bg(block_group))
-+ if (btrfs_is_stripe_alloc_bg(block_group) ||
-+ btrfs_is_stripe_meta_bg(block_group))
- return do_allocation_stripe(block_group, ffe_ctl,
- bg_ret);
- return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
-diff --git a/fs/btrfs/extent_io.c b/fs/btrfs/extent_io.c
-index 5ff630630490e..188e167848f91 100644
---- a/fs/btrfs/extent_io.c
-+++ b/fs/btrfs/extent_io.c
-@@ -2392,6 +2392,16 @@ static void end_bbio_meta_write(struct btrfs_bio *bbio)
- if (bbio->bio.bi_status != BLK_STS_OK)
- set_btree_ioerr(eb);
-
-+ /*
-+ * Tell the stripe run this tree block is written. Data reports the
-+ * same thing from ordered extent completion; metadata has no ordered
-+ * extent, so without this the run's inflight bytes would never come
-+ * back down and nothing waiting on it could ever proceed. Reported
-+ * on error too: the bytes will not be written again, and a run that
-+ * cannot drain is worse than one that drains after a failed write.
-+ */
-+ btrfs_open_stripe_write_done_bytenr(eb->fs_info, eb->start, eb->len);
-+
- /*
- * Clear writeback on the buffer's own folios. The bio may carry the
- * shared zero page instead (EXTENT_BUFFER_ZONED_ZEROOUT), so iterate
-@@ -2653,6 +2663,14 @@ int btree_writepages(struct address_space *mapping, struct writeback_control *wb
- while ((eb = eb_batch_next(&batch)) != NULL) {
- ctx.eb = eb;
-
-+ /*
-+ * Leave it dirty for the commit, so its stripe goes
-+ * out in one piece instead of once per writeback
-+ * pass.
-+ */
-+ if (btrfs_defer_stripe_meta_write(fs_info, eb, wbc))
-+ continue;
-+
- ret = write_meta_extent_buffer(&ctx, wbc);
- if (ret == -EBUSY) {
- ret = 0;
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index b9074d21f90f6..e4671fc7e5c15 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2113,7 +2113,7 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
- u64 trapped, claimable, nstripes;
- u32 *freep;
-
-- if (!btrfs_is_stripe_alloc_bg(bg))
-+ if (!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg))
- return;
- if (READ_ONCE(bg->stripe_unusable_ready))
- return;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 8c587dd13965a..d1e961ce4e490 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -3142,6 +3142,8 @@ static void audit_uncovered_rmw(struct btrfs_raid_bio *rbio)
- static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
- {
- struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ struct btrfs_block_group *bg;
-+ bool covered = false;
-
- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
- return;
-@@ -3156,6 +3158,21 @@ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
-
- atomic64_inc(&fs_info->stripe_park_stats.meta_rmw);
- audit_uncovered_rmw(rbio);
-+ /*
-+ * A raid56 metadata group under stripe_meta is covered: its
-+ * read-modify-writes are partial writes inside one transaction's
-+ * run, counted by the audit as meta_rmw_cur, and the audit warns
-+ * by itself should one ever touch a committed block. Only system
-+ * chunks and mixed groups are the uncovered case this message is
-+ * about.
-+ */
-+ bg = btrfs_lookup_block_group(fs_info, rbio->bioc->full_stripe_logical);
-+ if (bg) {
-+ covered = btrfs_is_stripe_meta_bg(bg);
-+ btrfs_put_block_group(bg);
-+ }
-+ if (covered)
-+ return;
- btrfs_warn_rl(fs_info,
- "read-modify-write of full stripe %llu: this block group is not covered by stripe_alloc, the raid56 write hole applies to it",
- rbio->bioc->full_stripe_logical);
-diff --git a/fs/btrfs/transaction.c b/fs/btrfs/transaction.c
-index 4f781df772202..6007dce716bf5 100644
---- a/fs/btrfs/transaction.c
-+++ b/fs/btrfs/transaction.c
-@@ -23,6 +23,8 @@
- #include "dev-replace.h"
- #include "qgroup.h"
- #include "block-group.h"
-+#include "free-space-cache.h"
-+#include "raid56.h"
- #include "space-info.h"
- #include "fs.h"
- #include "accessors.h"
-@@ -1345,6 +1347,13 @@ static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
- blk_start_plug(&plug);
- ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
- blk_finish_plug(&plug);
-+ /*
-+ * Everything this commit is going to submit has been submitted, so any
-+ * rbio still parked waiting for a sibling is waiting for one that will
-+ * never come. Kick them down now rather than let the wait below sit
-+ * out their park deadline.
-+ */
-+ btrfs_flush_parked_rbios(fs_info, 0, U64_MAX, true);
- ret2 = btrfs_wait_extents(fs_info, dirty_pages);
-
- if (ret)
-@@ -2661,6 +2670,16 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
- goto scrub_continue;
- }
-
-+ /*
-+ * Every tree block this transaction allocated is now on disk, so its
-+ * metadata stripe runs can be closed and drained. This is the point
-+ * the earlier btrfs_retire_open_stripes() deliberately left them
-+ * alone for: closing before here would strand blocks the commit had
-+ * not allocated yet, draining before here would wait on writes it had
-+ * not issued.
-+ */
-+ btrfs_retire_meta_stripes(fs_info, cur_trans->transid);
-+
- ret = write_all_supers(trans);
- /*
- * the super is written, we can safely allow the tree-loggers
-diff --git a/fs/btrfs/tree-log.c b/fs/btrfs/tree-log.c
-index d902d169680a4..3a2391b616694 100644
---- a/fs/btrfs/tree-log.c
-+++ b/fs/btrfs/tree-log.c
-@@ -2938,6 +2938,28 @@ static int clean_log_buffer(struct btrfs_trans_handle *trans,
- wait_on_extent_buffer_writeback(eb);
- btrfs_tree_unlock(eb);
-
-+ /*
-+ * A log tree block discarded before it was ever written has no
-+ * writeback completion coming: nothing else will report it to its
-+ * stripe run, and an unreported allocation keeps the run's inflight
-+ * count from ever draining. Report it abandoned here. Written
-+ * blocks were already reported by their write endio (the writeback
-+ * wait above means no submission is still in flight), and log blocks
-+ * from a previous mount walked during log replay carry the WRITTEN
-+ * flag on disk, so both are excluded.
-+ */
-+ if (!btrfs_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN)) {
-+ struct btrfs_block_group *stripe_bg;
-+
-+ stripe_bg = btrfs_lookup_block_group(fs_info, eb->start);
-+ if (stripe_bg) {
-+ if (btrfs_is_stripe_meta_bg(stripe_bg))
-+ btrfs_open_stripe_write_abandoned(stripe_bg,
-+ eb->start, eb->len);
-+ btrfs_put_block_group(stripe_bg);
-+ }
-+ }
-+
- if (trans) {
- int ret;
-
---
-2.47.3
-
+++ /dev/null
-From 5fc8c3c4793dfd054c91db27d0d7c85330922a4c Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:17:59 -0400
-Subject: [RFC PATCH 039/116] btrfs: stripe_alloc: drain the legacy allocator's
- writes before arming the write-hole check at a runtime enable
-To: linux-btrfs@vger.kernel.org
-
-Enabling stripe_alloc on a live filesystem (the btrfs.stripe_alloc property)
-flips the policy while the legacy allocator may still have writes in
-flight. Those extents sit in partly used stripes that no stripe run covers,
-so the first of them to reach rmw_rbio() after the flip trips
-btrfs_stripe_check_write()'s "write to stripe outside any live stripe run"
-WARN_ONCE and taints the kernel, although nothing violated the policy: the
-data was placed before the policy existed. punch-hole-warn-repro.sh hits it
-on the switch when its killed writers still have dirty data (bhive, 7.3-rc2
-lane, 2026-09-12); the same code on 6.18 escaped only by timing.
-
-Keep the check off from the flip until every ordered extent that could have
-been allocated before it has completed. The property is applied inside a
-transaction, where flushing delalloc cannot wait, so the drain runs in a
-worker: start delalloc on all roots, wait for all ordered extents, clear the
-flag. Extents allocated after the flip have stripe runs and are unaffected;
-a mount-time enable (the root directory's property) has nothing in flight and
-does not queue the drain. close_ctree() flushes the worker so it cannot
-outlive the filesystem.
-
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/block-group.c | 37 +++++++++++++++++++++++++++++++++++++
- fs/btrfs/block-group.h | 1 +
- fs/btrfs/disk-io.c | 2 ++
- fs/btrfs/fs.h | 9 +++++++++
- 4 files changed, 49 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index d64f882cec24d..989cbbaa33c38 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -5,6 +5,8 @@
- #include "misc.h"
- #include "ctree.h"
- #include "block-group.h"
-+#include "ordered-data.h"
-+#include "btrfs_inode.h"
- #include "space-info.h"
- #include "disk-io.h"
- #include "free-space-cache.h"
-@@ -2058,8 +2060,27 @@ static void warn_stripe_alloc_uncovered(struct btrfs_fs_info *info)
- * when the root directory inode loads its properties -- before any user IO
- * -- or at runtime from btrfs_set_prop().
- */
-+/*
-+ * Drain the writes the legacy allocator placed before stripe_alloc was
-+ * enabled on a live filesystem, then arm the write-hole invariant check.
-+ * Runs in a worker: the property that enables the policy is applied inside
-+ * a transaction, where flushing delalloc cannot wait.
-+ */
-+void btrfs_stripe_alloc_enable_work(struct work_struct *work)
-+{
-+ struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
-+ stripe_alloc_enable_work);
-+
-+ btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
-+ btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
-+ clear_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags);
-+ btrfs_info(fs_info,
-+ "stripe_alloc: writes placed before the policy was enabled have landed");
-+}
-+
- int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
- {
-+ bool live = test_bit(BTRFS_FS_OPEN, &fs_info->flags);
- int ret;
-
- if (btrfs_test_opt(fs_info, STRIPE_ALLOC))
-@@ -2067,6 +2088,17 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
- ret = btrfs_stripe_alloc_check_support(fs_info);
- if (ret)
- return ret;
-+ /*
-+ * On a live filesystem the legacy allocator may still have writes in
-+ * flight. Their extents sit in partly used stripes that no stripe run
-+ * covers, so the write-hole invariant check would report them although
-+ * they were placed before the policy existed. Keep the check off until
-+ * every ordered extent that could have been allocated before the flip
-+ * has landed; extents allocated after it have stripe runs. A mount-time
-+ * enable has nothing in flight and skips the drain.
-+ */
-+ if (live)
-+ set_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags);
- btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
- warn_stripe_alloc_uncovered(fs_info);
- /*
-@@ -2079,6 +2111,8 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
- stripe_alloc_sweep_groups(fs_info, true);
- btrfs_info(fs_info,
- "using stripe-exclusive allocation for raid56 data");
-+ if (live)
-+ queue_work(system_unbound_wq, &fs_info->stripe_alloc_enable_work);
- return 0;
- }
-
-@@ -2735,6 +2769,9 @@ void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
-
- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
- return;
-+ /* the legacy allocator's writes are still landing after a runtime enable */
-+ if (test_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags))
-+ return;
- bg = btrfs_lookup_block_group(fs_info, full_stripe_start);
- if (!bg)
- return;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index bacabac29e351..f8cb733ad3772 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -524,6 +524,7 @@ bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr);
- bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg);
- bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg);
- void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force);
-+void btrfs_stripe_alloc_enable_work(struct work_struct *work);
- #ifdef CONFIG_BTRFS_DEBUG
- void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
- u64 full_stripe_start, bool sub_stripe);
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index 5d306267e3f47..37d87114f69e4 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -2804,6 +2804,7 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
- INIT_LIST_HEAD(&fs_info->delalloc_roots);
- INIT_LIST_HEAD(&fs_info->caching_block_groups);
- INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
-+ INIT_WORK(&fs_info->stripe_alloc_enable_work, btrfs_stripe_alloc_enable_work);
- fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
- fs_info->stripe_park_sync_timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
- spin_lock_init(&fs_info->open_stripe_lock);
-@@ -4502,6 +4503,7 @@ void __cold close_ctree(struct btrfs_fs_info *fs_info)
- */
- btrfs_run_delayed_iputs(fs_info);
-
-+ flush_work(&fs_info->stripe_alloc_enable_work);
- cancel_work_sync(&fs_info->async_reclaim_work);
- cancel_work_sync(&fs_info->async_data_reclaim_work);
- cancel_work_sync(&fs_info->preempt_reclaim_work);
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 035e0cc80edd8..297964037a975 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -234,6 +234,13 @@ enum {
- */
- BTRFS_FS_UNALIGNED_TREE_BLOCK,
-
-+ /*
-+ * stripe_alloc was enabled on a live filesystem and the legacy
-+ * allocator's writes have not all landed yet: the write-hole
-+ * invariant check stays off until they have.
-+ */
-+ BTRFS_FS_STRIPE_ALLOC_ENABLING,
-+
- #if BITS_PER_LONG == 32
- /* Indicate if we have error/warn message printed on 32bit systems */
- BTRFS_FS_32BIT_ERROR,
-@@ -962,6 +969,8 @@ struct btrfs_fs_info {
- struct semaphore uuid_tree_rescan_sem;
-
- /* Used to reclaim the metadata space in the background. */
-+ /* drains the legacy allocator's writes after a runtime stripe_alloc enable */
-+ struct work_struct stripe_alloc_enable_work;
- struct work_struct async_reclaim_work;
- struct work_struct async_data_reclaim_work;
- struct work_struct preempt_reclaim_work;
---
-2.47.3
-
--- /dev/null
+From 7aae3e102d63ae77c7c24d64c3d472708641092b Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Fri, 2 Oct 2026 02:41:44 -0400
+Subject: [RFC PATCH 39/85] btrfs: stripe_alloc: pad a stripe's allocated
+ sectors whose write is still to come (allow_rmw part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: pad a stripe's allocated sectors
+whose write is still to come" (earlier in this series) that need code
+from "btrfs: stripe_alloc: isolate nodatacow and preallocated extents by
+stripe", which comes after it in this series: they are applied here,
+once "btrfs: stripe_alloc: isolate nodatacow and preallocated extents by
+stripe" is in, instead of with the rest of "btrfs: stripe_alloc: pad a
+stripe's allocated sectors whose write is still to come".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 107377e8cf697..38a129d405173 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1314,6 +1314,7 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ if (!test_bit(first + i, run->live)) {
+ set_bit(i, dead);
+ } else if (run->written &&
++ run->class != BTRFS_STRIPE_RUN_NOCOW &&
+ !test_bit(first + i, run->written)) {
+ set_bit(i, dead);
+ if (unwritten)
+--
+2.47.3
+
--- /dev/null
+From 0437ebeb84516f0d77b626d5ec03d23100ca56a5 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:40 -0400
+Subject: [RFC PATCH 40/85] btrfs: stripe_alloc: allow-rmw policy, and
+ write-in-place for isolated nocow extents
+To: linux-btrfs@vger.kernel.org
+
+Re-enable write-in-place for nodatacow files and preallocated extents
+under stripe-exclusive allocation, with the understood caveat that the
+write hole cannot be prevented for data that opts out of COW: an
+in-place write RMWs its stripe's parity, so a degraded crash can tear
+the stripe. What CAN be guaranteed is the blast radius: in-place is
+permitted only for extents whose full stripes are isolated to the
+writing inode, so such a crash can tear only the writing file's own
+data -- the nodatacow contract, no worse.
+
+The gate is per extent, decided where nocow eligibility is already
+checked: fast path, the stripe belongs to one of the inode's own
+NOCOW-class runs (which only ever held its extents); slow path, the
+committed extent tree proves sole ownership (single plain data ref,
+count 1, matching root and objectid; anything shared, foreign or
+metadata fails). The fully-free claim rule keeps uncommitted foreign
+extents out of partially used stripes, so the committed tree is
+authoritative. Extents that fail -- anything allocated before stripe
+isolation existed, extents shared through reflink or snapshots,
+relocated extents -- simply stay force-COWed, and because their rewrite
+is steered into the inode's private NOCOW run, the next overwrite of
+the same data passes: legacy nocow files migrate themselves to
+isolation in one COW generation, with no tool and no flag day.
+
+Log-commit settling skips NOCOW-class runs: nodatacow data gets no
+fsync survival guarantee (its own later in-place writes can always
+tear it), so closing the run would trap its tail for nothing. The
+write-hole debug checker skips groups that hosted NOCOW-class runs,
+like relocation-used groups, since isolated in-place writes land in
+stripes whose runs have drained. Settling, the fsync steering and the
+checker come later in this series, so these parts of the change are in
+its "(fsync part)", "(fsync part 2)" and "(debug part)" patches.
+
+The interface is a word-list policy naming the cases in which
+stripe_alloc may permit the legacy unsafe RMW, each independently:
+
+ nodatacow in-place writes for nodatacow files' extents
+ prealloc in-place writes into preallocated extents
+ fsync waive the close-at-log-commit guarantee: no settling, no
+ per-inode LOG steering, no carry-forward; logged stripes
+ may be extended and RMWed as without stripe_alloc
+
+It is "allow_rmw", not "allow_overwrite": the fsync case overwrites
+nothing, but all three permit read-modify-write of stripes that a
+degraded crash can then tear. The nodatacow and prealloc cases require
+the per-extent stripe isolation above (the blast radius stays confined
+to the writing file); fsync restores the exposure stock btrfs has,
+where a degraded crash may cost just-fsynced data, detectably, in
+exchange for none of the log-commit costs.
+
+The policy is persistent as the btrfs.stripe_alloc_allow_rmw property
+on the top-level root directory, following stripe_alloc's precedent
+(applied when the root inode loads during mount, before any user IO).
+Words are separated by comma, space or colon. Everything defaults off:
+plain stripe_alloc keeps forcing COW and keeps the full fsync guarantee.
+
+Sync writes into a NOCOW-class run do not park: in-place overwrites arrive
+one fsync at a time with nothing to merge and, unlike the datacow fsync
+path, nothing kicks them before the page writeback wait (the sync park
+deadline was most of a 3.7ms per-fsync regression against stock
+nodatacow). Async writeback still parks there.
+
+The ownership walk checks the extent item's size before reading its
+inline backref: a data extent whose only backref is a keyed
+EXTENT_DATA_REF item (the leaf had no room to grow the item) has none, and
+counts as not owned.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 240 ++++++++++++++++++++++++++++++++++++++++-
+ fs/btrfs/block-group.h | 12 +++
+ fs/btrfs/extent-tree.c | 3 +
+ fs/btrfs/file.c | 2 +
+ fs/btrfs/fs.h | 21 ++++
+ fs/btrfs/inode.c | 12 ++-
+ fs/btrfs/props.c | 42 ++++++++
+ fs/btrfs/raid56.c | 14 ++-
+ 8 files changed, 343 insertions(+), 3 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 38a129d405173..dcb49e5abfc92 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1159,6 +1159,236 @@ bool btrfs_stripe_run_strands(struct btrfs_block_group *bg, u64 stripe)
+ return ret;
+ }
+
++/*
++ * Parse the value of the btrfs.stripe_alloc_allow_rmw property, a word list
++ * ("nodatacow", "prealloc", "fsync"), into its mask. Words are separated by
++ * comma, space or colon. An empty value yields an empty mask. Returns
++ * -EINVAL on any unknown word.
++ */
++int btrfs_parse_stripe_rmw(const char *value, size_t len, u32 *mask)
++{
++ u32 m = 0;
++ size_t i = 0;
++
++ while (i < len) {
++ size_t j = i;
++
++ while (j < len && value[j] != ',' && value[j] != ' ' &&
++ value[j] != ':')
++ j++;
++ if (j - i == strlen("nodatacow") &&
++ !strncmp(value + i, "nodatacow", j - i))
++ m |= BTRFS_STRIPE_RMW_NODATACOW;
++ else if (j - i == strlen("prealloc") &&
++ !strncmp(value + i, "prealloc", j - i))
++ m |= BTRFS_STRIPE_RMW_PREALLOC;
++ else if (j - i == strlen("fsync") &&
++ !strncmp(value + i, "fsync", j - i))
++ m |= BTRFS_STRIPE_RMW_FSYNC;
++ else if (j != i)
++ return -EINVAL;
++ i = j + 1;
++ }
++ *mask = m;
++ return 0;
++}
++
++/*
++ * Does every committed extent in [start, start + len) belong solely to
++ * @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.
++ */
++static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
++ u64 root_id, u64 ino, u64 start, u64 len)
++{
++ struct btrfs_root *extent_root = btrfs_extent_root(fs_info, start);
++ struct btrfs_path *path;
++ struct btrfs_key key;
++ bool ret = true;
++ int err;
++
++ if (!extent_root)
++ return false;
++ path = btrfs_alloc_path();
++ if (!path)
++ return false;
++
++ key.objectid = start;
++ key.type = BTRFS_EXTENT_ITEM_KEY;
++ key.offset = 0;
++ err = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
++ if (err < 0) {
++ ret = false;
++ goto out;
++ }
++ /* An extent starting before @start may still overlap it. */
++ err = btrfs_previous_extent_item(extent_root, path, 0);
++ if (err < 0) {
++ ret = false;
++ goto out;
++ }
++ if (err > 0) {
++ btrfs_release_path(path);
++ key.objectid = start;
++ key.type = BTRFS_EXTENT_ITEM_KEY;
++ key.offset = 0;
++ err = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
++ if (err < 0) {
++ ret = false;
++ goto out;
++ }
++ }
++
++ while (true) {
++ struct extent_buffer *leaf = path->nodes[0];
++ int slot = path->slots[0];
++ struct btrfs_extent_item *ei;
++ struct btrfs_extent_inline_ref *iref;
++ struct btrfs_extent_data_ref *dref;
++ int type;
++
++ if (slot >= btrfs_header_nritems(leaf)) {
++ err = btrfs_next_leaf(extent_root, path);
++ if (err < 0) {
++ ret = false;
++ goto out;
++ }
++ if (err > 0)
++ break;
++ continue;
++ }
++ btrfs_item_key_to_cpu(leaf, &key, slot);
++ if (key.objectid >= start + len)
++ break;
++ if (key.type == BTRFS_METADATA_ITEM_KEY) {
++ /*
++ * key.offset is the level, not a length; a tree
++ * block spans nodesize bytes. One from before the
++ * range (e.g. where the pre-range positioning landed
++ * on a metadata block group's last item) is harmless.
++ */
++ if (key.objectid + fs_info->nodesize > start) {
++ ret = false;
++ goto out;
++ }
++ path->slots[0]++;
++ continue;
++ }
++ if (key.type != BTRFS_EXTENT_ITEM_KEY ||
++ key.objectid + key.offset <= start) {
++ path->slots[0]++;
++ continue;
++ }
++
++ ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
++ if (btrfs_extent_refs(leaf, ei) != 1 ||
++ !(btrfs_extent_flags(leaf, ei) & BTRFS_EXTENT_FLAG_DATA)) {
++ ret = false;
++ goto out;
++ }
++ /*
++ * With a keyed (non-inline) backref the item ends after the
++ * header, and reading an inline ref would read the next item.
++ * Treat it as not owned, the conservative answer.
++ */
++ if (btrfs_item_size(leaf, slot) < sizeof(*ei) +
++ btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY)) {
++ ret = false;
++ goto out;
++ }
++ iref = (struct btrfs_extent_inline_ref *)(ei + 1);
++ type = btrfs_get_extent_inline_ref_type(leaf, iref,
++ BTRFS_REF_TYPE_DATA);
++ if (type != BTRFS_EXTENT_DATA_REF_KEY) {
++ ret = false;
++ goto out;
++ }
++ dref = (struct btrfs_extent_data_ref *)(&iref->offset);
++ if (btrfs_extent_data_ref_root(leaf, dref) != root_id ||
++ btrfs_extent_data_ref_objectid(leaf, dref) != ino ||
++ btrfs_extent_data_ref_count(leaf, dref) != 1) {
++ ret = false;
++ goto out;
++ }
++ path->slots[0]++;
++ }
++out:
++ btrfs_free_path(path);
++ return ret;
++}
++
++/*
++ * May [start, start + num_bytes) be written in place under stripe-exclusive
++ * allocation? Only when stripe_alloc_allow_rmw includes @which and every
++ * full stripe the range touches is isolated to @inode: an in-place write
++ * RMWs parity, so a crash can tear every extent sharing the stripe, and
++ * isolation confines that to the file that opted out of COW. Fast path:
++ * the stripe is in one of the inode's own NOCOW runs. Slow path: the
++ * committed extent tree proves sole ownership. Extents that fail stay
++ * COWed, and their rewrite lands in the inode's NOCOW run, so the next
++ * overwrite passes.
++ */
++bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
++ u64 num_bytes, u32 which)
++{
++ struct btrfs_fs_info *fs_info = inode->root->fs_info;
++ struct btrfs_block_group *bg;
++ const u64 root_id = btrfs_root_id(inode->root);
++ const u64 ino = btrfs_ino(inode);
++ u64 fsl;
++ u64 cur;
++ u64 end;
++ bool ret = true;
++
++ if (!(btrfs_stripe_allow_rmw(fs_info) & which))
++ return false;
++ bg = btrfs_lookup_block_group(fs_info, start);
++ if (!bg)
++ return false;
++ if (!btrfs_is_stripe_alloc_bg(bg)) {
++ /* Not a raid56 data group: nothing forces COW here anyway. */
++ btrfs_put_block_group(bg);
++ return true;
++ }
++
++ fsl = bg->full_stripe_len;
++ cur = bg->start + round_down(start - bg->start, fsl);
++ end = start + num_bytes;
++ while (cur < end) {
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ int verdict = 0; /* 0 = unknown, 1 = ok, -1 = foreign */
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (cur < run->start || cur >= run->end)
++ continue;
++ if (run->class == BTRFS_STRIPE_RUN_NOCOW &&
++ run->owner == ino)
++ verdict = 1;
++ else
++ verdict = -1;
++ break;
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++
++ if (verdict == 0 &&
++ !stripe_extents_owned_by(fs_info, root_id, ino, cur, fsl))
++ verdict = -1;
++ if (verdict < 0) {
++ ret = false;
++ break;
++ }
++ cur += fsl;
++ }
++ btrfs_put_block_group(bg);
++ return ret;
++}
++
+ /*
+ * Lower an allocation ceiling to the end of the last live sector at or above
+ * @floor. Sectors between it and the frontier were allocated and abandoned:
+@@ -1478,6 +1708,11 @@ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ * the commit drain already waits for and everything above it is dead space
+ * padding may fill.
+ */
++bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
++{
++ return btrfs_stripe_open_run_class(fs_info, logical, NULL);
++}
++
+ /*
+ * The part of [*start, *start + *len) that @run owns and tracks in its
+ * written map: inside [run->start, run->end) -- the map itself reaches
+@@ -1595,7 +1830,8 @@ bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
+ return ret;
+ }
+
+-bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
++bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
++ enum btrfs_stripe_run_class *class)
+ {
+ struct btrfs_block_group *bg;
+ struct btrfs_open_stripe_run *run;
+@@ -1608,6 +1844,8 @@ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+ if (logical >= run->start && logical < run->end) {
++ if (class)
++ *class = run->class;
+ ret = true;
+ break;
+ }
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 52dfab2a188ca..195864599c316 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -132,6 +132,13 @@ enum btrfs_block_group_flags {
+ * counter must be rescanned at commit (stripe_alloc only).
+ */
+ BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY,
++ /*
++ * The group has hosted NOCOW-class stripe runs. When
++ * stripe_alloc_allow_rmw permits it, isolated nodatacow/prealloc
++ * extents are overwritten in place after their runs drain, so the
++ * write-hole debug check skips such groups (sticky, debug only).
++ */
++ BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED,
+ /*
+ * A RAID5/6 group with a single data stripe, which is mapped as
+ * RAID1/RAID1C3 (its chunk map's type differs from on_disk_type). Its
+@@ -489,6 +496,8 @@ void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
+ u64 len);
+ bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
+ u64 stripe_start, u64 stripe_len);
++bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
++ enum btrfs_stripe_run_class *class);
+ 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);
+@@ -518,6 +527,9 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ u64 stripe_len, unsigned long *dead,
+ 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);
++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);
+ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 6a1e26eb8278b..524c803716aff 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4332,6 +4332,9 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
+ if (ret == -ENOMEM)
+ return ret;
+ if (!ret) {
++ if (ffe_ctl->steer_class == BTRFS_STRIPE_RUN_NOCOW)
++ set_bit(BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED,
++ &block_group->runtime_flags);
+ stripe_split_taken(ffe_ctl, num_bytes);
+ WRITE_ONCE(steer_inode->log_run_hint, offset);
+ ffe_ctl->found_offset = offset;
+diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
+index 7d1f84afe6cf3..73941a48cf4d7 100644
+--- a/fs/btrfs/file.c
++++ b/fs/btrfs/file.c
+@@ -1557,6 +1557,8 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
+ * one fsync is taken as a signal that more will follow.
+ */
+ if (btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
++ !(btrfs_stripe_allow_rmw(fs_info) &
++ BTRFS_STRIPE_RMW_FSYNC) &&
+ !test_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags))
+ set_bit(BTRFS_INODE_LOG_ALLOC, &inode->runtime_flags);
+
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 015f492b1f5d3..b23133fff440b 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -283,6 +283,18 @@ enum {
+ BTRFS_MOUNT_STRIPE_ALLOC = (1ULL << 34),
+ };
+
++/*
++ * Cases in which stripe_alloc may permit the legacy unsafe RMW-in-place
++ * (the write hole returns for the stripes such a write touches, confined
++ * as each case's machinery allows). Set from the
++ * btrfs.stripe_alloc_allow_rmw property.
++ */
++enum {
++ BTRFS_STRIPE_RMW_NODATACOW = (1U << 0),
++ BTRFS_STRIPE_RMW_PREALLOC = (1U << 1),
++ BTRFS_STRIPE_RMW_FSYNC = (1U << 2),
++};
++
+ /* These mount options require a full read-only fs, no new transaction is allowed. */
+ #define BTRFS_MOUNT_FULL_RO_MASK \
+ (BTRFS_MOUNT_NOLOGREPLAY | \
+@@ -893,6 +905,8 @@ struct btrfs_fs_info {
+ atomic64_t reloc_run_retained;
+ atomic64_t reloc_run_released;
+ } stripe_run_stats;
++ /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
++ u32 stripe_rmw_prop;
+ /*
+ * Park deadlines, ms (sysfs); 0 disables parking for that class. See
+ * rbio_try_park().
+@@ -1334,6 +1348,13 @@ static inline int btrfs_need_cleaner_sleep(const struct btrfs_fs_info *fs_info)
+ btrfs_fs_closing(fs_info);
+ }
+
++static inline u32 btrfs_stripe_allow_rmw(const struct btrfs_fs_info *fs_info)
++{
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return 0;
++ return READ_ONCE(fs_info->stripe_rmw_prop);
++}
++
+ static inline void btrfs_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
+ {
+ clear_and_wake_up_bit(BTRFS_FS_UNFINISHED_DROPS, &fs_info->flags);
+diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
+index 56e516441be7e..60c44c371d6bd 100644
+--- a/fs/btrfs/inode.c
++++ b/fs/btrfs/inode.c
+@@ -1888,9 +1888,19 @@ static int can_nocow_file_extent(struct btrfs_path *path,
+ * data relocation inode is exempt: its preallocated extents live in
+ * relocation-class stripe runs that never share stripes with other
+ * data, and relocation depends on its writes landing in place.
++ * When the btrfs.stripe_alloc_allow_rmw property allows it for
++ * nodatacow or prealloc extents, an extent whose stripes are isolated
++ * to this inode may be written in place after all: the write hole it
++ * reintroduces can tear only the writing file's own data, which is
++ * the nodatacow/prealloc contract.
+ */
+ if (!btrfs_is_data_reloc_root(root) &&
+- btrfs_stripe_alloc_forces_cow(root->fs_info, io_start))
++ btrfs_stripe_alloc_forces_cow(root->fs_info, io_start) &&
++ !btrfs_stripe_nocow_writable(inode, io_start,
++ args->file_extent.num_bytes,
++ extent_type == BTRFS_FILE_EXTENT_PREALLOC ?
++ BTRFS_STRIPE_RMW_PREALLOC :
++ BTRFS_STRIPE_RMW_NODATACOW))
+ goto out;
+
+ /*
+diff --git a/fs/btrfs/props.c b/fs/btrfs/props.c
+index 334657a98fdc2..741ccacb42f84 100644
+--- a/fs/btrfs/props.c
++++ b/fs/btrfs/props.c
+@@ -469,6 +469,40 @@ static const char *prop_stripe_alloc_extract(const struct btrfs_inode *inode)
+ return NULL;
+ }
+
++static int prop_stripe_rmw_validate(const struct btrfs_inode *inode,
++ const char *value, size_t len)
++{
++ u32 mask;
++
++ if (!prop_stripe_alloc_scope_ok(inode))
++ return -EINVAL;
++ if (!value || len == 0)
++ return 0;
++ return btrfs_parse_stripe_rmw(value, len, &mask);
++}
++
++static int prop_stripe_rmw_apply(struct btrfs_inode *inode,
++ const char *value, size_t len)
++{
++ struct btrfs_fs_info *fs_info = inode->root->fs_info;
++ u32 mask = 0;
++
++ /* Ignore stray copies; only the top-level root carries policy. */
++ if (!prop_stripe_alloc_scope_ok(inode))
++ return 0;
++ if (value && len &&
++ btrfs_parse_stripe_rmw(value, len, &mask))
++ return -EINVAL;
++ WRITE_ONCE(fs_info->stripe_rmw_prop, mask);
++ return 0;
++}
++
++static const char *prop_stripe_rmw_extract(const struct btrfs_inode *inode)
++{
++ /* Not inheritable; nothing regenerates the value from inode state. */
++ return NULL;
++}
++
+ static bool prop_stripe_alloc_ignore(const struct btrfs_inode *inode)
+ {
+ return false;
+@@ -505,6 +539,14 @@ static struct prop_handler prop_handlers[] = {
+ .ignore = prop_stripe_alloc_ignore,
+ .inheritable = 0
+ },
++ {
++ .xattr_name = XATTR_BTRFS_PREFIX "stripe_alloc_allow_rmw",
++ .validate = prop_stripe_rmw_validate,
++ .apply = prop_stripe_rmw_apply,
++ .extract = prop_stripe_rmw_extract,
++ .ignore = prop_stripe_alloc_ignore,
++ .inheritable = 0
++ },
+ };
+
+ int btrfs_inode_inherit_props(struct btrfs_trans_handle *trans,
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 3c702231c6f44..1dea8aa3ef539 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -1000,8 +1000,11 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ const unsigned int sync_timeout_ms =
+ READ_ONCE(fs_info->stripe_park_sync_timeout_ms);
+ unsigned int timeout_ms = READ_ONCE(fs_info->stripe_park_timeout_ms);
++ enum btrfs_stripe_run_class class;
+
+- if (!btrfs_stripe_in_open_run(fs_info, rbio->bioc->full_stripe_logical))
++ if (!btrfs_stripe_open_run_class(fs_info,
++ rbio->bioc->full_stripe_logical,
++ &class))
+ return false;
+
+ spin_lock(&rbio->bio_list_lock);
+@@ -1013,6 +1016,15 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ if (timeout_ms == 0)
+ return false;
+
++ /*
++ * A sync write into a nodatacow inode's private run has a waiter and
++ * nothing to merge with (in-place overwrites arrive one fsync at a
++ * time): park only async writeback there.
++ */
++ if (class == BTRFS_STRIPE_RUN_NOCOW &&
++ timeout_ms == BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS)
++ return false;
++
+ /*
+ * A sync rbio whose submission batch was already merged by its
+ * unplug callback has nothing more coming from its submitter; the
+--
+2.47.3
+
+++ /dev/null
-From a453b51b9a437ef2b973388abb60efb07a27d2a4 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:00 -0400
-Subject: [RFC PATCH 040/116] btrfs: stripe_alloc: keep the admitted bytes
- placeable when a group goes read-only
-To: linux-btrfs@vger.kernel.org
-
-inc_block_group_ro() checks that the rest of the space_info can absorb
-the group's free space in bytes. Under stripe_alloc the data admission
-gate promised writers whole stripes: bytes_may_use plus the held margin
-against bytes_stripe_claimable. Making a group read-only removes its
-claimable stripes from that supply after the promise was made, so with
-the reclaim worker relocating a group at the fill edge, admitted
-writebacks found no stripe and were dropped:
-
- allocation failed flags 129, wanted 8192 ...
- space_info DATA has 450560 free, is full ... block group ... [readonly]
-
-Refuse the read-only transition while the admitted bytes would no
-longer fit in the claimable supply without this group. Scrub, balance
-and reclaim retry later; this is the fail-early direction and only bites
-transiently at the edge, since bytes_may_use drains as writeback
-completes.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 25 +++++++++++++++++++++++++
- 1 file changed, 25 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 989cbbaa33c38..2ca280f3d24bd 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -3881,6 +3881,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
---
-2.47.3
-
+++ /dev/null
-From f43d637979ad59db61287dd03e80db53252d0b77 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:01 -0400
-Subject: [RFC PATCH 041/116] btrfs: stripe_alloc: never let relocation wait on
- the whole-stripe gate
-To: linux-btrfs@vger.kernel.org
-
-The data admission gate refuses reservations that would not fit in the
-whole-stripe supply, and a refused reservation waits as a flush ticket
-for space to appear. Relocation reserves its prealloc clusters through
-the same path, so at the fill edge the reclaim worker sat for half an
-hour in
-
- btrfs_reclaim_bgs_work -> btrfs_relocate_chunk -> relocate_block_group
- -> relocate_file_extent_cluster -> prealloc_file_extent_cluster
- -> btrfs_alloc_data_chunk_ondemand -> __reserve_bytes
-
-holding the exclusive operation and the group it was emptying, while the
-gate waited for exactly the stripes that relocation was supposed to
-free. User writers queued behind that head ticket and unmount hung on
-their writeback.
-
-Exempting relocation from the gate altogether is wrong too: it then
-takes whole stripes that admitted writers were promised, and their
-writebacks are dropped at the edge. Give relocation its own flush type,
-BTRFS_RESERVE_FLUSH_DATA_RELOC, that is subject to the same bound but
-never waits: if the reservation does not fit beyond the bytes already
-promised it fails at once, the relocation is abandoned cleanly and is
-retried when the trigger next finds room. Zoned relocation already
-has a flush type of its own for the same reason.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/delalloc-space.c | 4 ++++
- fs/btrfs/space-info.c | 16 +++++++++++++---
- fs/btrfs/space-info.h | 8 ++++++++
- 3 files changed, 25 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/delalloc-space.c b/fs/btrfs/delalloc-space.c
-index 8aa5d113ccac8..27b492cb0c1d8 100644
---- a/fs/btrfs/delalloc-space.c
-+++ b/fs/btrfs/delalloc-space.c
-@@ -129,6 +129,10 @@ int btrfs_alloc_data_chunk_ondemand(const struct btrfs_inode *inode, u64 bytes)
- 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);
-
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 53a4d3c3decfb..1cc48844089f1 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -1818,6 +1818,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);
-@@ -1895,8 +1896,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);
- }
-
- /*
-@@ -1938,7 +1944,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;
-@@ -2096,9 +2103,12 @@ int btrfs_reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
- int ret;
-
- ASSERT(flush == BTRFS_RESERVE_FLUSH_DATA ||
-+ flush == BTRFS_RESERVE_FLUSH_DATA_RELOC ||
- 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);
-
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index c8143f39f89b0..867c0b9cc3eed 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -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_ALL,
-
- /*
---
-2.47.3
-
--- /dev/null
+From cafd58d8083939417609bbb04bd6816fef59f62f Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:50 -0400
+Subject: [RFC PATCH 41/85] btrfs: stripe_alloc: tunable park deadlines, and
+ say why padding declined (allow_rmw part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: tunable park deadlines, and say why
+padding declined" (earlier in this series) that need code from "btrfs:
+stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow
+extents", which comes after it in this series: they are applied here,
+once "btrfs: stripe_alloc: allow-rmw policy, and write-in-place for
+isolated nocow extents" is in, instead of with the rest of "btrfs:
+stripe_alloc: tunable park deadlines, and say why padding declined".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/raid56.c | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 1dea8aa3ef539..169e1cccd73cd 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -1022,7 +1022,7 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
+ * time): park only async writeback there.
+ */
+ if (class == BTRFS_STRIPE_RUN_NOCOW &&
+- timeout_ms == BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS)
++ timeout_ms == sync_timeout_ms)
+ return false;
+
+ /*
+--
+2.47.3
+
+++ /dev/null
-From 306fa981802bac422d18668da6b26b483cabaebf Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:02 -0400
-Subject: [RFC PATCH 042/116] btrfs: stripe_alloc: give a queued stripe group a
- chunk to relocate into when the supply is short
-To: linux-btrfs@vger.kernel.org
-
-A relocation data reservation never takes a ticket, so the flush state
-machine never runs for it, and with it goes the chunk allocation every
-other data reservation gets when its space_info is full. That did not
-show while other groups still had whole stripes. Once the reclaim
-worker had emptied and removed five of seven data groups, the two left
-were the trapped ones it was queued to move next, their claimable
-supply was under a megabyte, and every relocation failed with ENOSPC
-while 2.6 GiB of the devices sat unallocated.
-
-Have the reclaim worker allocate one chunk before it relocates a stripe
-group whose live bytes exceed the claimable supply of the other groups.
-An earlier version did this from the reservation path instead, for any
-refused relocation reservation; that let a live device shrink -- which
-relocates into space it does not have and is meant to fail cleanly at
-that reservation -- grow the data space_info chunk by chunk until the
-raid1 metadata had nowhere to go and the relocation aborted the
-transaction in merge_reloc_roots() (6.18 acceptance suite T6). The
-worker is the one caller that should be making room.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 28 ++++++++++++++++++++++++++++
- 1 file changed, 28 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 2ca280f3d24bd..186f06965412e 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -4429,6 +4429,34 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- u64 old_total;
- int ret = 0;
-
-+ /*
-+ * A stripe_alloc / stripe_meta group's live extents can only move into
-+ * whole free stripes, and relocation never waits for them. Once the
-+ * worker has emptied and removed enough groups, the ones left are the
-+ * trapped ones it was queued to move next with next to nothing
-+ * claimable, while gigabytes may sit unallocated: give it a chunk to
-+ * relocate into, once per attempt. Here rather than in the reservation
-+ * path so that a device shrink, which relocates without room by design,
-+ * keeps failing cleanly instead of growing into space it cannot use.
-+ */
-+ if (btrfs_is_stripe_alloc_bg(bg) || btrfs_is_stripe_meta_bg(bg)) {
-+ u64 elsewhere = READ_ONCE(space_info->bytes_stripe_claimable);
-+
-+ elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
-+ if (elsewhere < READ_ONCE(bg->used)) {
-+ struct btrfs_trans_handle *trans;
-+
-+ trans = btrfs_join_transaction(fs_info->tree_root);
-+ if (!IS_ERR(trans)) {
-+ btrfs_chunk_alloc(trans, space_info,
-+ btrfs_get_alloc_profile(fs_info,
-+ space_info->flags),
-+ CHUNK_ALLOC_FORCE);
-+ btrfs_end_transaction(trans);
-+ }
-+ }
-+ }
-+
- /* Don't race with allocators so take the groups_sem */
- down_write(&space_info->groups_sem);
-
---
-2.47.3
-
--- /dev/null
+From ee51d53e1180106cedb240a3133381863b5ef054 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:53 -0400
+Subject: [RFC PATCH 42/85] btrfs: stripe_alloc: track per-sector liveness and
+ pad from the map (allow_rmw part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: track per-sector liveness and pad
+from the map" (earlier in this series) that need code from "btrfs:
+stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow
+extents", which comes after it in this series: they are applied here,
+once "btrfs: stripe_alloc: allow-rmw policy, and write-in-place for
+isolated nocow extents" is in, instead of with the rest of "btrfs:
+stripe_alloc: track per-sector liveness and pad from the map".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 18 ++++++++++++------
+ 1 file changed, 12 insertions(+), 6 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index dcb49e5abfc92..e4a201c89d44a 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1843,12 +1843,18 @@ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
+ return false;
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+- if (logical >= run->start && logical < run->end) {
+- if (class)
+- *class = run->class;
+- ret = true;
+- break;
+- }
++ if (logical < run->start || logical >= run->end)
++ continue;
++ /*
++ * Draining runs match too (see btrfs_stripe_in_open_run()):
++ * a closed run's end is shrunk to its frontier, so a write
++ * into it is below the frontier and its stripes are still
++ * exclusive.
++ */
++ if (class)
++ *class = run->class;
++ ret = true;
++ break;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ btrfs_put_block_group(bg);
+--
+2.47.3
+
+++ /dev/null
-From b32e47af319c32883e41c50ac16c18d3088e6539 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:03 -0400
-Subject: [RFC PATCH 043/116] btrfs: stripe_alloc: charge relocation a margin
- per reservation, not per extent
-To: linux-btrfs@vger.kernel.org
-
-The stripe margin is one full stripe per outstanding extent, collateral
-for the tails a commit traps under delalloc that has not been placed
-yet. The data relocation inode charged it too, for extents that are
-already allocated: relocating a group of 16-48K files inflated
-bytes_stripe_margin to 150 MB, more than the claimable supply, so the
-next cluster reservation failed at once and the reclaim trigger retried
-the same six groups 130 times in 15 minutes while the margin swung
-between zero and 150 MB with nothing dirty.
-
-Do not charge the per-extent margin for the data relocation root.
-Instead, when a relocation reservation is checked against the
-whole-stripe supply, round it up to whole stripes and add one stripe of
-collateral, which is what relocation's own open runs can lose at the
-next commit.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/space-info.c | 47 +++++++++++++++++++++++++++++--------------
- 1 file changed, 32 insertions(+), 15 deletions(-)
-
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 1cc48844089f1..9ff38370833e9 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -453,6 +453,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) {
-@@ -665,7 +671,8 @@ static void remove_ticket(struct btrfs_space_info *space_info,
- * FLUSH_DATA ticket retry). A later phase adds bytes_stripe_open to the bound to
- * match statfs exactly and recover that space.
- */
--static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 bytes)
-+static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 bytes,
-+ bool reloc)
- {
- struct btrfs_fs_info *fs_info = space_info->fs_info;
- const u64 unit = READ_ONCE(fs_info->stripe_margin_unit);
-@@ -674,19 +681,28 @@ static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 byte
- !(space_info->flags & BTRFS_BLOCK_GROUP_DATA) || !unit)
- return true;
- /*
-- * An allocation of @bytes that opens a run claims
-- * round_up(bytes, unit) whole stripes. A delalloc write's
-- * margin (below) covers that for itself, but a
-- * preallocation holds no margin -- it has no outstanding
-- * extent -- and was admitted for its byte size alone, so
-- * each fallocate() short of a stripe took up to a stripe
-- * more than the gate had charged, out of the supply behind
-- * writes already admitted: at the fill edge those writes
-- * then found no stripe and were dropped. Charge the
-- * roundup. (The excess is not held past admission; a
-- * preallocation allocates in the same call.)
-+ * 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.
- */
-- bytes = round_up(bytes, unit);
-+ if (reloc) {
-+ bytes = round_up(bytes, unit) + unit;
-+ } else {
-+ /*
-+ * An allocation of @bytes that opens a run claims
-+ * round_up(bytes, unit) whole stripes. A delalloc write's
-+ * margin (below) covers that for itself, but a
-+ * preallocation holds no margin -- it has no outstanding
-+ * extent -- and was admitted for its byte size alone, so
-+ * each fallocate() short of a stripe took up to a stripe
-+ * more than the gate had charged, out of the supply behind
-+ * writes already admitted: at the fill edge those writes
-+ * then found no stripe and were dropped. Charge the
-+ * roundup. (The excess is not held past admission; a
-+ * preallocation allocates in the same call.)
-+ */
-+ bytes = round_up(bytes, unit);
-+ }
- /*
- * Every outstanding data extent holds a whole-stripe margin
- * (bytes_stripe_margin) as collateral against the commit that
-@@ -731,7 +747,7 @@ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info)
- /* 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)) &&
-- stripe_claimable_admit(space_info, ticket->bytes)) {
-+ stripe_claimable_admit(space_info, ticket->bytes, false)) {
- btrfs_space_info_update_bytes_may_use(space_info, ticket->bytes);
- remove_ticket(space_info, ticket, 0);
- space_info->tickets_id++;
-@@ -1971,7 +1987,8 @@ 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)) &&
-- stripe_claimable_admit(space_info, orig_bytes)) {
-+ stripe_claimable_admit(space_info, orig_bytes,
-+ flush == BTRFS_RESERVE_FLUSH_DATA_RELOC)) {
- btrfs_space_info_update_bytes_may_use(space_info, orig_bytes);
- ret = 0;
- }
---
-2.47.3
-
--- /dev/null
+From 17c29738aeed56dea82bcc78e661387c315c5e27 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:41 -0400
+Subject: [RFC PATCH 43/85] btrfs: stripe_alloc: persist nocow runs across
+ commits and remounts
+To: linux-btrfs@vger.kernel.org
+
+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 | 336 +++++++++++++++++++++++++++++-
+ fs/btrfs/block-group.h | 14 +-
+ fs/btrfs/extent-tree.c | 29 ++-
+ fs/btrfs/free-space-cache.c | 85 ++++++++
+ fs/btrfs/free-space-cache.h | 2 +
+ fs/btrfs/fs.h | 2 +
+ fs/btrfs/inode.c | 4 +-
+ fs/btrfs/sysfs.c | 6 +-
+ fs/btrfs/tests/free-space-tests.c | 29 +++
+ 9 files changed, 480 insertions(+), 27 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index e4a201c89d44a..caca03bab794a 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -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 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ * 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 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg, u64 ino,
+ 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 @@ static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
+ * 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
+@@ -2011,6 +2294,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;
+@@ -2023,6 +2307,20 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
+
+ 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)
+@@ -2061,6 +2359,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)
+@@ -3771,6 +4072,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);
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 195864599c316..0371749c8ad0a 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -473,10 +473,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,
+@@ -501,6 +505,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);
+ /*
+@@ -528,7 +534,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);
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 524c803716aff..5a464351b72de 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4327,8 +4327,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) {
+@@ -5097,17 +5098,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,
+@@ -5120,6 +5126,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);
+ }
+ }
+
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 76877414bf7fc..5a0bd884dcc35 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1749,6 +1749,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);
+ }
+
+@@ -2493,6 +2494,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.
+ *
+diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
+index d89127c24f11e..a1de48848d6b3 100644
+--- a/fs/btrfs/free-space-cache.h
++++ b/fs/btrfs/free-space-cache.h
+@@ -111,6 +111,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);
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index b23133fff440b..3981823c3b879 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -901,6 +901,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;
+diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
+index 60c44c371d6bd..8b7fd4704349a 100644
+--- a/fs/btrfs/inode.c
++++ b/fs/btrfs/inode.c
+@@ -1900,7 +1900,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;
+
+ /*
+@@ -5706,6 +5707,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 &&
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 17570b99b1a41..325f6cb1e7167 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1179,11 +1179,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);
+
+diff --git a/fs/btrfs/tests/free-space-tests.c b/fs/btrfs/tests/free-space-tests.c
+index 4022cadcd9e4c..5da244e148321 100644
+--- a/fs/btrfs/tests/free-space-tests.c
++++ b/fs/btrfs/tests/free-space-tests.c
+@@ -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);
+--
+2.47.3
+
--- /dev/null
+From fc70bed6ee5389cfaa680f350387c570fae0567d Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:45 -0400
+Subject: [RFC PATCH 44/85] btrfs: stripe_alloc: count open stripe run
+ remainders against data reservations (allow_rmw part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: count open stripe run remainders
+against data reservations" (earlier in this series) that need code from
+"btrfs: stripe_alloc: persist nocow runs across commits and remounts",
+which comes after it in this series: they are applied here, once "btrfs:
+stripe_alloc: persist nocow runs across commits and remounts" is in,
+instead of with the rest of "btrfs: stripe_alloc: count open stripe run
+remainders against data reservations".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index caca03bab794a..dbf5073e07869 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1840,6 +1840,7 @@ void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
+ btrfs_get_block_group(bg);
+ spin_unlock(&fs_info->open_stripe_lock);
+ btrfs_add_free_space(bg, tail_start, tail_len);
++ stripe_open_remainder_sync(bg);
+ btrfs_put_block_group(bg);
+ goto restart;
+ }
+--
+2.47.3
+
+++ /dev/null
-From 9d0303ebca525fb6bcfdbdf18579bf824c6e8ce2 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:04 -0400
-Subject: [RFC PATCH 044/116] btrfs: stripe_alloc: keep the relocation group's
- stripes out of the admission supply
-To: linux-btrfs@vger.kernel.org
-
-do_allocation_stripe() dedicates one block group to data relocation
-(fs_info->data_reloc_bg, as the zoned allocator does): while a
-relocation runs, its allocations go only there and everyone else's skip
-it, until the relocation finishes or the group fills. The admission
-gate did not know: it counted that group's claimable stripes in the
-supply for ordinary writes. At the fill edge with background reclaim
-running, the dedicated group was the only one with claimable stripes
-left, ordinary writes were admitted against them, and their writebacks
-were dropped:
-
- stripe_alloc DROP DUMP: sinfo may_use 3837952 claimable 561053696 ...
- bg 7048265728 ... claimable 561053696 ... runs open <- data_reloc_bg
- every other group: claimable 0
-
-Track the dedicated group's claimable bytes in the space_info
-(bytes_stripe_claimable_reloc: set when a group is dedicated, cleared
-when the dedication is released or the group is removed, followed by
-the per-group claimable deltas and re-summed by the commit rescan) and
-admit ordinary reservations against the supply minus that amount.
-
-Relocation itself is admitted against the whole supply, dedicated group
-included. Confining it to the dedicated group's bytes was tried first
-and refused relocation as soon as that group -- the first one the
-allocator visits, often holding only a couple of free stripes -- ran
-short of a reservation's whole stripes plus one, while hundreds of
-megabytes of whole stripes sat in other groups: the allocator would
-have dropped the dedication and moved on had it been asked, but the
-gate failed each queued group with ENOSPC within fifteen milliseconds
-and the reclaim worker retried every thirty seconds, with no relocation
-ever completing. bytes_may_use is one counter for both sides, so the
-sum admitted still fits in the supply.
-
-Assisted-by: Claude:claude-fable-5
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/block-group.c | 21 +++++++++-
- fs/btrfs/extent-tree.c | 12 +++++-
- fs/btrfs/free-space-cache.c | 8 ++++
- fs/btrfs/space-info.c | 83 ++++++++++++++++++++++---------------
- fs/btrfs/space-info.h | 5 +++
- 5 files changed, 94 insertions(+), 35 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 186f06965412e..f100a2badde76 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2669,6 +2669,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))
-@@ -2704,6 +2705,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);
- }
- }
- }
-@@ -2712,6 +2716,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
-@@ -2814,10 +2819,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);
-+ }
- }
-
- /*
-@@ -2841,6 +2855,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);
- }
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 921c2c1956f70..a8dc64824034b 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4258,6 +4258,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 offset;
- bool skip = false;
-@@ -4297,14 +4298,23 @@ 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 !=
- (block_group->start == fs_info->data_reloc_bg)))
- 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;
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index e4671fc7e5c15..4533159a01929 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1543,6 +1543,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);
- }
-
-@@ -2182,6 +2188,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);
- }
- }
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 9ff38370833e9..1e9946369c184 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -685,42 +685,59 @@ static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 byte
- * placed): charge it whole stripes plus one, the tail its own open
- * runs can lose at the next commit.
- */
-- if (reloc) {
-- bytes = round_up(bytes, unit) + unit;
-- } else {
-+ {
-+ 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.
-+ * Relocation prefers its dedicated group, but when
-+ * that group runs dry the allocator drops the
-+ * dedication and moves on to another group; confining
-+ * admission to the dedicated group's claimable bytes
-+ * refused relocation (ENOSPC after a handful of 16K
-+ * clusters, retried every 30 seconds) while hundreds
-+ * of megabytes of whole stripes sat in other groups.
-+ */
-+ bytes = round_up(bytes, unit) + unit;
-+ } else {
-+ /* ...and that group is out of reach for everyone else */
-+ supply -= min(supply, dedicated);
-+ /*
-+ * An allocation of @bytes that opens a run claims
-+ * round_up(bytes, unit) whole stripes. A delalloc write's
-+ * margin (below) covers that for itself, but a
-+ * preallocation holds no margin -- it has no outstanding
-+ * extent -- and was admitted for its byte size alone, so
-+ * each fallocate() short of a stripe took up to a stripe
-+ * more than the gate had charged, out of the supply behind
-+ * writes already admitted: at the fill edge those writes
-+ * then found no stripe and were dropped. Charge the
-+ * roundup. (The excess is not held past admission; a
-+ * preallocation allocates in the same call.)
-+ */
-+ bytes = round_up(bytes, unit);
-+ }
- /*
-- * An allocation of @bytes that opens a run claims
-- * round_up(bytes, unit) whole stripes. A delalloc write's
-- * margin (below) covers that for itself, but a
-- * preallocation holds no margin -- it has no outstanding
-- * extent -- and was admitted for its byte size alone, so
-- * each fallocate() short of a stripe took up to a stripe
-- * more than the gate had charged, out of the supply behind
-- * writes already admitted: at the fill edge those writes
-- * then found no stripe and were dropped. Charge the
-- * roundup. (The excess is not held past admission; a
-- * preallocation allocates in the same call.)
-+ * Every outstanding data extent holds a whole-stripe margin
-+ * (bytes_stripe_margin) as collateral against the commit that
-+ * closes its open run and traps the tail.
-+ * btrfs_space_info_used() charges that margin against
-+ * total_bytes, but what an admitted write actually draws on is
-+ * the whole-stripe supply: left out of this bound, the stripes
-+ * behind bytes admitted earlier are lost at the next commit, and
-+ * a write that passed admission finds no stripe at writeback
-+ * (ENOSPC despite reservation margin, data dropped). The margin
-+ * is owed to the writers already admitted, so every later
-+ * admission has to respect it -- relocation included: admitted
-+ * without it at the fill edge, relocation consumed the whole
-+ * stripes that small writes' claims then needed, and those
-+ * writes were dropped in bursts that tracked the relocations.
- */
-- bytes = round_up(bytes, unit);
-+ bytes += space_info->bytes_stripe_margin;
-+ return space_info->bytes_may_use + bytes <= supply;
- }
-- /*
-- * Every outstanding data extent holds a whole-stripe margin
-- * (bytes_stripe_margin) as collateral against the commit that
-- * closes its open run and traps the tail.
-- * btrfs_space_info_used() charges that margin against
-- * total_bytes, but what an admitted write actually draws on is
-- * the whole-stripe supply: left out of this bound, the stripes
-- * behind bytes admitted earlier are lost at the next commit, and
-- * a write that passed admission finds no stripe at writeback
-- * (ENOSPC despite reservation margin, data dropped). The margin
-- * is owed to the writers already admitted, so every later
-- * admission has to respect it -- relocation included: admitted
-- * without it at the fill edge, relocation consumed the whole
-- * stripes that small writes' claims then needed, and those
-- * writes were dropped in bursts that tracked the relocations.
-- */
-- bytes += space_info->bytes_stripe_margin;
-- return space_info->bytes_may_use + bytes <= space_info->bytes_stripe_claimable;
- }
-
- /*
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 867c0b9cc3eed..5abb8fd072b3c 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -166,6 +166,11 @@ struct btrfs_space_info {
- cannot admit writes against it, and
- subtracted in statfs (from a different
- base -- the free space cache walk). */
-+ 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
---
-2.47.3
-
--- /dev/null
+From d7415060a9e2c225a14c877d1d6e26568a78b984 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:06 -0400
+Subject: [RFC PATCH 45/85] btrfs: stripe_alloc: hand groups full of trapped
+ free space to the reclaim worker
+To: linux-btrfs@vger.kernel.org
+
+Zoned filesystems mark a block group for reclaim as soon as its
+unusable bytes reach bg_reclaim_threshold percent of its capacity, so
+space that can no longer be written is recycled without an operator
+running balance. stripe_alloc had no equivalent. The non-zoned
+trigger consults the threshold only where a free drops a group's used
+bytes across it, and the test hosts were already running every mount
+with bg_reclaim_threshold=75 when this was measured: trapped tails
+still accumulated until balance (1.86 GiB of 6.5 GiB after a few hours
+of churn), while every byte-based check counted them as free, because
+that predicate keys on used bytes only and fires only at the crossing
+-- a group hollowed out after it was already below the threshold, or
+one whose used bytes never moved while its stripes trapped, is never
+queued, and a group at the same used fraction with nothing trapped is.
+
+Mark a group for the existing reclaim worker when its trapped bytes
+reach the threshold; the worker re-checks with
+should_reclaim_block_group(). The predicate, factored out as
+btrfs_stripe_bg_wants_reclaim(), compares the trapped bytes with the
+group's free space (length minus used) rather than its length -- a
+stripe_alloc group also holds claimable whole stripes, and in practice
+fragmentation settles around two thirds of the group trapped with a
+fifth used, nothing left worth writing into yet below any sensible
+fraction of the length -- and requires room for the group's live data
+in the rest of the claimable supply after the bytes already promised to
+admitted writers, so a group that cannot be relocated is left alone
+until space is freed instead of being retried every commit while the
+read-only transitions starve writers.
+
+The trigger runs from the cleaner, which the transaction thread wakes
+every cycle whether or not a transaction exists, as well as at the
+commit-time rescan: on an idle filesystem nothing rescans, and a group
+already on another list (a chunk created in the running transaction is
+still on trans->new_bgs) cannot be linked to the reclaim list, so the
+five-minute hysteresis stamp is taken only when the mark actually
+lands. The worker re-checks whatever it takes, so a stale read costs at
+most one wasted attempt. bg_reclaim_threshold defaults to 0 on
+non-zoned filesystems, so nothing changes until the sysfs knob is set;
+the default is left for review. Relocation needs inc_block_group_ro()
+to succeed, hence the earlier fix.
+
+The worker does not defer a queued stripe group that has bytes reserved
+or pinned: it was queued for space no waiting frees, and under COW churn
+it can have blocks reserved or pinned at any moment (under stripe_meta,
+a metadata group always does).
+Relocation waits for in-flight allocations and writers on its own.
+
+The stripe_meta block group part of this change moved to
+"btrfs: stripe_meta: extend stripe reclaim to metadata block groups".
+
+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 | 94 +++++++++++++++++++++++++++++++++++--
+ fs/btrfs/block-group.h | 4 +-
+ fs/btrfs/free-space-cache.c | 63 +++++++++++++++++++++++++
+ fs/btrfs/free-space-cache.h | 1 +
+ 4 files changed, 157 insertions(+), 5 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index dbf5073e07869..32948c0ec5b33 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -4318,17 +4318,51 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ u64 old_total;
+ int ret = 0;
+
++ /*
++ * A stripe_alloc group's live extents can only move into
++ * whole free stripes. When the rest of the space_info has too few
++ * claimable bytes for them, allocate a chunk to relocate into, once per
++ * attempt. Done here rather than in the reservation path so that a
++ * device shrink, which relocates without spare room by design, still
++ * fails cleanly.
++ */
++ if (btrfs_is_stripe_alloc_bg(bg)) {
++ u64 elsewhere = READ_ONCE(space_info->bytes_stripe_claimable);
++
++ elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
++ if (elsewhere < READ_ONCE(bg->used)) {
++ struct btrfs_trans_handle *trans;
++
++ trans = btrfs_join_transaction(fs_info->tree_root);
++ if (!IS_ERR(trans)) {
++ btrfs_chunk_alloc(trans, space_info,
++ btrfs_get_alloc_profile(fs_info,
++ space_info->flags),
++ CHUNK_ALLOC_FORCE);
++ btrfs_end_transaction(trans);
++ }
++ }
++ }
++
+ /* Don't race with allocators so take the groups_sem */
+ down_write(&space_info->groups_sem);
+
+ spin_lock(&space_info->lock);
+ spin_lock(&bg->lock);
+- if (bg->reserved || bg->pinned || bg->ro) {
++ if (bg->ro ||
++ ((bg->reserved || bg->pinned) &&
++ !btrfs_is_stripe_alloc_bg(bg))) {
+ /*
+ * We want to bail if we made new allocations or have
+ * outstanding allocations in this block group. We do
+ * the ro check in case balance is currently acting on
+ * this block group.
++ *
++ * Not for a stripe_alloc group: under
++ * COW churn it always has blocks reserved or pinned,
++ * so the bail-out would defer it forever, while the
++ * trapped free space it was queued for only grows.
++ * Relocation waits for in-flight allocations itself.
+ */
+ spin_unlock(&bg->lock);
+ spin_unlock(&space_info->lock);
+@@ -4632,21 +4666,73 @@ void btrfs_reclaim_bgs_work(struct work_struct *work)
+ btrfs_reclaim_block_groups(fs_info, -1);
+ }
+
++/*
++ * Periodic re-evaluation of stripe_alloc groups from the
++ * cleaner. The commit-time rescan only sees groups whose free space changed
++ * in that transaction, and only when there is a transaction: a mark that
++ * did not land (the group was on another list) or a group the worker dropped
++ * would otherwise wait for the next commit, which an idle filesystem at the
++ * fill edge never produces. Same predicate and five-minute hysteresis as
++ * the rescan; the worker re-checks everything it takes.
++ */
++static void btrfs_stripe_reclaim_tick(struct btrfs_fs_info *fs_info)
++{
++ struct btrfs_space_info *sinfo;
++
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return;
++ list_for_each_entry(sinfo, &fs_info->space_info, list) {
++ int raid;
++
++ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
++ continue;
++ if (READ_ONCE(sinfo->bg_reclaim_threshold) <= 0)
++ continue;
++ down_read(&sinfo->groups_sem);
++ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
++ struct btrfs_block_group *bg;
++
++ if (!(btrfs_raid_array[raid].bg_flag &
++ BTRFS_BLOCK_GROUP_RAID56_MASK))
++ continue;
++ list_for_each_entry(bg, &sinfo->block_groups[raid],
++ list) {
++ if (bg->stripe_reclaim_jiffies &&
++ !time_after(jiffies,
++ bg->stripe_reclaim_jiffies +
++ 5 * 60 * HZ))
++ continue;
++ if (!btrfs_stripe_bg_wants_reclaim(bg))
++ continue;
++ spin_lock(&bg->lock);
++ if (btrfs_mark_bg_to_reclaim(bg))
++ bg->stripe_reclaim_jiffies = jiffies ?: 1;
++ spin_unlock(&bg->lock);
++ }
++ }
++ up_read(&sinfo->groups_sem);
++ }
++}
++
+ void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
+ {
+ btrfs_reclaim_sweep(fs_info);
++ btrfs_stripe_reclaim_tick(fs_info);
+ spin_lock(&fs_info->unused_bgs_lock);
+ if (!list_empty(&fs_info->reclaim_bgs))
+ queue_work(system_dfl_wq, &fs_info->reclaim_bgs_work);
+ spin_unlock(&fs_info->unused_bgs_lock);
+ }
+
+-void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
++/* Returns true when the group was linked to the reclaim list. */
++bool btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
+ {
+ struct btrfs_fs_info *fs_info = bg->fs_info;
+
+- if (btrfs_link_bg_list(bg, &fs_info->reclaim_bgs))
+- trace_btrfs_add_reclaim_block_group(bg);
++ if (!btrfs_link_bg_list(bg, &fs_info->reclaim_bgs))
++ return false;
++ trace_btrfs_add_reclaim_block_group(bg);
++ return true;
+ }
+
+ static int read_bg_from_eb(struct btrfs_fs_info *fs_info, const struct btrfs_key *key,
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 0371749c8ad0a..d9e6f295e0e7f 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -306,6 +306,8 @@ struct btrfs_block_group {
+ * under the same lock.
+ */
+ u64 stripe_stranded;
++ /* jiffies when the reclaim trigger last queued this group (stripe_alloc) */
++ unsigned long stripe_reclaim_jiffies;
+ /*
+ * Directly measured claimable supply: bytes of fully free, aligned
+ * whole stripes in the free space cache -- exactly what
+@@ -568,7 +570,7 @@ void btrfs_mark_bg_unused(struct btrfs_block_group *bg);
+ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limit);
+ void btrfs_reclaim_bgs_work(struct work_struct *work);
+ void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info);
+-void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg);
++bool btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg);
+ bool btrfs_reclaim_backoff_active(struct btrfs_space_info *space_info);
+ int btrfs_read_block_groups(struct btrfs_fs_info *info);
+ struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 5a0bd884dcc35..c49268bd5b01d 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -2375,6 +2375,45 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+ }
+
+
++/*
++ * Does this stripe_alloc group want the reclaim worker? Like
++ * zoned's zone_unusable reclaim: once enough of the group's FREE space is
++ * trapped in partially used stripes (zoned compares with the capacity, but a
++ * stripe group also holds claimable whole stripes), relocation packs the live
++ * extents into whole stripes elsewhere and frees the group. Only groups
++ * whose live data is below the same threshold are cheap enough to move, and
++ * only when that data fits in the claimable supply of the OTHER groups:
++ * relocation needs whole stripes too, and a group queued while there is
++ * nowhere to move it starves writers with read-only transitions and fails
++ * each time at the fill edge. The worker re-checks with
++ * should_reclaim_block_group(). Reads the counters without locks; the
++ * commit-time rescan calls it with fresh values, the cleaner's periodic
++ * re-evaluation with slightly stale ones, and either error is caught by
++ * the worker.
++ */
++bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
++{
++ struct btrfs_space_info *sinfo = bg->space_info;
++ const int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
++ const u64 used = READ_ONCE(bg->used);
++ const u64 trapped = READ_ONCE(bg->stripe_unusable);
++ u64 elsewhere;
++ u64 promised;
++
++ if (thresh <= 0 || bg->ro || !READ_ONCE(bg->stripe_unusable_ready))
++ return false;
++ if (trapped < mult_perc(bg->length - min(used, bg->length), thresh))
++ return false;
++ if (used >= mult_perc(bg->length, thresh))
++ return false;
++ elsewhere = READ_ONCE(sinfo->bytes_stripe_claimable);
++ promised = READ_ONCE(sinfo->bytes_may_use) +
++ READ_ONCE(sinfo->bytes_stripe_margin);
++ elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
++ elsewhere -= min(elsewhere, promised);
++ return elsewhere >= used;
++}
++
+ /*
+ * Recompute a stripe_alloc block group's trapped free space from a fresh scan
+ * and fold the change into the space_info total. Called at commit for groups
+@@ -2385,6 +2424,7 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
+ {
+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ bool reclaim = false;
+ u64 nstripes;
+ u32 *freep;
+
+@@ -2420,9 +2460,32 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
+ bg->stripe_unusable = trapped;
+ bg->stripe_claimable = scanned;
+ spin_unlock(&bg->space_info->lock);
++ /*
++ * Hand a group full of trapped free space to the reclaim
++ * worker (btrfs_stripe_bg_wants_reclaim()), but not again
++ * within five minutes of the last mark: a relocation that
++ * failed at the fill edge is not going to succeed a commit
++ * later, and re-queueing it every commit starves writers
++ * with read-only transitions.
++ */
++ if ((!bg->stripe_reclaim_jiffies ||
++ time_after(jiffies, bg->stripe_reclaim_jiffies + 5 * 60 * HZ)) &&
++ btrfs_stripe_bg_wants_reclaim(bg))
++ reclaim = true;
+ }
+ spin_unlock(&ctl->tree_lock);
+ kvfree(freep);
++ if (reclaim) {
++ /*
++ * Stamp the hysteresis only if the mark lands: a group still on
++ * another list (a new chunk on trans->new_bgs) cannot be
++ * queued, and must stay eligible at the next rescan.
++ */
++ spin_lock(&bg->lock);
++ if (btrfs_mark_bg_to_reclaim(bg))
++ bg->stripe_reclaim_jiffies = jiffies ?: 1;
++ spin_unlock(&bg->lock);
++ }
+ /*
+ * The space_info total is recomputed authoritatively from the sum of
+ * armed groups by btrfs_scan_stripe_unusable() after all rescans, so it
+diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
+index a1de48848d6b3..f373471f459b8 100644
+--- a/fs/btrfs/free-space-cache.h
++++ b/fs/btrfs/free-space-cache.h
+@@ -121,6 +121,7 @@ u64 btrfs_stripe_claimable_in_range(struct btrfs_block_group *bg, u64 bytenr,
+ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
+ void btrfs_stripe_unmanaged_sync(struct btrfs_block_group *block_group);
+ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
++bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg);
+ void btrfs_dump_free_space(struct btrfs_block_group *block_group,
+ u64 bytes);
+ int btrfs_find_space_cluster(struct btrfs_block_group *block_group,
+--
+2.47.3
+
+++ /dev/null
-From fcea2a2a870153edcc955ec89836193e11a9395b Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:05 -0400
-Subject: [RFC PATCH 045/116] btrfs: stripe_alloc: let a data write fall back
- to the relocation group rather than drop
-To: linux-btrfs@vger.kernel.org
-
-Dedicating a group to relocation takes its claimable stripes away from
-every other writer at once. Admission stops counting them from then
-on, but a write admitted a moment earlier against exactly those stripes
-still has to be placed, and with the group hard-excluded it was not:
-ten milliseconds after "relocating block group 2976120832" a 16K
-writeback allocation returned ENOSPC and its data was dropped, the one
-drop left in a fill-to-the-edge run under reclaim. The read-only
-transition has a guard for this; the dedication had none.
-
-Keep the exclusion for the allocator's first passes and lift it once
-the search reaches the chunk-allocation loop, i.e. only when no other
-group can serve the write. The class tag on the stripe runs already
-guarantees the two sides never share a stripe, so the fallback costs
-relocation a few stripes, not its correctness. Zoned's hard exclusion
-follows from append-only zones, which do not apply here.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/extent-tree.c | 19 +++++++++++++++++--
- 1 file changed, 17 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index a8dc64824034b..9474bc89fb6d6 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4305,8 +4305,23 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- }
- if (fs_info->data_reloc_bg &&
- (ffe_ctl->for_data_reloc !=
-- (block_group->start == fs_info->data_reloc_bg)))
-- skip = true;
-+ (block_group->start == fs_info->data_reloc_bg))) {
-+ /*
-+ * Relocation stays in its group. Everyone else stays out of
-+ * it only while the other groups can serve them: the
-+ * dedication can land after a write was admitted against
-+ * this group's stripes (the read-only guard covers that
-+ * transition, not this one), and refusing the write here
-+ * drops its data at writeback. The class tag on the runs
-+ * keeps the two sides from ever sharing a stripe, so a
-+ * last-resort allocation in the relocation group is safe,
-+ * merely unhelpful to relocation. Zoned's hard exclusion
-+ * follows from append-only zones, which do not apply here.
-+ */
-+ if (ffe_ctl->for_data_reloc ||
-+ ffe_ctl->loop < LOOP_ALLOC_CHUNK)
-+ skip = true;
-+ }
- spin_unlock(&fs_info->relocation_bg_lock);
- if (dedicated_now && block_group->space_info) {
- /* its claimable stripes now belong to relocation alone */
---
-2.47.3
-
--- /dev/null
+From 5597aa5fed5c31b4b3138152b8fcae6cdc20e028 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:19 -0400
+Subject: [RFC PATCH 46/85] btrfs: stripe_alloc: count whole stripes stranded
+ behind live runs as trapped (reclaim part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: count whole stripes stranded behind
+live runs as trapped" (earlier in this series) that need code from
+"btrfs: stripe_alloc: hand groups full of trapped free space to the
+reclaim worker", which comes after it in this series: they are applied
+here, once "btrfs: stripe_alloc: hand groups full of trapped free space
+to the reclaim worker" is in, instead of with the rest of "btrfs:
+stripe_alloc: count whole stripes stranded behind live runs as trapped".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/free-space-cache.c | 8 +++++++-
+ 1 file changed, 7 insertions(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index c49268bd5b01d..67e878534ab20 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -2396,7 +2396,13 @@ bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
+ struct btrfs_space_info *sinfo = bg->space_info;
+ const int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
+ const u64 used = READ_ONCE(bg->used);
+- const u64 trapped = READ_ONCE(bg->stripe_unusable);
++ const u64 unusable = READ_ONCE(bg->stripe_unusable);
++ /*
++ * Stripes stranded behind live runs are trapped for admission but not
++ * for reclaim: they come back by themselves when the run is freed, and
++ * relocating the group would only force that.
++ */
++ const u64 trapped = unusable - min(unusable, READ_ONCE(bg->stripe_stranded));
+ u64 elsewhere;
+ u64 promised;
+
+--
+2.47.3
+
+++ /dev/null
-From d9236a5d0b0a3ce1ecc3243f5f6be0a636bb4d30 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:06 -0400
-Subject: [RFC PATCH 046/116] btrfs: stripe_alloc: hand groups full of trapped
- free space to the reclaim worker
-To: linux-btrfs@vger.kernel.org
-
-Zoned filesystems mark a block group for reclaim as soon as its
-unusable bytes reach bg_reclaim_threshold percent of its capacity, so
-space that can no longer be written is recycled without an operator
-running balance. stripe_alloc had no equivalent. The non-zoned
-trigger consults the threshold only where a free drops a group's used
-bytes across it, and the test hosts were already running every mount
-with bg_reclaim_threshold=75 when this was measured: trapped tails
-still accumulated until balance (1.86 GiB of 6.5 GiB after a few hours
-of churn), while every byte-based check counted them as free, because
-that predicate keys on used bytes only and fires only at the crossing
--- a group hollowed out after it was already below the threshold, or
-one whose used bytes never moved while its stripes trapped, is never
-queued, and a group at the same used fraction with nothing trapped is.
-
-Mark a group for the existing reclaim worker when its trapped bytes
-reach the threshold; the worker re-checks with
-should_reclaim_block_group(). The predicate, factored out as
-btrfs_stripe_bg_wants_reclaim(), compares the trapped bytes with the
-group's free space (length minus used) rather than its length -- a
-stripe_alloc group also holds claimable whole stripes, and in practice
-fragmentation settles around two thirds of the group trapped with a
-fifth used, nothing left worth writing into yet below any sensible
-fraction of the length -- and requires room for the group's live data
-in the rest of the claimable supply after the bytes already promised to
-admitted writers, so a group that cannot be relocated is left alone
-until space is freed instead of being retried every commit while the
-read-only transitions starve writers.
-
-The trigger runs from the cleaner, which the transaction thread wakes
-every cycle whether or not a transaction exists, as well as at the
-commit-time rescan: on an idle filesystem nothing rescans, and a group
-already on another list (a chunk created in the running transaction is
-still on trans->new_bgs) cannot be linked to the reclaim list, so the
-five-minute hysteresis stamp is taken only when the mark actually
-lands. The worker re-checks whatever it takes, so a stale read costs at
-most one wasted attempt. bg_reclaim_threshold defaults to 0 on
-non-zoned filesystems, so nothing changes until the sysfs knob is set;
-the default is left for review. Relocation needs inc_block_group_ro()
-to succeed, hence the earlier fix.
-
-Assisted-by: Claude:claude-fable-5
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/block-group.c | 59 +++++++++++++++++++++++++++++++--
- fs/btrfs/block-group.h | 4 ++-
- fs/btrfs/free-space-cache.c | 65 +++++++++++++++++++++++++++++++++++++
- fs/btrfs/free-space-cache.h | 1 +
- 4 files changed, 125 insertions(+), 4 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index f100a2badde76..d9097e961f2a8 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -4686,21 +4686,74 @@ void btrfs_reclaim_bgs_work(struct work_struct *work)
- btrfs_reclaim_block_groups(fs_info, -1);
- }
-
-+/*
-+ * Periodic re-evaluation of stripe_alloc / stripe_meta groups from the
-+ * cleaner. The commit-time rescan only sees groups whose free space changed
-+ * in that transaction, and only when there is a transaction: a mark that
-+ * did not land (the group was on another list) or a group the worker dropped
-+ * would otherwise wait for the next commit, which an idle filesystem at the
-+ * fill edge never produces. Same predicate and five-minute hysteresis as
-+ * the rescan; the worker re-checks everything it takes.
-+ */
-+static void btrfs_stripe_reclaim_tick(struct btrfs_fs_info *fs_info)
-+{
-+ struct btrfs_space_info *sinfo;
-+
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return;
-+ list_for_each_entry(sinfo, &fs_info->space_info, list) {
-+ int raid;
-+
-+ if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
-+ BTRFS_BLOCK_GROUP_METADATA)))
-+ continue;
-+ if (READ_ONCE(sinfo->bg_reclaim_threshold) <= 0)
-+ continue;
-+ down_read(&sinfo->groups_sem);
-+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-+ struct btrfs_block_group *bg;
-+
-+ if (!(btrfs_raid_array[raid].bg_flag &
-+ BTRFS_BLOCK_GROUP_RAID56_MASK))
-+ continue;
-+ list_for_each_entry(bg, &sinfo->block_groups[raid],
-+ list) {
-+ if (bg->stripe_reclaim_jiffies &&
-+ !time_after(jiffies,
-+ bg->stripe_reclaim_jiffies +
-+ 5 * 60 * HZ))
-+ continue;
-+ if (!btrfs_stripe_bg_wants_reclaim(bg))
-+ continue;
-+ spin_lock(&bg->lock);
-+ if (btrfs_mark_bg_to_reclaim(bg))
-+ bg->stripe_reclaim_jiffies = jiffies ?: 1;
-+ spin_unlock(&bg->lock);
-+ }
-+ }
-+ up_read(&sinfo->groups_sem);
-+ }
-+}
-+
- void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
- {
- btrfs_reclaim_sweep(fs_info);
-+ btrfs_stripe_reclaim_tick(fs_info);
- spin_lock(&fs_info->unused_bgs_lock);
- if (!list_empty(&fs_info->reclaim_bgs))
- queue_work(system_dfl_wq, &fs_info->reclaim_bgs_work);
- spin_unlock(&fs_info->unused_bgs_lock);
- }
-
--void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
-+/* Returns true when the group was linked to the reclaim list. */
-+bool btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
- {
- struct btrfs_fs_info *fs_info = bg->fs_info;
-
-- if (btrfs_link_bg_list(bg, &fs_info->reclaim_bgs))
-- trace_btrfs_add_reclaim_block_group(bg);
-+ if (!btrfs_link_bg_list(bg, &fs_info->reclaim_bgs))
-+ return false;
-+ trace_btrfs_add_reclaim_block_group(bg);
-+ return true;
- }
-
- static int read_bg_from_eb(struct btrfs_fs_info *fs_info, const struct btrfs_key *key,
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index f8cb733ad3772..0f8e4c165d54c 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -300,6 +300,8 @@ struct btrfs_block_group {
- * (honest f_bavail); the reservation layer is deliberately unchanged.
- */
- u64 stripe_unusable;
-+ /* jiffies when the reclaim trigger last queued this group (stripe_alloc) */
-+ unsigned long stripe_reclaim_jiffies;
- /*
- * Directly measured claimable supply: bytes of fully free, aligned
- * whole stripes in the free space cache -- exactly what
-@@ -555,7 +557,7 @@ void btrfs_mark_bg_unused(struct btrfs_block_group *bg);
- void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limit);
- void btrfs_reclaim_bgs_work(struct work_struct *work);
- void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info);
--void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg);
-+bool btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg);
- int btrfs_read_block_groups(struct btrfs_fs_info *info);
- struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
- struct btrfs_space_info *space_info,
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 4533159a01929..b49c551276dd5 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2195,6 +2195,45 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
- }
-
-
-+/*
-+ * Does this stripe_alloc / stripe_meta group want the reclaim worker? Like
-+ * zoned's zone_unusable reclaim: once enough of the group's FREE space is
-+ * trapped in partially used stripes (zoned compares with the capacity, but a
-+ * stripe group also holds claimable whole stripes), relocation packs the live
-+ * extents into whole stripes elsewhere and frees the group. Only groups
-+ * whose live data is below the same threshold are cheap enough to move, and
-+ * only when that data fits in the claimable supply of the OTHER groups:
-+ * relocation needs whole stripes too, and a group queued while there is
-+ * nowhere to move it starves writers with read-only transitions and fails
-+ * each time at the fill edge. The worker re-checks with
-+ * should_reclaim_block_group(). Reads the counters without locks; the
-+ * commit-time rescan calls it with fresh values, the cleaner's periodic
-+ * re-evaluation with slightly stale ones, and either error is caught by
-+ * the worker.
-+ */
-+bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_space_info *sinfo = bg->space_info;
-+ const int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
-+ const u64 used = READ_ONCE(bg->used);
-+ const u64 trapped = READ_ONCE(bg->stripe_unusable);
-+ u64 elsewhere;
-+ u64 promised;
-+
-+ if (thresh <= 0 || bg->ro || !READ_ONCE(bg->stripe_unusable_ready))
-+ return false;
-+ if (trapped < mult_perc(bg->length - min(used, bg->length), thresh))
-+ return false;
-+ if (used >= mult_perc(bg->length, thresh))
-+ return false;
-+ elsewhere = READ_ONCE(sinfo->bytes_stripe_claimable);
-+ promised = READ_ONCE(sinfo->bytes_may_use) +
-+ READ_ONCE(sinfo->bytes_stripe_margin);
-+ elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
-+ elsewhere -= min(elsewhere, promised);
-+ return elsewhere >= used;
-+}
-+
- /*
- * Recompute a stripe_alloc block group's trapped free space from a fresh scan
- * and fold the change into the space_info total. Called at commit for groups
-@@ -2205,6 +2244,7 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
- void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
- {
- struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-+ bool reclaim = false;
- u64 nstripes;
- u32 *freep;
-
-@@ -2237,9 +2277,34 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
- "bg %llu incremental stripe_claimable %llu above scanned %llu",
- bg->start, bg->stripe_claimable, scanned);
- bg->stripe_claimable = scanned;
-+ /*
-+ * Hand a group full of trapped free space to the reclaim
-+ * worker (btrfs_stripe_bg_wants_reclaim()), but not again
-+ * within five minutes of the last mark: a relocation that
-+ * failed at the fill edge is not going to succeed a commit
-+ * later, and re-queueing it every commit starves writers
-+ * with read-only transitions.
-+ */
-+ if ((!bg->stripe_reclaim_jiffies ||
-+ time_after(jiffies, bg->stripe_reclaim_jiffies + 5 * 60 * HZ)) &&
-+ btrfs_stripe_bg_wants_reclaim(bg))
-+ reclaim = true;
- }
- spin_unlock(&ctl->tree_lock);
- kvfree(freep);
-+ if (reclaim) {
-+ /*
-+ * Stamp the hysteresis only when the mark lands. A group
-+ * that is already on another list (a chunk created this
-+ * transaction is still on trans->new_bgs) cannot be linked,
-+ * and stamping it anyway lost the mark for five minutes and,
-+ * on an idle filesystem with no commit to rescan it, for good.
-+ */
-+ spin_lock(&bg->lock);
-+ if (btrfs_mark_bg_to_reclaim(bg))
-+ bg->stripe_reclaim_jiffies = jiffies ?: 1;
-+ spin_unlock(&bg->lock);
-+ }
- /*
- * The space_info total is recomputed authoritatively from the sum of
- * armed groups by btrfs_scan_stripe_unusable() after all rescans, so it
-diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
-index 1cff596a4900d..330bb988f9592 100644
---- a/fs/btrfs/free-space-cache.h
-+++ b/fs/btrfs/free-space-cache.h
-@@ -118,6 +118,7 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *block_group);
- void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
- void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
-+bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg);
- void btrfs_dump_free_space(struct btrfs_block_group *block_group,
- u64 bytes);
- int btrfs_find_space_cluster(struct btrfs_block_group *block_group,
---
-2.47.3
-
--- /dev/null
+From 47e107d59d085279c4b94662f59a916745cce5c7 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Tue, 29 Sep 2026 05:29:38 -0400
+Subject: [RFC PATCH 47/85] btrfs: stripe_alloc: compact mostly live groups
+ instead of skipping them
+To: linux-btrfs@vger.kernel.org
+
+Reclaim only takes a stripe_alloc group whose live data is below
+bg_reclaim_threshold: moving everything out of a fuller group costs nearly
+a group's worth of writes and needs that much claimable space elsewhere.
+But trapped free space is not confined to emptyish groups. Under steady
+COW churn a group can stay mostly live while every commit leaves
+partially used stripes behind. Metadata under stripe_meta showed it
+first: on a raid6 metadata fill the trapped share of the metadata free
+space reached 88% with no group ever falling below the threshold:
+reclaim never ran, and the space never came back.
+
+A group like that does not need all of its data moved. The trapped space
+is in its partially used stripes; moving only the extents in those
+stripes makes them whole again. An extent spanning several stripes frees
+its bytes in all of them when it moves, so the stripes it shares with
+others must move too, transitively: the selection is the closure of the
+partial stripes under "shares an extent with".
+
+Compaction runs from the reclaim worker, for a group whose live data does
+not fall below the threshold, once its trapped space reaches
+stripe_compact percent of the whole group. (The test whole relocation
+uses, trapped share of the FREE space, never admits a mostly live group:
+its little free space is mostly whole stripes.)
+
+ - The group goes read-only as for relocation. After a commit, so the
+ free space cache and the extent tree's commit root agree, the partial
+ stripes are read from the free space cache and the closure is found
+ with a union-find over the group's stripes in one pass over its extent
+ items, each union carrying the live bytes of its extents.
+
+ - If the closure would move more than half the group's live bytes, the
+ group is relocated whole and removed instead: that costs about the
+ same and also gives back the group's raw space.
+
+ - Otherwise relocation runs with find_next_extent() skipping every
+ extent outside the selection, through both data stages, and the group
+ is committed (so what moved out is unpinned) and made writable again
+ instead of removed. replace_file_extents() rewrites only the pointers
+ to selected extents: the others did not move and have no new location
+ (a leaf referencing both kinds is common).
+
+Balance, device shrink and removal still relocate whole groups
+(btrfs_relocate_chunk() is unchanged; btrfs_compact_chunk() is the new
+entry point). sysfs stripe_compact is the trapped percent of a group's
+length that makes it a candidate (default 10; 0 turns compaction off),
+and stripe_run_stats counts compaction passes, fallbacks to whole
+relocation, stripes evacuated and bytes moved.
+
+The destination is ordinary relocation's: the moved extents need whole
+claimable stripes in other groups, and a commit during the pass can leave
+a partial stripe at the tail of a relocation run there. The admission
+test for compaction therefore asks for half the group's live bytes
+claimable elsewhere, the most a compaction can move.
+
+The stripe_meta block group part of this change moved to
+"btrfs: stripe_meta: extend stripe reclaim to metadata block groups".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 42 +++++-
+ fs/btrfs/disk-io.c | 1 +
+ fs/btrfs/free-space-cache.c | 144 ++++++++++++++-----
+ fs/btrfs/free-space-cache.h | 3 +
+ fs/btrfs/fs.h | 14 ++
+ fs/btrfs/relocation.c | 272 +++++++++++++++++++++++++++++++++++-
+ fs/btrfs/relocation.h | 2 +-
+ fs/btrfs/sysfs.c | 44 +++++-
+ fs/btrfs/volumes.c | 28 +++-
+ fs/btrfs/volumes.h | 2 +
+ 10 files changed, 503 insertions(+), 49 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 32948c0ec5b33..7a486f1301d39 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -4317,6 +4317,7 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ u64 reserved;
+ u64 old_total;
+ int ret = 0;
++ bool compact = false;
+
+ /*
+ * A stripe_alloc group's live extents can only move into
+@@ -4328,9 +4329,13 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ */
+ if (btrfs_is_stripe_alloc_bg(bg)) {
+ u64 elsewhere = READ_ONCE(space_info->bytes_stripe_claimable);
++ u64 need = READ_ONCE(bg->used);
+
++ /* Compaction moves at most half of it. */
++ if (btrfs_stripe_bg_wants_compaction(bg))
++ need /= 2;
+ elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
+- if (elsewhere < READ_ONCE(bg->used)) {
++ if (elsewhere < need) {
+ struct btrfs_trans_handle *trans;
+
+ trans = btrfs_join_transaction(fs_info->tree_root);
+@@ -4401,10 +4406,19 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ * the first place.
+ */
+ if (!should_reclaim_block_group(bg, bg->length)) {
+- spin_unlock(&bg->lock);
+- spin_unlock(&space_info->lock);
+- up_write(&space_info->groups_sem);
+- return 0;
++ /*
++ * Too full to relocate whole. A stripe_alloc
++ * group whose free space is trapped in partially used stripes
++ * can still be compacted: only the extents in those stripes
++ * move.
++ */
++ compact = btrfs_stripe_bg_wants_compaction(bg);
++ if (!compact) {
++ spin_unlock(&bg->lock);
++ spin_unlock(&space_info->lock);
++ up_write(&space_info->groups_sem);
++ return 0;
++ }
+ }
+
+ spin_unlock(&bg->lock);
+@@ -4456,7 +4470,23 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ "reclaim: relocating block group %llu flags 0x%llx length %llu used %llu reserved %llu",
+ bg->start, bg->flags,
+ bg->length, used, reserved);
+- ret = btrfs_relocate_chunk(fs_info, bg->start, false);
++ if (compact) {
++ bool compacted;
++
++ ret = btrfs_compact_chunk(fs_info, bg->start, &compacted);
++ /*
++ * Compacted, the group stays: drop our read-only hold. It
++ * gave back trapped space, not a chunk; what moved is counted
++ * in stripe_run_stats.
++ */
++ if (!ret && compacted) {
++ btrfs_dec_block_group_ro(bg);
++ used = 0;
++ reserved = 0;
++ }
++ } else {
++ ret = btrfs_relocate_chunk(fs_info, bg->start, false);
++ }
+ if (btrfs_is_zoned(fs_info) && ret == -EAGAIN) {
+ btrfs_dec_block_group_ro(bg);
+ btrfs_debug(fs_info, "deferring reclaim of chunk %llu", bg->start);
+diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
+index 0b23e576ed4ed..7a882a47829c4 100644
+--- a/fs/btrfs/disk-io.c
++++ b/fs/btrfs/disk-io.c
+@@ -2806,6 +2806,7 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
+ INIT_LIST_HEAD(&fs_info->caching_block_groups);
+ INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
+ fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
++ fs_info->stripe_compact = 10;
+ fs_info->stripe_park_sync_timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
+ spin_lock_init(&fs_info->open_stripe_lock);
+ spin_lock_init(&fs_info->delalloc_root_lock);
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 67e878534ab20..40a0c3c62bd5a 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -2173,26 +2173,18 @@ static u64 stripe_unusable_nstripes(const struct btrfs_block_group *bg)
+ }
+
+ /*
+- * Total trapped free bytes (free space in partially filled stripes) over the
+- * whole block group -- the authoritative definition of stripe_unusable,
+- * recomputed at cache-in and after each commit that changed the group's free
+- * space. Every free byte is accumulated into a per-stripe array (so a stripe
+- * whose total free is neither zero nor a whole stripe is partially filled, and
+- * its free bytes are trapped). @freep is a zeroed array of stripe_unusable_
+- * nstripes() u32 entries the caller allocates before taking the tree lock (it
+- * can be large); this runs with ctl->tree_lock held.
++ * Accumulate every free byte of @bg into its stripe's slot of @freep (a zeroed
++ * array of stripe_unusable_nstripes() entries). Returns the bytes counted.
++ * Caller holds ctl->tree_lock.
+ */
+-static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
+- u64 nstripes)
++static u64 stripe_free_walk(struct btrfs_block_group *bg, u32 *freep)
+ {
+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
+ const u32 unit = bg->fs_info->sectorsize;
+ const u64 fsl = bg->full_stripe_len;
+ const u64 bg_start = bg->start;
+ u64 counted = 0;
+- u64 trapped = 0;
+ struct rb_node *n;
+- u64 i;
+
+ lockdep_assert_held(&ctl->tree_lock);
+
+@@ -2221,6 +2213,27 @@ static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
+ e->offset + e->bytes, &counted);
+ }
+ }
++ return counted;
++}
++
++/*
++ * The authoritative stripe_unusable of the block group: free bytes in
++ * partially filled stripes, plus whole free stripes stranded behind live
++ * runs. Recomputed at cache-in and after each commit that changed the
++ * group's free space. @freep is a zeroed array of
++ * stripe_unusable_nstripes() entries, allocated by the caller before taking
++ * ctl->tree_lock, which is held here.
++ */
++static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
++ u64 nstripes)
++{
++ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ const u64 fsl = bg->full_stripe_len;
++ u64 counted;
++ u64 trapped = 0;
++ u64 i;
++
++ counted = stripe_free_walk(bg, freep);
+
+ /* Every free byte was distributed to exactly one stripe (debug check). */
+ ASSERT(counted == ctl->free_space,
+@@ -2240,6 +2253,38 @@ static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
+ return trapped;
+ }
+
++/*
++ * For compaction: set in @map (@nstripes bits, zeroed by the caller) every
++ * stripe of @bg that holds free space but not a whole stripe of it. Returns
++ * how many, or a negative errno.
++ */
++s64 btrfs_stripe_partial_map(struct btrfs_block_group *bg, unsigned long *map,
++ u64 nstripes)
++{
++ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
++ const u64 fsl = bg->full_stripe_len;
++ s64 found = 0;
++ u32 *freep;
++ u64 i;
++
++ if (nstripes != stripe_unusable_nstripes(bg))
++ return -EINVAL;
++ freep = kvcalloc(nstripes, sizeof(*freep), GFP_NOFS);
++ if (!freep)
++ return -ENOMEM;
++ spin_lock(&ctl->tree_lock);
++ stripe_free_walk(bg, freep);
++ spin_unlock(&ctl->tree_lock);
++ for (i = 0; i < nstripes; i++) {
++ if (freep[i] && freep[i] < fsl) {
++ set_bit(i, map);
++ found++;
++ }
++ }
++ kvfree(freep);
++ return found;
++}
++
+ /*
+ * The legacy allocator parks a group's free space in an allocation cluster
+ * (for a metadata group, its whole initial extent), where the group's own
+@@ -2376,22 +2421,23 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+
+
+ /*
+- * Does this stripe_alloc group want the reclaim worker? Like
+- * zoned's zone_unusable reclaim: once enough of the group's FREE space is
+- * trapped in partially used stripes (zoned compares with the capacity, but a
+- * stripe group also holds claimable whole stripes), relocation packs the live
+- * extents into whole stripes elsewhere and frees the group. Only groups
+- * whose live data is below the same threshold are cheap enough to move, and
+- * only when that data fits in the claimable supply of the OTHER groups:
+- * relocation needs whole stripes too, and a group queued while there is
+- * nowhere to move it starves writers with read-only transitions and fails
+- * each time at the fill edge. The worker re-checks with
+- * should_reclaim_block_group(). Reads the counters without locks; the
+- * commit-time rescan calls it with fresh values, the cleaner's periodic
+- * re-evaluation with slightly stale ones, and either error is caught by
+- * the worker.
++ * Does this stripe_alloc group want the reclaim worker? As
++ * with zoned's zone_unusable, reclaim once enough of the group's free space
++ * is trapped. A group whose live data is below the threshold is relocated
++ * whole; a fuller one is compacted (btrfs_compact_chunk()), moving only the
++ * extents in its partial stripes. Either way, only when the data fits in
++ * the other groups' claimable supply: relocation needs whole stripes too,
++ * and queueing a group with nowhere to move it only costs writers read-only
++ * transitions. Counters are read unlocked; the worker re-checks.
+ */
+-bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
++enum stripe_reclaim_kind {
++ STRIPE_RECLAIM_NONE,
++ STRIPE_RECLAIM_RELOCATE,
++ STRIPE_RECLAIM_COMPACT,
++};
++
++static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
++ bool check_room)
+ {
+ struct btrfs_space_info *sinfo = bg->space_info;
+ const int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
+@@ -2403,21 +2449,53 @@ bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
+ * relocating the group would only force that.
+ */
+ const u64 trapped = unusable - min(unusable, READ_ONCE(bg->stripe_stranded));
++ enum stripe_reclaim_kind kind = STRIPE_RECLAIM_RELOCATE;
++ u64 need = used;
+ u64 elsewhere;
+ u64 promised;
+
+ if (thresh <= 0 || bg->ro || !READ_ONCE(bg->stripe_unusable_ready))
+- return false;
+- if (trapped < mult_perc(bg->length - min(used, bg->length), thresh))
+- return false;
+- if (used >= mult_perc(bg->length, thresh))
+- return false;
++ return STRIPE_RECLAIM_NONE;
++ if (used >= mult_perc(bg->length, thresh)) {
++ /*
++ * Too full to move whole: compact once trapped space reaches
++ * stripe_compact percent of the group's length. (A share of
++ * free space, as below, would stay small here: a mostly live
++ * group's little free space is mostly whole stripes.)
++ */
++ const u32 pct = READ_ONCE(bg->fs_info->stripe_compact);
++
++ if (!pct || trapped < mult_perc(bg->length, pct))
++ return STRIPE_RECLAIM_NONE;
++ kind = STRIPE_RECLAIM_COMPACT;
++ need = used / 2;
++ } else if (trapped < mult_perc(bg->length - min(used, bg->length),
++ thresh)) {
++ return STRIPE_RECLAIM_NONE;
++ }
++ if (!check_room)
++ return kind;
+ elsewhere = READ_ONCE(sinfo->bytes_stripe_claimable);
+ promised = READ_ONCE(sinfo->bytes_may_use) +
+ READ_ONCE(sinfo->bytes_stripe_margin);
+ elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
+ elsewhere -= min(elsewhere, promised);
+- return elsewhere >= used;
++ return elsewhere >= need ? kind : STRIPE_RECLAIM_NONE;
++}
++
++bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
++{
++ return stripe_bg_reclaim_kind(bg, true) != STRIPE_RECLAIM_NONE;
++}
++
++/*
++ * For the reclaim worker, about a group it took: compact it rather than
++ * relocate it whole. Room is not re-checked; the worker makes room first,
++ * and relocation fails cleanly without it.
++ */
++bool btrfs_stripe_bg_wants_compaction(struct btrfs_block_group *bg)
++{
++ return stripe_bg_reclaim_kind(bg, false) == STRIPE_RECLAIM_COMPACT;
+ }
+
+ /*
+diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
+index f373471f459b8..93d7e4a8f999c 100644
+--- a/fs/btrfs/free-space-cache.h
++++ b/fs/btrfs/free-space-cache.h
+@@ -122,6 +122,9 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_gr
+ void btrfs_stripe_unmanaged_sync(struct btrfs_block_group *block_group);
+ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
+ bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg);
++bool btrfs_stripe_bg_wants_compaction(struct btrfs_block_group *bg);
++s64 btrfs_stripe_partial_map(struct btrfs_block_group *bg, unsigned long *map,
++ u64 nstripes);
+ void btrfs_dump_free_space(struct btrfs_block_group *block_group,
+ u64 bytes);
+ int btrfs_find_space_cluster(struct btrfs_block_group *block_group,
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 3981823c3b879..cc11757f59fa1 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -906,9 +906,23 @@ struct btrfs_fs_info {
+ /* Relocation runs retained past their drain, and released. */
+ atomic64_t reloc_run_retained;
+ atomic64_t reloc_run_released;
++ /* compaction passes that kept their group */
++ atomic64_t compact_runs;
++ /* compaction plans over the cap, relocated whole instead */
++ atomic64_t compact_fallbacks;
++ /* stripes evacuated by compaction (closure included) */
++ atomic64_t compact_stripes;
++ /* live bytes compaction moved */
++ atomic64_t compact_bytes;
+ } stripe_run_stats;
+ /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
+ u32 stripe_rmw_prop;
++ /*
++ * Reclaim compacts a mostly live stripe_alloc group once
++ * this percent of its length is trapped; 0 = never (sysfs
++ * stripe_compact, default 10). See btrfs_compact_chunk().
++ */
++ u32 stripe_compact;
+ /*
+ * Park deadlines, ms (sysfs); 0 disables parking for that class. See
+ * rbio_try_park().
+diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
+index 35240a459e4ed..79e65dfd9d14b 100644
+--- a/fs/btrfs/relocation.c
++++ b/fs/btrfs/relocation.c
+@@ -180,8 +180,40 @@ struct reloc_control {
+ bool found_file_extent;
+
+ refcount_t refs;
++
++ /*
++ * Compaction: the stripes whose extents are relocated (compact_plan());
++ * NULL relocates the whole group.
++ */
++ unsigned long *compact_map;
++ u64 compact_fsl;
+ };
+
++/*
++ * Stripe compaction. A stripe_alloc group whose free space is
++ * trapped in partially used stripes, but whose live data mostly fills whole
++ * ones, does not need all of that data moved to get the space back: only the
++ * extents in the partial stripes, and -- since moving an extent frees its
++ * bytes in every stripe it spans -- the extents sharing a stripe with those,
++ * transitively. compact_plan() selects that closure, find_next_extent()
++ * skips every extent outside it, and the group is kept and made writable
++ * again instead of removed.
++ */
++static bool compact_selected(const struct reloc_control *rc, u64 start, u64 len)
++{
++ const struct btrfs_block_group *bg = rc->block_group;
++ u64 first, last;
++
++ if (!rc->compact_map)
++ return true;
++ if (start < bg->start || !len)
++ return false;
++ first = div64_u64(start - bg->start, rc->compact_fsl);
++ last = div64_u64(min(start + len, bg->start + bg->length) - 1 - bg->start,
++ rc->compact_fsl);
++ return find_next_bit(rc->compact_map, last + 1, first) <= last;
++}
++
+ static struct reloc_control *get_reloc_control(struct btrfs_fs_info *fs_info)
+ {
+ struct reloc_control *rc;
+@@ -226,6 +258,7 @@ static void put_reloc_control(struct reloc_control *rc)
+ if (rc->block_group)
+ btrfs_put_block_group(rc->block_group);
+
++ bitmap_free(rc->compact_map);
+ kfree(rc);
+ }
+ }
+@@ -974,8 +1007,14 @@ int replace_file_extents(struct btrfs_trans_handle *trans,
+ num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
+ if (bytenr == 0)
+ continue;
++ /*
++ * Only the extents that moved have a new location: under
++ * compaction that is the selected ones, not every extent in
++ * the group.
++ */
+ if (!in_range(bytenr, rc->block_group->start,
+- rc->block_group->length))
++ rc->block_group->length) ||
++ !compact_selected(rc, bytenr, num_bytes))
+ continue;
+
+ /*
+@@ -3537,6 +3576,11 @@ int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
+ else
+ rc->search_start = key.objectid +
+ fs_info->nodesize;
++ if (!compact_selected(rc, key.objectid,
++ rc->search_start - key.objectid)) {
++ path->slots[0]++;
++ goto next;
++ }
+ memcpy(extent_key, &key, sizeof(key));
+ return 0;
+ }
+@@ -5424,18 +5468,207 @@ static int do_nonremap_reloc(struct btrfs_fs_info *fs_info, bool verbose,
+ rc->extents_found, stage_to_string(finishes_stage));
+ }
+
+- WARN_ON(rc->block_group->pinned > 0);
+- WARN_ON(rc->block_group->reserved > 0);
+- WARN_ON(rc->block_group->used > 0);
++ /* A compacted group keeps the extents it was not asked to move. */
++ if (!rc->compact_map) {
++ WARN_ON(rc->block_group->pinned > 0);
++ WARN_ON(rc->block_group->reserved > 0);
++ WARN_ON(rc->block_group->used > 0);
++ }
+
+ return 0;
+ }
+
++static u32 compact_root(u32 *parent, u32 x)
++{
++ while (parent[x] != x) {
++ parent[x] = parent[parent[x]];
++ x = parent[x];
++ }
++ return x;
++}
++
++/*
++ * Select the stripes to evacuate: the partially used ones, and every stripe
++ * joined to one of them through an extent spanning both. A union-find over
++ * the group's stripes, in one pass over its extent items in the commit root,
++ * each union carrying the live bytes of its extents. Sets rc->compact_map;
++ * returns the live bytes the selection moves in @moved and the number of
++ * stripes selected in @nsel.
++ */
++static int compact_plan(struct reloc_control *rc, u64 *moved, u64 *nsel)
++{
++ struct btrfs_block_group *bg = rc->block_group;
++ const u64 fsl = bg->full_stripe_len;
++ const u64 end = bg->start + bg->length;
++ BTRFS_PATH_AUTO_FREE(path);
++ struct btrfs_key key;
++ unsigned long *map = NULL;
++ unsigned long *sel = NULL;
++ u32 *parent = NULL;
++ u64 *bytes = NULL;
++ u64 nstripes;
++ s64 npartial;
++ u64 i;
++ int ret;
++
++ *moved = 0;
++ *nsel = 0;
++ if (!fsl)
++ return -EINVAL;
++ nstripes = div64_u64(bg->length + fsl - 1, fsl);
++ if (nstripes > U32_MAX)
++ return -EINVAL;
++
++ path = btrfs_alloc_path();
++ map = bitmap_zalloc(nstripes, GFP_NOFS);
++ sel = bitmap_zalloc(nstripes, GFP_NOFS);
++ parent = kvmalloc_array(nstripes, sizeof(*parent), GFP_NOFS);
++ bytes = kvcalloc(nstripes, sizeof(*bytes), GFP_NOFS);
++ if (!path || !map || !sel || !parent || !bytes) {
++ ret = -ENOMEM;
++ goto out;
++ }
++ npartial = btrfs_stripe_partial_map(bg, map, nstripes);
++ if (npartial < 0) {
++ ret = npartial;
++ goto out;
++ }
++ for (i = 0; i < nstripes; i++)
++ parent[i] = i;
++
++ path->search_commit_root = true;
++ path->skip_locking = true;
++ path->need_commit_sem = true;
++ key.objectid = bg->start;
++ key.type = 0;
++ key.offset = 0;
++ ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
++ if (ret < 0)
++ goto out;
++ while (1) {
++ struct extent_buffer *leaf = path->nodes[0];
++ u64 len;
++ u32 a, b, r;
++
++ if (path->slots[0] >= btrfs_header_nritems(leaf)) {
++ ret = btrfs_next_leaf(rc->extent_root, path);
++ if (ret < 0)
++ goto out;
++ if (ret > 0)
++ break;
++ cond_resched();
++ continue;
++ }
++ btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
++ path->slots[0]++;
++ if (key.objectid >= end)
++ break;
++ if (key.type == BTRFS_EXTENT_ITEM_KEY)
++ len = key.offset;
++ else
++ continue;
++ if (key.objectid < bg->start || !len)
++ continue;
++ a = div64_u64(key.objectid - bg->start, fsl);
++ b = div64_u64(min(key.objectid + len, end) - 1 - bg->start, fsl);
++ r = compact_root(parent, a);
++ for (u32 s = a + 1; s <= b; s++) {
++ u32 t = compact_root(parent, s);
++
++ if (t != r) {
++ parent[t] = r;
++ bytes[r] += bytes[t];
++ }
++ }
++ bytes[r] += len;
++ }
++ ret = 0;
++
++ /* Select every union holding a partial stripe... */
++ for_each_set_bit(i, map, nstripes) {
++ u32 r = compact_root(parent, i);
++
++ if (!__test_and_set_bit(r, sel))
++ *moved += bytes[r];
++ }
++ /* ...and evacuate all of its stripes. */
++ for (i = 0; i < nstripes; i++) {
++ if (test_bit(compact_root(parent, i), sel)) {
++ __set_bit(i, map);
++ (*nsel)++;
++ }
++ }
++ rc->compact_map = map;
++ rc->compact_fsl = fsl;
++ map = NULL;
++out:
++ bitmap_free(map);
++ bitmap_free(sel);
++ kvfree(parent);
++ kvfree(bytes);
++ return ret;
++}
++
++/*
++ * Plan the compaction of a read-only group. Returns 1 to compact
++ * (rc->compact_map set), 0 to relocate the whole group instead -- the
++ * closure would move more than half its live bytes, most of the cost of
++ * moving all of them, which also gets the group's raw space back -- or a
++ * negative errno.
++ */
++static int compact_prepare(struct reloc_control *rc)
++{
++ struct btrfs_block_group *bg = rc->block_group;
++ struct btrfs_fs_info *fs_info = bg->fs_info;
++ struct btrfs_trans_handle *trans;
++ u64 moved, nsel, used;
++ int ret;
++
++ /*
++ * Settle first: what the group freed stays pinned until a commit, and
++ * the plan reads the free space cache and the commit root, which then
++ * agree.
++ */
++ trans = btrfs_join_transaction(rc->extent_root);
++ if (IS_ERR(trans))
++ return PTR_ERR(trans);
++ ret = btrfs_commit_transaction(trans);
++ if (ret)
++ return ret;
++ ret = btrfs_cache_block_group(bg, true);
++ if (ret)
++ return ret;
++ ret = compact_plan(rc, &moved, &nsel);
++ if (ret)
++ return ret;
++
++ spin_lock(&bg->lock);
++ used = bg->used;
++ spin_unlock(&bg->lock);
++ if (moved > used / 2) {
++ bitmap_free(rc->compact_map);
++ rc->compact_map = NULL;
++ atomic64_inc(&fs_info->stripe_run_stats.compact_fallbacks);
++ return 0;
++ }
++ atomic64_inc(&fs_info->stripe_run_stats.compact_runs);
++ atomic64_add(nsel, &fs_info->stripe_run_stats.compact_stripes);
++ atomic64_add(moved, &fs_info->stripe_run_stats.compact_bytes);
++ btrfs_info(fs_info,
++ "compacting block group %llu: %llu stripes, %llu of %llu live bytes",
++ bg->start, nsel, moved, used);
++ return 1;
++}
++
+ /*
+ * function to relocate all extents in a block group.
++ *
++ * @compact: NULL relocates the whole group. Pointing at true, the group is
++ * compacted if that moves at most half its live bytes and relocated whole
++ * otherwise; on return it says which. A compacted group is left writable.
+ */
+ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
+- bool verbose)
++ bool verbose, bool *compact)
+ {
+ struct btrfs_block_group *bg;
+ struct btrfs_root *extent_root = btrfs_extent_root(fs_info, group_start);
+@@ -5444,6 +5677,7 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
+ struct btrfs_path *path = NULL;
+ int ret;
+ bool bg_is_ro = false;
++ bool compacting = false;
+
+ if (unlikely(!extent_root)) {
+ btrfs_err(fs_info,
+@@ -5540,6 +5774,18 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
+ ret = btrfs_zone_finish(rc->block_group);
+ WARN_ON(ret && ret != -EAGAIN);
+
++ /* Compaction is for the relocation that moves extents, not remapping. */
++ if (compact && *compact && should_relocate_using_remap_tree(bg))
++ *compact = false;
++ if (compact && *compact) {
++ ret = compact_prepare(rc);
++ if (ret < 0)
++ goto out;
++ compacting = ret;
++ *compact = compacting;
++ ret = 0;
++ }
++
+ if (should_relocate_using_remap_tree(bg)) {
+ if (bg->remap_bytes != 0) {
+ ret = move_existing_remaps(fs_info, bg, path);
+@@ -5559,6 +5805,22 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
+ ret = do_nonremap_reloc(fs_info, verbose, rc);
+ }
+
++ if (!ret && compacting) {
++ struct btrfs_trans_handle *trans;
++
++ /*
++ * The group stays. Commit, so what moved out of it is unpinned
++ * and its stripes are whole again before it is writable.
++ */
++ trans = btrfs_join_transaction(rc->extent_root);
++ if (IS_ERR(trans))
++ ret = PTR_ERR(trans);
++ else
++ ret = btrfs_commit_transaction(trans);
++ btrfs_dec_block_group_ro(rc->block_group);
++ bg_is_ro = false;
++ }
++
+ out:
+ if (ret && bg_is_ro)
+ btrfs_dec_block_group_ro(rc->block_group);
+diff --git a/fs/btrfs/relocation.h b/fs/btrfs/relocation.h
+index bb7a86e7dbe3a..e9f95976aae4b 100644
+--- a/fs/btrfs/relocation.h
++++ b/fs/btrfs/relocation.h
+@@ -24,7 +24,7 @@ static inline bool should_relocate_using_remap_tree(const struct btrfs_block_gro
+ }
+
+ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
+- bool verbose);
++ bool verbose, bool *compact);
+ int btrfs_init_reloc_root(struct btrfs_trans_handle *trans, struct btrfs_root *root);
+ int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
+ struct btrfs_root *root);
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 325f6cb1e7167..56140f1f34c35 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1180,12 +1180,20 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
+ "claim_refused_live_run %lld\n"
+ "strand_scan_bytes %lld\n"
+ "strand_rescan_marks %lld\n"
+- "nocow_run_dead_closed %lld\n",
++ "nocow_run_dead_closed %lld\n"
++ "compact_runs %lld\n"
++ "compact_fallbacks %lld\n"
++ "compact_stripes %lld\n"
++ "compact_bytes %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.nocow_run_dead_closed));
++ atomic64_read(&fs_info->stripe_run_stats.nocow_run_dead_closed),
++ atomic64_read(&fs_info->stripe_run_stats.compact_runs),
++ atomic64_read(&fs_info->stripe_run_stats.compact_fallbacks),
++ atomic64_read(&fs_info->stripe_run_stats.compact_stripes),
++ atomic64_read(&fs_info->stripe_run_stats.compact_bytes));
+ }
+ BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
+
+@@ -1223,6 +1231,37 @@ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
+ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_sync_timeout_ms, stripe_park_sync_timeout_ms);
+ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_congestion, stripe_park_congestion);
+
++/*
++ * Reclaim compacts a mostly live stripe group once this percent of its length
++ * is trapped (btrfs_compact_chunk()); 0 turns compaction off.
++ */
++static ssize_t btrfs_stripe_compact_show(struct kobject *kobj,
++ struct kobj_attribute *a, char *buf)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++
++ return sysfs_emit(buf, "%u\n", READ_ONCE(fs_info->stripe_compact));
++}
++
++static ssize_t btrfs_stripe_compact_store(struct kobject *kobj,
++ struct kobj_attribute *a,
++ const char *buf, size_t len)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++ unsigned int val;
++ int ret;
++
++ ret = kstrtouint(buf, 10, &val);
++ if (ret)
++ return ret;
++ if (val > 100)
++ return -EINVAL;
++ WRITE_ONCE(fs_info->stripe_compact, val);
++ return len;
++}
++BTRFS_ATTR_RW(, stripe_compact, btrfs_stripe_compact_show,
++ btrfs_stripe_compact_store);
++
+
+
+ static ssize_t btrfs_clone_alignment_show(struct kobject *kobj,
+@@ -1596,6 +1635,7 @@ static const struct attribute *btrfs_attrs[] = {
+ BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
+ BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
+ BTRFS_ATTR_PTR(, stripe_park_congestion),
++ BTRFS_ATTR_PTR(, stripe_compact),
+ BTRFS_ATTR_PTR(, temp_fsid),
+ NULL,
+ };
+diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
+index ae2d0a814d63e..c9f81b0975fe0 100644
+--- a/fs/btrfs/volumes.c
++++ b/fs/btrfs/volumes.c
+@@ -3737,7 +3737,8 @@ static int btrfs_relocate_chunk_finish(struct btrfs_fs_info *fs_info,
+ return ret;
+ }
+
+-int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool verbose)
++static int relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
++ bool verbose, bool *compact)
+ {
+ struct btrfs_block_group *block_group;
+ int ret;
+@@ -3764,7 +3765,7 @@ int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool v
+
+ /* step one, relocate all the extents inside this chunk */
+ btrfs_scrub_pause(fs_info);
+- ret = btrfs_relocate_block_group(fs_info, chunk_offset, verbose);
++ ret = btrfs_relocate_block_group(fs_info, chunk_offset, verbose, compact);
+ btrfs_scrub_continue(fs_info);
+ if (ret) {
+ /*
+@@ -3776,6 +3777,10 @@ int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool v
+ return ret;
+ }
+
++ /* Compacted: the group keeps the rest of its live extents. */
++ if (compact && *compact)
++ return 0;
++
+ block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
+ if (!block_group)
+ return -ENOENT;
+@@ -3791,6 +3796,25 @@ int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool v
+ return ret;
+ }
+
++int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool verbose)
++{
++ return relocate_chunk(fs_info, chunk_offset, verbose, NULL);
++}
++
++/*
++ * Compact a stripe_alloc group: relocate only the extents in
++ * its partially used stripes (and those sharing a stripe with them) and keep
++ * it. When that would move more than half its live bytes the group is
++ * relocated and removed as by btrfs_relocate_chunk() instead; @compacted
++ * says which happened.
++ */
++int btrfs_compact_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
++ bool *compacted)
++{
++ *compacted = true;
++ return relocate_chunk(fs_info, chunk_offset, false, compacted);
++}
++
+ static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
+ {
+ struct btrfs_root *chunk_root = fs_info->chunk_root;
+diff --git a/fs/btrfs/volumes.h b/fs/btrfs/volumes.h
+index bce6134218f48..f57b73ae996bc 100644
+--- a/fs/btrfs/volumes.h
++++ b/fs/btrfs/volumes.h
+@@ -787,6 +787,8 @@ int btrfs_recover_balance(struct btrfs_fs_info *fs_info);
+ int btrfs_pause_balance(struct btrfs_fs_info *fs_info);
+ int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
+ bool verbose);
++int btrfs_compact_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
++ bool *compacted);
+ int btrfs_cancel_balance(struct btrfs_fs_info *fs_info);
+ bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset);
+ void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index);
+--
+2.47.3
+
+++ /dev/null
-From 5d738c8b02afd0dfa89f40059067b19f68082130 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:06 -0400
-Subject: [RFC PATCH 047/116] btrfs: stripe_alloc: relocate a queued stripe
- group even while it has reserved or pinned bytes
-To: linux-btrfs@vger.kernel.org
-
-The reclaim worker defers any group that has bytes reserved or pinned,
-on the theory that it was queued for falling below the used threshold
-and may be about to go empty on its own. A stripe_alloc or stripe_meta
-group is queued for the opposite reason -- free space trapped in
-partially used stripes, which no amount of waiting frees -- and under
-COW churn a metadata group has blocks reserved or pinned at every
-moment, so the worker skipped every one of seven queued metadata
-groups for the whole of a fill-to-the-edge test and relocated none.
-Relocation already waits for in-flight allocations and writers on its
-own; take the group.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 11 ++++++++++-
- 1 file changed, 10 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index d9097e961f2a8..64030c597705f 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -4481,12 +4481,21 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
-
- spin_lock(&space_info->lock);
- spin_lock(&bg->lock);
-- if (bg->reserved || bg->pinned || bg->ro) {
-+ if (bg->ro ||
-+ ((bg->reserved || bg->pinned) &&
-+ !btrfs_is_stripe_alloc_bg(bg) &&
-+ !btrfs_is_stripe_meta_bg(bg))) {
- /*
- * We want to bail if we made new allocations or have
- * outstanding allocations in this block group. We do
- * the ro check in case balance is currently acting on
- * this block group.
-+ *
-+ * Not for a stripe_alloc or stripe_meta group: under
-+ * COW churn it always has blocks reserved or pinned,
-+ * so the bail-out would defer it forever, while the
-+ * trapped free space it was queued for only grows.
-+ * Relocation waits for in-flight allocations itself.
- */
- spin_unlock(&bg->lock);
- spin_unlock(&space_info->lock);
---
-2.47.3
-
--- /dev/null
+From ce90272a1e42dbd3b8cb55d8caf659b53f2218c4 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 1 Oct 2026 00:57:50 -0400
+Subject: [RFC PATCH 48/85] btrfs: stripe_alloc: keep relocation's stripe runs
+ until relocation ends (reclaim part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: keep relocation's stripe runs until
+relocation ends" (earlier in this series) that need code from "btrfs:
+stripe_alloc: compact mostly live groups instead of skipping them",
+which comes after it in this series: they are applied here, once "btrfs:
+stripe_alloc: compact mostly live groups instead of skipping them" is
+in, instead of with the rest of "btrfs: stripe_alloc: keep relocation's
+stripe runs until relocation ends".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/sysfs.c | 4 ++++
+ 1 file changed, 4 insertions(+)
+
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 56140f1f34c35..586b9eb7a637e 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1181,6 +1181,8 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
+ "strand_scan_bytes %lld\n"
+ "strand_rescan_marks %lld\n"
+ "nocow_run_dead_closed %lld\n"
++ "reloc_run_retained %lld\n"
++ "reloc_run_released %lld\n"
+ "compact_runs %lld\n"
+ "compact_fallbacks %lld\n"
+ "compact_stripes %lld\n"
+@@ -1190,6 +1192,8 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
+ 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.nocow_run_dead_closed),
++ atomic64_read(&fs_info->stripe_run_stats.reloc_run_retained),
++ atomic64_read(&fs_info->stripe_run_stats.reloc_run_released),
+ atomic64_read(&fs_info->stripe_run_stats.compact_runs),
+ atomic64_read(&fs_info->stripe_run_stats.compact_fallbacks),
+ atomic64_read(&fs_info->stripe_run_stats.compact_stripes),
+--
+2.47.3
+
+++ /dev/null
-From 62783d7e1cf15e3bf7142abededac55926f35cb3 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:07 -0400
-Subject: [RFC PATCH 048/116] btrfs: stripe_meta: maintain trapped free space
- for metadata groups like data
-To: linux-btrfs@vger.kernel.org
-
-btrfs_block_group_init_stripe_unusable() arms stripe_meta groups and adds
-their trapped bytes to the METADATA space_info, but the disarm, rescan
-and commit-time scan only accept btrfs_is_stripe_alloc_bg() (DATA), so
-a metadata group's contribution was frozen at its first value: never
-updated as tree blocks were freed inside stripes, never dropped when the
-group went read-only or was removed. Tree blocks can only be placed in
-fully free stripes, so the trapped bytes are as unusable as for data and
-need the same maintenance.
-
-Accept stripe_meta groups on the three maintenance paths, let the commit
-scan sum METADATA space_infos, and apply the read-only subtraction to
-the metadata branch of inc_block_group_ro() as well.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 18 ++++++++++++++++--
- fs/btrfs/free-space-cache.c | 4 ++--
- 2 files changed, 18 insertions(+), 4 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 64030c597705f..ef7f53471de4a 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2672,7 +2672,13 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- u64 total_claimable_reloc = 0;
- int raid;
-
-- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
-+ /*
-+ * Data groups under stripe_alloc and metadata groups under
-+ * stripe_meta both place extents in whole stripes only, so
-+ * both carry trapped free space. Mixed groups are refused.
-+ */
-+ if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
-+ BTRFS_BLOCK_GROUP_METADATA)))
- continue;
- down_read(&sinfo->groups_sem);
- for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-@@ -3931,8 +3937,16 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
- * btrfs_can_overcommit check here, and we need to pass in
- * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
- * leeway to allow us to mark this block group as read only.
-+ *
-+ * As for data above: a stripe_meta group's trapped bytes are
-+ * already in the space_info total, do not re-provide them.
- */
-- if (btrfs_can_overcommit(sinfo, num_bytes, BTRFS_RESERVE_NO_FLUSH))
-+ u64 trapped = 0;
-+
-+ if (READ_ONCE(cache->stripe_unusable_ready))
-+ trapped = min(READ_ONCE(cache->stripe_unusable), num_bytes);
-+ if (btrfs_can_overcommit(sinfo, num_bytes - trapped,
-+ BTRFS_RESERVE_NO_FLUSH))
- ret = 0;
- }
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index b49c551276dd5..c005065b2b532 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2168,7 +2168,7 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
- u64 trapped;
- u64 claimable;
-
-- if (!btrfs_is_stripe_alloc_bg(bg))
-+ if (!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg))
- return;
-
- spin_lock(&ctl->tree_lock);
-@@ -2248,7 +2248,7 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
- u64 nstripes;
- u32 *freep;
-
-- if (!btrfs_is_stripe_alloc_bg(bg))
-+ if (!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg))
- return;
-
- nstripes = stripe_unusable_nstripes(bg);
---
-2.47.3
-
--- /dev/null
+From 5e7bdfed533872a8dcf42c0bf0c61093e904e7d0 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Tue, 20 Oct 2026 13:04:19 -0400
+Subject: [RFC PATCH 49/85] btrfs: stripe_alloc: log compaction and trapped
+ bytes in the reclaim log
+To: linux-btrfs@vger.kernel.org
+
+Say in the reclaim debug lines whether a stripe group is being compacted
+or relocated, with the trapped bytes the reclaim trigger counted, and
+whether it was compacted or relocated. Without that, stripe-reclaim-test,
+which counts reclaims in the log, could not tell automatic compaction from
+relocation, and an octopus replace stalled behind a reclaim the log did not
+explain.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 17 ++++++++++-------
+ 1 file changed, 10 insertions(+), 7 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 7a486f1301d39..4f0e50004cef1 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -4316,8 +4316,10 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ u64 used;
+ u64 reserved;
+ u64 old_total;
++ u64 trapped;
+ int ret = 0;
+ bool compact = false;
++ bool compacted = false;
+
+ /*
+ * A stripe_alloc group's live extents can only move into
+@@ -4463,16 +4465,17 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ spin_lock(&bg->lock);
+ used = bg->used;
+ reserved = bg->reserved;
++ /* Trapped as the reclaim trigger counts it. */
++ trapped = bg->stripe_unusable -
++ min(bg->stripe_unusable, bg->stripe_stranded);
+ spin_unlock(&bg->lock);
+
+ trace_btrfs_reclaim_block_group(bg);
+ btrfs_debug(fs_info,
+-"reclaim: relocating block group %llu flags 0x%llx length %llu used %llu reserved %llu",
+- bg->start, bg->flags,
+- bg->length, used, reserved);
++"reclaim: %s block group %llu flags 0x%llx length %llu used %llu reserved %llu trapped %llu",
++ compact ? "compacting" : "relocating", bg->start, bg->flags,
++ bg->length, used, reserved, trapped);
+ if (compact) {
+- bool compacted;
+-
+ ret = btrfs_compact_chunk(fs_info, bg->start, &compacted);
+ /*
+ * Compacted, the group stays: drop our read-only hold. It
+@@ -4511,8 +4514,8 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ spin_unlock(&space_info->lock);
+ if (!ret) {
+ (*reclaimed)++;
+- btrfs_debug(fs_info, "reclaim: relocated block group %llu",
+- bg->start);
++ btrfs_debug(fs_info, "reclaim: %s block group %llu",
++ compacted ? "compacted" : "relocated", bg->start);
+ }
+
+ return ret;
+--
+2.47.3
+
+++ /dev/null
-From 0af088bb8082f875a17f43d079ce2118ced9b8f7 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:08 -0400
-Subject: [RFC PATCH 049/116] btrfs: stripe_meta: back the global reserve with
- usable stripes, and say when a tree block finds none
-To: linux-btrfs@vger.kernel.org
-
-With trapped and open-run bytes counted as used in the METADATA
-space_info, the overcommit check already admits tree block reservations
-only against whole free stripes plus unallocated space, so no separate
-metadata gate is needed. Two loose ends remain.
-
-btrfs_update_global_block_rsv() forces a chunk allocation when the
-global reserve is at least the space_info's total, but under stripe_meta
-the reserve can only be spent in whole stripes: compare it against the
-capacity minus the trapped bytes so a metadata chunk is allocated while
-unallocated space still exists, instead of the reserve running dry at
-the fill edge.
-
-And when a raid56 stripe_meta tree block allocation does fail with
-ENOSPC -- which aborts the transaction -- print the stripe counters,
-the metadata twin of the data-side "returned ENOSPC despite reservation
-margin" warning, so an accounting hole is identifiable from the log.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-rsv.c | 9 ++++++++-
- fs/btrfs/extent-tree.c | 24 ++++++++++++++++++++++++
- 2 files changed, 32 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/block-rsv.c b/fs/btrfs/block-rsv.c
-index fd604631b9ca8..d78ae83bd00d0 100644
---- a/fs/btrfs/block-rsv.c
-+++ b/fs/btrfs/block-rsv.c
-@@ -400,7 +400,14 @@ void btrfs_update_global_block_rsv(struct btrfs_fs_info *fs_info)
-
- block_rsv->full = (block_rsv->reserved == block_rsv->size);
-
-- if (block_rsv->size >= sinfo->total_bytes)
-+ /*
-+ * The global reserve must be backed by space a tree block can
-+ * actually land in. Under stripe_meta that excludes the bytes
-+ * trapped in partially used stripes, so compare against the usable
-+ * capacity, not the raw total, and force a chunk allocation as soon
-+ * as the reserve would not fit in it.
-+ */
-+ if (block_rsv->size >= sinfo->total_bytes - sinfo->bytes_stripe_unusable)
- sinfo->force_alloc = CHUNK_ALLOC_FORCE;
- spin_unlock(&block_rsv->lock);
- spin_unlock(&sinfo->lock);
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 9474bc89fb6d6..fee586ac38546 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -5202,6 +5202,30 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- 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);
-+ /*
-+ * Metadata twin. A tree block reservation was admitted
-+ * against the whole-stripe supply (trapped and open-run bytes
-+ * count as used in the space_info), so a raid56 stripe_meta
-+ * tree block should always find a whole stripe or an open
-+ * run. If it does not, the transaction aborts: report the
-+ * counters so the accounting hole can be identified.
-+ */
-+ if (!is_data && btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
-+ (flags & BTRFS_BLOCK_GROUP_RAID56_MASK)) {
-+ struct btrfs_space_info *sinfo;
-+
-+ sinfo = btrfs_find_space_info(fs_info, flags);
-+ if (sinfo)
-+ btrfs_warn_rl(fs_info,
-+ "stripe_meta: tree block allocation of %llu bytes returned ENOSPC: claimable %llu open %llu trapped %llu may_use %llu reserved %llu total %llu",
-+ num_bytes,
-+ sinfo->bytes_stripe_claimable,
-+ sinfo->bytes_stripe_open,
-+ sinfo->bytes_stripe_unusable,
-+ sinfo->bytes_may_use,
-+ sinfo->bytes_reserved,
-+ sinfo->total_bytes);
-+ }
- }
-
- return ret;
---
-2.47.3
-
--- /dev/null
+From b2f61eea4161613ad769f238ca4e3a577933db32 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Tue, 20 Oct 2026 14:41:37 -0400
+Subject: [RFC PATCH 50/85] btrfs: stripe_alloc: add stripe_reclaim_now to
+ reclaim stripes on demand
+To: linux-btrfs@vger.kernel.org
+
+Background reclaim of stripe_alloc raid56 groups runs when a
+commit-time rescan, or the cleaner's tick at most every five minutes per
+group, finds a group past bg_reclaim_threshold. Nothing lets an operator
+say "reclaim now": during an idle period, before a large write, or for one
+group seen trapped. The only tool is balance, which relocates whole groups
+whatever their state and cannot compact.
+
+Add /sys/fs/btrfs/<uuid>/stripe_reclaim_now (write-only, root):
+
+ echo all > stripe_reclaim_now (or "1")
+ Queue every stripe_alloc raid56 group that the
+ reclaim predicate picks: relocate below the threshold once enough
+ of its free space is trapped, compact above it once stripe_compact
+ percent of its length is trapped. The five-minute hysteresis is
+ ignored.
+
+ echo <start> > stripe_reclaim_now
+ Reclaim the group at that logical start (decimal or 0x hex, as
+ `btrfs inspect-internal dump-tree -t chunk` and the "reclaim: "
+ debug lines print it) whatever its trapped space:
+ compact it if it is above the threshold and has trapped stripes,
+ relocate it otherwise.
+
+The threshold is the space_info's bg_reclaim_threshold, or 75
+(BTRFS_DEFAULT_RECLAIM_THRESH) where that is 0, the non-zoned default,
+since the request is explicit. Both forms keep the room check: the other
+groups' claimable stripes, plus the one chunk the worker allocates when
+those fall short, must take what moves. The write returns once the groups
+are queued; it does not wait for the reclaim. The worker re-checks its
+thresholds and would drop a group it was asked to reclaim, so a group
+queued by this knob carries the kind of reclaim to do
+(stripe_reclaim_forced), which the worker honours once and clears.
+
+Errors: -ENOENT when no group starts there; -EINVAL for anything but a
+stripe_alloc raid56 group (balance's vrange filter relocates
+the others); -EBUSY when the group is read-only (a balance or scrub has
+it); -EAGAIN when it is already on a list (queued, unused or new);
+-ENOSPC when there is no room; -EROFS on a read-only or errored
+filesystem. The worker takes the balance exclusive operation and gives the
+list back when another holds it, so a request made while a balance,
+replace, resize or device add/remove runs would wait unseen: it fails at
+once with -EAGAIN and nothing is queued; retry when the operation is done.
+The reclaim worker's own hold (a balance with no balance control) is not
+refused, as the worker picks up the new entries.
+
+Expected use: an idle-time job (cron) writes "all"; an operator writes the
+start of one group taken from the "reclaim: " debug lines or from the
+chunk tree. The queued groups are logged at debug level with the same
+"reclaim: " prefix.
+
+There is no in-tree btrfs sysfs documentation; the btrfs-progs sysfs
+chapter should list the file.
+
+Tested with stripe-reclaim-now-test.sh (raid56-wh-harness): with
+background reclaim off nothing moves; one group is relocated alone, and a
+group above the threshold with trapped stripes is compacted; "all"
+reclaims and trapped space falls; no such group, not a number, a raid1
+metadata group and a read-only mount fail with the codes above, and a
+paused balance and a running replace fail with -EAGAIN; data verifies and
+btrfs check is clean.
+
+The stripe_meta block group part of this change moved to
+"btrfs: stripe_meta: extend stripe reclaim to metadata block groups".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 164 +++++++++++++++++++++++++++++++++++-
+ fs/btrfs/block-group.h | 7 ++
+ fs/btrfs/free-space-cache.c | 53 +++++++++---
+ fs/btrfs/free-space-cache.h | 9 ++
+ fs/btrfs/sysfs.c | 29 +++++++
+ 5 files changed, 247 insertions(+), 15 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 4f0e50004cef1..7050b82514cb6 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -4318,6 +4318,7 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ u64 old_total;
+ u64 trapped;
+ int ret = 0;
++ u8 forced = READ_ONCE(bg->stripe_reclaim_forced);
+ bool compact = false;
+ bool compacted = false;
+
+@@ -4334,7 +4335,8 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ u64 need = READ_ONCE(bg->used);
+
+ /* Compaction moves at most half of it. */
+- if (btrfs_stripe_bg_wants_compaction(bg))
++ if (forced ? forced == STRIPE_RECLAIM_COMPACT :
++ btrfs_stripe_bg_wants_compaction(bg))
+ need /= 2;
+ elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
+ if (elsewhere < need) {
+@@ -4356,6 +4358,9 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+
+ spin_lock(&space_info->lock);
+ spin_lock(&bg->lock);
++ /* A forced reclaim is done once, or dropped with the group. */
++ forced = bg->stripe_reclaim_forced;
++ bg->stripe_reclaim_forced = STRIPE_RECLAIM_NONE;
+ if (bg->ro ||
+ ((bg->reserved || bg->pinned) &&
+ !btrfs_is_stripe_alloc_bg(bg))) {
+@@ -4407,7 +4412,10 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ * check, which is more meaningful when adding to the list in
+ * the first place.
+ */
+- if (!should_reclaim_block_group(bg, bg->length)) {
++ if (forced) {
++ /* stripe_reclaim_now chose already; the thresholds may say no. */
++ compact = (forced == STRIPE_RECLAIM_COMPACT);
++ } else if (!should_reclaim_block_group(bg, bg->length)) {
+ /*
+ * Too full to relocate whole. A stripe_alloc
+ * group whose free space is trapped in partially used stripes
+@@ -4768,6 +4776,158 @@ bool btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
+ return true;
+ }
+
++/*
++ * Room for a forced reclaim beyond the other groups' claimable stripes: the
++ * one chunk the reclaim worker allocates when they fall short (see
++ * btrfs_reclaim_block_group()), estimated as the data share of the
++ * unallocated device space at @bg's width, capped at @bg's length.
++ */
++static u64 stripe_reclaim_chunk_room(struct btrfs_block_group *bg)
++{
++ struct btrfs_fs_info *fs_info = bg->fs_info;
++ struct btrfs_chunk_map *map;
++ u64 unalloc = atomic64_read(&fs_info->free_chunk_space);
++ u64 room;
++
++ map = btrfs_get_chunk_map(fs_info, bg->start, 1);
++ if (IS_ERR(map))
++ return 0;
++ room = div_u64(unalloc * nr_data_stripes(map), map->num_stripes);
++ btrfs_free_chunk_map(map);
++ return min(room, bg->length);
++}
++
++/*
++ * Queue @bg for the reclaim worker with the reclaim it is to do. Returns
++ * false when the group is already on a list (queued, unused or new).
++ */
++static bool stripe_reclaim_now_queue(struct btrfs_block_group *bg,
++ enum stripe_reclaim_kind kind)
++{
++ bool queued;
++
++ spin_lock(&bg->lock);
++ bg->stripe_reclaim_forced = kind;
++ queued = btrfs_mark_bg_to_reclaim(bg);
++ if (queued)
++ bg->stripe_reclaim_jiffies = jiffies ?: 1;
++ else
++ bg->stripe_reclaim_forced = STRIPE_RECLAIM_NONE;
++ spin_unlock(&bg->lock);
++ if (queued)
++ btrfs_debug(bg->fs_info,
++ "reclaim: queued block group %llu to %s (stripe_reclaim_now)",
++ bg->start, kind == STRIPE_RECLAIM_COMPACT ?
++ "compact" : "relocate");
++ return queued;
++}
++
++/*
++ * /sys/fs/btrfs/<uuid>/stripe_reclaim_now: reclaim stripe_alloc
++ * raid56 block groups now, e.g. from an idle-time job, rather than waiting
++ * for the commit-time rescan and its five-minute hysteresis. The threshold
++ * is the space_info's bg_reclaim_threshold, or BTRFS_DEFAULT_RECLAIM_THRESH
++ * where that is 0 (reclaim off), since the request is explicit.
++ *
++ * @all: queue every such group the reclaim predicate picks at that
++ * threshold (relocate below it, compact above it once stripe_compact percent
++ * is trapped), ignoring the hysteresis.
++ *
++ * Otherwise @start names one group (its logical start): it is reclaimed
++ * whatever the trapped minimums say, compacted if it is above the threshold
++ * and has trapped stripes, relocated otherwise. -ENOENT: no group starts
++ * there; -EINVAL: not a stripe_alloc raid56 group (relocate
++ * any other group with balance's vrange filter); -EBUSY: the group is
++ * read-only (balance or scrub hold it); -EAGAIN: it is already on a list
++ * (queued, unused or new); -ENOSPC: the other groups' claimable stripes plus
++ * one new chunk cannot take what would move.
++ *
++ * Both return once the groups are queued, without waiting for the reclaim.
++ * The worker takes the balance exclusive operation and gives the list back
++ * when another operation holds it, so a request made while a balance,
++ * replace, resize or device add/remove runs fails at once with -EAGAIN
++ * rather than wait unseen; nothing is queued. The reclaim worker's own hold
++ * (a balance with no balance control) is not refused: it picks up the new
++ * entries.
++ */
++int btrfs_stripe_reclaim_now(struct btrfs_fs_info *fs_info, bool all, u64 start)
++{
++ struct btrfs_space_info *sinfo;
++ struct btrfs_block_group *bg;
++ enum btrfs_exclusive_operation op;
++ enum stripe_reclaim_kind kind;
++ int queued = 0;
++ int ret = 0;
++
++ if (sb_rdonly(fs_info->sb) || BTRFS_FS_ERROR(fs_info))
++ return -EROFS;
++ spin_lock(&fs_info->super_lock);
++ op = fs_info->exclusive_operation;
++ spin_unlock(&fs_info->super_lock);
++ if (op != BTRFS_EXCLOP_NONE &&
++ (op != BTRFS_EXCLOP_BALANCE || READ_ONCE(fs_info->balance_ctl)))
++ return -EAGAIN;
++
++ if (!all) {
++ bg = btrfs_lookup_block_group(fs_info, start);
++ if (!bg)
++ return -ENOENT;
++ if (bg->start != start) {
++ ret = -ENOENT;
++ } else if (!btrfs_is_stripe_alloc_bg(bg)) {
++ ret = -EINVAL;
++ } else if (READ_ONCE(bg->ro)) {
++ ret = -EBUSY;
++ } else {
++ int thresh = READ_ONCE(bg->space_info->bg_reclaim_threshold);
++
++ kind = btrfs_stripe_bg_reclaim_now_kind(bg,
++ thresh > 0 ? thresh : BTRFS_DEFAULT_RECLAIM_THRESH,
++ true, stripe_reclaim_chunk_room(bg));
++ if (kind == STRIPE_RECLAIM_NONE)
++ ret = READ_ONCE(bg->ro) ? -EBUSY : -ENOSPC;
++ else if (stripe_reclaim_now_queue(bg, kind))
++ queued = 1;
++ else
++ ret = -EAGAIN;
++ }
++ btrfs_put_block_group(bg);
++ if (ret)
++ return ret;
++ goto kick;
++ }
++
++ list_for_each_entry(sinfo, &fs_info->space_info, list) {
++ int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
++ int raid;
++
++ if (thresh <= 0)
++ thresh = BTRFS_DEFAULT_RECLAIM_THRESH;
++ down_read(&sinfo->groups_sem);
++ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
++ if (!(btrfs_raid_array[raid].bg_flag &
++ BTRFS_BLOCK_GROUP_RAID56_MASK))
++ continue;
++ list_for_each_entry(bg, &sinfo->block_groups[raid], list) {
++ if (!btrfs_is_stripe_alloc_bg(bg))
++ continue;
++ kind = btrfs_stripe_bg_reclaim_now_kind(bg, thresh,
++ false, stripe_reclaim_chunk_room(bg));
++ if (kind != STRIPE_RECLAIM_NONE &&
++ stripe_reclaim_now_queue(bg, kind))
++ queued++;
++ }
++ }
++ up_read(&sinfo->groups_sem);
++ }
++ btrfs_debug(fs_info, "reclaim: stripe_reclaim_now queued %d block groups",
++ queued);
++kick:
++ if (queued)
++ queue_work(system_dfl_wq, &fs_info->reclaim_bgs_work);
++ return 0;
++}
++
+ static int read_bg_from_eb(struct btrfs_fs_info *fs_info, const struct btrfs_key *key,
+ const struct btrfs_path *path)
+ {
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index d9e6f295e0e7f..5e32c44017212 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -308,6 +308,12 @@ struct btrfs_block_group {
+ u64 stripe_stranded;
+ /* jiffies when the reclaim trigger last queued this group (stripe_alloc) */
+ unsigned long stripe_reclaim_jiffies;
++ /*
++ * Reclaim forced by stripe_reclaim_now (enum stripe_reclaim_kind):
++ * the reclaim worker does this instead of re-checking its thresholds,
++ * once, and clears it. Protected by ->lock.
++ */
++ u8 stripe_reclaim_forced;
+ /*
+ * Directly measured claimable supply: bytes of fully free, aligned
+ * whole stripes in the free space cache -- exactly what
+@@ -572,6 +578,7 @@ void btrfs_reclaim_bgs_work(struct work_struct *work);
+ void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info);
+ bool btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg);
+ bool btrfs_reclaim_backoff_active(struct btrfs_space_info *space_info);
++int btrfs_stripe_reclaim_now(struct btrfs_fs_info *fs_info, bool all, u64 start);
+ int btrfs_read_block_groups(struct btrfs_fs_info *info);
+ struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
+ struct btrfs_space_info *space_info,
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 40a0c3c62bd5a..1078f2019743f 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -2430,19 +2430,15 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+ * and queueing a group with nowhere to move it only costs writers read-only
+ * transitions. Counters are read unlocked; the worker re-checks.
+ */
+-enum stripe_reclaim_kind {
+- STRIPE_RECLAIM_NONE,
+- STRIPE_RECLAIM_RELOCATE,
+- STRIPE_RECLAIM_COMPACT,
+-};
+-
+-static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
+- bool check_room)
++static enum stripe_reclaim_kind __stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
++ int thresh, bool force,
++ bool check_room,
++ u64 extra_room)
+ {
+ struct btrfs_space_info *sinfo = bg->space_info;
+- const int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
++ const bool ready = READ_ONCE(bg->stripe_unusable_ready);
+ const u64 used = READ_ONCE(bg->used);
+- const u64 unusable = READ_ONCE(bg->stripe_unusable);
++ const u64 unusable = ready ? READ_ONCE(bg->stripe_unusable) : 0;
+ /*
+ * Stripes stranded behind live runs are trapped for admission but not
+ * for reclaim: they come back by themselves when the run is freed, and
+@@ -2454,9 +2450,19 @@ static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group
+ u64 elsewhere;
+ u64 promised;
+
+- if (thresh <= 0 || bg->ro || !READ_ONCE(bg->stripe_unusable_ready))
++ if (thresh <= 0 || bg->ro || (!ready && !force))
+ return STRIPE_RECLAIM_NONE;
+- if (used >= mult_perc(bg->length, thresh)) {
++ if (force) {
++ /*
++ * Forced (stripe_reclaim_now naming this group): no trapped
++ * minimum. Compact a group too full to move whole if it has
++ * any trapped stripe, otherwise relocate it.
++ */
++ if (used >= mult_perc(bg->length, thresh) && trapped) {
++ kind = STRIPE_RECLAIM_COMPACT;
++ need = used / 2;
++ }
++ } else if (used >= mult_perc(bg->length, thresh)) {
+ /*
+ * Too full to move whole: compact once trapped space reaches
+ * stripe_compact percent of the group's length. (A share of
+@@ -2480,7 +2486,15 @@ static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group
+ READ_ONCE(sinfo->bytes_stripe_margin);
+ elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
+ elsewhere -= min(elsewhere, promised);
+- return elsewhere >= need ? kind : STRIPE_RECLAIM_NONE;
++ return elsewhere + extra_room >= need ? kind : STRIPE_RECLAIM_NONE;
++}
++
++static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
++ bool check_room)
++{
++ return __stripe_bg_reclaim_kind(bg,
++ READ_ONCE(bg->space_info->bg_reclaim_threshold),
++ false, check_room, 0);
+ }
+
+ bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
+@@ -2488,6 +2502,19 @@ bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
+ return stripe_bg_reclaim_kind(bg, true) != STRIPE_RECLAIM_NONE;
+ }
+
++/*
++ * For stripe_reclaim_now: the reclaim @bg gets at threshold @thresh, room
++ * checked with @extra_room bytes (the chunk the worker may allocate) added to
++ * the other groups' claimable supply. @force drops the trapped minimums: see
++ * btrfs_stripe_reclaim_now().
++ */
++enum stripe_reclaim_kind btrfs_stripe_bg_reclaim_now_kind(struct btrfs_block_group *bg,
++ int thresh, bool force,
++ u64 extra_room)
++{
++ return __stripe_bg_reclaim_kind(bg, thresh, force, true, extra_room);
++}
++
+ /*
+ * For the reclaim worker, about a group it took: compact it rather than
+ * relocate it whole. Room is not re-checked; the worker makes room first,
+diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
+index 93d7e4a8f999c..18e5e26a4b231 100644
+--- a/fs/btrfs/free-space-cache.h
++++ b/fs/btrfs/free-space-cache.h
+@@ -121,8 +121,17 @@ u64 btrfs_stripe_claimable_in_range(struct btrfs_block_group *bg, u64 bytenr,
+ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
+ void btrfs_stripe_unmanaged_sync(struct btrfs_block_group *block_group);
+ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
++enum stripe_reclaim_kind {
++ STRIPE_RECLAIM_NONE,
++ STRIPE_RECLAIM_RELOCATE,
++ STRIPE_RECLAIM_COMPACT,
++};
++
+ bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg);
+ bool btrfs_stripe_bg_wants_compaction(struct btrfs_block_group *bg);
++enum stripe_reclaim_kind btrfs_stripe_bg_reclaim_now_kind(struct btrfs_block_group *bg,
++ int thresh, bool force,
++ u64 extra_room);
+ s64 btrfs_stripe_partial_map(struct btrfs_block_group *bg, unsigned long *map,
+ u64 nstripes);
+ void btrfs_dump_free_space(struct btrfs_block_group *block_group,
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 586b9eb7a637e..753de9e6357da 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1266,6 +1266,34 @@ static ssize_t btrfs_stripe_compact_store(struct kobject *kobj,
+ BTRFS_ATTR_RW(, stripe_compact, btrfs_stripe_compact_show,
+ btrfs_stripe_compact_store);
+
++/*
++ * Reclaim stripe_alloc raid56 block groups now: "all" (or "1")
++ * queues every group the reclaim predicate picks, a block group's logical
++ * start forces that group. See btrfs_stripe_reclaim_now().
++ */
++static ssize_t btrfs_stripe_reclaim_now_store(struct kobject *kobj,
++ struct kobj_attribute *a,
++ const char *buf, size_t len)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++ u64 start = 0;
++ bool all;
++ int ret;
++
++ if (!capable(CAP_SYS_ADMIN))
++ return -EPERM;
++
++ all = sysfs_streq(buf, "all") || sysfs_streq(buf, "1");
++ if (!all) {
++ ret = kstrtou64(buf, 0, &start);
++ if (ret)
++ return ret;
++ }
++ ret = btrfs_stripe_reclaim_now(fs_info, all, start);
++ return ret ? ret : len;
++}
++BTRFS_ATTR_W(, stripe_reclaim_now, btrfs_stripe_reclaim_now_store);
++
+
+
+ static ssize_t btrfs_clone_alignment_show(struct kobject *kobj,
+@@ -1640,6 +1668,7 @@ static const struct attribute *btrfs_attrs[] = {
+ BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
+ BTRFS_ATTR_PTR(, stripe_park_congestion),
+ BTRFS_ATTR_PTR(, stripe_compact),
++ BTRFS_ATTR_PTR(, stripe_reclaim_now),
+ BTRFS_ATTR_PTR(, temp_fsid),
+ NULL,
+ };
+--
+2.47.3
+
+++ /dev/null
-From a2d61f5c5b26a8f88bc1f79eb1236e290937624c Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:12 -0400
-Subject: [RFC PATCH 050/116] btrfs: stripe_meta: hold back whole stripes so
- tree blocks always land and trapped groups can be reclaimed
-To: linux-btrfs@vger.kernel.org
-
-Two failures at the metadata fill edge under stripe_meta, both seen
-with the tiny-file fill test on raid5 metadata.
-
-The first is a transaction abort. A tree block is reserved in bytes
-and admitted while claimable whole stripes cover the outstanding
-reservations, but it is placed in whole stripes: the open run it would
-have joined is closed at the transaction boundary, so every group
-claims at least one fresh full stripe per transaction. The last few
-megabytes of claimable supply go to those claims, made for reservations
-admitted earlier, and the next admitted tree block finds no stripe at
-all ("stripe_meta: tree block allocation of 16384 bytes returned
-ENOSPC: claimable 0 open 1622016 trapped 1614266368"), which aborts the
-transaction. Pre-pay two transactions' worth of claims -- twice the
-number of writable groups times the widest full stripe -- in the
-space_info's stripe margin, recomputed at each commit scan. Best-fit
-run selection opens a fresh run only when a group's runs are full, so
-this is a few megabytes, not a fraction of the space_info.
-
-The second is a filesystem that quietly runs out at half capacity.
-COW frees trap stripes rather than free them: a stripe is claimable
-again only once every tree block in it is dead, which random deaths in
-a sixteen-block stripe essentially never achieve, so the METADATA
-space_info settles around half used, half trapped and no claimable
-stripe left (3.04 GiB metadata, 49% used, fs not writable, deletes
-included). Only relocation packs live tree blocks back into whole
-stripes, and it needs the moved group's live bytes claimable elsewhere
-before it starts -- by the time the trigger fires there is nothing
-left. Hold back a reserve of whole stripes -- the largest writable
-group's length, capped at a quarter of the space_info, nothing with a
-single group -- from every metadata reservation except those made by
-the relocation task, identified by a task pointer that reloc_ctl
-already implies. Reservations admitted against the reserve reach the
-same tickets, so the flag travels with the ticket. The reserve is an
-accounting hold-back, not a partition: a committing transaction still
-allocates from those stripes when it must, and the next scan restates
-the reserve from what remains. Both counters are cleared when
-stripe_alloc is turned off, since the scan that maintains them stops
-with it.
-
-The reserve is reported through sysfs as bytes_stripe_reserve and in
-the space_info dump, whose stripe_claimable and stripe_margin values
-were printed under each other's label.
-
-The reserve belongs to the whole of btrfs_relocate_block_group(), not
-only the stretches where reloc_ctl is set: relocation reserves metadata
-before its first stage (create_reloc_inode() starts a transaction for
-six items), and that reservation, made as an ordinary user, fails with
--ENOSPC exactly when relocation is needed -- once the claimable supply
-has fallen below the reserve. fs_info->reloc_owner records the task
-for the whole run (reloc_chunk_start() serializes it) and counts as
-relocation here.
-
-Assisted-by: Claude:claude-fable-5
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 57 ++++++++++++++++++++++++++++++++++++++++--
- fs/btrfs/fs.h | 15 +++++++++++
- fs/btrfs/relocation.c | 4 +++
- fs/btrfs/space-info.c | 34 ++++++++++++++++++++-----
- fs/btrfs/space-info.h | 23 +++++++++++++++--
- fs/btrfs/sysfs.c | 2 ++
- 6 files changed, 125 insertions(+), 10 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index ef7f53471de4a..3225bc71af203 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2006,8 +2006,21 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
- list_for_each_entry(sinfo, &fs_info->space_info, list) {
- int raid;
-
-- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
-+ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA)) {
-+ /*
-+ * Metadata: the scan that maintains the stripe_meta
-+ * margin and reserve stops with the option, so clear
-+ * them here or they hold metadata back forever.
-+ */
-+ if (!arm && (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)) {
-+ spin_lock(&sinfo->lock);
-+ sinfo->bytes_stripe_margin = 0;
-+ sinfo->bytes_stripe_reserve = 0;
-+ btrfs_try_granting_tickets(sinfo);
-+ spin_unlock(&sinfo->lock);
-+ }
- continue;
-+ }
- down_read(&sinfo->groups_sem);
- for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
- struct btrfs_block_group *bg;
-@@ -2670,6 +2683,9 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- u64 total = 0;
- u64 total_claimable = 0;
- u64 total_claimable_reloc = 0;
-+ u64 largest = 0;
-+ u64 unit = 0;
-+ u32 nr_rw = 0;
- int raid;
-
- /*
-@@ -2714,7 +2730,10 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- if (bg->start == READ_ONCE(fs_info->data_reloc_bg))
- total_claimable_reloc +=
- READ_ONCE(bg->stripe_claimable);
-+ nr_rw++;
-+ largest = max(largest, bg->length);
- }
-+ unit = max(unit, bg->full_stripe_len);
- }
- }
- up_read(&sinfo->groups_sem);
-@@ -2723,6 +2742,40 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- sinfo->bytes_stripe_unusable = total;
- sinfo->bytes_stripe_claimable = total_claimable;
- sinfo->bytes_stripe_claimable_reloc = total_claimable_reloc;
-+ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA)) {
-+ u64 reserve = 0;
-+
-+ /*
-+ * stripe_meta. A tree block is reserved in bytes but
-+ * placed in whole stripes: the run it would join is
-+ * closed at the transaction boundary, so each group
-+ * claims at least one fresh stripe per transaction.
-+ * Pre-pay two transactions' worth of such claims, or
-+ * the last claimable stripes go to claims made for
-+ * reservations admitted earlier and an admitted tree
-+ * block finds none, which aborts the transaction.
-+ */
-+ sinfo->bytes_stripe_margin = 2ULL * nr_rw * unit;
-+ /*
-+ * COW frees trap stripes rather than free them (a
-+ * stripe is claimable again only once every block in
-+ * it is dead), so the space_info settles around half
-+ * used, half trapped. Only relocation packs live tree
-+ * blocks back into whole stripes, and it needs the
-+ * moved group's live bytes claimable elsewhere first.
-+ * Hold back enough for any one group, capped at a
-+ * quarter of the space_info, from everyone but the
-+ * relocation task. With a single group there is no
-+ * elsewhere to hold it for. This is an accounting
-+ * hold-back only: a committing transaction still
-+ * allocates from these stripes if it must.
-+ */
-+ if (nr_rw > 1 && unit)
-+ reserve = round_up(min(largest,
-+ sinfo->total_bytes / 4),
-+ unit);
-+ sinfo->bytes_stripe_reserve = reserve;
-+ }
- /*
- * The rescan usually lowers the counter (mid-transaction
- * incremental adds overcount conservatively); admission
-@@ -3946,7 +3999,7 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
- if (READ_ONCE(cache->stripe_unusable_ready))
- trapped = min(READ_ONCE(cache->stripe_unusable), num_bytes);
- if (btrfs_can_overcommit(sinfo, num_bytes - trapped,
-- BTRFS_RESERVE_NO_FLUSH))
-+ BTRFS_RESERVE_NO_FLUSH, false))
- ret = 0;
- }
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 297964037a975..ff46ee994eb61 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -785,6 +785,21 @@ struct btrfs_fs_info {
- struct btrfs_space_info *data_sinfo;
-
- struct reloc_control *reloc_ctl;
-+ /*
-+ * The task running relocation while reloc_ctl is set. Under
-+ * stripe_meta it alone may reserve metadata out of the whole stripes
-+ * held back in bytes_stripe_reserve, so that a trapped metadata
-+ * group can always be relocated (see btrfs_can_overcommit()).
-+ */
-+ struct task_struct *reloc_task;
-+ /*
-+ * The task inside btrfs_relocate_block_group(), for its whole run
-+ * (relocation is serialized by reloc_chunk_start()). reloc_task only
-+ * covers the stretches where reloc_ctl is set; the reservations made
-+ * before and between them -- creating the data reloc inode first of
-+ * all -- are relocation's too, and may draw on the same reserve.
-+ */
-+ struct task_struct *reloc_owner;
-
- /* data_alloc_cluster is only used in ssd_spread mode */
- struct btrfs_free_cluster data_alloc_cluster;
-diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
-index 03b9834b57223..f02d04eacf5f0 100644
---- a/fs/btrfs/relocation.c
-+++ b/fs/btrfs/relocation.c
-@@ -3550,6 +3550,7 @@ static void set_reloc_control(struct reloc_control *rc)
- spin_lock(&fs_info->reloc_ctl_lock);
- fs_info->reloc_ctl = rc;
- spin_unlock(&fs_info->reloc_ctl_lock);
-+ WRITE_ONCE(fs_info->reloc_task, current);
- mutex_unlock(&fs_info->reloc_mutex);
- }
-
-@@ -3561,6 +3562,7 @@ static void unset_reloc_control(struct reloc_control *rc)
- spin_lock(&fs_info->reloc_ctl_lock);
- fs_info->reloc_ctl = NULL;
- spin_unlock(&fs_info->reloc_ctl_lock);
-+ WRITE_ONCE(fs_info->reloc_task, NULL);
- mutex_unlock(&fs_info->reloc_mutex);
- }
-
-@@ -5495,6 +5497,7 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
- ret = reloc_chunk_start(fs_info);
- if (ret < 0)
- goto out_put_rc;
-+ WRITE_ONCE(fs_info->reloc_owner, current);
-
- ret = btrfs_inc_block_group_ro(rc->block_group, true);
- if (ret)
-@@ -5568,6 +5571,7 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
- if (!btrfs_is_zoned(fs_info))
- btrfs_release_data_reloc_bg(fs_info);
- btrfs_free_path(path);
-+ WRITE_ONCE(fs_info->reloc_owner, NULL);
- reloc_chunk_end(fs_info);
- out_put_rc:
- put_reloc_control(rc);
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 1e9946369c184..df50d0c7e1fd2 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -187,6 +187,8 @@ struct reserve_ticket {
- u64 bytes;
- int error;
- bool steal;
-+ /* Made by the relocation task: may draw on bytes_stripe_reserve. */
-+ bool reloc;
- struct list_head list;
- wait_queue_head_t wait;
- spinlock_t lock;
-@@ -612,7 +614,7 @@ static inline bool can_overcommit(const struct btrfs_space_info *space_info,
- }
-
- bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
-- enum btrfs_reserve_flush_enum flush)
-+ enum btrfs_reserve_flush_enum flush, bool reloc)
- {
- u64 used;
-
-@@ -621,6 +623,13 @@ bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
- return false;
-
- used = btrfs_space_info_used(space_info, true);
-+ /*
-+ * The stripe_meta reserve exists for relocation: it is the room in
-+ * which the live tree blocks of a trapped group are packed into whole
-+ * stripes. Everyone else sees it as used.
-+ */
-+ if (reloc)
-+ used -= min(used, space_info->bytes_stripe_reserve);
-
- return check_can_overcommit(space_info, used, bytes, flush);
- }
-@@ -757,14 +766,22 @@ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info)
- while (!list_empty(head)) {
- struct reserve_ticket *ticket;
- u64 used_after;
-+ u64 tused;
-
- ticket = list_first_entry(head, struct reserve_ticket, list);
- used_after = used + ticket->bytes;
-+ /*
-+ * Relocation's tickets may draw on the stripe_meta reserve: for
-+ * this ticket only, the tickets after it still see it as used.
-+ */
-+ tused = used;
-+ if (ticket->reloc)
-+ tused -= min(tused, space_info->bytes_stripe_reserve);
-
- /* 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)) &&
-- stripe_claimable_admit(space_info, ticket->bytes, false)) {
-+ if ((tused + ticket->bytes <= space_info->total_bytes ||
-+ can_overcommit(space_info, tused, ticket->bytes, flush)) &&
-+ stripe_claimable_admit(space_info, ticket->bytes, ticket->reloc)) {
- btrfs_space_info_update_bytes_may_use(space_info, ticket->bytes);
- remove_ticket(space_info, ticket, 0);
- space_info->tickets_id++;
-@@ -813,13 +830,13 @@ 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 stripe_unusable=%llu stripe_open=%llu stripe_margin=%llu stripe_claimable=%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_claimable=%llu stripe_margin=%llu stripe_reserve=%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_stripe_unusable, info->bytes_stripe_open,
- info->bytes_stripe_claimable,
-- info->bytes_stripe_margin);
-+ info->bytes_stripe_margin, info->bytes_stripe_reserve);
- }
-
- void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
-@@ -1962,6 +1979,8 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
- u64 used;
- int ret = -ENOSPC;
- bool pending_tickets;
-+ const bool reloc = (READ_ONCE(fs_info->reloc_task) == current) ||
-+ (READ_ONCE(fs_info->reloc_owner) == current);
-
- ASSERT(orig_bytes, "orig_bytes=%llu", orig_bytes);
- /*
-@@ -2001,6 +2020,8 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
- * Carry on if we have enough space (short-circuit) OR call
- * can_overcommit() to ensure we can overcommit to continue.
- */
-+ if (reloc)
-+ used -= min(used, space_info->bytes_stripe_reserve);
- if (!pending_tickets &&
- ((used + orig_bytes <= space_info->total_bytes) ||
- can_overcommit(space_info, used, orig_bytes, flush)) &&
-@@ -2037,6 +2058,7 @@ 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.reloc = reloc;
- if (trace_btrfs_reserve_ticket_enabled())
- start_ns = ktime_get_ns();
-
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 5abb8fd072b3c..6a3711ae00cf3 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -192,7 +192,25 @@ struct btrfs_space_info {
- writeback can never trap space out
- from under an admitted reservation.
- Charged and released in lockstep with
-- the inodes' outstanding_extents. */
-+ the inodes' outstanding_extents.
-+ On a stripe_meta METADATA space_info
-+ it is instead set at each commit scan
-+ to two transactions' worth of whole
-+ stripe claims: every group can claim
-+ a fresh stripe per transaction for a
-+ tree block admitted in bytes. */
-+ u64 bytes_stripe_reserve; /* stripe_meta: whole stripes held back
-+ from every metadata reservation except
-+ the relocation task's, so that any one
-+ metadata group's live tree blocks can
-+ be moved into whole stripes elsewhere.
-+ COW frees trap rather than free
-+ stripes, so without it the space_info
-+ settles half used, half trapped, with
-+ nothing left for reclaim to move
-+ into. Counted in
-+ btrfs_space_info_used(); recomputed
-+ at each commit scan. */
-
- u64 max_extent_size; /* This will hold the maximum extent size of
- the space info if we had an ENOSPC in the
-@@ -338,6 +356,7 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
- s_info->bytes_zone_unusable +
- s_info->bytes_stripe_unusable + s_info->bytes_stripe_open +
- s_info->bytes_stripe_margin +
-+ s_info->bytes_stripe_reserve +
- (may_use_included ? s_info->bytes_may_use : 0);
- }
-
-@@ -358,7 +377,7 @@ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
- enum btrfs_reserve_flush_enum flush);
- void btrfs_try_granting_tickets(struct btrfs_space_info *space_info);
- bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
-- enum btrfs_reserve_flush_enum flush);
-+ enum btrfs_reserve_flush_enum flush, bool reloc);
-
- static inline void btrfs_space_info_free_bytes_may_use(
- struct btrfs_space_info *space_info,
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 0369a7c04c54f..cb844168fde51 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -821,6 +821,7 @@ SPACE_INFO_ATTR(bytes_stripe_unusable);
- SPACE_INFO_ATTR(bytes_stripe_claimable);
- SPACE_INFO_ATTR(bytes_stripe_open);
- SPACE_INFO_ATTR(bytes_stripe_margin);
-+SPACE_INFO_ATTR(bytes_stripe_reserve);
- SPACE_INFO_ATTR(disk_used);
- SPACE_INFO_ATTR(disk_total);
- SPACE_INFO_ATTR(reclaim_count);
-@@ -953,6 +954,7 @@ static struct attribute *space_info_attrs[] = {
- BTRFS_ATTR_PTR(space_info, bytes_stripe_claimable),
- BTRFS_ATTR_PTR(space_info, bytes_stripe_open),
- BTRFS_ATTR_PTR(space_info, bytes_stripe_margin),
-+ BTRFS_ATTR_PTR(space_info, bytes_stripe_reserve),
- BTRFS_ATTR_PTR(space_info, disk_used),
- BTRFS_ATTR_PTR(space_info, disk_total),
- BTRFS_ATTR_PTR(space_info, bg_reclaim_threshold),
---
-2.47.3
-
--- /dev/null
+From 09ecfab617ebaa1cb76f626ebe7c752342436e7f Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 22 Oct 2026 04:02:52 -0400
+Subject: [RFC PATCH 51/85] btrfs: stripe_alloc: back off stripe reclaim after
+ repeated ENOSPC
+To: linux-btrfs@vger.kernel.org
+
+The reclaim worker backs off a space_info after repeated -ENOSPC failures.
+Under stripe_alloc two more paths queue trapped groups, the commit-time
+rescan and the cleaner tick, every five minutes each; have them honour the
+backoff too, and have the reclaim predicate require room for relocation's
+up-front metadata reservation as well. A stripe_reclaim_now request is
+still tried during a backoff.
+
+It showed in two ways:
+
+ - The octopus P1 pass (raid5 6 x 3 GiB, misc-next, bhive 2026-10-20):
+ with the data space fully allocated and ~2 GiB trapped, reclaim held the
+ exclusive operation for over an hour of fsstress and long after it,
+ "error relocating chunk ...: -28" repeating (28 attempts, 13 errors in
+ one loop), so a resize could not start and the replace failed. The
+ worker sat in a metadata reservation (btrfs_block_rsv_refill under
+ relocate_block_group): metadata had no room either.
+
+ - reclaim-futile-test.sh (raid5 6 x 1 GiB at the edge, fsstress churn):
+ 226 reclaim errors in 600 s. Of the -28 returns, relocation's data
+ reservation lost the claimable stripes the room check had counted to
+ the concurrent writers.
+
+The room check (claimable stripes in the other groups) is an estimate
+taken when the group is queued, and it did not cover metadata: it now
+also requires room for relocation's up-front metadata reservation (512
+tree blocks, twice RELOCATION_RESERVED_NODES), which the octopus failure
+needed.
+
+Tested: reclaim-futile-test.sh measured 226 reclaim errors in 600 s on the
+lane without the backoff (the fill-edge shape that loops; it does not loop
+on every run). With it no run logged more than 5 errors per 600 s; in one,
+five relocations failed with -ENOSPC and reclaim backed off once
+(reclaim_backoffs +1), then resumed. stripe-reclaim-test and
+stripe-reclaim-now-test pass.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 9 ++++++---
+ fs/btrfs/free-space-cache.c | 34 +++++++++++++++++++++++++++++++++-
+ 2 files changed, 39 insertions(+), 4 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 7050b82514cb6..2af51e4883cb6 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -4531,7 +4531,7 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+
+ /*
+ * Reclaim gives up on a space_info for a while after this many reclaims in a
+- * row failed with -ENOSPC. Relocating a group needs room for
++ * row failed with -ENOSPC. Relocating or compacting a group needs room for
+ * its live data (and metadata reservations for moving it); at the fill edge
+ * there is none, every attempt fails after doing its work, and retrying each
+ * failed group on every worker run held the balance exclusive operation for
+@@ -4655,9 +4655,10 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
+ /*
+ * Backing off: drop the group rather than requeue it. The
+ * rescans and usage updates queue it again once reclaim may
+- * succeed.
++ * succeed. A stripe_reclaim_now request is tried regardless.
+ */
+- if (btrfs_reclaim_backoff_active(space_info)) {
++ if (!READ_ONCE(bg->stripe_reclaim_forced) &&
++ btrfs_reclaim_backoff_active(space_info)) {
+ ret = 0;
+ } else {
+ int before = reclaimed;
+@@ -4745,6 +4746,8 @@ static void btrfs_stripe_reclaim_tick(struct btrfs_fs_info *fs_info)
+ continue;
+ if (!btrfs_stripe_bg_wants_reclaim(bg))
+ continue;
++ if (btrfs_reclaim_backoff_active(sinfo))
++ break;
+ spin_lock(&bg->lock);
+ if (btrfs_mark_bg_to_reclaim(bg))
+ bg->stripe_reclaim_jiffies = jiffies ?: 1;
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 1078f2019743f..eaed680e362dc 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -2430,6 +2430,33 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+ * and queueing a group with nowhere to move it only costs writers read-only
+ * transitions. Counters are read unlocked; the worker re-checks.
+ */
++/*
++ * Relocation reserves metadata before it moves anything: 256 tree blocks
++ * up front (RELOCATION_RESERVED_NODES), doubled on its first shortfall. When
++ * the metadata space_info can neither hold nor overcommit that, relocating
++ * or compacting a data group fails with -ENOSPC after the group was made
++ * read-only, while the worker held the exclusive operation (octopus P1 at the
++ * fill edge, bhive 2026-10-20: the data side had room, metadata had none).
++ */
++#define STRIPE_RECLAIM_META_NODES 512
++
++static bool stripe_reclaim_meta_room(struct btrfs_fs_info *fs_info)
++{
++ struct btrfs_space_info *meta;
++ const u64 bytes = (u64)fs_info->nodesize * STRIPE_RECLAIM_META_NODES;
++
++ bool ok;
++
++ meta = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
++ if (!meta)
++ return true;
++ spin_lock(&meta->lock);
++ ok = btrfs_space_info_used(meta, true) + bytes <= meta->total_bytes ||
++ btrfs_can_overcommit(meta, bytes, BTRFS_RESERVE_FLUSH_ALL);
++ spin_unlock(&meta->lock);
++ return ok;
++}
++
+ static enum stripe_reclaim_kind __stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
+ int thresh, bool force,
+ bool check_room,
+@@ -2486,7 +2513,9 @@ static enum stripe_reclaim_kind __stripe_bg_reclaim_kind(struct btrfs_block_grou
+ READ_ONCE(sinfo->bytes_stripe_margin);
+ elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
+ elsewhere -= min(elsewhere, promised);
+- return elsewhere + extra_room >= need ? kind : STRIPE_RECLAIM_NONE;
++ if (elsewhere + extra_room < need)
++ return STRIPE_RECLAIM_NONE;
++ return stripe_reclaim_meta_room(bg->fs_info) ? kind : STRIPE_RECLAIM_NONE;
+ }
+
+ static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
+@@ -2586,6 +2615,9 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
+ }
+ spin_unlock(&ctl->tree_lock);
+ kvfree(freep);
++ /* Reclaim backing off after ENOSPC: leave the group, the stamp too. */
++ if (reclaim && btrfs_reclaim_backoff_active(bg->space_info))
++ reclaim = false;
+ if (reclaim) {
+ /*
+ * Stamp the hysteresis only if the mark lands: a group still on
+--
+2.47.3
+
+++ /dev/null
-From a345272f69ec86151bdbbf98cbcd474333c50386 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:13 -0400
-Subject: [RFC PATCH 051/116] btrfs: stripe_meta: do not steal from the global
- reserve below the relocation reserve
-To: linux-btrfs@vger.kernel.org
-
-With the whole-stripe reserve in place the fill stopped cleanly at the
-edge: 374 MiB claimable, the reserve plus margin plus the outstanding
-reservations, no canary, no abort. Then the test deleted half of its
-tiny files, and every unlink that the gate refused came back through
-the global reserve steal, which does not look at stripes. Deleting an
-inline file is pure COW churn under stripe_meta: it frees no stripe,
-since the leaf it lived in stays, and each transaction of unlinks takes
-fresh stripes. Metadata used did not move by a megabyte while the
-claimable supply went from 374 MiB to zero, and the next commit aborted
-with the canary ("claimable 0 open 1490944 trapped 1506082816").
-
-Refuse the steal once the claimable supply is down to the relocation
-reserve plus the claim margin. The unlink fails with ENOSPC, which is
-recoverable, instead of the abort, which is not, and the reserve stays
-with the background relocation that is the only thing that turns
-trapped space back into whole stripes.
-
-Mount-time orphan cleanup is the exception. Eviction takes its space
-from the steal (BTRFS_RESERVE_FLUSH_EVICT), and when an eviction fails
-btrfs_orphan_cleanup() finds the same orphan again and stops with
--EINVAL, which fails the read-write mount. A filesystem that cannot be
-mounted read-write can never run the relocation the reserve is kept
-for, so the task running the cleanup in btrfs_start_pre_rw_mount()
-(fs_info->mount_cleanup_task, mount and ro->rw remount) may steal
-regardless; its consumption is bounded by the orphans on disk.
-
-Assisted-by: Claude:claude-fable-5
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/disk-io.c | 7 ++++++-
- fs/btrfs/fs.h | 9 +++++++++
- fs/btrfs/space-info.c | 26 ++++++++++++++++++++++++++
- 3 files changed, 41 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index 37d87114f69e4..8986bab67590e 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -3145,17 +3145,22 @@ int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
- if (ret)
- return ret;
-
-+ WRITE_ONCE(fs_info->mount_cleanup_task, current);
- ret = btrfs_cleanup_fs_roots(fs_info);
-- if (ret)
-+ if (ret) {
-+ WRITE_ONCE(fs_info->mount_cleanup_task, NULL);
- return ret;
-+ }
-
- down_read(&fs_info->cleanup_work_sem);
- if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
- (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
- up_read(&fs_info->cleanup_work_sem);
-+ WRITE_ONCE(fs_info->mount_cleanup_task, NULL);
- return ret;
- }
- up_read(&fs_info->cleanup_work_sem);
-+ WRITE_ONCE(fs_info->mount_cleanup_task, NULL);
-
- mutex_lock(&fs_info->cleaner_mutex);
- ret = btrfs_recover_relocation(fs_info);
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index ff46ee994eb61..bb0ac9ce4ccba 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -800,6 +800,15 @@ struct btrfs_fs_info {
- * all -- are relocation's too, and may draw on the same reserve.
- */
- struct task_struct *reloc_owner;
-+ /*
-+ * The task running the mount-time (and ro->rw remount) orphan
-+ * cleanup in btrfs_start_pre_rw_mount(). Its evictions may steal
-+ * from the global reserve even below the stripe_meta reserve: a
-+ * mount that cannot finish orphan cleanup fails, and a filesystem
-+ * that cannot be mounted read-write can never run the relocation
-+ * the reserve is held back for.
-+ */
-+ struct task_struct *mount_cleanup_task;
-
- /* data_alloc_cluster is only used in ssd_spread mode */
- struct btrfs_free_cluster data_alloc_cluster;
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index df50d0c7e1fd2..ed883c7b398cb 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -189,6 +189,8 @@ struct reserve_ticket {
- bool steal;
- /* Made by the relocation task: may draw on bytes_stripe_reserve. */
- bool reloc;
-+ /* Made by the mount-time orphan cleanup: may steal regardless. */
-+ bool mount_cleanup;
- struct list_head list;
- wait_queue_head_t wait;
- spinlock_t lock;
-@@ -1286,6 +1288,28 @@ static bool steal_from_global_rsv(struct btrfs_space_info *space_info,
- if (global_rsv->space_info != space_info)
- return false;
-
-+ /*
-+ * stripe_meta: the global reserve is refilled by fiat at every
-+ * commit, so its bytes are only as real as the whole stripes behind
-+ * them. Once the claimable supply is down to the relocation reserve,
-+ * a stolen reservation admits a transaction that consumes fresh
-+ * stripes through COW while everything it frees comes back trapped
-+ * (an unlink of an inline file returns nothing at all), until a tree
-+ * block finds no stripe and the commit aborts. Refuse the steal:
-+ * -ENOSPC from an unlink is recoverable, an abort is not, and the
-+ * reserve stays with the background relocation that will make room.
-+ */
-+ /*
-+ * Except for the mount-time orphan cleanup: its evictions are bounded
-+ * by the orphans on disk, and refusing them fails the mount, which
-+ * leaves no way to run the relocation the reserve is kept for.
-+ */
-+ if (space_info->bytes_stripe_reserve && !ticket->mount_cleanup &&
-+ space_info->bytes_stripe_claimable <
-+ space_info->bytes_stripe_reserve + space_info->bytes_stripe_margin +
-+ ticket->bytes)
-+ return false;
-+
- spin_lock(&global_rsv->lock);
- min_bytes = mult_perc(global_rsv->size, 10);
- if (global_rsv->reserved < min_bytes + ticket->bytes) {
-@@ -2059,6 +2083,8 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
- spin_lock_init(&ticket.lock);
- ticket.steal = can_steal(flush);
- ticket.reloc = reloc;
-+ ticket.mount_cleanup =
-+ READ_ONCE(fs_info->mount_cleanup_task) == current;
- if (trace_btrfs_reserve_ticket_enabled())
- start_ns = ktime_get_ns();
-
---
-2.47.3
-
--- /dev/null
+From c76ecce44b21c74f5e253d032b848547a34165c8 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:31 -0400
+Subject: [RFC PATCH 52/85] btrfs: stripe_alloc: settle a logged extent's
+ stripes at log commit
+To: linux-btrfs@vger.kernel.org
+
+Stripe-exclusive allocation bounds degraded-crash damage to the current
+transaction, but within that window two log commits can still share a
+stripe: fsync 1 writes the head of a stripe, the open run keeps filling
+it, and a later write's read-modify-write rewrites the parity that
+protects fsync 1's data. A degraded crash during the second write tears
+the first -- the write hole's shape, confined to the log window, and the
+reason the fsync guarantee has so far been "loss is detectable" rather
+than "completed fsyncs survive".
+
+Close it with a case analysis. A logged extent in a full stripe is
+already safe: nothing ever writes a full stripe again, since COW never
+overwrites and there are no free sectors left to allocate. A logged
+extent in a partial stripe is exposed only to future writes into that
+stripe's remaining sectors -- so at log commit, close the stripe's open
+run (nothing further allocates into it), kick any parked partial writes
+for it, and wait for its in-flight data IO before the log super is
+written. This is the log-window analogue of invariant I2, which the
+commit-time retirement provides for full commits. Both log paths are
+hooked: the fast path per extent map in log_one_extent(), and the
+full-sync path where copy_items() walks new data extents (old-transaction
+extents are skipped there, and are exactly the ones already settled by
+their own commit).
+
+The drain is join-free: write_done reporting needs no transaction join,
+so waiting under the inode log mutex and a running transaction handle is
+safe. It is not bounded: it has no timeout and waits for data IO to
+complete. Run inflight is counted from allocation, which happens during
+writeback with submission following in the same pass, so in practice the
+wait is bio flight time plus the parked-write deadline that the flush
+short-circuits. (A later patch shares LOG runs per log transaction and
+makes that the default; its settle waits until every allocated sector in
+the logged extent's stripes is written, other writers' sectors included,
+and is not bounded either.)
+
+The cost is spatial: every fsync that logs an extent in a partial stripe
+retires that stripe early, trapping its unwritten tail like any other
+partially filled stripe until it frees or balance reclaims it.
+Fsync-heavy workloads therefore burn a stripe tail per touched stripe
+per fsync; the follow-up per-inode log runs and copy-forward relocation
+exist to reclaim exactly that cost, and are optimizations on top of the
+guarantee this patch completes.
+
+On a filesystem that has gone into error the settle wait does not sleep
+for IO: the log commit fails anyway, and the ordered extents in flight are
+only torn down at unmount.
+
+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 | 81 ++++++++++++++++++++++++++++++++++++++++++
+ fs/btrfs/block-group.h | 2 ++
+ fs/btrfs/tree-log.c | 29 +++++++++++++++
+ 3 files changed, 112 insertions(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 2af51e4883cb6..7b3a8827302e7 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1731,6 +1731,24 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ }
+
+
++/* No open or draining run covers @bytenr any more. */
++static bool stripe_log_range_settled(struct btrfs_block_group *bg, u64 bytenr)
++{
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ bool settled = true;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (bytenr >= run->start && bytenr < run->offset) {
++ settled = false;
++ break;
++ }
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ return settled;
++}
++
+ /*
+ * Disk end of @inode's last regular file extent, or 0: the re-adoption
+ * candidate for a nocow allocation arriving with no allocation hint --
+@@ -1848,6 +1866,69 @@ void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
+ spin_unlock(&fs_info->open_stripe_lock);
+ }
+
++/*
++ * A log commit is about to make the extent at [bytenr, bytenr + num_bytes)
++ * durable. Once the log super lands, no later write may extend or RMW the
++ * extent's stripes -- the log-window analogue of invariant I2, which the
++ * commit-time retirement provides for full commits. Close the open run
++ * covering the extent so nothing further allocates into its stripes, kick
++ * any parked partial writes for it, and wait for all data IO into it to
++ * finish. Extents in full or already-settled stripes cost one list walk.
++ *
++ * The drain is bounded: run inflight is counted from allocation, which
++ * happens during writeback with submission following in the same pass, so
++ * the wait is bio flight time plus the parked-write deadline that the flush
++ * below short-circuits. It is a pure data-IO wait (no transaction joins),
++ * safe under the inode log mutex and a running transaction handle.
++ */
++void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
++ u64 num_bytes)
++{
++ struct btrfs_block_group *bg;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ u64 tail_start = 0;
++ u64 tail_len = 0;
++ u64 flush_start = 0;
++ u64 flush_len = 0;
++
++ if (list_empty_careful(&fs_info->open_stripe_bgs))
++ return;
++ bg = btrfs_lookup_block_group(fs_info, bytenr);
++ if (!bg)
++ return;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (bytenr < run->start || bytenr >= run->offset)
++ continue;
++ flush_start = run->start;
++ flush_len = run->end - run->start;
++ if (run->open) {
++ int class;
++ int band;
++
++ 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)
++ bg->open_stripe[class][band] = NULL;
++ tail_len = close_open_stripe_run(bg, run, &tail_start);
++ }
++ break;
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++
++ if (tail_len)
++ btrfs_add_free_space(bg, tail_start, tail_len);
++ if (flush_len) {
++ btrfs_flush_parked_rbios(fs_info, flush_start, flush_len, false);
++ wait_var_event(&bg->open_stripe_runs,
++ stripe_log_range_settled(bg, bytenr) ||
++ BTRFS_FS_ERROR(fs_info));
++ }
++ btrfs_put_block_group(bg);
++}
++
+ /*
+ * Can stripe-exclusive allocation be enabled on this filesystem? Called for
+ * the "stripe_alloc" filesystem property, on a mounted (or mounting, options
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 5e32c44017212..32bbbad20a817 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -544,6 +544,8 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
+ u64 num_bytes, u32 which, bool nowait);
+ int btrfs_parse_stripe_rmw(const char *value, size_t len, u32 *mask);
++void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
++ u64 num_bytes);
+ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
+ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
+ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
+diff --git a/fs/btrfs/tree-log.c b/fs/btrfs/tree-log.c
+index e50f924bca59f..6aa8db5b1044e 100644
+--- a/fs/btrfs/tree-log.c
++++ b/fs/btrfs/tree-log.c
+@@ -4875,6 +4875,23 @@ static noinline int copy_items(struct btrfs_trans_handle *trans,
+ return BTRFS_LOG_FORCE_COMMIT;
+ }
+
++ /*
++ * New data extent made durable by this log commit: settle its
++ * stripes. This must not hide behind the csum skips below --
++ * a nodatasum inode's extents need their stripes settled all
++ * the same. Inline extents and holes have no stripes.
++ */
++ if (!is_old_extent &&
++ btrfs_file_extent_type(src, extent) == BTRFS_FILE_EXTENT_REG) {
++ disk_bytenr = btrfs_file_extent_disk_bytenr(src, extent);
++ disk_num_bytes =
++ btrfs_file_extent_disk_num_bytes(src, extent);
++ if (disk_bytenr)
++ btrfs_log_settle_stripes(trans->fs_info,
++ disk_bytenr,
++ disk_num_bytes);
++ }
++
+ if (skip_csum)
+ goto add_to_batch;
+
+@@ -5163,6 +5180,18 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
+
+ block_len = em->disk_num_bytes;
+ compress_type = btrfs_extent_map_compression(em);
++
++ /*
++ * This log commit makes the extent durable: settle its stripes so no
++ * later write in this transaction can tear them (see
++ * btrfs_log_settle_stripes()). Preallocated extents carry no data
++ * and holes have no stripes; both are skipped.
++ */
++ if (!(em->flags & EXTENT_FLAG_PREALLOC) &&
++ em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
++ btrfs_log_settle_stripes(inode->root->fs_info, em->disk_bytenr,
++ em->disk_num_bytes);
++
+ if (compress_type != BTRFS_COMPRESS_NONE) {
+ btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start);
+ btrfs_set_stack_file_extent_disk_num_bytes(&fi, block_len);
+--
+2.47.3
+
+++ /dev/null
-From e14fa735950e55e7e840b6e6a5c60af1bf5525e1 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:14 -0400
-Subject: [RFC PATCH 052/116] btrfs: stripe_meta: let the transaction
- machinery's own reservations draw on the reserve
-To: linux-btrfs@vger.kernel.org
-
-With the whole-stripe reserve counted as used for everyone but the
-relocation task, a committing transaction whose handle reserve runs dry
-mid-COW gets ENOSPC from btrfs_use_block_rsv(): its NO_FLUSH fallback
-reservation is refused as soon as the claimable supply is below the
-reserve, and the global reserve behind it has been refilled by fiat
-against stripes that do not exist. Seen on the delete phase of the
-metadata fill test with relocation running: claimable 163 MiB, reserve
-352 MiB, delayed refs freeing the deleted leaves, and the extent tree
-COW that freeing needs aborted the transaction with ENOSPC while
-163 MiB of whole stripes sat unused (no allocator canary: the allocator
-was never asked).
-
-The reserve exists to hold back user operations so relocation and the
-commit that follows it have room; it must not hold back the commit.
-Let NO_FLUSH, FLUSH_LIMIT (delayed refs, delayed inodes) and EMERGENCY
-reservations draw on it like relocation does. They are bounded and
-kernel-internal; user reservations (FLUSH_ALL, ALL_STEAL, EVICT, DATA)
-still stop at the reserve.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/space-info.c | 14 +++++++++++++-
- 1 file changed, 13 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index ed883c7b398cb..41ade2b7e89a1 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -2003,8 +2003,20 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
- u64 used;
- int ret = -ENOSPC;
- bool pending_tickets;
-+ /*
-+ * Who may draw on the stripe_meta reserve (bytes_stripe_reserve):
-+ * the relocation task, which is what the reserve is for, and the
-+ * transaction machinery's own bounded reservations -- NO_FLUSH from
-+ * btrfs_use_block_rsv() when a handle's reserve runs dry mid-COW,
-+ * FLUSH_LIMIT for delayed refs and delayed inodes, EMERGENCY -- which
-+ * a committing transaction cannot fail without aborting. User
-+ * operations (FLUSH_ALL, ALL_STEAL, EVICT, DATA) stay behind it.
-+ */
- const bool reloc = (READ_ONCE(fs_info->reloc_task) == current) ||
-- (READ_ONCE(fs_info->reloc_owner) == current);
-+ (READ_ONCE(fs_info->reloc_owner) == current) ||
-+ flush == BTRFS_RESERVE_NO_FLUSH ||
-+ flush == BTRFS_RESERVE_FLUSH_LIMIT ||
-+ flush == BTRFS_RESERVE_FLUSH_EMERGENCY;
-
- ASSERT(orig_bytes, "orig_bytes=%llu", orig_bytes);
- /*
---
-2.47.3
-
--- /dev/null
+From e1e8599602e0ab71282791410e7db2f0b3e9a6ac Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:45 -0400
+Subject: [RFC PATCH 53/85] btrfs: stripe_alloc: count open stripe run
+ remainders against data reservations (fsync part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: count open stripe run remainders
+against data reservations" (earlier in this series) that need code from
+"btrfs: stripe_alloc: settle a logged extent's stripes at log commit",
+which comes after it in this series: they are applied here, once "btrfs:
+stripe_alloc: settle a logged extent's stripes at log commit" is in,
+instead of with the rest of "btrfs: stripe_alloc: count open stripe run
+remainders against data reservations".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 4 +++-
+ 1 file changed, 3 insertions(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 7b3a8827302e7..080e2707239be 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1918,8 +1918,10 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+
+- if (tail_len)
++ if (tail_len) {
+ btrfs_add_free_space(bg, tail_start, tail_len);
++ stripe_open_remainder_sync(bg);
++ }
+ if (flush_len) {
+ btrfs_flush_parked_rbios(fs_info, flush_start, flush_len, false);
+ wait_var_event(&bg->open_stripe_runs,
+--
+2.47.3
+
+++ /dev/null
-From 046e0e80fdb7b805226ce232e0302807a1d4c4af Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:15 -0400
-Subject: [RFC PATCH 053/116] btrfs: stripe_meta: let a group go read-only for
- relocation against the reserve
-To: linux-btrfs@vger.kernel.org
-
-The read-only guard keeps admitted bytes placeable by refusing to take a
-group's usable free space out of the supply when the space_info could
-not absorb it. With the whole-stripe reserve counted as used, that
-refusal comes by the width of the reserve at the fill edge: two
-eligible metadata groups sat marked for reclaim through a 300 second
-wait and the worker dropped each on inc_block_group_ro() -- the
-space_info was 7 MiB short of the check with 376 MiB of whole stripes
-claimable, 352 MiB of them the reserve that exists for this move.
-
-Going read-only is the first step of relocation, so let the guard draw
-on the reserve the way relocation's own reservations do.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 9 ++++++++-
- 1 file changed, 8 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 3225bc71af203..6032c4dc6f7fe 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -3998,8 +3998,15 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
-
- if (READ_ONCE(cache->stripe_unusable_ready))
- trapped = min(READ_ONCE(cache->stripe_unusable), num_bytes);
-+ /*
-+ * The stripe_meta reserve is the room a group's live blocks
-+ * move into when it is relocated, and going read-only is the
-+ * first step of exactly that: count the reserve as available
-+ * here, or the guard refuses every relocation at the edge by
-+ * the width of the reserve.
-+ */
- if (btrfs_can_overcommit(sinfo, num_bytes - trapped,
-- BTRFS_RESERVE_NO_FLUSH, false))
-+ BTRFS_RESERVE_NO_FLUSH, true))
- ret = 0;
- }
-
---
-2.47.3
-
--- /dev/null
+From 480cf210e8b628cc824e3a754f3cd900cd781327 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:40 -0400
+Subject: [RFC PATCH 54/85] btrfs: stripe_alloc: allow-rmw policy, and
+ write-in-place for isolated nocow extents (fsync part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: allow-rmw policy, and write-in-place
+for isolated nocow extents" (earlier in this series) that need code from
+"btrfs: stripe_alloc: settle a logged extent's stripes at log commit",
+which comes after it in this series: they are applied here, once "btrfs:
+stripe_alloc: settle a logged extent's stripes at log commit" is in,
+instead of with the rest of "btrfs: stripe_alloc: allow-rmw policy, and
+write-in-place for isolated nocow extents".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 11 +++++++++++
+ 1 file changed, 11 insertions(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 080e2707239be..1eabdc2653b26 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1892,6 +1892,9 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
+ u64 flush_start = 0;
+ u64 flush_len = 0;
+
++ /* stripe_alloc_allow_rmw=fsync waives the log-commit guarantee. */
++ if (btrfs_stripe_allow_rmw(fs_info) & BTRFS_STRIPE_RMW_FSYNC)
++ return;
+ if (list_empty_careful(&fs_info->open_stripe_bgs))
+ return;
+ bg = btrfs_lookup_block_group(fs_info, bytenr);
+@@ -1902,6 +1905,14 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+ if (bytenr < run->start || bytenr >= run->offset)
+ continue;
++ /*
++ * A nodatacow file's logged extents get no fsync survival
++ * guarantee -- the file's own later in-place writes can
++ * always tear them -- so closing its run would trap the
++ * tail for nothing.
++ */
++ if (run->class == BTRFS_STRIPE_RUN_NOCOW)
++ break;
+ flush_start = run->start;
+ flush_len = run->end - run->start;
+ if (run->open) {
+--
+2.47.3
+
+++ /dev/null
-From b3cc985b256acbf78501db4bf618b11f962e5663 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:16 -0400
-Subject: [RFC PATCH 054/116] btrfs: stripe_alloc: show per-group trapped bytes
- in the space info dump
-To: linux-btrfs@vger.kernel.org
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/space-info.c | 6 +++++-
- 1 file changed, 5 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 41ade2b7e89a1..07e5aacc07c58 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -864,11 +864,15 @@ void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
-
- spin_lock(&cache->lock);
- avail = btrfs_block_group_available_space(cache);
-+ if (READ_ONCE(cache->stripe_unusable_ready))
-+ avail -= min(avail, READ_ONCE(cache->stripe_unusable));
- btrfs_info(fs_info,
--"block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %llu delalloc %llu super %llu zone_unusable (%llu bytes available) %s",
-+"block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %llu delalloc %llu super %llu zone_unusable %llu stripe_unusable (%llu bytes available) %s",
- cache->start, cache->length, cache->used, cache->pinned,
- cache->reserved, cache->delalloc_bytes,
- cache->bytes_super, cache->zone_unusable,
-+ READ_ONCE(cache->stripe_unusable_ready) ?
-+ READ_ONCE(cache->stripe_unusable) : 0,
- avail, cache->ro ? "[readonly]" : "");
- spin_unlock(&cache->lock);
- btrfs_dump_free_space(cache, bytes);
---
-2.47.3
-
--- /dev/null
+From 026d160272731cde3642ea1c7017802fbc51ee70 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:37 -0400
+Subject: [RFC PATCH 55/85] btrfs: stripe_alloc: carry an inode's log tail
+ forward at fsync
+To: linux-btrfs@vger.kernel.org
+
+Closing a log-active inode's private stripe run at each log commit
+traps the run's final partial stripe tail every time the inode fsyncs:
+a steady fsync stream burns one stripe per log commit until the stripes
+free or balance runs.
+
+Reclaim the tails by carrying the partial stripe's live data forward.
+At each log commit, the settling walk now computes the closed run's
+final partial stripe, and the logging paths record the file ranges of
+the logged extents that live inside it on a small per-inode table
+(bounded; overflow just means an extent is not carried). At the
+inode's next fsync, before its delalloc flush, each recorded range that
+still maps to the recorded disk bytenr is re-dirtied, defrag style
+(reserve, reset delalloc state, mark the folios dirty; absent folios
+are read back, which is a plain read of settled data). The flush then
+COWs the carried ranges together with the new data into the inode's
+current private run, and the old partial stripe empties and frees
+whole.
+
+Everything downstream is the ordinary COW pipeline: new extent maps,
+ordered extents, checksums, file extent items and delayed refs, and
+the log's modified-extents snapshot -- taken inside btrfs_log_inode
+after the flush -- picks up the new addresses by itself. Reflinked
+ranges need no special handling: foreign referents keep the old extent
+alive in its closed (never again written) stripe, and only the space
+reclaim degrades. A range that was rewritten, truncated, punched or
+compressed simply fails the mapping check and stays put.
+
+Crash safety does not regress. A carried extent's old copy is dropped
+through the normal paths: if it was committed, the free pins until the
+transaction commits; if it was logged but never committed, its ADD and
+DROP delayed refs cancel in cleanup_ref_head(), which also pins
+must_insert_reserved heads -- either way the old blocks cannot be
+reallocated before the log that references them is superseded.
+
+The settling walk also learned to report the partial stripe through a
+widened btrfs_log_settle_stripes() signature (inode and file range
+instead of fs_info); compressed extents pass a zero file length to opt
+out of carrying while still settling.
+
+The re-dirty reserves with NO_FLUSH. carry_one_range() takes the folio
+locks and the extent range lock before reserving, and a flushing
+(ticketed) reservation can sleep in wait_reserve_ticket() until the
+flusher makes progress -- but every way forward needs the locks we
+hold: FLUSH_DELALLOC has to write back the carried range, which blocks
+in __folio_lock() on our locked folio, and a transaction commit (with
+flushoncommit) waits for the same writeback. The whole filesystem then
+wedges behind the stuck commit. Carrying is best effort by design and
+the carried range's data is already durable in its old stripe, so on
+ENOSPC just skip the carry and let the old stripe free the slow way.
+
+The carry's reservation does not flush at all, including the qgroup
+reserve: btrfs_check_data_free_space_noflush() reserves data space and
+qgroup space without flushing, since try_flush_qgroup() would write back
+the folios the carry holds locked. On EDQUOT, as on ENOSPC, the range is
+just not carried. The carry also clears a stale EXTENT_NORESERVE (left by
+a NOCOW write) with the other delalloc bits, so the data space it reserved
+is released when the range is later written NOCOW.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+Assisted-by: Claude:claude-opus-5
+---
+ fs/btrfs/block-group.c | 90 ++++++++++++++++++++-
+ fs/btrfs/block-group.h | 4 +-
+ fs/btrfs/btrfs_inode.h | 31 +++++++
+ fs/btrfs/defrag.c | 165 ++++++++++++++++++++++++++++++++++++++
+ fs/btrfs/defrag.h | 1 +
+ fs/btrfs/delalloc-space.c | 35 +++++++-
+ fs/btrfs/delalloc-space.h | 3 +
+ fs/btrfs/file.c | 11 +++
+ fs/btrfs/inode.c | 3 +
+ fs/btrfs/qgroup.c | 12 +++
+ fs/btrfs/qgroup.h | 3 +
+ fs/btrfs/tree-log.c | 15 ++--
+ 12 files changed, 360 insertions(+), 13 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 1eabdc2653b26..e58d3e96bcc0a 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -543,6 +543,11 @@ static u64 stripe_round_down(u64 val, u64 fsl)
+ return div64_u64(val, fsl) * fsl;
+ }
+
++static bool stripe_is_aligned(u64 val, u64 fsl)
++{
++ return stripe_round_down(val, fsl) == val;
++}
++
+ /*
+ * 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))
+@@ -1749,6 +1754,63 @@ static bool stripe_log_range_settled(struct btrfs_block_group *bg, u64 bytenr)
+ return settled;
+ }
+
++/*
++ * Remember, on the logging inode, a logged extent that lives in the final
++ * partial stripe of one of the inode's recently closed runs, so that the
++ * next fsync can re-dirty its file range and carry the data forward into
++ * the then-current run -- letting the old partial stripe free whole. A
++ * zero @file_len means the caller does not want this extent carried
++ * (e.g. compressed extents, which would recompress). @ps_len is nonzero
++ * when the settling walk could see the run and computed its final partial
++ * stripe. Every table here is small and bounded; on overflow the extent
++ * simply is not carried and its stripe frees the slow way. Caller holds
++ * the inode's log_mutex, which serializes against the fsync-entry consumer.
++ */
++static void log_carry_record(struct btrfs_inode *inode, u64 file_start,
++ u64 file_len, u64 bytenr, u64 num_bytes,
++ u64 ps_start, u64 ps_len)
++{
++ struct btrfs_log_carry *carry = inode->log_carry;
++ int n, i;
++
++ if (!carry) {
++ carry = kzalloc(sizeof(*carry), GFP_NOFS);
++ if (!carry)
++ return;
++ inode->log_carry = carry;
++ }
++ if (ps_len) {
++ n = min_t(int, carry->nr_ps, BTRFS_LOG_CARRY_NR_PS);
++ for (i = 0; i < n; i++)
++ if (carry->ps_start[i] == ps_start)
++ break;
++ if (i == n) {
++ int slot = carry->nr_ps % BTRFS_LOG_CARRY_NR_PS;
++
++ carry->ps_start[slot] = ps_start;
++ carry->ps_len[slot] = ps_len;
++ carry->nr_ps++;
++ }
++ }
++ if (!file_len || carry->nr_ranges >= BTRFS_LOG_CARRY_NR_RANGES)
++ return;
++ n = min_t(int, carry->nr_ps, BTRFS_LOG_CARRY_NR_PS);
++ for (i = 0; i < n; i++)
++ if (bytenr < carry->ps_start[i] + carry->ps_len[i] &&
++ bytenr + num_bytes > carry->ps_start[i])
++ break;
++ if (i == n)
++ return;
++ for (i = 0; i < carry->nr_ranges; i++)
++ if (carry->range[i].start == file_start &&
++ carry->range[i].len == file_len)
++ return;
++ carry->range[carry->nr_ranges].start = file_start;
++ carry->range[carry->nr_ranges].len = file_len;
++ carry->range[carry->nr_ranges].disk_bytenr = bytenr;
++ carry->nr_ranges++;
++}
++
+ /*
+ * Disk end of @inode's last regular file extent, or 0: the re-adoption
+ * candidate for a nocow allocation arriving with no allocation hint --
+@@ -1880,10 +1942,15 @@ void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
+ * the wait is bio flight time plus the parked-write deadline that the flush
+ * below short-circuits. It is a pure data-IO wait (no transaction joins),
+ * safe under the inode log mutex and a running transaction handle.
++ *
++ * [file_start, file_start + file_len) is the extent's file range, recorded
++ * for carry-forward when the extent sits in the run's final partial stripe;
++ * file_len == 0 opts the extent out of carrying (settling still happens).
+ */
+-void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
+- u64 num_bytes)
++void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
++ u64 file_len, u64 bytenr, u64 num_bytes)
+ {
++ struct btrfs_fs_info *fs_info = inode->root->fs_info;
+ struct btrfs_block_group *bg;
+ struct btrfs_open_stripe_run *run;
+ unsigned long flags;
+@@ -1891,6 +1958,8 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
+ u64 tail_len = 0;
+ u64 flush_start = 0;
+ u64 flush_len = 0;
++ u64 ps_start = 0;
++ u64 ps_len = 0;
+
+ /* stripe_alloc_allow_rmw=fsync waives the log-commit guarantee. */
+ if (btrfs_stripe_allow_rmw(fs_info) & BTRFS_STRIPE_RMW_FSYNC)
+@@ -1903,6 +1972,8 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ u64 filled;
++
+ if (bytenr < run->start || bytenr >= run->offset)
+ continue;
+ /*
+@@ -1915,6 +1986,18 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
+ break;
+ flush_start = run->start;
+ flush_len = run->end - run->start;
++ /*
++ * The run's final partial stripe, whether this call closes
++ * the run or an earlier settle already did (offset froze at
++ * close). Runs start stripe-aligned, so alignment relative
++ * to run->start is stripe alignment.
++ */
++ filled = run->offset - run->start;
++ if (!stripe_is_aligned(filled, bg->full_stripe_len)) {
++ ps_start = run->start +
++ stripe_round_down(filled, bg->full_stripe_len);
++ ps_len = bg->full_stripe_len;
++ }
+ if (run->open) {
+ int class;
+ int band;
+@@ -1929,6 +2012,9 @@ void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+
++ log_carry_record(inode, file_start, file_len, bytenr, num_bytes,
++ ps_start, ps_len);
++
+ if (tail_len) {
+ btrfs_add_free_space(bg, tail_start, tail_len);
+ stripe_open_remainder_sync(bg);
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 32bbbad20a817..d6b2c12c7230c 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -544,8 +544,8 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
+ u64 num_bytes, u32 which, bool nowait);
+ int btrfs_parse_stripe_rmw(const char *value, size_t len, u32 *mask);
+-void btrfs_log_settle_stripes(struct btrfs_fs_info *fs_info, u64 bytenr,
+- u64 num_bytes);
++void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
++ u64 file_len, u64 bytenr, u64 num_bytes);
+ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info);
+ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info);
+ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info);
+diff --git a/fs/btrfs/btrfs_inode.h b/fs/btrfs/btrfs_inode.h
+index 663e925b14300..8cb09b291597a 100644
+--- a/fs/btrfs/btrfs_inode.h
++++ b/fs/btrfs/btrfs_inode.h
+@@ -140,6 +140,31 @@ enum {
+ BTRFS_INODE_ROOT_STUB,
+ };
+
++/*
++ * Carry-forward bookkeeping for a log-active inode whose LOG runs are
++ * private (stripe_log_data_shared clear). ps_start/ps_len remember the
++ * final partial stripes of the inode's recently closed private runs (a
++ * small ring; older entries are overwritten). range[] records the file
++ * ranges of logged extents living in those partial stripes, for the next
++ * fsync to re-dirty; disk_bytenr lets the consumer verify the range still
++ * maps there before carrying. Bounded loss: when the ring or the range
++ * table overflows, the extra extents simply stay put and their stripes free
++ * the slow way.
++ */
++#define BTRFS_LOG_CARRY_NR_PS 4
++#define BTRFS_LOG_CARRY_NR_RANGES 48
++struct btrfs_log_carry {
++ int nr_ps;
++ u64 ps_start[BTRFS_LOG_CARRY_NR_PS];
++ u64 ps_len[BTRFS_LOG_CARRY_NR_PS];
++ int nr_ranges;
++ struct {
++ u64 start;
++ u64 len;
++ u64 disk_bytenr;
++ } range[BTRFS_LOG_CARRY_NR_RANGES];
++};
++
+ /* in memory btrfs inode */
+ struct btrfs_inode {
+ /* which subvolume this inode belongs to */
+@@ -329,6 +354,12 @@ struct btrfs_inode {
+ u64 ref_root_id;
+ };
+
++ /*
++ * Carry-forward state (struct btrfs_log_carry), lazily allocated;
++ * recorded and consumed under log_mutex.
++ */
++ struct btrfs_log_carry *log_carry;
++
+ /*
+ * Start of the last extent allocated from one of this inode's private
+ * stripe runs (LOG or NOCOW class). Only a search hint, so
+diff --git a/fs/btrfs/defrag.c b/fs/btrfs/defrag.c
+index cbc532b49c67d..1e3bc1051b9d2 100644
+--- a/fs/btrfs/defrag.c
++++ b/fs/btrfs/defrag.c
+@@ -1263,6 +1263,171 @@ static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
+ return ret;
+ }
+
++/*
++ * Carry-forward for log-active inodes with private LOG runs (see struct
++ * btrfs_log_carry). Re-dirty a file range recorded at the last log commit
++ * so the coming writeback COWs it into the inode's current private stripe
++ * run and the old partial stripe can free whole. The range is carried only
++ * while it still fully maps to the recorded disk bytenr; a range that was
++ * rewritten, truncated, hole-punched or already carried fails that check
++ * and is skipped -- skipping only costs the space optimization, never
++ * correctness. Modeled on defrag_one_range().
++ */
++static int carry_one_range(struct btrfs_inode *inode, u64 start, u64 len,
++ u64 disk_bytenr)
++{
++ struct btrfs_fs_info *fs_info = inode->root->fs_info;
++ struct extent_changeset *data_reserved = NULL;
++ struct extent_state *cached_state = NULL;
++ struct extent_map *em;
++ struct folio **folios;
++ const unsigned int nr_pages = ((start + len - 1) >> PAGE_SHIFT) -
++ (start >> PAGE_SHIFT) + 1;
++ u64 cur;
++ int ret = 0;
++
++ ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
++ IS_ALIGNED(len, fs_info->sectorsize));
++
++ folios = kzalloc_objs(struct folio *, nr_pages, GFP_NOFS);
++ if (!folios)
++ return -ENOMEM;
++
++ cur = start;
++ for (int i = 0; cur < start + len && i < nr_pages; i++) {
++ folios[i] = defrag_prepare_one_folio(inode, cur >> PAGE_SHIFT);
++ if (IS_ERR(folios[i])) {
++ ret = PTR_ERR(folios[i]);
++ folios[i] = NULL;
++ goto free_folios;
++ }
++ cur = folio_next_pos(folios[i]);
++ }
++ for (int i = 0; i < nr_pages && folios[i]; i++)
++ folio_wait_writeback(folios[i]);
++
++ ASSERT(folios[0]);
++ btrfs_lock_extent(&inode->io_tree, folio_pos(folios[0]), cur - 1,
++ &cached_state);
++ /* Still fully mapped to the recorded location? */
++ em = btrfs_get_extent(inode, NULL, start, len);
++ if (IS_ERR(em)) {
++ ret = PTR_ERR(em);
++ goto unlock_extent;
++ }
++ if (em->disk_bytenr >= EXTENT_MAP_LAST_BYTE ||
++ (em->flags & EXTENT_FLAG_PREALLOC) ||
++ btrfs_extent_map_compression(em) != BTRFS_COMPRESS_NONE ||
++ em->start > start ||
++ em->start + em->len < start + len ||
++ btrfs_extent_map_block_start(em) + (start - em->start) !=
++ disk_bytenr) {
++ btrfs_free_extent_map(em);
++ goto unlock_extent;
++ }
++ btrfs_free_extent_map(em);
++
++ /*
++ * We hold the folio locks and the extent lock, so a flushing
++ * reservation can deadlock: satisfying a space ticket needs delalloc
++ * writeback -- or a transaction commit, which with flushoncommit waits
++ * for that writeback -- and a qgroup flush (try_flush_qgroup() on
++ * EDQUOT) writes back the root's delalloc and waits for its ordered
++ * extents, or waits for another task doing so. Writeback of this
++ * range blocks in __folio_lock on the folios held here, and the
++ * folios are often dirty: an fsync'ed append dirties the folio holding
++ * the old tail. Reserve space and qgroup space without flushing;
++ * carrying is optional, so on ENOSPC or EDQUOT the tail just stays in
++ * its old stripe (see btrfs_carry_log_tail).
++ */
++ ret = btrfs_check_data_free_space_noflush(inode, &data_reserved, start,
++ len);
++ if (ret < 0)
++ goto unlock_extent;
++ ret = btrfs_delalloc_reserve_metadata(inode, len, len, true);
++ if (ret < 0) {
++ btrfs_free_reserved_data_space(inode, data_reserved, start,
++ len);
++ extent_changeset_free(data_reserved);
++ goto unlock_extent;
++ }
++ /*
++ * Part of the range may already be delalloc (an fsync'ed append
++ * dirties the old tail block). As in btrfs_reset_extent_delalloc(),
++ * clearing it with EXTENT_DO_ACCOUNTING releases that delalloc's own
++ * reservations, and the ones made above cover the whole range. Clear
++ * EXTENT_NORESERVE too: a NOCOW write that reserved no data space must
++ * not leave the flag on a range whose data space is now reserved, or
++ * that reservation is never released if the range is written NOCOW
++ * (the clear hook skips the release for EXTENT_NORESERVE, and checks
++ * the flag before clearing it, so the old state releases nothing).
++ */
++ btrfs_clear_extent_bit(&inode->io_tree, start, start + len - 1,
++ EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
++ EXTENT_DEFRAG | EXTENT_NORESERVE, &cached_state);
++ btrfs_set_extent_bit(&inode->io_tree, start, start + len - 1,
++ EXTENT_DELALLOC, &cached_state);
++ for (int i = 0; i < nr_pages && folios[i]; i++) {
++ struct folio *folio = folios[i];
++
++ if (start >= folio_next_pos(folio) ||
++ start + len <= folio_pos(folio))
++ continue;
++ btrfs_folio_clamp_set_dirty(fs_info, folio, start, len);
++ }
++ btrfs_delalloc_release_extents(inode, len);
++ extent_changeset_free(data_reserved);
++unlock_extent:
++ btrfs_unlock_extent(&inode->io_tree, folio_pos(folios[0]), cur - 1,
++ &cached_state);
++free_folios:
++ for (int i = 0; i < nr_pages; i++) {
++ if (!folios[i])
++ break;
++ folio_unlock(folios[i]);
++ folio_put(folios[i]);
++ }
++ kfree(folios);
++ return ret;
++}
++
++/*
++ * Consume the inode's carry table (see struct btrfs_log_carry): re-dirty
++ * every recorded range so the caller's upcoming writeback carries them
++ * into the inode's current private stripe run. Does nothing with shared
++ * LOG runs (stripe_log_data_shared). Called at fsync entry with the inode
++ * locked; takes log_mutex only to detach the table, so the logging side
++ * never records into a half-consumed list. All failures are soft: an
++ * uncarried range just leaves its old stripe to free the slow way.
++ */
++void btrfs_carry_log_tail(struct btrfs_inode *inode)
++{
++ struct btrfs_log_carry *copy;
++
++ if (!btrfs_test_opt(inode->root->fs_info, STRIPE_ALLOC))
++ return;
++ if (!READ_ONCE(inode->log_carry))
++ return;
++ copy = kmalloc(sizeof(*copy), GFP_NOFS);
++ if (!copy)
++ return;
++ mutex_lock(&inode->log_mutex);
++ if (!inode->log_carry || !inode->log_carry->nr_ranges) {
++ mutex_unlock(&inode->log_mutex);
++ kfree(copy);
++ return;
++ }
++ memcpy(copy, inode->log_carry, sizeof(*copy));
++ inode->log_carry->nr_ranges = 0;
++ mutex_unlock(&inode->log_mutex);
++
++ for (int i = 0; i < copy->nr_ranges; i++)
++ carry_one_range(inode, copy->range[i].start,
++ copy->range[i].len,
++ copy->range[i].disk_bytenr);
++ kfree(copy);
++}
++
+ static int defrag_one_cluster(struct btrfs_inode *inode,
+ struct file_ra_state *ra,
+ u64 start, u32 len, u32 extent_thresh,
+diff --git a/fs/btrfs/defrag.h b/fs/btrfs/defrag.h
+index a7f917a38dbfb..0b2a124151893 100644
+--- a/fs/btrfs/defrag.h
++++ b/fs/btrfs/defrag.h
+@@ -16,6 +16,7 @@ struct btrfs_ioctl_defrag_range_args;
+ int btrfs_defrag_file(struct btrfs_inode *inode, struct file_ra_state *ra,
+ struct btrfs_ioctl_defrag_range_args *range,
+ u64 newer_than, unsigned long max_to_defrag);
++void btrfs_carry_log_tail(struct btrfs_inode *inode);
+ int __init btrfs_auto_defrag_init(void);
+ void __cold btrfs_auto_defrag_exit(void);
+ void btrfs_add_inode_defrag(struct btrfs_inode *inode, u32 extent_thresh);
+diff --git a/fs/btrfs/delalloc-space.c b/fs/btrfs/delalloc-space.c
+index d09bf6aa43352..bfb11760b9eae 100644
+--- a/fs/btrfs/delalloc-space.c
++++ b/fs/btrfs/delalloc-space.c
+@@ -154,9 +154,10 @@ int btrfs_alloc_data_chunk_ondemand_held(const struct btrfs_inode *inode,
+ flush, 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)
++static int check_data_free_space(struct btrfs_inode *inode,
++ struct extent_changeset **reserved, u64 start,
++ u64 len, bool noflush, bool qgroup_noflush,
++ u64 *stripe_held)
+ {
+ struct btrfs_fs_info *fs_info = inode->root->fs_info;
+ enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_DATA;
+@@ -201,7 +202,11 @@ int btrfs_check_data_free_space(struct btrfs_inode *inode,
+ *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 (qgroup_noflush)
++ ret = btrfs_qgroup_reserve_data_noflush(inode, reserved, start,
++ len);
++ else
++ ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
+ if (ret < 0) {
+ if (stripe_held) {
+ btrfs_release_data_margin_probe(inode, stripe_margin);
+@@ -216,6 +221,27 @@ int btrfs_check_data_free_space(struct btrfs_inode *inode,
+ return ret;
+ }
+
++int btrfs_check_data_free_space(struct btrfs_inode *inode,
++ struct extent_changeset **reserved, u64 start,
++ u64 len, bool noflush, u64 *stripe_held)
++{
++ return check_data_free_space(inode, reserved, start, len, noflush,
++ false, stripe_held);
++}
++
++/*
++ * Reserve data space and qgroup space for [@start, @start + @len) without
++ * flushing either, for callers holding folio or extent locks of @inode:
++ * both flushes write back delalloc, the inode's own included. (The noflush
++ * of btrfs_check_data_free_space() covers only the space reservation.)
++ */
++int btrfs_check_data_free_space_noflush(struct btrfs_inode *inode,
++ struct extent_changeset **reserved,
++ u64 start, u64 len)
++{
++ return check_data_free_space(inode, reserved, start, len, true, true,
++ NULL);
++}
+
+ /* 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)
+@@ -223,6 +249,7 @@ 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.
+diff --git a/fs/btrfs/delalloc-space.h b/fs/btrfs/delalloc-space.h
+index 37860ced7a723..3c8dded8cdd43 100644
+--- a/fs/btrfs/delalloc-space.h
++++ b/fs/btrfs/delalloc-space.h
+@@ -15,6 +15,9 @@ int btrfs_alloc_data_chunk_ondemand_held(const struct btrfs_inode *inode,
+ int btrfs_check_data_free_space(struct btrfs_inode *inode,
+ struct extent_changeset **reserved, u64 start, u64 len,
+ bool noflush, u64 *stripe_held);
++int btrfs_check_data_free_space_noflush(struct btrfs_inode *inode,
++ struct extent_changeset **reserved,
++ u64 start, u64 len);
+ 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);
+diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
+index 73941a48cf4d7..1af09fbaf2bf9 100644
+--- a/fs/btrfs/file.c
++++ b/fs/btrfs/file.c
+@@ -35,6 +35,7 @@
+ #include "extent-tree.h"
+ #include "file-item.h"
+ #include "ioctl.h"
++#include "defrag.h"
+ #include "raid56.h"
+ #include "file.h"
+ #include "super.h"
+@@ -1591,6 +1592,16 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
+ else
+ btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
+
++ /*
++ * With private LOG runs (stripe_log_data_shared clear), re-dirty the
++ * tail ranges recorded at the last log commit so the writeback below
++ * carries them into the inode's current private stripe run, letting
++ * the old partial stripe free whole (see struct btrfs_log_carry).
++ * Purely a space optimization: a range that cannot be carried is
++ * simply skipped.
++ */
++ btrfs_carry_log_tail(inode);
++
+ /*
+ * Before we acquired the inode's lock and the mmap lock, someone may
+ * have dirtied more pages in the target range. We need to make sure
+diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
+index 8b7fd4704349a..d183371910b3d 100644
+--- a/fs/btrfs/inode.c
++++ b/fs/btrfs/inode.c
+@@ -8144,6 +8144,7 @@ struct inode *btrfs_alloc_inode(struct super_block *sb)
+ ei->last_reflink_trans = 0;
+ ei->last_log_commit = 0;
+ ei->log_run_hint = 0;
++ ei->log_carry = NULL;
+
+ spin_lock_init(&ei->lock);
+ ei->outstanding_extents = 0;
+@@ -8183,6 +8184,7 @@ struct inode *btrfs_alloc_inode(struct super_block *sb)
+ void btrfs_test_destroy_inode(struct inode *inode)
+ {
+ btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
++ kfree(BTRFS_I(inode)->log_carry);
+ kfree(BTRFS_I(inode)->file_extent_tree);
+ kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
+ }
+@@ -8190,6 +8192,7 @@ void btrfs_test_destroy_inode(struct inode *inode)
+
+ void btrfs_free_inode(struct inode *inode)
+ {
++ kfree(BTRFS_I(inode)->log_carry);
+ kfree(BTRFS_I(inode)->file_extent_tree);
+ kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
+ }
+diff --git a/fs/btrfs/qgroup.c b/fs/btrfs/qgroup.c
+index baef546fa213e..e7dbf9666c2b9 100644
+--- a/fs/btrfs/qgroup.c
++++ b/fs/btrfs/qgroup.c
+@@ -4372,6 +4372,18 @@ int btrfs_qgroup_reserve_data(struct btrfs_inode *inode,
+ return qgroup_reserve_data(inode, reserved_ret, start, len);
+ }
+
++/*
++ * Like btrfs_qgroup_reserve_data(), but return -EDQUOT instead of flushing,
++ * for callers holding folio or extent locks of @inode: the flush writes back
++ * delalloc (the inode's own included) and waits for ordered extents.
++ */
++int btrfs_qgroup_reserve_data_noflush(struct btrfs_inode *inode,
++ struct extent_changeset **reserved_ret,
++ u64 start, u64 len)
++{
++ return qgroup_reserve_data(inode, reserved_ret, start, len);
++}
++
+ /* Free ranges specified by @reserved, normally in error path */
+ static int qgroup_free_reserved_data(struct btrfs_inode *inode,
+ struct extent_changeset *reserved,
+diff --git a/fs/btrfs/qgroup.h b/fs/btrfs/qgroup.h
+index a29b4e216f25d..b37de68f87dc0 100644
+--- a/fs/btrfs/qgroup.h
++++ b/fs/btrfs/qgroup.h
+@@ -400,6 +400,9 @@ int btrfs_verify_qgroup_counts(const struct btrfs_fs_info *fs_info, u64 qgroupid
+ /* New io_tree based accurate qgroup reserve API */
+ int btrfs_qgroup_reserve_data(struct btrfs_inode *inode,
+ struct extent_changeset **reserved, u64 start, u64 len);
++int btrfs_qgroup_reserve_data_noflush(struct btrfs_inode *inode,
++ struct extent_changeset **reserved,
++ u64 start, u64 len);
+ int btrfs_qgroup_release_data(struct btrfs_inode *inode, u64 start, u64 len, u64 *released);
+ int btrfs_qgroup_free_data(struct btrfs_inode *inode,
+ struct extent_changeset *reserved, u64 start,
+diff --git a/fs/btrfs/tree-log.c b/fs/btrfs/tree-log.c
+index 6aa8db5b1044e..d902d169680a4 100644
+--- a/fs/btrfs/tree-log.c
++++ b/fs/btrfs/tree-log.c
+@@ -4887,9 +4887,12 @@ static noinline int copy_items(struct btrfs_trans_handle *trans,
+ disk_num_bytes =
+ btrfs_file_extent_disk_num_bytes(src, extent);
+ if (disk_bytenr)
+- btrfs_log_settle_stripes(trans->fs_info,
+- disk_bytenr,
+- disk_num_bytes);
++ btrfs_log_settle_stripes(inode,
++ ins_keys[dst_index].offset,
++ btrfs_file_extent_compression(src, extent) ?
++ 0 :
++ btrfs_file_extent_num_bytes(src, extent),
++ disk_bytenr, disk_num_bytes);
+ }
+
+ if (skip_csum)
+@@ -5189,8 +5192,10 @@ static int log_one_extent(struct btrfs_trans_handle *trans,
+ */
+ if (!(em->flags & EXTENT_FLAG_PREALLOC) &&
+ em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
+- btrfs_log_settle_stripes(inode->root->fs_info, em->disk_bytenr,
+- em->disk_num_bytes);
++ btrfs_log_settle_stripes(inode, em->start,
++ compress_type == BTRFS_COMPRESS_NONE ?
++ em->len : 0,
++ em->disk_bytenr, em->disk_num_bytes);
+
+ if (compress_type != BTRFS_COMPRESS_NONE) {
+ btrfs_set_stack_file_extent_disk_bytenr(&fi, block_start);
+--
+2.47.3
+
+++ /dev/null
-From b6509d0f3eb7ec6b053b7e4881f0beeac41b6ab2 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:17 -0400
-Subject: [RFC PATCH 055/116] btrfs: stripe_alloc: tell a dead tree block from
- a live one in the metadata RMW audit
-To: linux-btrfs@vger.kernel.org
-
-The audit reports any older-generation header under a read-modify-write
-as a write hole, and counted over six hundred per metadata fill test.
-Since runs close at every transaction and freed stripes are reclaimed
-whole, most such headers belong to blocks that died with their stripe:
-the stripe was claimed fully free, the dead blocks kept their headers,
-and a torn parity write over them damages nothing a reader can reach.
-
-Ask the committed extent tree, the witness a degraded read after a
-crash would consult, whether the block is still referenced. Count and
-report a live one as before (now with its bytenr and reference count),
-and count a dead one as meta_rmw_ghost without a warning.
-
-A sector the run has already re-allocated in the current transaction
-carries an extent item of the current generation for the new block
-while the old header is still on disk (the new write has not landed):
-that is not a live block either, so the item generation must match the
-header generation. Without that check every single-stripe run of the
-current transaction reported its dead predecessors as holes (90 of 135
-warnings in one fill test; the other 45 were the raid5 system chunk).
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/fs.h | 2 +
- fs/btrfs/raid56.c | 94 +++++++++++++++++++++++++++++++++++++++++++++--
- fs/btrfs/sysfs.c | 2 +
- 3 files changed, 94 insertions(+), 4 deletions(-)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index bb0ac9ce4ccba..a483722cfacaa 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -903,6 +903,8 @@ struct btrfs_fs_info {
- */
- atomic64_t meta_rmw_cur;
- atomic64_t meta_rmw_old;
-+ atomic64_t meta_rmw_ghost; /* older header, block dead in the
-+ committed extent tree */
- atomic64_t meta_rmw_free;
- atomic64_t congestion_short;
- } stripe_park_stats;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index d1e961ce4e490..7a825b3507033 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -3040,6 +3040,66 @@ static bool rmw_peek_eb_generation(struct btrfs_raid_bio *rbio, u32 i,
- return found_bytenr == logical && !bad_fsid;
- }
-
-+/*
-+ * Is @bytenr a tree block the committed extent tree still references? Read
-+ * the commit root without locking, as the caching thread does, so this is
-+ * safe from the raid56 worker with no transaction to join; a lookup that
-+ * cannot answer counts the block as live.
-+ */
-+static bool rmw_block_referenced(struct btrfs_fs_info *fs_info, u64 bytenr,
-+ u64 header_gen, u64 *refs, u64 *extent_gen)
-+{
-+ struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
-+ struct btrfs_path *path;
-+ struct btrfs_key key;
-+ bool live = true;
-+ int ret;
-+
-+ *refs = 0;
-+ *extent_gen = 0;
-+ path = btrfs_alloc_path();
-+ if (!path)
-+ return true;
-+ path->search_commit_root = 1;
-+ path->skip_locking = 1;
-+ key.objectid = bytenr;
-+ key.type = BTRFS_METADATA_ITEM_KEY;
-+ key.offset = (u64)-1;
-+ down_read(&fs_info->commit_root_sem);
-+ ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
-+ if (ret > 0)
-+ ret = btrfs_previous_extent_item(extent_root, path, bytenr);
-+ if (ret == 0) {
-+ btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
-+ if (key.objectid == bytenr &&
-+ (key.type == BTRFS_METADATA_ITEM_KEY ||
-+ key.type == BTRFS_EXTENT_ITEM_KEY)) {
-+ struct btrfs_extent_item *ei;
-+
-+ ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
-+ struct btrfs_extent_item);
-+ *refs = btrfs_extent_refs(path->nodes[0], ei);
-+ *extent_gen = btrfs_extent_generation(path->nodes[0], ei);
-+ /*
-+ * An extent item at this bytenr from a LATER
-+ * transaction than the header on disk belongs to a
-+ * new block allocated here whose write has not landed
-+ * yet; the header is the dead previous occupant.
-+ * Only an item of the header's own generation makes
-+ * the block on disk live.
-+ */
-+ live = (*refs != 0 && *extent_gen == header_gen);
-+ } else {
-+ live = false;
-+ }
-+ } else if (ret > 0) {
-+ live = false;
-+ }
-+ up_read(&fs_info->commit_root_sem);
-+ btrfs_free_path(path);
-+ return live;
-+}
-+
- /*
- * Decide whether an uncovered read-modify-write is a write hole or only a
- * cost, by looking at what is actually in the stripe.
-@@ -3116,10 +3176,36 @@ static void audit_uncovered_rmw(struct btrfs_raid_bio *rbio)
- atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_cur);
- continue;
- }
-- atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_old);
-- btrfs_warn_rl(fs_info,
--"read-modify-write of stripe %llu rewrites parity over committed tree block at generation %llu while writing generation %llu: write hole",
-- rbio->bioc->full_stripe_logical, gen, write_gen);
-+ /*
-+ * An older header is only a write hole if the block is still
-+ * referenced in the committed extent tree: a stripe reclaimed
-+ * after every block in it died is claimed fully free and its
-+ * dead blocks keep their headers, and a torn write over those
-+ * damages nothing a reader can reach. The committed tree is
-+ * the witness a degraded read after a crash would consult, so
-+ * ask it (no transaction: delayed refs of the running one are
-+ * not yet what a crash would see).
-+ */
-+ {
-+ const int stripe_nr = i / rbio->stripe_nsectors;
-+ const int sectornr = i % rbio->stripe_nsectors;
-+ const u64 logical = rbio->bioc->full_stripe_logical +
-+ (u64)stripe_nr * rbio->bioc->stripe_len +
-+ (u64)sectornr * fs_info->sectorsize;
-+ u64 refs;
-+ u64 egen;
-+
-+ if (!rmw_block_referenced(fs_info, logical, gen, &refs,
-+ &egen)) {
-+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_ghost);
-+ continue;
-+ }
-+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_old);
-+ btrfs_warn_rl(fs_info,
-+"read-modify-write of stripe %llu rewrites parity over committed tree block %llu at generation %llu (refs %llu, extent generation %llu) while writing generation %llu: write hole",
-+ rbio->bioc->full_stripe_logical, logical,
-+ gen, refs, egen, write_gen);
-+ }
- }
- }
-
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index cb844168fde51..1481ed2cf1571 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1140,6 +1140,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "meta_rmw %lld\n"
- "meta_rmw_cur %lld\n"
- "meta_rmw_old %lld\n"
-+ "meta_rmw_ghost %lld\n"
- "meta_rmw_free %lld\n"
- "congestion_short %lld\n"
- "parked_now %d\n",
-@@ -1160,6 +1161,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
-+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_ghost),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free),
- atomic64_read(&fs_info->stripe_park_stats.congestion_short),
- atomic_read(&fs_info->stripe_parked_now));
---
-2.47.3
-
--- /dev/null
+From b4a377a8995decd762e20496278a30ecf10bf7b8 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:40 -0400
+Subject: [RFC PATCH 56/85] btrfs: stripe_alloc: allow-rmw policy, and
+ write-in-place for isolated nocow extents (fsync part 2)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: allow-rmw policy, and write-in-place
+for isolated nocow extents" (earlier in this series) that need code from
+"btrfs: stripe_alloc: carry an inode's log tail forward at fsync", which
+comes after it in this series: they are applied here, once "btrfs:
+stripe_alloc: carry an inode's log tail forward at fsync" is in, instead
+of with the rest of "btrfs: stripe_alloc: allow-rmw policy, and
+write-in-place for isolated nocow extents".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/defrag.c | 3 +++
+ 1 file changed, 3 insertions(+)
+
+diff --git a/fs/btrfs/defrag.c b/fs/btrfs/defrag.c
+index 1e3bc1051b9d2..9fdf94ecb5c93 100644
+--- a/fs/btrfs/defrag.c
++++ b/fs/btrfs/defrag.c
+@@ -1406,6 +1406,9 @@ void btrfs_carry_log_tail(struct btrfs_inode *inode)
+
+ if (!btrfs_test_opt(inode->root->fs_info, STRIPE_ALLOC))
+ return;
++ if (btrfs_stripe_allow_rmw(inode->root->fs_info) &
++ BTRFS_STRIPE_RMW_FSYNC)
++ return;
+ if (!READ_ONCE(inode->log_carry))
+ return;
+ copy = kmalloc(sizeof(*copy), GFP_NOFS);
+--
+2.47.3
+
+++ /dev/null
-From 868e49a6d6d0474e799e3fb02bc41ab131b379d9 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:18 -0400
-Subject: [RFC PATCH 056/116] btrfs: stripe_alloc: do not read an inline
- backref off a keyed-ref extent item
-To: linux-btrfs@vger.kernel.org
-
-stripe_extents_owned_by() decides whether every extent in a stripe range
-belongs to one inode by reading the single inline backref of each data
-extent item. A data extent's only backref is keyed rather than inline
-when the leaf had no room to grow the item: insert_inline_extent_backref()
-returns -EAGAIN and insert_extent_backref() adds a separate
-EXTENT_DATA_REF item. Such an extent item ends right after the header,
-so the walk read the next item's bytes as an inline ref and
-btrfs_get_extent_inline_ref_type() warned:
-
- BTRFS error (device dm-22): eb 81657856 iref 0x3a5c invalid extent inline ref type 1
- WARNING: CPU: 6 PID: 199813 at fs/btrfs/extent-tree.c:380 btrfs_get_extent_inline_ref_type+0xe0/0x190
- stripe_extents_owned_by+0x270/0x310
- btrfs_alloc_from_inode_stripe_run+0x48e/0x6a0
- find_free_extent+0xf9b/0x1870
- btrfs_reserve_extent+0x214/0x890
- __btrfs_prealloc_file_range+0xf1/0x470
- btrfs_fallocate+0xa99/0x10f0
-
-The answer was already the conservative "not owned" (the garbage type is
-not EXTENT_DATA_REF_KEY), so only the warning and the taint were wrong.
-Check the item size before reading the inline ref and treat a keyed-ref
-extent as not owned.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 15 +++++++++++++++
- 1 file changed, 15 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 6032c4dc6f7fe..09a6f47937882 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1437,6 +1437,21 @@ static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
- ret = false;
- goto out;
- }
-+ /*
-+ * The extent's single backref is keyed, not inline, when the
-+ * leaf had no room to grow the item (insert_inline_extent_backref()
-+ * returns -EAGAIN and insert_extent_backref() adds a separate
-+ * EXTENT_DATA_REF item). Such an extent item ends right after
-+ * the header, and reading an inline ref there reads the next
-+ * item's bytes: btrfs_get_extent_inline_ref_type() warns about
-+ * "invalid extent inline ref type 1". Treat it as not owned;
-+ * the answer is the conservative one either way.
-+ */
-+ if (btrfs_item_size(leaf, slot) < sizeof(*ei) +
-+ btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY)) {
-+ ret = false;
-+ goto out;
-+ }
- iref = (struct btrfs_extent_inline_ref *)(ei + 1);
- type = btrfs_get_extent_inline_ref_type(leaf, iref,
- BTRFS_REF_TYPE_DATA);
---
-2.47.3
-
+++ /dev/null
-From 46a0df1d2260a3afec5094779745bc6878f564ce Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:19 -0400
-Subject: [RFC PATCH 057/116] btrfs: stripe_alloc: count whole stripes stranded
- behind live runs as trapped
-To: linux-btrfs@vger.kernel.org
-
-The data admission gate admits a reservation while the whole-stripe
-supply, bytes_stripe_claimable, covers it, and the per-commit scan
-measures that supply as the block group's wholly free full stripes.
-But a wholly free stripe inside a live stripe run's range cannot be
-claimed: btrfs_stripe_run_range_usable() rejects any claim overlapping
-a run object, because a second run over the same range would make the
-range-to-run lookups ambiguous. The run was claimed over the stripe,
-the extents allocated there were freed again, and the run has not been
-freed yet. For a COW run that window closes at the next commit; a
-nodatacow inode's private run deliberately survives commits and lives
-until the inode is evicted.
-
-On a raid56 filesystem filled to ENOSPC by fsstress (thousands of
-fallocated files, so thousands of cached inodes each holding a private
-NOCOW run) a live walk of the free space cache showed the accounting
-exact -- the wholly free stripes summed to bytes_stripe_claimable to the
-byte -- and 99% of them inside the ranges of open NOCOW runs with no
-inflight IO: 22.8 MiB of 22.8 MiB behind 387 runs in one group, 73.4 MiB
-of 73.4 MiB behind 976 runs in another. Every claim failed in O(1) on
-the "no claimable run" verdict, every write() admitted against the 99 MiB
-of phantom supply failed at writeback, and the data was dropped ("data
-writeback allocation ... returned ENOSPC despite reservation margin"),
-about 100,000 delalloc ranges per run of the degraded acceptance suite
-where the stock allocator drops none.
-
-Have the scan take such stripes out of the claimable supply: count them
-in stripe_unusable, which btrfs_space_info_used() already charges so the
-gate cannot admit against them, and record them separately as
-stripe_stranded so that btrfs_stripe_bg_wants_reclaim() does not ask
-relocation to recover space that comes back by itself. When a run is
-freed, mark its group for rescan so the next commit credits the stripes
-back. The space_info total is exposed as bytes_stripe_stranded in sysfs
-and in the space info dump.
-
-This makes the gate honest -- write() gets the ENOSPC instead of
-writeback dropping the data -- but does not return the stranded space
-while the runs live; that is the run lifecycle's business.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 51 +++++++++++++++++++++++++++++++++++++
- fs/btrfs/block-group.h | 12 +++++++++
- fs/btrfs/free-space-cache.c | 15 ++++++++++-
- fs/btrfs/space-info.c | 5 ++--
- fs/btrfs/space-info.h | 5 ++++
- fs/btrfs/sysfs.c | 2 ++
- 6 files changed, 87 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 09a6f47937882..94c5bbe457907 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -686,6 +686,14 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
- list_del(&run->list);
- bitmap_free(run->live);
- kfree(run);
-+ /*
-+ * Wholly free stripes inside this run's range were counted as trapped
-+ * by the last stripe_unusable scan (btrfs_stripe_run_stranded_stripes());
-+ * with the run gone they are claimable again, so have the next commit
-+ * rescan the group and credit them back.
-+ */
-+ if (READ_ONCE(bg->stripe_unusable_ready))
-+ set_bit(BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY, &bg->runtime_flags);
- wake_up_var(&bg->open_stripe_runs);
- }
-
-@@ -1260,6 +1268,46 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- return true;
- }
-
-+/*
-+ * For the stripe_unusable scan: wholly free stripes that overlap a live
-+ * stripe run's range cannot be claimed while the run object exists (see
-+ * btrfs_stripe_run_range_usable()) -- the run was claimed over them, the
-+ * extents allocated there were freed again, and the run has not been freed
-+ * yet; a nodatacow inode's private run lives until the inode is evicted.
-+ * Counted as claimable, they let the admission gate admit writes the claim
-+ * path then refuses, and writeback drops the data. Take them out of @freep
-+ * (so the caller counts them neither as claimable nor as partial) and return
-+ * their total; free_open_stripe_run() marks the group for rescan so they
-+ * are credited back when the run dies. Caller holds ctl->tree_lock;
-+ * stripe_run_lock nests inside it.
-+ */
-+u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
-+ u64 nstripes)
-+{
-+ const u64 fsl = bg->full_stripe_len;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ u64 stranded = 0;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ u64 idx, last;
-+
-+ if (run->end <= run->start)
-+ continue;
-+ idx = div64_u64(run->start - bg->start, fsl);
-+ last = div64_u64(run->end - 1 - bg->start, fsl);
-+ for (; idx <= last && idx < nstripes; idx++) {
-+ if (freep[idx] != fsl)
-+ continue;
-+ freep[idx] = 0;
-+ stranded += fsl;
-+ }
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ return stranded;
-+}
-+
- /*
- * Parse a stripe_alloc_allow_rmw word list ("nodatacow",
- * "prealloc", "fsync") into its mask. Words are separated by comma,
-@@ -2698,6 +2746,7 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- u64 total = 0;
- u64 total_claimable = 0;
- u64 total_claimable_reloc = 0;
-+ u64 total_stranded = 0;
- u64 largest = 0;
- u64 unit = 0;
- u32 nr_rw = 0;
-@@ -2740,6 +2789,7 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- */
- if (READ_ONCE(bg->stripe_unusable_ready)) {
- total += READ_ONCE(bg->stripe_unusable);
-+ total_stranded += READ_ONCE(bg->stripe_stranded);
- total_claimable +=
- READ_ONCE(bg->stripe_claimable);
- if (bg->start == READ_ONCE(fs_info->data_reloc_bg))
-@@ -2757,6 +2807,7 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- sinfo->bytes_stripe_unusable = total;
- sinfo->bytes_stripe_claimable = total_claimable;
- sinfo->bytes_stripe_claimable_reloc = total_claimable_reloc;
-+ sinfo->bytes_stripe_stranded = total_stranded;
- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA)) {
- u64 reserve = 0;
-
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 0f8e4c165d54c..8e9e3b31f26e6 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -300,6 +300,16 @@ struct btrfs_block_group {
- * (honest f_bavail); the reservation layer is deliberately unchanged.
- */
- u64 stripe_unusable;
-+ /*
-+ * The part of stripe_unusable that is wholly free stripes lying inside
-+ * live stripe-run ranges (stripe_alloc): the run was claimed over them,
-+ * the extents allocated there were freed again, and the run object
-+ * still exists, so btrfs_stripe_run_range_usable() refuses to claim
-+ * them. Trapped for admission, but they come back by themselves when
-+ * the run is freed, so reclaim leaves them out. Set by the same scan,
-+ * under the same lock.
-+ */
-+ u64 stripe_stranded;
- /* jiffies when the reclaim trigger last queued this group (stripe_alloc) */
- unsigned long stripe_reclaim_jiffies;
- /*
-@@ -480,6 +490,8 @@ bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
- const struct writeback_control *wbc);
- bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class);
-+u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
-+ u64 nstripes);
- bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- u64 run_start, u64 *run_len);
- /*
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index c005065b2b532..5e8362205e3b9 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2101,6 +2101,13 @@ static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
- "stripe_unusable_scan counted=%llu != free_space=%llu",
- counted, ctl->free_space);
-
-+ /*
-+ * Whole stripes stranded behind live stripe runs are free but not
-+ * claimable until their run is freed: trapped, like a partial stripe's
-+ * free bytes, so the admission gate does not admit writes against them.
-+ */
-+ bg->stripe_stranded = btrfs_stripe_run_stranded_stripes(bg, freep, nstripes);
-+ trapped = bg->stripe_stranded;
- for (i = 0; i < nstripes; i++)
- if (freep[i] && freep[i] < fsl)
- trapped += freep[i];
-@@ -2216,7 +2223,13 @@ bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
- struct btrfs_space_info *sinfo = bg->space_info;
- const int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
- const u64 used = READ_ONCE(bg->used);
-- const u64 trapped = READ_ONCE(bg->stripe_unusable);
-+ const u64 unusable = READ_ONCE(bg->stripe_unusable);
-+ /*
-+ * Stripes stranded behind live runs are trapped for admission but not
-+ * for reclaim: they come back by themselves when the run is freed, and
-+ * relocating the group would only force that.
-+ */
-+ const u64 trapped = unusable - min(unusable, READ_ONCE(bg->stripe_stranded));
- u64 elsewhere;
- u64 promised;
-
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 07e5aacc07c58..0c5757218960f 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -832,11 +832,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 stripe_unusable=%llu stripe_open=%llu stripe_claimable=%llu stripe_margin=%llu stripe_reserve=%llu",
-+"space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu stripe_unusable=%llu stripe_stranded=%llu stripe_open=%llu stripe_claimable=%llu stripe_margin=%llu stripe_reserve=%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_stripe_unusable, info->bytes_stripe_open,
-+ info->bytes_stripe_unusable, info->bytes_stripe_stranded,
-+ info->bytes_stripe_open,
- info->bytes_stripe_claimable,
- info->bytes_stripe_margin, info->bytes_stripe_reserve);
- }
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 6a3711ae00cf3..b4d7e2ad9daf8 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -166,6 +166,11 @@ struct btrfs_space_info {
- cannot admit writes against it, and
- subtracted in statfs (from a different
- base -- the free space cache walk). */
-+ u64 bytes_stripe_stranded; /* the part of bytes_stripe_unusable that
-+ is whole stripes stranded behind live
-+ stripe runs (see the block group's
-+ stripe_stranded); back to claimable when
-+ the runs are freed */
- u64 bytes_stripe_claimable_reloc; /* the part of bytes_stripe_claimable
- in the group dedicated to data
- relocation (fs_info->data_reloc_bg):
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 1481ed2cf1571..391eeabd029f8 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -818,6 +818,7 @@ 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_stranded);
- SPACE_INFO_ATTR(bytes_stripe_claimable);
- SPACE_INFO_ATTR(bytes_stripe_open);
- SPACE_INFO_ATTR(bytes_stripe_margin);
-@@ -951,6 +952,7 @@ 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_stranded),
- BTRFS_ATTR_PTR(space_info, bytes_stripe_claimable),
- BTRFS_ATTR_PTR(space_info, bytes_stripe_open),
- BTRFS_ATTR_PTR(space_info, bytes_stripe_margin),
---
-2.47.3
-
--- /dev/null
+From ad5d2f9e6baf74ded8f1bb164aad9080b98aaf69 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Tue, 6 Oct 2026 00:11:38 -0400
+Subject: [RFC PATCH 57/85] btrfs: stripe_alloc: share LOG data runs per log
+ transaction
+To: linux-btrfs@vger.kernel.org
+
+An fsyncing inode's data goes into a private LOG-class stripe run, which
+each log commit settles: the run is closed, the commit waits for all of the
+run's data IO, and the extents left in its final partial stripe are
+recorded for carry-forward, so the next fsync re-dirties them and moves
+them into the inode's new run. Every fsync therefore leaves one partial
+stripe per inode, and a back-to-back fsync loop rewrites the previous
+fsync's tail each time.
+
+Share the runs instead:
+
+- LOG-class runs are keyed by (subvolume, log_transid at allocation)
+ instead of the inode, so the inodes logging in one log transaction fill
+ the same stripes. An allocation of a full stripe or more keeps the
+ inode's private run, so small fsync extents never share the partial last
+ stripe of a large one and wait for its IO.
+- A log commit does not close a shared run. It seals the stripe holding
+ the end of the logged extent: the run's frontier moves to that stripe's
+ end, the skipped sectors go back to the free space cache like a closed
+ run's tail (the stripe's final write pads them), and the run goes on in
+ the next stripe. Nothing allocates beside the extent after its log
+ commit.
+- The settle kicks only the logged extent's stripes and waits until every
+ allocated sector in them is written (the run's written map), rather than
+ for the whole run to drain. Writers sharing those stripes park and merge
+ into the same full-stripe write, so the wait couples an fsync to them and
+ to nothing else. It has no timeout: returning while a neighbour's sector
+ is unwritten would let its later partial write RMW the extent after the
+ log made it durable. Completed writes wake the waiters.
+- Nothing is carried forward: a final partial stripe stays until the
+ extents in it are freed or compaction moves them.
+
+Measured on 5 x 8 GiB raid5 data with raid1 and raid5 metadata, against
+private runs with carry-forward, same rep: at 16 and 64 writers and with
+one fsync per inode, 1.2-2.9x the fsyncs/s (one 64-writer rep of eight:
+0.8x), 3-8x fewer device bytes per fsync and less slab; one writer is at
+parity on latency with 17-29% fewer device bytes. The one workload that
+can lose is two large streaming writers beside small fsync writers: a small
+fsync waits for neighbours that joined its stripe and sit behind the large
+IO (0.5-1.9x the fsyncs/s; the p99.9 there is dominated by a multi-second
+log-commit tail that both modes, and stock raid5, show).
+
+/sys/fs/btrfs/<uuid>/stripe_log_data_shared (default 1) switches a
+filesystem back to private runs with carry-forward. stripe_run_stats gains
+log_settle_waits and log_settle_wait_ns (both), log_carry_ranges and
+log_carry_bytes (private runs), and log_seals and log_seal_bytes (shared
+runs).
+
+Private LOG and NOCOW runs are matched by (subvolume root id, inode
+number), since inode numbers are unique only within a subvolume (every
+subvolume's first file is inode 257): matching by inode alone let
+same-numbered inodes of different subvolumes join each other's runs,
+breaking NOCOW isolation, and let an eviction close other subvolumes'
+runs and the META_LOG run of a subvolume whose id equals the inode number.
+Eviction closes only the inode's own LOG and NOCOW runs, and the shared
+LOG key uses the whole root id.
+
+btrfs_log_settle_stripes() reads stripe_log_data_shared once per settle,
+and every completed write wakes the settle waiters whatever the knob says,
+so a sysfs change cannot leave an fsync waiting for a run only the commit
+it blocks would provide.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 228 +++++++++++++++++++++++++++++++++--------
+ fs/btrfs/defrag.c | 6 ++
+ fs/btrfs/disk-io.c | 1 +
+ fs/btrfs/fs.h | 19 ++++
+ fs/btrfs/sysfs.c | 26 +++++
+ 5 files changed, 239 insertions(+), 41 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index e58d3e96bcc0a..ce88e22f780aa 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -498,7 +498,14 @@ struct btrfs_open_stripe_run {
+ u64 offset; /* next unallocated byte */
+ u64 inflight_bytes; /* reserved bytes with data IO pending */
+ u64 open_seq; /* fs_info->stripe_retire_seq at open */
+- u64 owner; /* LOG class: btrfs_ino of the owner */
++ /*
++ * Private runs are found by (root, owner): root is the subvolume's
++ * root id, owner the inode number (LOG, NOCOW), a shared LOG key
++ * (bit 63 set, see stripe_run_owner()), or for META_LOG the root id
++ * again. Inode numbers are only unique within a subvolume.
++ */
++ u64 root;
++ u64 owner;
+ enum btrfs_stripe_run_class class;
+ bool open; /* accepting allocations */
+ bool persistent; /* survives commits; see close_block_group_stripe_runs() */
+@@ -978,18 +985,40 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ }
+
+ /*
+- * Allocate num_bytes for a log-active inode from its private LOG-class run
+- * in this block group, claiming a fresh run when the inode has none here or
+- * the current one does not fit. Private runs are never placed in the shared
+- * band slots and are found by owner lookup, so no other allocation can join
+- * an inode's run and one inode's log commit settles only its own stripes.
++ * The owner a private run is found by: the inode, or with
++ * stripe_log_data_shared a LOG-class run shared by every inode of the
++ * subvolume logging in the same log transaction. An allocation of a full
++ * stripe or more keeps the inode's private run, so small fsync extents never
++ * share the partial last stripe of a large one and wait for its IO. Bit 63
++ * keeps the shared keys apart from inode numbers; the subvolume is matched
++ * separately, by run->root.
++ */
++static u64 stripe_run_owner(struct btrfs_inode *inode,
++ enum btrfs_stripe_run_class class, u64 num_bytes,
++ u64 fsl)
++{
++ struct btrfs_root *root = inode->root;
++
++ if (class == BTRFS_STRIPE_RUN_LOG && num_bytes < fsl &&
++ READ_ONCE(root->fs_info->stripe_log_data_shared))
++ return BIT_ULL(63) | (u32)READ_ONCE(root->log_transid);
++ return btrfs_ino(inode);
++}
++
++/*
++ * Allocate num_bytes for @inode from its private run of @class (LOG or
++ * NOCOW) in this block group, claiming a fresh run when there is none or it
++ * does not fit. With stripe_log_data_shared, small LOG allocations use the
++ * run the subvolume shares for the current log transaction
++ * (stripe_run_owner()). Private runs are never placed in a band slot and
++ * are found by subvolume and owner, so a log commit settles only stripes
++ * holding its own extents. A NOCOW allocation may instead re-adopt the
++ * free tail of the inode's last partial stripe (@readopt_hint).
+ *
+- * A replaced run (too small for this allocation) is closed immediately: the
+- * inode moves on to the fresh run, so keeping the remainder open would only
+- * strand it until the commit-time retirement. Two racing allocations for
+- * the same inode can each claim a fresh run; the owner walk then serves one
+- * of them and the other drains and retires at the next commit -- an
+- * occasional trapped tail, not a correctness problem.
++ * A run too small for this allocation is closed at once rather than left
++ * to strand its tail until commit. Two racing allocations for one owner
++ * may each claim a run; the spare drains at the next commit, costing a
++ * trapped tail, not correctness.
+ *
+ * Returns 0 and sets *ret_offset, -ENOSPC if no fully-free stripe run in
+ * this block group can satisfy the allocation, or -ENOMEM.
+@@ -1002,7 +1031,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
+ {
+ struct btrfs_fs_info *fs_info = bg->fs_info;
+ const u64 fsl = bg->full_stripe_len;
+- const u64 ino = btrfs_ino(inode);
++ const u64 root_id = btrfs_root_id(inode->root);
++ const u64 ino = stripe_run_owner(inode, class, num_bytes, fsl);
+ struct btrfs_open_stripe_run *new_run;
+ struct btrfs_open_stripe_run *run;
+ unsigned long flags;
+@@ -1017,7 +1047,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+- if (run->class != class || run->owner != ino || !run->open)
++ if (run->class != class || run->root != root_id ||
++ run->owner != ino || !run->open)
+ continue;
+ if (num_bytes <= run->end - run->offset) {
+ *ret_offset = run->offset;
+@@ -1069,8 +1100,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
+ * 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) &&
++ if (stripe_extents_owned_by(fs_info, root_id, ino, stripe, fsl,
++ &frontier, true) &&
+ frontier > stripe && frontier < stripe + fsl &&
+ num_bytes <= stripe + fsl - frontier) {
+ tlen = stripe + fsl - frontier;
+@@ -1138,6 +1169,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
+ BTRFS_STRIPE_RMW_PREALLOC));
+ if (class == BTRFS_STRIPE_RUN_NOCOW)
+ atomic64_inc(&fs_info->stripe_run_stats.nocow_run_opened);
++ new_run->root = root_id;
+ new_run->owner = ino;
+ new_run->start = start;
+ new_run->end = start + len;
+@@ -1531,7 +1563,7 @@ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
+ if (cur < run->start || cur >= run->end)
+ continue;
+ if (run->class == BTRFS_STRIPE_RUN_NOCOW &&
+- run->owner == ino)
++ run->root == root_id && run->owner == ino)
+ verdict = 1;
+ else
+ verdict = -1;
+@@ -1809,6 +1841,7 @@ static void log_carry_record(struct btrfs_inode *inode, u64 file_start,
+ carry->range[carry->nr_ranges].len = file_len;
+ carry->range[carry->nr_ranges].disk_bytenr = bytenr;
+ carry->nr_ranges++;
++ atomic64_inc(&inode->root->fs_info->stripe_run_stats.log_carry_ranges);
+ }
+
+ /*
+@@ -1885,15 +1918,14 @@ bool btrfs_block_group_has_stripe_runs(struct btrfs_block_group *bg)
+ }
+
+ /*
+- * 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.
++ * Close @inode's open LOG and NOCOW runs at eviction, so a persistent NOCOW
++ * run's claimed tail does not stay unusable for the rest of the mount. The
++ * 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 root_id = btrfs_root_id(inode->root);
+ const u64 ino = btrfs_ino(inode);
+ struct btrfs_block_group *bg;
+
+@@ -1910,7 +1942,10 @@ void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+- if (!run->open || run->owner != ino)
++ if (!run->open || run->root != root_id ||
++ run->owner != ino ||
++ (run->class != BTRFS_STRIPE_RUN_LOG &&
++ run->class != BTRFS_STRIPE_RUN_NOCOW))
+ continue;
+ tail_len = close_open_stripe_run(bg, run, &tail_start);
+ break;
+@@ -1928,29 +1963,108 @@ void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
+ spin_unlock(&fs_info->open_stripe_lock);
+ }
+
++/*
++ * A log commit on a shared LOG run: instead of closing the run, move its
++ * frontier past the stripe holding the end of the logged extent, so nothing
++ * allocates beside the extent after the log commit while the run goes on in
++ * the next stripe. The skipped sectors are not live (the pad oracle fills
++ * them) and go back to the free space cache like a closed run's tail: inside
++ * a partly live stripe they count as trapped until the stripe frees, and a
++ * later close returns only [offset, end), which no longer includes them.
++ * Caller holds bg->stripe_run_lock. Returns the skipped length.
++ */
++static u64 seal_log_stripe(struct btrfs_block_group *bg,
++ struct btrfs_open_stripe_run *run, u64 ext_end,
++ u64 *skip_start)
++{
++ const u64 fsl = bg->full_stripe_len;
++ u64 boundary;
++ u64 skip;
++
++ if (!run->open)
++ return 0;
++ boundary = bg->start + stripe_round_down(ext_end - 1 - bg->start, fsl) + fsl;
++ if (run->offset >= boundary)
++ return 0;
++ boundary = min(boundary, run->end);
++ skip = boundary - run->offset;
++ *skip_start = run->offset;
++ run->offset = boundary;
++ bg->stripe_open_remainder -= skip;
++ if (run->offset == run->end) {
++ int class;
++ int band;
++
++ 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)
++ bg->open_stripe[class][band] = NULL;
++ run->open = false;
++ if (open_stripe_run_drained(run) && !run->retained)
++ free_open_stripe_run(bg, run);
++ }
++ return skip;
++}
++
++static bool run_unwritten_in(struct btrfs_open_stripe_run *run, u64 start,
++ u64 len);
++
++/*
++ * Per-stripe settle (stripe_log_data_shared): every allocated sector of the
++ * stripes holding [bytenr, bytenr + num_bytes) has been written, or no run
++ * covers them any more. Writers sharing those stripes park and merge into
++ * the same full-stripe write, so this waits for them and for nothing else in
++ * the run.
++ */
++static bool stripe_log_extent_written(struct btrfs_block_group *bg,
++ u64 bytenr, u64 num_bytes)
++{
++ const u64 fsl = bg->full_stripe_len;
++ const u64 s = bg->start + stripe_round_down(bytenr - bg->start, fsl);
++ const u64 e = bg->start +
++ stripe_round_down(bytenr + num_bytes - bg->start + fsl - 1, fsl);
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ bool written = true;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (bytenr < run->start || bytenr >= run->offset)
++ continue;
++ if (run_unwritten_in(run, s, e - s))
++ written = false;
++ break;
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ return written;
++}
++
+ /*
+ * A log commit is about to make the extent at [bytenr, bytenr + num_bytes)
+- * durable. Once the log super lands, no later write may extend or RMW the
+- * extent's stripes -- the log-window analogue of invariant I2, which the
+- * commit-time retirement provides for full commits. Close the open run
+- * covering the extent so nothing further allocates into its stripes, kick
+- * any parked partial writes for it, and wait for all data IO into it to
+- * finish. Extents in full or already-settled stripes cost one list walk.
++ * durable, after which no later write may extend or RMW its stripes. Close
++ * the run covering the extent so nothing more allocates into its stripes,
++ * kick any parked partial writes there, and wait for all IO into the run to
++ * finish. This is a pure data-IO wait (no transaction joins), bounded by
++ * bio flight time because parked writes are flushed first, and is safe
++ * under the inode log mutex and a running transaction handle.
+ *
+- * The drain is bounded: run inflight is counted from allocation, which
+- * happens during writeback with submission following in the same pass, so
+- * the wait is bio flight time plus the parked-write deadline that the flush
+- * below short-circuits. It is a pure data-IO wait (no transaction joins),
+- * safe under the inode log mutex and a running transaction handle.
++ * With stripe_log_data_shared a shared LOG run is not closed: the stripe
++ * holding the end of the extent is sealed (seal_log_stripe()). In that
++ * mode the wait, for any run, is for every allocated sector of the
++ * extent's stripes to be written (stripe_log_extent_written()) rather than
++ * for the run to drain. Neither wait has a timeout: returning early would
++ * let a neighbour's partial write RMW the extent after it is durable.
+ *
+ * [file_start, file_start + file_len) is the extent's file range, recorded
+- * for carry-forward when the extent sits in the run's final partial stripe;
+- * file_len == 0 opts the extent out of carrying (settling still happens).
++ * for carry-forward when the extent is in the run's final partial stripe
++ * (stripe_log_data_shared clear only); file_len == 0 opts out of carrying.
+ */
+ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
+ u64 file_len, u64 bytenr, u64 num_bytes)
+ {
+ struct btrfs_fs_info *fs_info = inode->root->fs_info;
++ /* Once: the seal and the wait below must agree on the mode. */
++ const bool shared = READ_ONCE(fs_info->stripe_log_data_shared);
+ struct btrfs_block_group *bg;
+ struct btrfs_open_stripe_run *run;
+ unsigned long flags;
+@@ -1960,6 +2074,8 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
+ u64 flush_len = 0;
+ u64 ps_start = 0;
+ u64 ps_len = 0;
++ u64 seal_start = 0;
++ u64 seal_len = 0;
+
+ /* stripe_alloc_allow_rmw=fsync waives the log-commit guarantee. */
+ if (btrfs_stripe_allow_rmw(fs_info) & BTRFS_STRIPE_RMW_FSYNC)
+@@ -1984,6 +2100,16 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
+ */
+ if (run->class == BTRFS_STRIPE_RUN_NOCOW)
+ break;
++ if (shared && (run->owner & BIT_ULL(63))) {
++ const u64 fsl = bg->full_stripe_len;
++
++ /* only the logged extent's stripes, not the shared run */
++ flush_start = bg->start + stripe_round_down(bytenr - bg->start, fsl);
++ flush_len = bg->start + stripe_round_down(bytenr + num_bytes - 1 - bg->start, fsl) +
++ fsl - flush_start;
++ seal_len = seal_log_stripe(bg, run, bytenr + num_bytes, &seal_start);
++ break;
++ }
+ flush_start = run->start;
+ flush_len = run->end - run->start;
+ /*
+@@ -2012,18 +2138,36 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+
+- log_carry_record(inode, file_start, file_len, bytenr, num_bytes,
+- ps_start, ps_len);
++ if (!shared)
++ log_carry_record(inode, file_start, file_len, bytenr, num_bytes,
++ ps_start, ps_len);
+
++ if (seal_len) {
++ btrfs_add_free_space(bg, seal_start, seal_len);
++ stripe_open_remainder_sync(bg);
++ atomic64_inc(&fs_info->stripe_run_stats.log_seals);
++ atomic64_add(seal_len, &fs_info->stripe_run_stats.log_seal_bytes);
++ }
+ if (tail_len) {
+ btrfs_add_free_space(bg, tail_start, tail_len);
+ stripe_open_remainder_sync(bg);
+ }
+ if (flush_len) {
++ ktime_t t0;
++
+ btrfs_flush_parked_rbios(fs_info, flush_start, flush_len, false);
+- wait_var_event(&bg->open_stripe_runs,
+- stripe_log_range_settled(bg, bytenr) ||
+- BTRFS_FS_ERROR(fs_info));
++ t0 = ktime_get();
++ if (shared)
++ wait_var_event(&bg->open_stripe_runs,
++ stripe_log_extent_written(bg, bytenr, num_bytes) ||
++ BTRFS_FS_ERROR(fs_info));
++ else
++ wait_var_event(&bg->open_stripe_runs,
++ stripe_log_range_settled(bg, bytenr) ||
++ BTRFS_FS_ERROR(fs_info));
++ atomic64_inc(&fs_info->stripe_run_stats.log_settle_waits);
++ atomic64_add(ktime_to_ns(ktime_sub(ktime_get(), t0)),
++ &fs_info->stripe_run_stats.log_settle_wait_ns);
+ }
+ btrfs_put_block_group(bg);
+ }
+@@ -2242,6 +2386,8 @@ void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
+ bitmap_set(run->written, first, nr);
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ /* Per-stripe log settles wait on the written map, not on a drain. */
++ wake_up_var(&bg->open_stripe_runs);
+ btrfs_put_block_group(bg);
+ if (not_live)
+ atomic64_add(not_live, &fs_info->stripe_park_stats.written_not_live);
+diff --git a/fs/btrfs/defrag.c b/fs/btrfs/defrag.c
+index 9fdf94ecb5c93..b4a55cb7eeb68 100644
+--- a/fs/btrfs/defrag.c
++++ b/fs/btrfs/defrag.c
+@@ -1411,6 +1411,9 @@ void btrfs_carry_log_tail(struct btrfs_inode *inode)
+ return;
+ if (!READ_ONCE(inode->log_carry))
+ return;
++ /* Shared per-log-transaction runs do not carry (and record nothing). */
++ if (READ_ONCE(inode->root->fs_info->stripe_log_data_shared))
++ return;
+ copy = kmalloc(sizeof(*copy), GFP_NOFS);
+ if (!copy)
+ return;
+@@ -1424,6 +1427,9 @@ void btrfs_carry_log_tail(struct btrfs_inode *inode)
+ inode->log_carry->nr_ranges = 0;
+ mutex_unlock(&inode->log_mutex);
+
++ for (int i = 0; i < copy->nr_ranges; i++)
++ atomic64_add(copy->range[i].len,
++ &inode->root->fs_info->stripe_run_stats.log_carry_bytes);
+ for (int i = 0; i < copy->nr_ranges; i++)
+ carry_one_range(inode, copy->range[i].start,
+ copy->range[i].len,
+diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
+index 7a882a47829c4..cb7f04ec8916f 100644
+--- a/fs/btrfs/disk-io.c
++++ b/fs/btrfs/disk-io.c
+@@ -2805,6 +2805,7 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
+ INIT_LIST_HEAD(&fs_info->delalloc_roots);
+ INIT_LIST_HEAD(&fs_info->caching_block_groups);
+ INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
++ fs_info->stripe_log_data_shared = true;
+ fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
+ fs_info->stripe_compact = 10;
+ fs_info->stripe_park_sync_timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index cc11757f59fa1..54b568b419bf0 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -891,6 +891,16 @@ struct btrfs_fs_info {
+ /* Completed-write sectors not live in their run (should be ~0). */
+ atomic64_t written_not_live;
+ } stripe_park_stats;
++ /*
++ * LOG-class data runs. Set (the default): runs are shared per
++ * (subvolume, log_transid); a log commit seals the stripe holding the
++ * end of the logged extent and the run goes on, allocations of a full
++ * stripe or more stay in the inode's private run, and the commit waits
++ * only for the logged extent's own stripes. Clear: one private run
++ * per fsyncing inode, closed at each log commit, with carry-forward of
++ * its final partial stripe. See btrfs_log_settle_stripes().
++ */
++ bool stripe_log_data_shared;
+ /* Stripe run lifecycle counters (sysfs stripe_run_stats). */
+ struct {
+ /* private NOCOW runs opened (they outlive commits) */
+@@ -914,6 +924,15 @@ struct btrfs_fs_info {
+ atomic64_t compact_stripes;
+ /* live bytes compaction moved */
+ atomic64_t compact_bytes;
++ /* log commits that waited to settle a logged extent, and how long */
++ atomic64_t log_settle_waits;
++ atomic64_t log_settle_wait_ns;
++ /* carry-forward: ranges recorded, bytes re-dirtied at fsync entry */
++ atomic64_t log_carry_ranges;
++ atomic64_t log_carry_bytes;
++ /* shared runs: frontier stripes sealed at log commit, bytes skipped */
++ atomic64_t log_seals;
++ atomic64_t log_seal_bytes;
+ } stripe_run_stats;
+ /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
+ u32 stripe_rmw_prop;
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 753de9e6357da..d90574a7f81f3 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1232,6 +1232,31 @@ static ssize_t btrfs_##_name##_store(struct kobject *kobj, \
+ BTRFS_ATTR_RW(, _name, btrfs_##_name##_show, btrfs_##_name##_store)
+
+ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
++
++static ssize_t btrfs_stripe_log_data_shared_show(struct kobject *kobj,
++ struct kobj_attribute *a, char *buf)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++
++ return sysfs_emit(buf, "%d\n", READ_ONCE(fs_info->stripe_log_data_shared) ? 1 : 0);
++}
++
++static ssize_t btrfs_stripe_log_data_shared_store(struct kobject *kobj,
++ struct kobj_attribute *a,
++ const char *buf, size_t len)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++ bool val;
++ int ret;
++
++ ret = kstrtobool(buf, &val);
++ if (ret)
++ return ret;
++ WRITE_ONCE(fs_info->stripe_log_data_shared, val);
++ return len;
++}
++BTRFS_ATTR_RW(, stripe_log_data_shared, btrfs_stripe_log_data_shared_show,
++ btrfs_stripe_log_data_shared_store);
+ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_sync_timeout_ms, stripe_park_sync_timeout_ms);
+ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_congestion, stripe_park_congestion);
+
+@@ -1665,6 +1690,7 @@ static const struct attribute *btrfs_attrs[] = {
+ BTRFS_ATTR_PTR(, stripe_park_stats),
+ BTRFS_ATTR_PTR(, stripe_run_stats),
+ BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
++ BTRFS_ATTR_PTR(, stripe_log_data_shared),
+ BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
+ BTRFS_ATTR_PTR(, stripe_park_congestion),
+ BTRFS_ATTR_PTR(, stripe_compact),
+--
+2.47.3
+
--- /dev/null
+From ef656afade0bf10d89629245f8a45c562c1e52b7 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:27 -0400
+Subject: [RFC PATCH 58/85] btrfs: add a write-hole invariant checker to the
+ raid56 write path
+To: linux-btrfs@vger.kernel.org
+
+With stripe-exclusive allocation, a raid56 data stripe may only be
+written while an open or draining stripe run covers it: after its run
+retires and drains at a transaction commit, nothing may ever write to
+it again, and a write outside any run means an allocation bypassed the
+policy. Both cases are the write hole about to happen.
+
+Check the invariant (under CONFIG_BTRFS_DEBUG) for every raid56 write
+operation, full-stripe and sub-stripe alike, at rmw_rbio() time. This
+turns every upstream violation -- a missed allocation path, a
+retirement ordering bug, an accounting leak -- into a deterministic
+WARN at the moment of the offending write, instead of silent damage
+that needs a crash plus a device failure plus a scrub to observe. The
+bios gathered in an rbio have not reported their IO done yet, so their
+runs cannot drain under the check: no false positives from completion
+races.
+
+Block groups that ever hosted relocation-class runs are skipped
+(sticky, debug-only flag): relocation legitimately overwrites its
+preallocated extents in place after their runs drain, and the write
+path cannot tell those writes from violations.
+
+A runtime enable of the policy (the btrfs.stripe_alloc property set on a
+live filesystem) flips it while the legacy allocator may still have writes
+in flight, in partly used stripes that no run covers, and the check would
+warn on the first of them. So a runtime enable holds the check off until
+a worker has started delalloc on all roots and waited for every ordered
+extent (the property is applied inside a transaction, where that cannot
+wait); the same wait writes any delalloc tail a writeback racing the
+enable left unsubmitted. A mount-time enable has nothing in flight.
+close_ctree() flushes the worker.
+
+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 | 90 ++++++++++++++++++++++++++++++++++++++++++
+ fs/btrfs/block-group.h | 16 ++++++++
+ fs/btrfs/disk-io.c | 2 +
+ fs/btrfs/extent-tree.c | 3 ++
+ fs/btrfs/fs.h | 9 +++++
+ fs/btrfs/raid56.c | 10 +++++
+ 6 files changed, 130 insertions(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index ce88e22f780aa..09aa4404f7058 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -5,6 +5,8 @@
+ #include "misc.h"
+ #include "ctree.h"
+ #include "block-group.h"
++#include "ordered-data.h"
++#include "btrfs_inode.h"
+ #include "space-info.h"
+ #include "disk-io.h"
+ #include "free-space-cache.h"
+@@ -2268,8 +2270,33 @@ static void warn_stripe_alloc_uncovered(struct btrfs_fs_info *info)
+ "stripe_alloc does not cover raid56 metadata: the write hole remains for metadata, consider converting it to raid1c3/raid1c4");
+ }
+
++/*
++ * Drain the writes the legacy allocator placed before stripe_alloc was
++ * enabled on a live filesystem, then arm the write-hole invariant check.
++ * Runs in a worker: the property that enables the policy is applied inside
++ * a transaction, where flushing delalloc cannot wait.
++ */
++void btrfs_stripe_alloc_enable_work(struct work_struct *work)
++{
++ struct btrfs_fs_info *fs_info = container_of(work, struct btrfs_fs_info,
++ stripe_alloc_enable_work);
++
++ btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
++ btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
++ clear_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags);
++ btrfs_info(fs_info,
++ "stripe_alloc: writes placed before the policy was enabled have landed");
++}
++
++/*
++ * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
++ * property on the top-level subvolume's root directory. Runs during mount
++ * when the root directory inode loads its properties -- before any user IO
++ * -- or at runtime from btrfs_set_prop().
++ */
+ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ {
++ bool live = test_bit(BTRFS_FS_OPEN, &fs_info->flags);
+ int ret;
+
+ if (btrfs_test_opt(fs_info, STRIPE_ALLOC))
+@@ -2277,6 +2304,17 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ ret = btrfs_stripe_alloc_check_support(fs_info);
+ if (ret)
+ return ret;
++ /*
++ * On a live filesystem the legacy allocator may still have writes in
++ * flight. Their extents sit in partly used stripes that no stripe run
++ * covers, so the write-hole invariant check would report them although
++ * they were placed before the policy existed. Keep the check off until
++ * every ordered extent that could have been allocated before the flip
++ * has landed; extents allocated after it have stripe runs. A mount-time
++ * enable has nothing in flight and skips the drain.
++ */
++ if (live)
++ set_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags);
+ btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
+ warn_stripe_alloc_uncovered(fs_info);
+ /*
+@@ -2289,6 +2327,8 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ stripe_alloc_sweep_groups(fs_info, true);
+ btrfs_info(fs_info,
+ "using stripe-exclusive allocation for raid56 data");
++ if (live)
++ queue_work(system_unbound_wq, &fs_info->stripe_alloc_enable_work);
+ return 0;
+ }
+
+@@ -2976,6 +3016,56 @@ bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr)
+ return ret;
+ }
+
++#ifdef CONFIG_BTRFS_DEBUG
++/*
++ * Write-hole invariant checker, called for every raid56 write (full-stripe
++ * and sub-stripe alike). Under stripe_alloc and stripe_meta a stripe may
++ * only be written while an open or draining run covers it; a write outside
++ * every run means a retired stripe is being rewritten or an allocation
++ * bypassed the policy.
++ *
++ * Groups that hosted RELOC or NOCOW runs are skipped: those extents are
++ * legitimately overwritten in place after their runs drain.
++ */
++void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
++ u64 full_stripe_start, bool sub_stripe)
++{
++ struct btrfs_open_stripe_run *run;
++ struct btrfs_block_group *bg;
++ unsigned long flags;
++ bool live = false;
++ u64 fsl;
++
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return;
++ /* the legacy allocator's writes are still landing after a runtime enable */
++ if (test_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags))
++ return;
++ bg = btrfs_lookup_block_group(fs_info, full_stripe_start);
++ if (!bg)
++ return;
++ if (!btrfs_is_stripe_alloc_bg(bg) ||
++ test_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED, &bg->runtime_flags))
++ goto out;
++ fsl = bg->full_stripe_len;
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (full_stripe_start < run->end &&
++ full_stripe_start + fsl > run->start) {
++ live = true;
++ break;
++ }
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ WARN_ONCE(!live,
++"btrfs: %s write to stripe %llu (block group %llu) outside any live stripe run: write hole window violated",
++ sub_stripe ? "sub-stripe" : "full-stripe",
++ full_stripe_start, bg->start);
++out:
++ btrfs_put_block_group(bg);
++}
++#endif
++
+ /*
+ * Drop the dedication of a block group to data relocation. Shared by the
+ * zoned allocator and the stripe allocation policy; both dedicate one
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index d6b2c12c7230c..7f4227e488fbd 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -127,6 +127,13 @@ enum btrfs_block_group_flags {
+ BLOCK_GROUP_FLAG_NEW,
+ BLOCK_GROUP_FLAG_FULLY_REMAPPED,
+ BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING,
++ /*
++ * The group has hosted relocation-class stripe runs. Relocation
++ * overwrites its preallocated extents in place after their runs
++ * drain, so the write-hole debug check cannot tell those writes
++ * from violations and skips such groups (sticky, debug only).
++ */
++ BLOCK_GROUP_FLAG_STRIPE_RELOC_USED,
+ /*
+ * Free space changed this transaction, so the group's stripe_unusable
+ * counter must be rescanned at commit (stripe_alloc only).
+@@ -556,6 +563,15 @@ void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info);
+ bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr);
+ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg);
+ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force);
++void btrfs_stripe_alloc_enable_work(struct work_struct *work);
++#ifdef CONFIG_BTRFS_DEBUG
++void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
++ u64 full_stripe_start, bool sub_stripe);
++#else
++static inline void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
++ u64 full_stripe_start,
++ bool sub_stripe) { }
++#endif
+ struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
+ u64 bytenr);
+ void btrfs_dec_nocow_writers(struct btrfs_block_group *bg);
+diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
+index cb7f04ec8916f..ad4046b12d011 100644
+--- a/fs/btrfs/disk-io.c
++++ b/fs/btrfs/disk-io.c
+@@ -2805,6 +2805,7 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
+ INIT_LIST_HEAD(&fs_info->delalloc_roots);
+ INIT_LIST_HEAD(&fs_info->caching_block_groups);
+ INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
++ INIT_WORK(&fs_info->stripe_alloc_enable_work, btrfs_stripe_alloc_enable_work);
+ fs_info->stripe_log_data_shared = true;
+ fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
+ fs_info->stripe_compact = 10;
+@@ -4504,6 +4505,7 @@ void __cold close_ctree(struct btrfs_fs_info *fs_info)
+ */
+ btrfs_run_delayed_iputs(fs_info);
+
++ flush_work(&fs_info->stripe_alloc_enable_work);
+ cancel_work_sync(&fs_info->async_reclaim_work);
+ cancel_work_sync(&fs_info->async_data_reclaim_work);
+ cancel_work_sync(&fs_info->preempt_reclaim_work);
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 5a464351b72de..cd945076a6d79 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4358,6 +4358,9 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
+ btrfs_clear_data_reloc_bg(block_group);
+ return 1;
+ }
++ if (class == BTRFS_STRIPE_RUN_RELOC)
++ set_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED,
++ &block_group->runtime_flags);
+ stripe_split_taken(ffe_ctl, num_bytes);
+ ffe_ctl->found_offset = offset;
+ ffe_ctl->search_start = offset;
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 54b568b419bf0..c09060496cb20 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -234,6 +234,13 @@ enum {
+ */
+ BTRFS_FS_UNALIGNED_TREE_BLOCK,
+
++ /*
++ * stripe_alloc was enabled on a live filesystem and the legacy
++ * allocator's writes have not all landed yet: the write-hole
++ * invariant check stays off until they have.
++ */
++ BTRFS_FS_STRIPE_ALLOC_ENABLING,
++
+ #if BITS_PER_LONG == 32
+ /* Indicate if we have error/warn message printed on 32bit systems */
+ BTRFS_FS_32BIT_ERROR,
+@@ -1023,6 +1030,8 @@ struct btrfs_fs_info {
+
+ struct semaphore uuid_tree_rescan_sem;
+
++ /* Drains legacy writes after stripe_alloc is enabled at runtime. */
++ struct work_struct stripe_alloc_enable_work;
+ /* Used to reclaim the metadata space in the background. */
+ struct work_struct async_reclaim_work;
+ struct work_struct async_data_reclaim_work;
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 169e1cccd73cd..3f469d62d5d46 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -3196,6 +3196,16 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ int sectornr;
+ int ret = 0;
+
++ /*
++ * Write-hole invariant check: every write must land in a stripe
++ * covered by a live stripe run when stripe-exclusive allocation is
++ * enabled. The bios gathered in this rbio have not reported their
++ * IO done yet, so their runs cannot drain under us.
++ */
++ btrfs_stripe_check_write(rbio->bioc->fs_info,
++ rbio->bioc->full_stripe_logical,
++ !rbio_is_full(rbio));
++
+ /*
+ * Allocate the pages for parity first, as P/Q pages will always be
+ * needed for both full-stripe and sub-stripe writes.
+--
+2.47.3
+
+++ /dev/null
-From 2c0f474a19cfc3a7cd92e3e19a78097cf20ea3ff Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:19 -0400
-Subject: [RFC PATCH 058/116] btrfs: stripe_alloc: give nocow extents a private
- run only while they may be written in place
-To: linux-btrfs@vger.kernel.org
-
-Preallocated extents and a nodatacow inode's extents are steered into a
-per-inode NOCOW-class stripe run, so that their stripes never hold any
-other file's data and an in-place write can be confined to the file that
-waived COW protection. Such a run survives transaction commits, so a
-slowly appended nocow file does not burn a stripe per commit.
-
-Both the steering and the survival were unconditional, but whether a
-nocow extent can be written in place at all is decided by the
-stripe_alloc_allow_rmw policy, and with nothing waived (the default)
-btrfs_stripe_nocow_writable() forces COW for every such write. The
-private runs then hold only ordinary COWed extents and unwritten
-preallocation, never in-place data, and their survival protects nothing:
-it only keeps the run object alive until the inode is evicted, and every
-whole stripe freed inside the run's range meanwhile -- a prealloc extent
-overwritten by a COWed one, or unlinked -- is stranded, counted free but
-refused to every claim. An fsstress run on a filesystem filled to
-ENOSPC left 387 and 976 such runs in single block groups, holding 99% of
-the group's free whole stripes.
-
-Steer into a NOCOW run only when the policy lets that kind of extent
-(prealloc or nodatacow) be written in place, and let a NOCOW run outlive
-commits only when the policy allowed in-place writes when the run was
-opened. The verdict is recorded in the run at open time so the commit's
-close and settle predicates cannot disagree with each other when the
-policy changes underneath them: a run opened under one policy keeps its
-lifecycle until it is closed by filling up, by the inode's eviction or
-by a forced quiesce.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 32 +++++++++++++++++++++++++-------
- fs/btrfs/extent-tree.c | 17 +++++++++++++----
- 2 files changed, 38 insertions(+), 11 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 94c5bbe457907..c13d6e4d4f8ae 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -507,6 +507,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() */
- /*
- * One bit per sector of the run: set while that sector holds an
- * allocation someone still intends to write, clear otherwise.
-@@ -1025,6 +1026,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->owner = 0;
- new_run->transid = transid;
- new_run->start = start;
-@@ -1209,6 +1211,17 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- }
- 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));
- new_run->owner = ino;
- new_run->start = start;
- new_run->end = start + len;
-@@ -2414,14 +2427,19 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
- continue;
- /*
- * A nodatacow inode's private run survives transaction
-- * commits: its stripes hold only that inode's expendable
-- * (write-hole-waived) data, so invariant I2 has nothing to
-- * protect there, and closing would burn a stripe per commit
-- * for a slowly appended nocow file. Forced quiescing
-+ * commits while the stripe_alloc_allow_rmw policy lets its
-+ * data be written in place: its stripes then hold only that
-+ * inode's expendable (write-hole-waived) data, so invariant
-+ * I2 has nothing to protect there, and closing would burn a
-+ * stripe per commit for a slowly appended nocow file. With
-+ * nothing waived the run holds ordinary COWed extents (or
-+ * unwritten preallocation) and closes like a COW run: kept
-+ * open, it only strands the whole stripes freed inside its
-+ * range until the inode is evicted. Forced quiescing
- * (read-only, removal, unmount: seq == U64_MAX) still closes
-- * them, as does the owning inode's eviction.
-+ * persistent runs, as does the owning inode's eviction.
- */
-- if (run->class == BTRFS_STRIPE_RUN_NOCOW && seq != U64_MAX)
-+ if (run->persistent && seq != U64_MAX)
- continue;
- /*
- * Metadata runs are still being filled at this point in the
-@@ -2469,7 +2487,7 @@ 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->class == BTRFS_STRIPE_RUN_NOCOW && seq != U64_MAX)
-+ if (run->persistent && seq != U64_MAX)
- continue;
- /* Metadata drains after tree writeback, not here. */
- if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index fee586ac38546..cb5c9c728e8d0 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -5112,13 +5112,22 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- * 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.
-+ * any other file's data) -- but only while the stripe_alloc_allow_rmw
-+ * policy lets that kind of extent be written in place: otherwise
-+ * every write to it is COWed like anyone else's, and a private run
-+ * (which outlives commits) would only strand the whole stripes freed
-+ * inside its range until the inode is evicted; 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.
- */
- 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,
---
-2.47.3
-
+++ /dev/null
-From 6a7339d6329e4cb1899e0ef9d379aa6e58bb63f0 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:20 -0400
-Subject: [RFC PATCH 059/116] btrfs: stripe_alloc: count nocow run lifecycles
- and stranded stripes in sysfs
-To: linux-btrfs@vger.kernel.org
-
-Add a stripe_run_stats file beside stripe_park_stats with lifetime
-counters for the paths the previous two patches touched, so a test can
-show that it exercised them rather than merely passed: private NOCOW
-runs opened, claim candidates refused for overlapping a live run, bytes
-of whole stripes the scans found stranded behind live runs, and rescans
-requested by a freed run to credit its stripes back.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/block-group.c | 12 ++++++++++--
- fs/btrfs/fs.h | 15 +++++++++++++++
- fs/btrfs/sysfs.c | 18 ++++++++++++++++++
- 3 files changed, 43 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index c13d6e4d4f8ae..5edba31e090d3 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -693,8 +693,10 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
- * with the run gone they are claimable again, so have the next commit
- * rescan the group and credit them back.
- */
-- if (READ_ONCE(bg->stripe_unusable_ready))
-+ if (READ_ONCE(bg->stripe_unusable_ready)) {
- set_bit(BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY, &bg->runtime_flags);
-+ atomic64_inc(&bg->fs_info->stripe_run_stats.strand_rescan_marks);
-+ }
- wake_up_var(&bg->open_stripe_runs);
- }
-
-@@ -1222,6 +1224,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- (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;
- new_run->start = start;
- new_run->end = start + len;
-@@ -1275,8 +1279,10 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- len = run->start - run_start;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-- if (len < bg->full_stripe_len)
-+ if (len < bg->full_stripe_len) {
-+ atomic64_inc(&bg->fs_info->stripe_run_stats.claim_refused_live_run);
- return false;
-+ }
- *run_len = len;
- return true;
- }
-@@ -1318,6 +1324,8 @@ u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
- }
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ if (stranded)
-+ atomic64_add(stranded, &bg->fs_info->stripe_run_stats.strand_scan_bytes);
- return stranded;
- }
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index a483722cfacaa..bce5cc5b09740 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -908,6 +908,21 @@ struct btrfs_fs_info {
- atomic64_t meta_rmw_free;
- atomic64_t congestion_short;
- } stripe_park_stats;
-+ /*
-+ * Stripe run lifecycle observability: lifetime counters exposed
-+ * through sysfs stripe_run_stats, so a test can show it exercised
-+ * the nocow private-run and stranded-stripe paths at all.
-+ */
-+ struct {
-+ /* private NOCOW runs opened (they outlive commits) */
-+ atomic64_t nocow_run_opened;
-+ /* claim candidates refused for overlapping a live run */
-+ atomic64_t claim_refused_live_run;
-+ /* bytes of whole stripes the scans found stranded behind live runs */
-+ atomic64_t strand_scan_bytes;
-+ /* rescans requested by a freed run to credit its stripes back */
-+ atomic64_t strand_rescan_marks;
-+ } stripe_run_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
- u32 stripe_rmw_prop;
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 391eeabd029f8..786a6dbb02fe0 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1170,6 +1170,23 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- }
- BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
-
-+static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
-+ struct kobj_attribute *a, char *buf)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+
-+ return sysfs_emit(buf,
-+ "nocow_run_opened %lld\n"
-+ "claim_refused_live_run %lld\n"
-+ "strand_scan_bytes %lld\n"
-+ "strand_rescan_marks %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));
-+}
-+BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
-+
- /*
- * Park deadlines, ms. Writable so the constants can be swept against a
- * workload rather than rebuilt per data point; 0 disables parking for that
-@@ -1574,6 +1591,7 @@ static const struct attribute *btrfs_attrs[] = {
- BTRFS_ATTR_PTR(, bg_reclaim_threshold),
- BTRFS_ATTR_PTR(, commit_stats),
- BTRFS_ATTR_PTR(, stripe_park_stats),
-+ BTRFS_ATTR_PTR(, stripe_run_stats),
- BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
- BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
- BTRFS_ATTR_PTR(, stripe_park_congestion),
---
-2.47.3
-
--- /dev/null
+From 1fb94c6dc46ba944ff8863f08acd8156ff904eae Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:48 -0400
+Subject: [RFC PATCH 59/85] btrfs: stripe_alloc: report read-modify-write of
+ uncovered stripes (debug part)
+To: linux-btrfs@vger.kernel.org
+
+The debug half of "btrfs: stripe_alloc: report read-modify-write of
+uncovered stripes", earlier in this series: the meta_rmw counter in
+stripe_park_stats, which goes with the series' other debug statistics.
+The warning itself is in that patch.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/fs.h | 1 +
+ fs/btrfs/raid56.c | 1 +
+ fs/btrfs/sysfs.c | 2 ++
+ 3 files changed, 4 insertions(+)
+
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index c09060496cb20..10c70314e9126 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -873,6 +873,7 @@ struct btrfs_fs_info {
+ * stripe.
+ */
+ atomic64_t pad_decline_uncovered;
++ atomic64_t meta_rmw;
+ atomic64_t congestion_short;
+ /* Stripes pinned in the rbio cache (rbio_needs_pin()). */
+ atomic64_t rbio_pinned;
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 3f469d62d5d46..05e2952ac074a 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -3185,6 +3185,7 @@ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
+ !(rbio->bioc->map_type & BTRFS_BLOCK_GROUP_METADATA))
+ return;
+
++ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw);
+ btrfs_warn_rl(fs_info,
+ "read-modify-write of full stripe %llu: this block group is not covered by stripe_alloc, the raid56 write hole applies to it",
+ rbio->bioc->full_stripe_logical);
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index d90574a7f81f3..d2889c9c89379 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1139,6 +1139,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "padded %lld\n"
+ "padded_unwritten %lld\n"
+ "rmw_reads %lld\n"
++ "meta_rmw %lld\n"
+ "rbio_pin_refused %lld\n"
+ "rbio_pinned_now %d\n"
+ "rbio_pinned_live %d\n"
+@@ -1158,6 +1159,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.padded),
+ atomic64_read(&fs_info->stripe_park_stats.padded_unwritten),
+ atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
++ atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_refused),
+ pinned,
+ live,
+--
+2.47.3
+
+++ /dev/null
-From 452563014c9870e31709cf8dd8a271d8b0fdb26f Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:21 -0400
-Subject: [RFC PATCH 060/116] btrfs: stripe_alloc: hold a stripe of margin
- across a preallocation
-To: linux-btrfs@vger.kernel.org
-
-Admission now charges a preallocation the roundup of its bytes to whole
-stripes, but that charge lives only for the check: between the
-reservation and the allocation only the raw bytes sit in bytes_may_use.
-fallocate() is quick, but eight fsstress processes preallocating at the
-fill edge were quick together, and each in-flight preallocation short of
-a stripe still took a stripe the gate had counted for someone else: the
-failure-time dump kept showing admitted writes with the supply gone.
-
-Do for preallocation what the delalloc margin does per outstanding
-extent: hold one stripe in bytes_stripe_margin from the successful data
-reservation until the caller's allocations are done, at the four users
-of btrfs_alloc_data_chunk_ondemand() -- fallocate's range loop, the
-zero-range preallocation, relocation's cluster preallocation and the
-encoded write's extent reservation. Released as soon as the claims have
-landed, so the hold costs nothing beyond that window.
-
-Assisted-by: Claude:claude-fable-5
----
- fs/btrfs/delalloc-space.c | 14 ++++++-
- fs/btrfs/delalloc-space.h | 2 +
- fs/btrfs/file.c | 17 ++++++--
- fs/btrfs/inode.c | 7 +++-
- fs/btrfs/relocation.c | 7 +++-
- fs/btrfs/space-info.c | 86 ++++++++++++++++++++++++++++++++++++---
- fs/btrfs/space-info.h | 3 ++
- 7 files changed, 123 insertions(+), 13 deletions(-)
-
-diff --git a/fs/btrfs/delalloc-space.c b/fs/btrfs/delalloc-space.c
-index 27b492cb0c1d8..4748c90897f5e 100644
---- a/fs/btrfs/delalloc-space.c
-+++ b/fs/btrfs/delalloc-space.c
-@@ -124,6 +124,17 @@ 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;
-@@ -139,7 +150,8 @@ int btrfs_alloc_data_chunk_ondemand(const struct btrfs_inode *inode, u64 bytes)
- 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,
-diff --git a/fs/btrfs/delalloc-space.h b/fs/btrfs/delalloc-space.h
-index c464cf0a88d9b..37860ced7a723 100644
---- a/fs/btrfs/delalloc-space.h
-+++ b/fs/btrfs/delalloc-space.h
-@@ -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);
-diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
-index 1cd9cc6f34b87..0a6e59c11b1f1 100644
---- a/fs/btrfs/file.c
-+++ b/fs/btrfs/file.c
-@@ -40,6 +40,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.
-@@ -2952,6 +2953,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,
-@@ -3077,8 +3079,9 @@ static int btrfs_zero_range(struct inode *inode,
- 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;
-@@ -3095,6 +3098,8 @@ static int btrfs_zero_range(struct inode *inode,
- 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 */
-@@ -3105,6 +3110,7 @@ static int btrfs_zero_range(struct inode *inode,
- }
- 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);
-@@ -3131,6 +3137,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;
-@@ -3255,8 +3262,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;
- }
-@@ -3291,6 +3299,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;
-
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index 98d376ce99eb8..d5732d8938f14 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -9943,6 +9943,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;
-
-@@ -10084,7 +10085,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);
-@@ -10113,6 +10115,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,
- false);
-+ btrfs_stripe_prealloc_release(fs_info, stripe_held);
-+ stripe_held = 0;
- if (ret)
- goto out_delalloc_release;
- extent_reserved = true;
-@@ -10161,6 +10165,7 @@ ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
- 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.
-diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
-index f02d04eacf5f0..ed44c1cd99f6a 100644
---- a/fs/btrfs/relocation.c
-+++ b/fs/btrfs/relocation.c
-@@ -2798,6 +2798,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),
-@@ -2815,8 +2816,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;
-
-@@ -2841,6 +2843,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,
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 0c5757218960f..a672d1b304cfb 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -191,6 +191,13 @@ struct reserve_ticket {
- bool reloc;
- /* Made by the mount-time orphan cleanup: may steal regardless. */
- bool mount_cleanup;
-+ /*
-+ * 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;
- struct list_head list;
- wait_queue_head_t wait;
- spinlock_t lock;
-@@ -485,6 +492,52 @@ void btrfs_stripe_margin_mod(struct btrfs_inode *inode, int mod)
- spin_unlock(&sinfo->lock);
- }
-
-+/*
-+ * The preallocation twin of the delalloc margin. A preallocation has no
-+ * outstanding extent to carry a margin, yet its allocation claims
-+ * round_up(bytes, stripe) whole stripes: admission charges the roundup
-+ * (stripe_claimable_admit()), but between the admission and the claim only
-+ * the raw bytes sit in bytes_may_use, and several preallocations in flight
-+ * together overran the supply behind writes admitted earlier. Hold one
-+ * stripe in the margin from a successful data reservation until the
-+ * caller's allocations are done. Returns the bytes held, 0 when the gate
-+ * is not in effect; the caller hands it back to the release.
-+ */
-+/*
-+ * Charge one whole stripe of collateral for a preallocation, under
-+ * space_info->lock and together with the bytes it is admitted for: the
-+ * caller's allocations claim round_up(bytes, stripe) whole stripes, and the
-+ * hold keeps that stripe out of the supply the gate shows to everyone else
-+ * until the claims land (btrfs_stripe_prealloc_release()). Charged after
-+ * the admission, with the lock dropped in between, two sub-stripe
-+ * preallocations could both be admitted against one stripe of supply and a
-+ * buffered write admitted alongside them found no stripe at writeback.
-+ */
-+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)
-@@ -785,6 +838,8 @@ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info)
- can_overcommit(space_info, tused, ticket->bytes, flush)) &&
- stripe_claimable_admit(space_info, ticket->bytes, ticket->reloc)) {
- 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;
-@@ -1998,8 +2053,8 @@ 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,
-+ enum btrfs_reserve_flush_enum flush, u64 *held)
- {
- struct btrfs_fs_info *fs_info = space_info->fs_info;
- struct work_struct *async_work;
-@@ -2069,6 +2124,8 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
- stripe_claimable_admit(space_info, orig_bytes,
- 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;
- }
-
-@@ -2102,6 +2159,8 @@ static int reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
- ticket.reloc = reloc;
- ticket.mount_cleanup =
- READ_ONCE(fs_info->mount_cleanup_task) == current;
-+ ticket.hold_stripe = held != NULL;
-+ ticket.held = 0;
- if (trace_btrfs_reserve_ticket_enabled())
- start_ns = ktime_get_ns();
-
-@@ -2149,7 +2208,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;
- }
-
- /*
-@@ -2172,7 +2234,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, flush, NULL);
- if (ret == -ENOSPC) {
- struct btrfs_fs_info *fs_info = space_info->fs_info;
-
-@@ -2197,6 +2259,18 @@ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
- */
- int btrfs_reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
- enum btrfs_reserve_flush_enum flush)
-+{
-+ return btrfs_reserve_data_bytes_held(space_info, bytes, 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)
- {
- struct btrfs_fs_info *fs_info = space_info->fs_info;
- int ret;
-@@ -2211,7 +2285,9 @@ int btrfs_reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
- "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, flush, held);
- if (ret == -ENOSPC) {
- trace_btrfs_space_reservation(fs_info, "space_info:enospc",
- space_info->flags, bytes, 1);
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index b4d7e2ad9daf8..61f942e0141d0 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -369,6 +369,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_block_group *block_group);
- void btrfs_update_space_info_chunk_size(struct btrfs_space_info *space_info,
- u64 chunk_size);
---
-2.47.3
-
--- /dev/null
+From 587a154b50c77423901bc29f0991dd3053fe0bf1 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:25 -0400
+Subject: [RFC PATCH 60/85] btrfs: stripe_alloc: say at mount whether the
+ policy is on (debug part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: say at mount whether the policy is
+on" (earlier in this series) that need code from "btrfs: add a
+write-hole invariant checker to the raid56 write path", which comes
+after it in this series: they are applied here, once "btrfs: add a
+write-hole invariant checker to the raid56 write path" is in, instead of
+with the rest of "btrfs: stripe_alloc: say at mount whether the policy
+is on".
+
+Assisted-by: Claude:claude-fable-5-1
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 8 +++++---
+ 1 file changed, 5 insertions(+), 3 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 09aa4404f7058..b24cabbd7a2ab 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -2325,10 +2325,12 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ * when their caching thread finishes, now that the policy is on.
+ */
+ stripe_alloc_sweep_groups(fs_info, true);
+- btrfs_info(fs_info,
+- "using stripe-exclusive allocation for raid56 data");
+- if (live)
++ /* At mount, btrfs_fill_super() reports the outcome. */
++ if (live) {
++ btrfs_info(fs_info,
++ "using stripe-exclusive allocation for raid56 data (filesystem property)");
+ queue_work(system_unbound_wq, &fs_info->stripe_alloc_enable_work);
++ }
+ return 0;
+ }
+
+--
+2.47.3
+
--- /dev/null
+From 4496c53dc0e42c3833b3c135678720b10a79ffdd Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:40 -0400
+Subject: [RFC PATCH 61/85] btrfs: stripe_alloc: allow-rmw policy, and
+ write-in-place for isolated nocow extents (debug part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: allow-rmw policy, and write-in-place
+for isolated nocow extents" (earlier in this series) that need code from
+"btrfs: add a write-hole invariant checker to the raid56 write path",
+which comes after it in this series: they are applied here, once "btrfs:
+add a write-hole invariant checker to the raid56 write path" is in,
+instead of with the rest of "btrfs: stripe_alloc: allow-rmw policy, and
+write-in-place for isolated nocow extents".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 3 ++-
+ 1 file changed, 2 insertions(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index b24cabbd7a2ab..6ecfd21c3e2d7 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -3047,7 +3047,8 @@ void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
+ if (!bg)
+ return;
+ if (!btrfs_is_stripe_alloc_bg(bg) ||
+- test_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED, &bg->runtime_flags))
++ test_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED, &bg->runtime_flags) ||
++ test_bit(BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED, &bg->runtime_flags))
+ goto out;
+ fsl = bg->full_stripe_len;
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+--
+2.47.3
+
+++ /dev/null
-From 8896655ef1341641de95f80d6ae08632f18e25df Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:22 -0400
-Subject: [RFC PATCH 061/116] btrfs: stripe_meta: carry raid56 metadata groups
- through a runtime enable or disable
-To: linux-btrfs@vger.kernel.org
-
-The property path arms and disarms the trapped-space accounting of the
-cached block groups, but stripe_alloc_sweep_groups() walked only DATA
-space_infos: a runtime enable left already-cached raid56 metadata groups
-unarmed until something else (a new chunk, a read-write transition)
-initialised them, so their trapped and claimable bytes were missing from
-metadata admission; a runtime disable left armed metadata groups' bytes
-in the space_info after the option was gone. Walk METADATA space_infos
-too, for both directions.
-
-Two more things a runtime toggle needs under raid56 metadata:
-
-The metadata retirement at commit returned at once without the option,
-so after a disable the running transaction's open metadata runs were
-never closed or drained and their block group references were held
-until unmount, where btrfs_free_block_groups() asserts on them. Retire
-unconditionally; the walk is over the list of groups with open runs and
-is empty when there is nothing to do.
-
-And the enable-time drain that keeps the write-hole check quiet until the
-legacy allocator's writes have landed only waited for data (delalloc and
-ordered extents). Tree blocks the legacy allocator placed in the
-transaction that was running at the flip are written by that
-transaction's commit, into the partly used stripes they were allocated
-in -- under raid56 metadata that commit is the last legacy
-read-modify-write, and the metadata RMW reporter says so:
-
- read-modify-write of stripe 42860544 rewrites parity over committed
- tree block 42860544 at generation 10 ... while writing generation 11:
- write hole
- btrfs: sub-stripe write to stripe 42860544 (block group 34603008)
- outside any live stripe run: write hole window violated
- WARNING: CPU: 1 PID: 408294 at fs/btrfs/block-group.c:2889
- btrfs_stripe_check_write+0x109/0x150
-
-Commit that transaction from the drain worker before arming the check.
-The exposure of the enabling transaction itself is inherent -- its
-blocks are already placed -- and bounded to that one commit.
-
-Found by stripe-meta-toggle-test.sh (runtime enable with a fill to the
-metadata edge, then a property-enabled filesystem disabled and
-unmounted), on raid5 and raid6 metadata.
-
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/block-group.c | 55 ++++++++++++++++++++++++++++--------------
- 1 file changed, 37 insertions(+), 18 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 5edba31e090d3..aa1eee2a61ca5 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2080,8 +2080,9 @@ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info)
- }
-
- /*
-- * Arm or disarm stripe_unusable accounting across all raid56 data block
-- * groups whose caches are loaded. Same walk as the commit-time rescan.
-+ * Arm or disarm stripe_unusable accounting across all raid56 data and
-+ * metadata block groups whose caches are loaded. Same walk as the
-+ * commit-time rescan.
- */
- static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
- {
-@@ -2090,20 +2091,25 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
- list_for_each_entry(sinfo, &fs_info->space_info, list) {
- int raid;
-
-- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA)) {
-- /*
-- * Metadata: the scan that maintains the stripe_meta
-- * margin and reserve stops with the option, so clear
-- * them here or they hold metadata back forever.
-- */
-- if (!arm && (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)) {
-- spin_lock(&sinfo->lock);
-- sinfo->bytes_stripe_margin = 0;
-- sinfo->bytes_stripe_reserve = 0;
-- btrfs_try_granting_tickets(sinfo);
-- spin_unlock(&sinfo->lock);
-- }
-+ if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
-+ BTRFS_BLOCK_GROUP_METADATA)))
- continue;
-+ /*
-+ * Metadata: the scan that maintains the stripe_meta margin
-+ * and reserve stops with the option, so clear them here or
-+ * they hold metadata back forever. The groups themselves
-+ * are armed and disarmed below like data groups: raid56
-+ * metadata places tree blocks in whole stripes from the
-+ * moment the option is on, so its trapped and claimable
-+ * bytes count from that moment and stop counting when it
-+ * goes off.
-+ */
-+ if (!arm && (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)) {
-+ spin_lock(&sinfo->lock);
-+ sinfo->bytes_stripe_margin = 0;
-+ sinfo->bytes_stripe_reserve = 0;
-+ btrfs_try_granting_tickets(sinfo);
-+ spin_unlock(&sinfo->lock);
- }
- down_read(&sinfo->groups_sem);
- for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-@@ -2170,6 +2176,15 @@ void btrfs_stripe_alloc_enable_work(struct work_struct *work)
-
- btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
- btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
-+ /*
-+ * Tree blocks the legacy allocator placed in the transaction that
-+ * was running at the flip are written by that transaction's commit,
-+ * into the partly used stripes they were allocated in: under raid56
-+ * metadata that commit is the last legacy read-modify-write, and the
-+ * metadata RMW reporter says so. Wait for it before arming the
-+ * check, which would otherwise report those writes as violations.
-+ */
-+ btrfs_commit_current_transaction(fs_info->tree_root);
- clear_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags);
- btrfs_info(fs_info,
- "stripe_alloc: writes placed before the policy was enabled have landed");
-@@ -2558,9 +2573,13 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
- LIST_HEAD(retire_list);
- unsigned long flags;
-
-- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-- return;
--
-+ /*
-+ * No option test: a runtime disable leaves the running transaction's
-+ * metadata runs open, and the commit that follows still has to close
-+ * and drain them or their block groups never drop their references.
-+ * The list is empty when nothing is open, so this costs nothing on a
-+ * filesystem that never had the policy.
-+ */
- spin_lock(&fs_info->open_stripe_lock);
- list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
- list_add_tail(&bg->open_stripe_retire_list, &retire_list);
---
-2.47.3
-
--- /dev/null
+From 369c9857cc08bba5420a2a23f8db57d28900f4a4 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Wed, 30 Sep 2026 18:07:52 -0400
+Subject: [RFC PATCH 62/85] btrfs: stripe_alloc: attribute each data
+ read-modify-write to why padding declined
+To: linux-btrfs@vger.kernel.org
+
+data_rmw counts read-modify-writes, and the pad_decline_* counters count
+the pad oracle's refusals, but a refusal does not always lead to a read
+(a full stripe or a cached one does not read), so the two cannot be
+subtracted: nothing says which RMWs the allocator explains. With
+allow_rmw empty, a data RMW in a stripe_alloc group is expected in two
+places only:
+
+ - at the open run's own frontier (the pad verdict UNCOVERED): the
+ sectors it reads belong to the same run, in the same transaction,
+ and are not durable yet;
+
+ - from relocation writing into its own preallocated extents, which no
+ root but the data reloc tree references until relocation moves the
+ pointers after writeback.
+
+Record the pad oracle's verdict on the rbio (rmw_try_pad_full()) and,
+at the RMW site, split data_rmw by it (data_rmw_<reason>, with
+data_rmw_not_tried when the oracle was not consulted and
+data_rmw_pad_ok_nomem when it agreed but the zero pages could not be
+allocated). NO_RUN is the oracle's catch-all exit, so split it further
+by the exit taken (data_rmw_norun_*) and count those in a read-only
+group (data_rmw_norun_bg_ro). Count the data RMWs written by the data
+reloc inode outside the frontier (data_rmw_reloc_writer, disjoint from
+data_rmw_uncovered). All in stripe_park_stats.
+
+A test can then assert that data_rmw - data_rmw_uncovered -
+data_rmw_reloc_writer is zero on a stripe_alloc filesystem, on a
+production kernel, with reclaim relocating during the run -- which it
+could not do from the totals alone.
+
+The cost is a byte of state per rbio and a few counter increments per
+RMW, plus one block group lookup for NO_RUN RMWs.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 17 +++++++++--
+ fs/btrfs/block-group.h | 17 +++++++++++
+ fs/btrfs/fs.h | 15 +++++++++
+ fs/btrfs/raid56.c | 69 ++++++++++++++++++++++++++++++++++++++++++
+ fs/btrfs/raid56.h | 9 ++++++
+ 5 files changed, 125 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 6ecfd21c3e2d7..6bef4d25d18e1 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1699,13 +1699,19 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+
+ if (list_empty_careful(&fs_info->open_stripe_bgs)) {
+ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
++ if (info)
++ info->norun = BTRFS_STRIPE_NORUN_NO_BGS;
+ return false;
+ }
+ bg = btrfs_lookup_block_group(fs_info, stripe_start);
+ if (!bg) {
+ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
++ if (info)
++ info->norun = BTRFS_STRIPE_NORUN_NO_BG;
+ return false;
+ }
++ if (info)
++ info->norun = BTRFS_STRIPE_NORUN_NO_COVER;
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+@@ -1718,6 +1724,7 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ info->run_end = run->end;
+ info->run_offset = run->offset;
+ info->inflight_bytes = run->inflight_bytes;
++ info->norun = BTRFS_STRIPE_NORUN_NO_LIVE;
+ }
+ if (!run->live || !run->live_nbits)
+ break;
+@@ -1731,8 +1738,11 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ * needs to pad. An open run's end is stripe aligned, so
+ * overhang there means a stripe the run does not own.
+ */
+- if (stripe_start + stripe_len > run->end && run->open)
++ if (stripe_start + stripe_len > run->end && run->open) {
++ if (info)
++ info->norun = BTRFS_STRIPE_NORUN_OVERHANG;
+ break;
++ }
+
+ first = (stripe_start - run->start) >> bits;
+ /*
+@@ -1741,8 +1751,11 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ * which sectors are dead, and padding acts on that by
+ * overwriting them.
+ */
+- if (first + nsectors > run->live_nbits)
++ if (first + nsectors > run->live_nbits) {
++ if (info)
++ info->norun = BTRFS_STRIPE_NORUN_PAST_MAP;
+ break;
++ }
+ bitmap_zero(dead, nsectors);
+ if (unwritten)
+ bitmap_zero(unwritten, nsectors);
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 7f4227e488fbd..4df2396ffc3b2 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -532,6 +532,22 @@ enum btrfs_stripe_pad_reason {
+ BTRFS_STRIPE_PAD_OK = 0,
+ BTRFS_STRIPE_PAD_NO_RUN, /* no open run covers the stripe */
+ BTRFS_STRIPE_PAD_UNCOVERED, /* a sector below the frontier is not covered */
++ BTRFS_STRIPE_PAD_NR_REASONS,
++};
++
++/*
++ * Which exit of btrfs_stripe_run_pad_mask() gave BTRFS_STRIPE_PAD_NO_RUN: a
++ * catch-all for every refusal, including "a run covers the stripe but its
++ * map cannot answer for it".
++ */
++enum btrfs_stripe_pad_norun {
++ BTRFS_STRIPE_NORUN_NO_BGS = 0, /* no block group has open runs */
++ BTRFS_STRIPE_NORUN_NO_BG, /* block group lookup failed */
++ BTRFS_STRIPE_NORUN_NO_COVER, /* no run's span covers the stripe */
++ BTRFS_STRIPE_NORUN_NO_LIVE, /* covering run has no live map */
++ BTRFS_STRIPE_NORUN_OVERHANG, /* open run's end cuts the stripe */
++ BTRFS_STRIPE_NORUN_PAST_MAP, /* stripe runs past the live map */
++ BTRFS_STRIPE_NORUN_NR,
+ };
+
+ struct btrfs_stripe_pad_info {
+@@ -540,6 +556,7 @@ struct btrfs_stripe_pad_info {
+ u64 run_offset; /* the allocation frontier */
+ u64 inflight_bytes;
+ u8 reason;
++ u8 norun; /* enum btrfs_stripe_pad_norun */
+ };
+
+ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 10c70314e9126..9d637c75ae38d 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -873,6 +873,21 @@ struct btrfs_fs_info {
+ * stripe.
+ */
+ atomic64_t pad_decline_uncovered;
++ /*
++ * data_rmw split by why padding declined for the rbio that
++ * did it: 0..2 are enum btrfs_stripe_pad_reason (0: the pad
++ * oracle agreed but the data page allocation failed), 3: not
++ * tried (stripe_alloc off, or no memory for the bitmap).
++ * data_rmw_norun splits the NO_RUN entry by enum
++ * btrfs_stripe_pad_norun; norun_ro counts those in a
++ * read-only (relocating) group. reloc_writer counts data RMWs
++ * written by the data reloc inode outside the open run's
++ * frontier, disjoint from data_rmw_by[UNCOVERED].
++ */
++ atomic64_t data_rmw_by[4];
++ atomic64_t data_rmw_norun[6];
++ atomic64_t data_rmw_norun_ro;
++ atomic64_t data_rmw_reloc_writer;
+ atomic64_t meta_rmw;
+ atomic64_t congestion_short;
+ /* Stripes pinned in the rbio cache (rbio_needs_pin()). */
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 05e2952ac074a..91780dae429aa 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -22,6 +22,7 @@
+ #include "file-item.h"
+ #include "btrfs_inode.h"
+ #include "block-group.h"
++#include "bio.h"
+
+ /* set when additional merges to this rbio are not allowed */
+ #define RBIO_RMW_LOCKED_BIT 1
+@@ -65,6 +66,9 @@
+ /* Set at park time and never cleared: this rbio once parked (stats). */
+ #define RBIO_WAS_PARKED_BIT 7
+
++/* rbio->pad_reason when rmw_try_pad_full() did not consult the pad oracle. */
++#define RBIO_PAD_NOT_TRIED 0xff
++
+ /*
+ * Set when a parked rbio carries (or merged) a REQ_SYNC bio: a waiter
+ * is blocked on it, so deadlines stay authoritative and neither the
+@@ -3027,6 +3031,65 @@ static void submit_write_bios(struct btrfs_raid_bio *rbio,
+ }
+ }
+
++static void rbio_record_pad(struct btrfs_raid_bio *rbio,
++ const struct btrfs_stripe_pad_info *info)
++{
++ rbio->pad_reason = info->reason;
++ rbio->pad_norun = info->norun;
++}
++
++static_assert(BTRFS_STRIPE_PAD_NR_REASONS + 1 ==
++ ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_park_stats.data_rmw_by));
++static_assert(BTRFS_STRIPE_NORUN_NR ==
++ ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_park_stats.data_rmw_norun));
++
++/*
++ * Attribute a read-modify-write to why padding declined for this rbio. With
++ * allow_rmw empty, a data RMW in a stripe_alloc group is expected in two
++ * places only: at the open run's own frontier (UNCOVERED: the sectors it
++ * reads are the same run's, in the same transaction, not yet durable), and
++ * from relocation writing into its own preallocated extents, which nothing
++ * but the data reloc inode references until relocation moves the pointers
++ * after writeback. Any other data RMW in a covered group is unexplained.
++ */
++static void rbio_count_rmw_reason(struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ u8 idx = rbio->pad_reason;
++ bool reloc_writer = false;
++ struct bio *bio;
++
++ if (idx >= BTRFS_STRIPE_PAD_NR_REASONS)
++ idx = BTRFS_STRIPE_PAD_NR_REASONS; /* not tried */
++ atomic64_inc(&fs_info->stripe_park_stats.data_rmw_by[idx]);
++ if (!(rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA))
++ return;
++
++ if (idx == BTRFS_STRIPE_PAD_NO_RUN) {
++ struct btrfs_block_group *bg;
++
++ if (rbio->pad_norun < BTRFS_STRIPE_NORUN_NR)
++ atomic64_inc(&fs_info->stripe_park_stats.data_rmw_norun[rbio->pad_norun]);
++ bg = btrfs_lookup_block_group(fs_info,
++ rbio->bioc->full_stripe_logical);
++ if (bg) {
++ if (data_race(bg->ro))
++ atomic64_inc(&fs_info->stripe_park_stats.data_rmw_norun_ro);
++ btrfs_put_block_group(bg);
++ }
++ }
++
++ /* The writer: the first bio's inode. */
++ spin_lock(&rbio->bio_list_lock);
++ bio = bio_list_peek(&rbio->bio_list);
++ if (bio && btrfs_bio(bio)->inode)
++ reloc_writer = btrfs_is_data_reloc_root(btrfs_bio(bio)->inode->root);
++ spin_unlock(&rbio->bio_list_lock);
++ /* Disjoint from the frontier count, so the two can be summed. */
++ if (reloc_writer && idx != BTRFS_STRIPE_PAD_UNCOVERED)
++ atomic64_inc(&fs_info->stripe_park_stats.data_rmw_reloc_writer);
++}
++
+ /*
+ * Try to avoid the RMW read phase of a sub-stripe write by zero-filling the
+ * uncovered data sectors. Legal only where the stripe's run says a sector
+@@ -3049,6 +3112,7 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ bool ok = false;
+ int i;
+
++ rbio->pad_reason = RBIO_PAD_NOT_TRIED;
+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
+ return false;
+
+@@ -3061,6 +3125,7 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ }
+ if (!btrfs_stripe_run_pad_mask(fs_info, stripe_start, stripe_len, dead,
+ unwritten, &info)) {
++ rbio_record_pad(rbio, &info);
+ trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
+ stripe_len, 0, 0, nsectors,
+ info.run_start, info.run_end,
+@@ -3089,6 +3154,7 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ if (!test_bit(i, dead)) {
+ atomic64_inc(&fs_info->stripe_park_stats.pad_decline_uncovered);
+ info.reason = BTRFS_STRIPE_PAD_UNCOVERED;
++ rbio_record_pad(rbio, &info);
+ trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
+ stripe_len, 0, covered,
+ nsectors,
+@@ -3109,6 +3175,8 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
+ if (!ok)
+ return false;
+
++ /* The oracle agreed: only a page allocation failure refuses now. */
++ rbio->pad_reason = BTRFS_STRIPE_PAD_OK;
+ if (alloc_rbio_data_pages(rbio) < 0)
+ return false;
+
+@@ -3237,6 +3305,7 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
+ atomic64_inc(&fs_info->stripe_park_stats.data_rmw);
+ if (!(rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA))
+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_reads);
++ rbio_count_rmw_reason(rbio);
+ /* A parked-then-flushed write that still had to read. */
+ if (test_bit(RBIO_WAS_PARKED_BIT, &rbio->flags))
+ atomic64_inc(&fs_info->stripe_park_stats.rmw_reads);
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index b1913e70a2187..d33baefc34b13 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -144,6 +144,15 @@ struct btrfs_raid_bio {
+ /* Flags that tell us if it is safe to merge with this bio. */
+ unsigned long flags;
+
++ /*
++ * Why the last rmw_try_pad_full() on this rbio did not pad, so the
++ * read-modify-write it leads to can be attributed: enum
++ * btrfs_stripe_pad_reason (OK here means the data page allocation
++ * failed), or RBIO_PAD_NOT_TRIED; and for NO_RUN, which exit.
++ */
++ u8 pad_reason;
++ u8 pad_norun;
++
+ /*
+ * Set if we're doing a parity rebuild for a read from higher up, which
+ * is handled differently from a parity rebuild as part of RMW.
+--
+2.47.3
+
+++ /dev/null
-From 0fd02d55577b85d92fb6429ed2065691fa3ce01e Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:23 -0400
-Subject: [RFC PATCH 062/116] btrfs: stripe_alloc: return a group's allocation
- cluster before scanning its stripes
-To: linux-btrfs@vger.kernel.org
-
-The legacy allocator moves free space entries of a block group into an
-allocation cluster -- for a metadata group, typically its whole initial
-free extent -- where the group's own free space tree no longer lists
-them although ctl->free_space still counts them. The stripe scan walks
-that tree, so on a group armed at a runtime enable after the legacy
-allocator had used it, the scan saw a fraction of the free space and
-the debug check that every free byte lands in exactly one stripe
-fired:
-
- assertion failed: counted == ctl->free_space :: 0, in
- fs/btrfs/free-space-cache.c:3395 (stripe_unusable_scan
- counted=1605632 != free_space=153534464)
- kernel BUG at fs/btrfs/free-space-cache.c:3395!
- RIP: stripe_unusable_scan.cold
- btrfs_block_group_init_stripe_unusable
- stripe_alloc_sweep_groups
- btrfs_enable_stripe_alloc
- prop_stripe_alloc_apply
-
-Without the assertion the group would have been armed with almost all
-of its free space neither trapped nor claimable. Data groups were only
-spared by the test rig: the legacy allocator clusters data only under
-ssd_spread, and every stripe_alloc run so far has mounted without it.
-
-Stripe-exclusive allocation never uses clusters, so hand the cluster's
-entries back to the group before the scan, both when arming and at the
-commit-time rescan (a legacy allocation already past the policy check
-at the flip can still set one up). Found by stripe-meta-toggle-test.sh
-on the first candidate that armed metadata groups at a runtime enable
-(raid5 metadata, 4 devices, mkfs-time metadata chunk).
-
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/free-space-cache.c | 27 +++++++++++++++++++++++++++
- 1 file changed, 27 insertions(+)
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 5e8362205e3b9..d01d480609b6a 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2114,6 +2114,31 @@ static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
- return trapped;
- }
-
-+/*
-+ * The legacy allocator parks a group's free space in an allocation cluster
-+ * (for a metadata group, its whole initial extent), where the group's own
-+ * tree no longer sees it and the stripe scan cannot count it.
-+ * Stripe-exclusive allocation never uses clusters, so a group that is being
-+ * armed -- or rescanned, if a legacy allocation was still in flight at a
-+ * runtime enable -- hands the cluster's entries back first.
-+ */
-+static void stripe_return_clusters(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_fs_info *fs_info = bg->fs_info;
-+ struct btrfs_free_cluster *cluster;
-+
-+ if (list_empty_careful(&bg->cluster_list))
-+ return;
-+ cluster = &fs_info->data_alloc_cluster;
-+ spin_lock(&cluster->refill_lock);
-+ btrfs_return_cluster_to_free_space(bg, cluster);
-+ spin_unlock(&cluster->refill_lock);
-+ cluster = &fs_info->meta_alloc_cluster;
-+ spin_lock(&cluster->refill_lock);
-+ btrfs_return_cluster_to_free_space(bg, cluster);
-+ spin_unlock(&cluster->refill_lock);
-+}
-+
- /*
- * Compute a stripe_alloc block group's initial trapped free space once its
- * free space cache is loaded, and enable incremental accounting from here on.
-@@ -2136,6 +2161,7 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
- if (!freep)
- return;
-
-+ stripe_return_clusters(bg);
- spin_lock(&ctl->tree_lock);
- if (bg->stripe_unusable_ready) {
- spin_unlock(&ctl->tree_lock);
-@@ -2269,6 +2295,7 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
- if (!freep)
- return;
-
-+ stripe_return_clusters(bg);
- spin_lock(&ctl->tree_lock);
- if (bg->stripe_unusable_ready) { /* skip if disarmed (read-only) */
- u64 scanned;
---
-2.47.3
-
--- /dev/null
+From 1b40736d13f7ed5208eaa5fa4f31b5ee0cd2330b Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Wed, 30 Sep 2026 18:07:56 -0400
+Subject: [RFC PATCH 63/85] btrfs: stripe_alloc: optionally audit data
+ read-modify-writes against the committed extent tree
+To: linux-btrfs@vger.kernel.org
+
+The attribution counters say which RMWs the allocator's design explains;
+they do not show that an RMW put nothing at risk. That depends on what
+the uncovered sectors hold: an RMW recomputes parity under them while
+they stay put, so a crash mid-write can tear them, and that matters
+only if a committed transaction references them and the owner is not
+relocation's own orphaned copy.
+
+Add an audit that answers it from the tree. For every data RMW, walk
+the commit root of the extent tree (no locking, as
+rmw_block_referenced() does; and like it, cached blocks only and
+commit_root_sem only when it is free, because the full stripe lock is
+held: a miss counts in audit_err, and mixed block groups, whose tree
+blocks share the stripe, are not audited) for extents overlapping the
+stripe's uncovered sectors, and read each one's data backrefs, inline
+and keyed. An extent owned only by the data reloc tree counts as
+relocation's (data_rmw_hole_reloc_only); any other owner, a shared ref
+(owner unknown), or no ref at all is foreign and counts as a write hole
+(data_rmw_hole_no_run / _uncovered / _other, by pad verdict). Log the
+writer of every foreign hole and of every NO_RUN RMW, rate-limited from
+separate call sites so a flood of the second cannot starve the first:
+root, inode, file offset, ordered extent flags, disk bytenr, stripe run
+sequence, and the covering run as the pad oracle saw it. The commit
+root switches just before the super lands, so the check can report a
+hole early, never hide one.
+
+A tree search per RMW is not free (a stock raid5 filesystem does
+thousands a minute), so the audit is built only with CONFIG_BTRFS_DEBUG
+and runs only while /sys/fs/btrfs/<uuid>/debug/stripe_rmw_audit is set,
+which it is not by default. Its counters are in
+debug/stripe_rmw_audit_stats, with data_rmw_audited so a reader can
+tell an audit that found nothing from one that never ran.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 2 +
+ fs/btrfs/block-group.h | 2 +
+ fs/btrfs/fs.h | 21 +++
+ fs/btrfs/raid56.c | 324 +++++++++++++++++++++++++++++++++++++++++
+ fs/btrfs/raid56.h | 8 +
+ fs/btrfs/sysfs.c | 61 ++++++++
+ 6 files changed, 418 insertions(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 6bef4d25d18e1..4072a83823f56 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -1724,6 +1724,8 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
+ info->run_end = run->end;
+ info->run_offset = run->offset;
+ info->inflight_bytes = run->inflight_bytes;
++ info->run_open = run->open;
++ info->run_class = run->class;
+ info->norun = BTRFS_STRIPE_NORUN_NO_LIVE;
+ }
+ if (!run->live || !run->live_nbits)
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 4df2396ffc3b2..c6dc7c1cdf1a5 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -557,6 +557,8 @@ struct btrfs_stripe_pad_info {
+ u64 inflight_bytes;
+ u8 reason;
+ u8 norun; /* enum btrfs_stripe_pad_norun */
++ u8 run_open; /* the covering run was open */
++ u8 run_class; /* and its class */
+ };
+
+ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 9d637c75ae38d..69d33accd21ee 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -914,6 +914,27 @@ struct btrfs_fs_info {
+ /* Completed-write sectors not live in their run (should be ~0). */
+ atomic64_t written_not_live;
+ } stripe_park_stats;
++
++#ifdef CONFIG_BTRFS_DEBUG
++ /*
++ * Audit of each data read-modify-write against the committed extent
++ * tree (raid56.c), off unless enabled through
++ * /sys/fs/btrfs/<uuid>/debug/stripe_rmw_audit. hole_by counts RMWs
++ * whose uncovered sectors hold committed extents that some root other
++ * than the data reloc tree owns (a real write hole), split like
++ * data_rmw_by; hole_reloc_only counts those owned by relocation alone.
++ */
++ bool stripe_rmw_audit;
++ struct {
++ atomic64_t audited;
++ atomic64_t hole_by[4];
++ atomic64_t hole_sectors;
++ atomic64_t hole_reloc_only;
++ atomic64_t hole_reloc_sectors;
++ atomic64_t reloc_writer_foreign;
++ atomic64_t audit_err;
++ } stripe_rmw_audit_stats;
++#endif
+ /*
+ * LOG-class data runs. Set (the default): runs are shared per
+ * (subvolume, log_transid); a log commit seals the stripe holding the
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 91780dae429aa..b892e085ac07a 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -23,6 +23,7 @@
+ #include "btrfs_inode.h"
+ #include "block-group.h"
+ #include "bio.h"
++#include "ordered-data.h"
+
+ /* set when additional merges to this rbio are not allowed */
+ #define RBIO_RMW_LOCKED_BIT 1
+@@ -3036,6 +3037,13 @@ static void rbio_record_pad(struct btrfs_raid_bio *rbio,
+ {
+ rbio->pad_reason = info->reason;
+ rbio->pad_norun = info->norun;
++#ifdef CONFIG_BTRFS_DEBUG
++ rbio->pad_run_open = info->run_open;
++ rbio->pad_run_class = info->run_class;
++ rbio->pad_run_start = info->run_start;
++ rbio->pad_run_end = info->run_end;
++ rbio->pad_run_offset = info->run_offset;
++#endif
+ }
+
+ static_assert(BTRFS_STRIPE_PAD_NR_REASONS + 1 ==
+@@ -3043,6 +3051,320 @@ static_assert(BTRFS_STRIPE_PAD_NR_REASONS + 1 ==
+ static_assert(BTRFS_STRIPE_NORUN_NR ==
+ ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_park_stats.data_rmw_norun));
+
++#ifdef CONFIG_BTRFS_DEBUG
++static_assert(BTRFS_STRIPE_PAD_NR_REASONS + 1 ==
++ ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_rmw_audit_stats.hole_by));
++
++/* What the audit found under one RMW's uncovered sectors. */
++struct rmw_audit {
++ int foreign; /* sectors under extents another root owns */
++ int reloc; /* sectors under extents only relocation owns */
++ u64 min_gen;
++ u64 max_gen;
++ u64 first; /* first foreign extent */
++ u64 first_root; /* one other root referencing it (0: shared ref) */
++};
++
++/* One extent being classified: its uncovered sectors and its owners. */
++struct rmw_audit_ext {
++ u64 bytenr;
++ u64 gen;
++ int sectors;
++ int reloc_refs;
++ int other_refs; /* includes shared refs: owner unknown, so foreign */
++ u64 other_root;
++};
++
++static void rmw_audit_ext_ref(struct rmw_audit_ext *e, u64 root)
++{
++ if (root == BTRFS_DATA_RELOC_TREE_OBJECTID) {
++ e->reloc_refs++;
++ } else {
++ e->other_refs++;
++ if (!e->other_root)
++ e->other_root = root;
++ }
++}
++
++static void rmw_audit_ext_done(struct rmw_audit *a, struct rmw_audit_ext *e)
++{
++ if (!e->sectors)
++ goto out;
++ /* No ref seen at all: be conservative and call it foreign. */
++ if (e->other_refs || !e->reloc_refs) {
++ if (!a->foreign) {
++ a->first = e->bytenr;
++ a->first_root = e->other_root;
++ }
++ a->foreign += e->sectors;
++ a->min_gen = min(a->min_gen, e->gen);
++ a->max_gen = max(a->max_gen, e->gen);
++ } else {
++ a->reloc += e->sectors;
++ }
++out:
++ memset(e, 0, sizeof(*e));
++}
++
++/*
++ * Classify the data sectors of this rbio's stripe that the write does NOT
++ * cover by the COMMITTED extent under them and that extent's owners. Those
++ * are the sectors a torn RMW can destroy after a crash. An extent owned only
++ * by the data reloc tree is relocation's own orphaned copy, discarded by
++ * orphan cleanup if a crash comes before its pointers move; any other owner
++ * is a real write hole. Commit root, no locking, as in
++ * rmw_block_referenced(). Returns -1 when the lookup cannot answer.
++ *
++ * The commit root is switched shortly before the super lands, so an extent
++ * of the transaction committing right now can count early: this errs towards
++ * reporting a hole, never towards hiding one.
++ */
++static int rmw_committed_uncovered(struct btrfs_raid_bio *rbio,
++ struct rmw_audit *a)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ const u64 stripe_start = rbio->bioc->full_stripe_logical;
++ const u64 stripe_end = stripe_start +
++ (u64)rbio->nr_data * rbio->bioc->stripe_len;
++ const u32 bits = fs_info->sectorsize_bits;
++ struct btrfs_root *extent_root = btrfs_extent_root(fs_info, stripe_start);
++ struct rmw_audit_ext e = { 0 };
++ struct btrfs_path *path;
++ struct btrfs_key key;
++ int ret;
++
++ memset(a, 0, sizeof(*a));
++ a->min_gen = U64_MAX;
++ /*
++ * The caller holds the full stripe lock, so nothing here may wait for
++ * something that can wait for this stripe: a tree block read that
++ * needs a raid56 rebuild of it (mixed block groups keep tree blocks in
++ * it, see fill_data_csums(), so they are not audited), or
++ * commit_root_sem, whose holder may be reading such a block. Read
++ * cached blocks only, and take the semaphore only if it is free. Each
++ * miss counts as an audit error.
++ */
++ if (rbio->bioc->map_type & BTRFS_BLOCK_GROUP_METADATA)
++ return -1;
++ path = btrfs_alloc_path();
++ if (!path)
++ return -1;
++ path->search_commit_root = 1;
++ path->skip_locking = 1;
++ path->nowait = 1;
++
++ if (!down_read_trylock(&fs_info->commit_root_sem)) {
++ btrfs_free_path(path);
++ return -1;
++ }
++ key.objectid = stripe_start;
++ key.type = BTRFS_EXTENT_ITEM_KEY;
++ key.offset = 0;
++ ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
++ if (ret < 0)
++ goto fail;
++ /* An extent starting below the stripe may reach into it. */
++ ret = btrfs_previous_extent_item(extent_root, path,
++ stripe_start > SZ_1G ? stripe_start - SZ_1G : 0);
++ if (ret < 0)
++ goto fail;
++ if (ret > 0) {
++ btrfs_release_path(path);
++ ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
++ if (ret < 0)
++ goto fail;
++ }
++ while (1) {
++ struct extent_buffer *leaf = path->nodes[0];
++ const int slot = path->slots[0];
++ struct btrfs_extent_item *ei;
++ unsigned long ptr, end;
++ u64 lo, hi;
++
++ if (slot >= btrfs_header_nritems(leaf)) {
++ ret = btrfs_next_leaf(extent_root, path);
++ if (ret < 0)
++ goto fail;
++ if (ret > 0)
++ break;
++ continue;
++ }
++ btrfs_item_key_to_cpu(leaf, &key, slot);
++
++ /* Keyed backrefs of the extent being classified. */
++ if (e.sectors && key.objectid == e.bytenr) {
++ if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
++ struct btrfs_extent_data_ref *dref;
++
++ dref = btrfs_item_ptr(leaf, slot,
++ struct btrfs_extent_data_ref);
++ rmw_audit_ext_ref(&e, btrfs_extent_data_ref_root(leaf, dref));
++ } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
++ e.other_refs++;
++ }
++ path->slots[0]++;
++ continue;
++ }
++ if (key.type != BTRFS_EXTENT_ITEM_KEY) {
++ if (key.objectid >= stripe_end)
++ break;
++ path->slots[0]++;
++ continue;
++ }
++ rmw_audit_ext_done(a, &e);
++ if (key.objectid >= stripe_end)
++ break;
++ if (key.objectid + key.offset <= stripe_start) {
++ path->slots[0]++;
++ continue;
++ }
++ ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
++ lo = max(key.objectid, stripe_start);
++ hi = min(key.objectid + key.offset, stripe_end);
++ for (u64 b = lo; b < hi; b += fs_info->sectorsize)
++ if (rbio->bio_paddrs[((b - stripe_start) >> bits) * rbio->sector_nsteps] == INVALID_PADDR)
++ e.sectors++;
++ if (!e.sectors) {
++ path->slots[0]++;
++ continue;
++ }
++ e.bytenr = key.objectid;
++ e.gen = btrfs_extent_generation(leaf, ei);
++ /* Inline backrefs: data extents carry no tree_block_info. */
++ ptr = (unsigned long)(ei + 1);
++ end = (unsigned long)ei + btrfs_item_size(leaf, slot);
++ while (ptr < end) {
++ struct btrfs_extent_inline_ref *iref = (void *)ptr;
++ const int type = btrfs_extent_inline_ref_type(leaf, iref);
++ const u32 size = btrfs_extent_inline_ref_size(type);
++
++ if (type == BTRFS_EXTENT_DATA_REF_KEY) {
++ struct btrfs_extent_data_ref *dref =
++ (void *)&iref->offset;
++
++ rmw_audit_ext_ref(&e, btrfs_extent_data_ref_root(leaf, dref));
++ } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
++ e.other_refs++;
++ } else if (type != BTRFS_EXTENT_OWNER_REF_KEY) {
++ /* Not a data ref we understand: foreign. */
++ e.other_refs++;
++ break;
++ }
++ if (!size)
++ break;
++ ptr += size;
++ }
++ path->slots[0]++;
++ }
++ rmw_audit_ext_done(a, &e);
++ up_read(&fs_info->commit_root_sem);
++ btrfs_free_path(path);
++ return a->foreign + a->reloc;
++fail:
++ up_read(&fs_info->commit_root_sem);
++ btrfs_free_path(path);
++ return -1;
++}
++
++/*
++ * With /sys/fs/btrfs/<uuid>/debug/stripe_rmw_audit set: prove from the
++ * committed extent tree, not from the allocator's design, that a data RMW put
++ * no other owner's committed data at risk, and log the writer of any that
++ * did (and of every NO_RUN RMW, the class the allocator cannot explain by
++ * construction). @idx is the RMW's data_rmw_by index.
++ */
++static void rbio_audit_rmw(struct btrfs_raid_bio *rbio, u8 idx)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ const u64 stripe_start = rbio->bioc->full_stripe_logical;
++ struct btrfs_block_group *bg;
++ struct rmw_audit a;
++ u64 root_id = 0, ino = 0, foff = 0, oflags = 0, oseq = 0, odisk = 0;
++ u64 bg_flags = 0;
++ bool orun = false;
++ int nbios = 0;
++ int ro = -1;
++ int ret;
++ struct bio *bio;
++
++ if (!READ_ONCE(fs_info->stripe_rmw_audit))
++ return;
++ atomic64_inc(&fs_info->stripe_rmw_audit_stats.audited);
++
++ spin_lock(&rbio->bio_list_lock);
++ bio_list_for_each(bio, &rbio->bio_list) {
++ struct btrfs_bio *bbio = btrfs_bio(bio);
++
++ if (nbios++)
++ continue;
++ if (!bbio->inode ||
++ btrfs_ino(bbio->inode) == BTRFS_BTREE_INODE_OBJECTID)
++ continue;
++ root_id = btrfs_root_id(bbio->inode->root);
++ ino = btrfs_ino(bbio->inode);
++ foff = bbio->file_offset;
++ if (bbio->ordered) {
++ oflags = bbio->ordered->flags;
++ oseq = bbio->ordered->stripe_seq;
++ odisk = bbio->ordered->disk_bytenr;
++ orun = bbio->ordered->stripe_run != NULL;
++ }
++ }
++ spin_unlock(&rbio->bio_list_lock);
++
++ /* The audit needs bio sectors mapped; idempotent. */
++ index_rbio_pages(rbio);
++ ret = rmw_committed_uncovered(rbio, &a);
++ if (ret < 0) {
++ atomic64_inc(&fs_info->stripe_rmw_audit_stats.audit_err);
++ } else if (a.foreign) {
++ atomic64_inc(&fs_info->stripe_rmw_audit_stats.hole_by[idx]);
++ atomic64_add(a.foreign, &fs_info->stripe_rmw_audit_stats.hole_sectors);
++ if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
++ atomic64_inc(&fs_info->stripe_rmw_audit_stats.reloc_writer_foreign);
++ } else if (a.reloc) {
++ atomic64_inc(&fs_info->stripe_rmw_audit_stats.hole_reloc_only);
++ }
++ if (ret > 0)
++ atomic64_add(a.reloc, &fs_info->stripe_rmw_audit_stats.hole_reloc_sectors);
++
++ if (idx == BTRFS_STRIPE_PAD_NO_RUN) {
++ bg = btrfs_lookup_block_group(fs_info, stripe_start);
++ if (bg) {
++ ro = data_race(bg->ro);
++ bg_flags = bg->flags;
++ btrfs_put_block_group(bg);
++ }
++ }
++
++ /*
++ * Separate call sites, so separate rate limits: a flood of NO_RUN
++ * lines cannot starve the hole lines.
++ */
++ if (ret > 0 && a.foreign)
++ btrfs_warn_rl(fs_info,
++"rmw audit: write hole: stripe %llu reason %u norun %u foreign %d reloc %d gen %llu..%llu first %llu first_root %lld fsgen %llu committed %llu writer root %lld ino %llu foff %llu oe_flags 0x%llx oe_disk %llu oe_seq %llu oe_run %d nbios %d",
++ stripe_start, idx, rbio->pad_norun, a.foreign,
++ a.reloc, a.min_gen, a.max_gen, a.first,
++ (s64)a.first_root, btrfs_get_fs_generation(fs_info),
++ btrfs_get_last_trans_committed(fs_info),
++ (s64)root_id, ino, foff, oflags, odisk, oseq, orun,
++ nbios);
++ else if (idx == BTRFS_STRIPE_PAD_NO_RUN)
++ btrfs_info_rl(fs_info,
++"rmw audit: no_run RMW stripe %llu norun %u bg_ro %d bg_flags 0x%llx run %llu..%llu off %llu open %u class %u reloc_sectors %d fsgen %llu committed %llu writer root %lld ino %llu foff %llu oe_flags 0x%llx oe_seq %llu oe_run %d nbios %d",
++ stripe_start, rbio->pad_norun, ro, bg_flags,
++ rbio->pad_run_start, rbio->pad_run_end,
++ rbio->pad_run_offset, rbio->pad_run_open,
++ rbio->pad_run_class, ret > 0 ? a.reloc : 0,
++ btrfs_get_fs_generation(fs_info),
++ btrfs_get_last_trans_committed(fs_info),
++ (s64)root_id, ino, foff, oflags, oseq, orun, nbios);
++}
++#else
++static void rbio_audit_rmw(struct btrfs_raid_bio *rbio, u8 idx) { }
++#endif
++
+ /*
+ * Attribute a read-modify-write to why padding declined for this rbio. With
+ * allow_rmw empty, a data RMW in a stripe_alloc group is expected in two
+@@ -3088,6 +3410,8 @@ static void rbio_count_rmw_reason(struct btrfs_raid_bio *rbio)
+ /* Disjoint from the frontier count, so the two can be summed. */
+ if (reloc_writer && idx != BTRFS_STRIPE_PAD_UNCOVERED)
+ atomic64_inc(&fs_info->stripe_park_stats.data_rmw_reloc_writer);
++
++ rbio_audit_rmw(rbio, idx);
+ }
+
+ /*
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index d33baefc34b13..60e058c6fffc1 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -152,6 +152,14 @@ struct btrfs_raid_bio {
+ */
+ u8 pad_reason;
+ u8 pad_norun;
++#ifdef CONFIG_BTRFS_DEBUG
++ /* The covering run as the pad oracle saw it, for the RMW audit's log. */
++ u8 pad_run_open;
++ u8 pad_run_class;
++ u64 pad_run_start;
++ u64 pad_run_end;
++ u64 pad_run_offset;
++#endif
+
+ /*
+ * Set if we're doing a parity rebuild for a read from higher up, which
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index d2889c9c89379..f6e83d2789c2f 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -521,12 +521,73 @@ static const struct attribute *discard_attrs[] = {
+
+ #ifdef CONFIG_BTRFS_DEBUG
+
++/*
++ * Audit every data read-modify-write against the committed extent tree
++ * (raid56.c): a tree search per RMW, so off by default.
++ */
++static ssize_t btrfs_stripe_rmw_audit_show(struct kobject *kobj,
++ struct kobj_attribute *a, char *buf)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
++
++ return sysfs_emit(buf, "%d\n", READ_ONCE(fs_info->stripe_rmw_audit));
++}
++
++static ssize_t btrfs_stripe_rmw_audit_store(struct kobject *kobj,
++ struct kobj_attribute *a,
++ const char *buf, size_t len)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
++ bool val;
++ int ret;
++
++ ret = kstrtobool(buf, &val);
++ if (ret)
++ return ret;
++ WRITE_ONCE(fs_info->stripe_rmw_audit, val);
++ return len;
++}
++BTRFS_ATTR_RW(debug_mount, stripe_rmw_audit, btrfs_stripe_rmw_audit_show,
++ btrfs_stripe_rmw_audit_store);
++
++static ssize_t btrfs_stripe_rmw_audit_stats_show(struct kobject *kobj,
++ struct kobj_attribute *a,
++ char *buf)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
++
++ return sysfs_emit(buf,
++ "data_rmw_audited %lld\n"
++ "data_rmw_hole_no_run %lld\n"
++ "data_rmw_hole_uncovered %lld\n"
++ "data_rmw_hole_other %lld\n"
++ "data_rmw_hole_sectors %lld\n"
++ "data_rmw_hole_reloc_only %lld\n"
++ "data_rmw_hole_reloc_sectors %lld\n"
++ "data_rmw_reloc_writer_foreign %lld\n"
++ "data_rmw_audit_err %lld\n",
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.audited),
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[BTRFS_STRIPE_PAD_NO_RUN]),
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[BTRFS_STRIPE_PAD_UNCOVERED]),
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[BTRFS_STRIPE_PAD_OK]) +
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[BTRFS_STRIPE_PAD_NR_REASONS]),
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_sectors),
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_reloc_only),
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_reloc_sectors),
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.reloc_writer_foreign),
++ atomic64_read(&fs_info->stripe_rmw_audit_stats.audit_err));
++}
++BTRFS_ATTR(debug_mount, stripe_rmw_audit_stats,
++ btrfs_stripe_rmw_audit_stats_show);
++
+ /*
+ * Per-filesystem runtime debugging exported via sysfs.
+ *
+ * Path: /sys/fs/btrfs/UUID/debug/
+ */
+ static const struct attribute *btrfs_debug_mount_attrs[] = {
++ BTRFS_ATTR_PTR(debug_mount, stripe_rmw_audit),
++ BTRFS_ATTR_PTR(debug_mount, stripe_rmw_audit_stats),
+ NULL,
+ };
+
+--
+2.47.3
+
+++ /dev/null
-From 3fe10c2fdcd6ba4afb17117499cf4403d11d132f Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:24 -0400
-Subject: [RFC PATCH 063/116] btrfs: stripe_alloc: release open stripe runs
- when a mount fails or an aborted filesystem unmounts
-To: linux-btrfs@vger.kernel.org
-
-A block group with open stripe runs holds a reference for as long as it
-is on fs_info->open_stripe_bgs, and only the commit-time retirement,
-having released the group's last run, drops it. Two paths never commit
-again: a mount whose log replay fails after it has already allocated
-tree blocks (each allocation opened a metadata run), and the unmount of
-a filesystem whose transaction aborted. btrfs_free_block_groups() then
-finds the leftover references and asserts:
-
- BTRFS: error (device loop0 state EAO) in btrfs_replay_log:2072:
- errno=-5 IO failure (Failed to recover log tree)
- assertion failed: refcount_read(&block_group->refs) == 1 :: 0, in
- fs/btrfs/block-group.c:7479
- kernel BUG at fs/btrfs/block-group.c:7479!
- RIP: btrfs_free_block_groups.cold
- open_ctree
- btrfs_get_tree.cold
-
-Hit by the raid56-metadata fsync-window characterization: a degraded
-mount whose log replay got as far as allocating before it met the torn
-log block, where an earlier run of the same case had failed while
-walking the log and never allocated. The mount task died holding the
-superblock lock and the next mount of the same devices hung on it.
-
-Release every open run and the references before the block groups are
-freed, on both paths. Nothing is in flight there: workers are stopped
-and the roots dropped; a run that still counts bytes in flight is
-reported and released anyway.
-
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/block-group.c | 44 ++++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/block-group.h | 1 +
- fs/btrfs/disk-io.c | 2 ++
- 3 files changed, 47 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index aa1eee2a61ca5..98f78ca7897fc 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2551,6 +2551,50 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
- * Calls are serialized by the transaction commit; @trans may be NULL for
- * the final cleanup call.
- */
-+/*
-+ * Teardown: release every open stripe run and the block group reference
-+ * each group with runs holds. The commit normally retires runs, and the
-+ * release of a group's last run drops its membership here; a mount that
-+ * fails after log replay has already allocated tree blocks, and an unmount
-+ * after a transaction abort, never commit again, and
-+ * btrfs_free_block_groups() then asserts on the leftover references. By
-+ * the time this runs the workers are stopped and the roots dropped, so no
-+ * IO is left to report; a run still counting bytes in flight is noted and
-+ * released all the same.
-+ */
-+void btrfs_free_open_stripe_runs(struct btrfs_fs_info *fs_info)
-+{
-+ LIST_HEAD(bgs);
-+ struct btrfs_block_group *bg, *tmp_bg;
-+ unsigned long flags;
-+
-+ spin_lock(&fs_info->open_stripe_lock);
-+ list_splice_init(&fs_info->open_stripe_bgs, &bgs);
-+ spin_unlock(&fs_info->open_stripe_lock);
-+
-+ list_for_each_entry_safe(bg, tmp_bg, &bgs, open_stripe_bg_list) {
-+ struct btrfs_open_stripe_run *run, *tmp;
-+
-+ list_del_init(&bg->open_stripe_bg_list);
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry_safe(run, tmp, &bg->open_stripe_runs, list) {
-+ if (run->inflight_bytes)
-+ btrfs_warn(fs_info,
-+"stripe run %llu-%llu in block group %llu released at teardown with %llu bytes still in flight",
-+ run->start, run->end, bg->start,
-+ run->inflight_bytes);
-+ list_del(&run->list);
-+ bitmap_free(run->live);
-+ kfree(run);
-+ }
-+ memset(bg->open_stripe, 0, sizeof(bg->open_stripe));
-+ bg->stripe_open_remainder = 0;
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ stripe_open_remainder_sync(bg);
-+ btrfs_put_block_group(bg);
-+ }
-+}
-+
- /*
- * Close and drain the metadata stripe runs, once every tree block this
- * transaction allocated has reached the disk.
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 8e9e3b31f26e6..6a09ecc13f0c8 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -483,6 +483,7 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
- u64 *open_seq);
- void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
- void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid);
-+void btrfs_free_open_stripe_runs(struct btrfs_fs_info *fs_info);
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
- bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index 8986bab67590e..8c5070a598750 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -3856,6 +3856,7 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
-
- fail_sb_buffer:
- btrfs_stop_all_workers(fs_info);
-+ btrfs_free_open_stripe_runs(fs_info);
- btrfs_free_block_groups(fs_info);
- fail_alloc:
- btrfs_mapping_tree_free(fs_info);
-@@ -4627,6 +4628,7 @@ void __cold close_ctree(struct btrfs_fs_info *fs_info)
- * accounting appear to be wrong because there's pending reserved bytes,
- * so make sure we do the block group cleanup afterwards.
- */
-+ btrfs_free_open_stripe_runs(fs_info);
- btrfs_free_block_groups(fs_info);
-
- iput(fs_info->btree_inode);
---
-2.47.3
-
--- /dev/null
+From 33f8c600f9ebddf923072c8eeb67f27a471ecfca Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sun, 4 Oct 2026 17:46:19 -0400
+Subject: [RFC PATCH 64/85] btrfs: stripe_alloc: break rbio pins and open
+ stripe runs down by run class
+To: linux-btrfs@vger.kernel.org
+
+Under fsync load the rbio cache holds up to ~190 pins its runs still need,
+against 35-55 with the same load on raid1 metadata, so most of them look
+like metadata stripes: tree-log blocks share the transaction's META run
+with the tree blocks COWed in it, a log commit writes its part of a stripe
+and the rest waits for the transaction commit. Data runs are private per
+fsyncing inode and closed at every log commit, so they should be many and
+short. Say which, instead of inferring it.
+
+stripe_park_stats gains rbio_pinned_live_<class> (live pins by the class of
+the run that still needs the stripe) and open_runs_<class> (open runs by
+class), for class cow, reloc, log, nocow and meta.
+btrfs_stripe_run_incomplete() becomes a wrapper around
+btrfs_stripe_run_incomplete_class(), which also says which run's class.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 70 ++++++++++++++++++++++++++++++++++--------
+ fs/btrfs/block-group.h | 3 ++
+ fs/btrfs/raid56.c | 20 +++++++++---
+ fs/btrfs/raid56.h | 2 +-
+ fs/btrfs/sysfs.c | 24 ++++++++++++---
+ 5 files changed, 98 insertions(+), 21 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 4072a83823f56..e59e3826d9bb8 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -2467,28 +2467,29 @@ static bool run_unwritten_in(struct btrfs_open_stripe_run *run, u64 start,
+ return false;
+ }
+
+-bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
+- u64 stripe_start, u64 stripe_len)
++/*
++ * As btrfs_stripe_run_incomplete(), returning the class of the run that
++ * leaves the stripe incomplete, or -1 if none does.
++ */
++int btrfs_stripe_run_incomplete_class(struct btrfs_fs_info *fs_info,
++ u64 stripe_start, u64 stripe_len)
+ {
+ struct btrfs_block_group *bg;
+ struct btrfs_open_stripe_run *run;
+ unsigned long flags;
+- bool ret = false;
++ int ret = -1;
+
+ if (list_empty_careful(&fs_info->open_stripe_bgs))
+- return false;
++ return -1;
+ bg = btrfs_lookup_block_group(fs_info, stripe_start);
+ if (!bg)
+- return false;
++ return -1;
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+- if (run->open && run->offset > stripe_start &&
+- run->offset < stripe_start + stripe_len) {
+- ret = true;
+- break;
+- }
+- if (run_unwritten_in(run, stripe_start, stripe_len)) {
+- ret = true;
++ if ((run->open && run->offset > stripe_start &&
++ run->offset < stripe_start + stripe_len) ||
++ run_unwritten_in(run, stripe_start, stripe_len)) {
++ ret = run->class;
+ break;
+ }
+ }
+@@ -2497,6 +2498,51 @@ bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
+ return ret;
+ }
+
++/*
++ * Is [stripe_start, stripe_start + stripe_len) still waiting for writes from
++ * a stripe run? Two ways:
++ *
++ * - an open run's allocation frontier lies strictly inside it: the run will
++ * allocate and write the rest of the stripe later, although every sector
++ * allocated so far may already be written;
++ * - a run covering it has sectors allocated (live) but not yet written: the
++ * frontier has moved past, and the writes are still in flight (writeback
++ * allocates a whole range before any of its bios complete).
++ *
++ * Either way the stripe has been written in part, and the rest will arrive
++ * as a sub-stripe write that needs the part already written.
++ */
++bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
++ u64 stripe_start, u64 stripe_len)
++{
++ return btrfs_stripe_run_incomplete_class(fs_info, stripe_start,
++ stripe_len) >= 0;
++}
++
++/* Open stripe runs by class, for sysfs: @counts has NR_CLASSES entries. */
++void btrfs_count_open_stripe_runs(struct btrfs_fs_info *fs_info, int *counts)
++{
++ struct btrfs_block_group *bg;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++
++ memset(counts, 0, sizeof(*counts) * BTRFS_STRIPE_RUN_NR_CLASSES);
++ spin_lock(&fs_info->open_stripe_lock);
++ list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list) {
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list)
++ if (run->open && run->class < BTRFS_STRIPE_RUN_NR_CLASSES)
++ counts[run->class]++;
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ }
++ spin_unlock(&fs_info->open_stripe_lock);
++}
++
++/*
++ * Like btrfs_stripe_in_open_run(), also reporting the covering run's
++ * class: the raid56 parking gate treats NOCOW-class runs specially
++ * (sync writes into them never park; see rbio_try_park()).
++ */
+ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
+ enum btrfs_stripe_run_class *class)
+ {
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index c6dc7c1cdf1a5..75775cb52ae8a 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -515,6 +515,9 @@ void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
+ u64 len);
+ bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
+ u64 stripe_start, u64 stripe_len);
++int btrfs_stripe_run_incomplete_class(struct btrfs_fs_info *fs_info,
++ u64 stripe_start, u64 stripe_len);
++void btrfs_count_open_stripe_runs(struct btrfs_fs_info *fs_info, int *counts);
+ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
+ enum btrfs_stripe_run_class *class);
+ u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index b892e085ac07a..e1fee64396457 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -796,22 +796,34 @@ void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info)
+ * eviction or a re-cache finds it.
+ */
+ void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
+- int *pinned, int *live)
++ int *pinned, int *live, int *live_by_class)
+ {
+ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
+ struct btrfs_raid_bio *rbio;
++ int class;
+
+ *cached = 0;
+ *pinned = 0;
+ *live = 0;
++ memset(live_by_class, 0, sizeof(*live_by_class) * BTRFS_STRIPE_RUN_NR_CLASSES);
+ if (!table)
+ return;
+ spin_lock(&table->cache_lock);
+ *cached = table->cache_size;
+ *pinned = table->nr_pinned;
+- list_for_each_entry(rbio, &table->stripe_cache, stripe_cache)
+- if (rbio_pin_live(rbio))
+- *live += 1;
++ list_for_each_entry(rbio, &table->stripe_cache, stripe_cache) {
++ if (!test_bit(RBIO_PINNED_BIT, &rbio->flags) ||
++ !btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ continue;
++ class = btrfs_stripe_run_incomplete_class(fs_info,
++ rbio->bioc->full_stripe_logical,
++ (u64)rbio->nr_data * rbio->bioc->stripe_len);
++ if (class < 0)
++ continue;
++ *live += 1;
++ if (class < BTRFS_STRIPE_RUN_NR_CLASSES)
++ live_by_class[class] += 1;
++ }
+ spin_unlock(&table->cache_lock);
+ }
+
+diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
+index 60e058c6fffc1..22687b6194f93 100644
+--- a/fs/btrfs/raid56.h
++++ b/fs/btrfs/raid56.h
+@@ -314,7 +314,7 @@ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
+ u64 num_bytes, bool force);
+ void btrfs_stop_parked_rbios(struct btrfs_fs_info *fs_info);
+ void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
+- int *pinned, int *live);
++ int *pinned, int *live, int *live_by_class);
+ void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info);
+
+ #endif
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index f6e83d2789c2f..609e3e4462a1c 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1186,10 +1186,19 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ struct kobj_attribute *a, char *buf)
+ {
+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
+- int cached, pinned, live;
+-
+- btrfs_rbio_cache_usage(fs_info, &cached, &pinned, &live);
+- return sysfs_emit(buf,
++ /* Indexed by enum btrfs_stripe_run_class. */
++ static const char * const class_names[] = {
++ "cow", "reloc", "log", "nocow",
++ };
++ int live_by_class[BTRFS_STRIPE_RUN_NR_CLASSES];
++ int open_runs[BTRFS_STRIPE_RUN_NR_CLASSES];
++ int cached, pinned, live, class;
++ ssize_t len;
++
++ BUILD_BUG_ON(ARRAY_SIZE(class_names) != BTRFS_STRIPE_RUN_NR_CLASSES);
++ btrfs_rbio_cache_usage(fs_info, &cached, &pinned, &live, live_by_class);
++ btrfs_count_open_stripe_runs(fs_info, open_runs);
++ len = sysfs_emit(buf,
+ "parked %lld\n"
+ "merged_bytes %lld\n"
+ "filled %lld\n"
+@@ -1230,6 +1239,13 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_swept),
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_commit_requests),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_reads));
++ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
++ len += sysfs_emit_at(buf, len, "rbio_pinned_live_%s %d\n",
++ class_names[class], live_by_class[class]);
++ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
++ len += sysfs_emit_at(buf, len, "open_runs_%s %d\n",
++ class_names[class], open_runs[class]);
++ return len;
+ }
+ BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
+
+--
+2.47.3
+
+++ /dev/null
-From 4b5986416d18781e2714aa6fda831007af8f2d95 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 19 Sep 2026 13:18:25 -0400
-Subject: [RFC PATCH 064/116] btrfs: stripe_alloc: say at mount whether the
- policy is on
-To: linux-btrfs@vger.kernel.org
-
-Nothing announced that stripe-exclusive allocation was on. The
-btrfs.stripe_alloc property applies when btrfs_fill_super() reads the
-root directory's inode and its properties, and btrfs_enable_stripe_alloc()
-prints its line only for a set on a live filesystem, so mounting a
-filesystem whose property was already set said nothing.
-
-An absent line therefore meant "off" and "on" equally well, and the only
-way to answer the question was to look at a live filesystem -- no use
-when the filesystem is someone else's, or when all that is left is a log
-from before a crash. Analysing a lockup from a filesystem whose
-btrfs.stripe_alloc property was set, I read that silence as the policy
-being off and said so, which was wrong.
-
-State it once in btrfs_fill_super(), after the root inode has been read
-so the property has had its say. The property path keeps its own line
-for a set on a live filesystem, where there is no mount to report; at
-mount it now stays quiet so the line is not printed twice.
-
-Nothing is printed when the policy is off, which keeps the common mount
-quiet and makes the absence of the line mean exactly one thing.
-
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/block-group.c | 12 +++++++++---
- fs/btrfs/super.c | 19 +++++++++++++++++++
- 2 files changed, 28 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 98f78ca7897fc..9e4369b8b99f7 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2221,10 +2221,16 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
- * when their caching thread finishes, now that the policy is on.
- */
- stripe_alloc_sweep_groups(fs_info, true);
-- btrfs_info(fs_info,
-- "using stripe-exclusive allocation for raid56 data");
-- if (live)
-+ /*
-+ * At mount btrfs_fill_super() states the outcome once, for the option
-+ * and the property alike, so repeating it here would only double the
-+ * line. A property set on a live filesystem has no such reporter.
-+ */
-+ if (live) {
-+ btrfs_info(fs_info,
-+ "using stripe-exclusive allocation for raid56 data (filesystem property)");
- queue_work(system_unbound_wq, &fs_info->stripe_alloc_enable_work);
-+ }
- return 0;
- }
-
-diff --git a/fs/btrfs/super.c b/fs/btrfs/super.c
-index a64d9cd48d12e..903bce51fb1fd 100644
---- a/fs/btrfs/super.c
-+++ b/fs/btrfs/super.c
-@@ -943,6 +943,23 @@ static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objec
- return 0;
- }
-
-+/*
-+ * State whether stripe-exclusive allocation is on.
-+ *
-+ * Nothing said so before. The btrfs.stripe_alloc property applies while the
-+ * root directory's inode is read, and no line went to the log, so silence
-+ * meant "off" and "on" equally well and the only way to answer the question
-+ * was to look at a live filesystem -- no use at all when reading a log after a
-+ * crash. Say it once at mount.
-+ */
-+static void btrfs_emit_stripe_alloc_state(struct btrfs_fs_info *info)
-+{
-+ if (!btrfs_test_opt(info, STRIPE_ALLOC))
-+ return;
-+ btrfs_info(info,
-+ "using stripe-exclusive allocation for raid56 data (filesystem property)");
-+}
-+
- static int btrfs_fill_super(struct super_block *sb,
- struct btrfs_fs_devices *fs_devices)
- {
-@@ -983,6 +1000,8 @@ static int btrfs_fill_super(struct super_block *sb,
- goto fail_close;
- }
-
-+ btrfs_emit_stripe_alloc_state(fs_info);
-+
- sb->s_root = d_make_root(&inode->vfs_inode);
- if (!sb->s_root) {
- ret = -ENOMEM;
---
-2.47.3
-
--- /dev/null
+From a57dba490e9d9cc8b4703be67e5e9ed983beb924 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Fri, 9 Oct 2026 19:13:11 -0400
+Subject: [RFC PATCH 65/85] btrfs: stripe_alloc: count and log ordered extents
+ that end with sectors unwritten
+To: linux-btrfs@vger.kernel.org
+
+When an ordered extent reports to its stripe run, sectors it allocated
+that no write reached are marked written so nothing waits for them (a
+failed write, truncated folios, a short direct write, error teardown).
+Whether any of these paths can still leave a waiter stuck in practice is
+not known: the log settle that motivated the marking seals and frees a
+shared LOG run before it would wait.
+
+Count such extents and their unwritten bytes in stripe_run_stats
+(unwritten_on_end, unwritten_on_end_bytes) and log each one, rate
+limited, with the extent's identity, truncated length and flags, to see
+which paths produce them.
+
+One class is harmless and is counted but not logged: an extent marked
+TRUNCATED, with no IOERR and not compressed (disk_num_bytes == num_bytes),
+whose unwritten sectors are exactly the part truncation cut off,
+[disk_bytenr + ALIGN(truncated_len, sectorsize), disk_bytenr +
+disk_num_bytes). It comes from a truncate or O_TRUNC racing writeback and
+from a direct write whose bounce-buffer copy faults before copying
+anything, and it would bury the lines the message is there to find.
+btrfs_open_stripe_write_done_run() returns the lowest unwritten sector so
+that the tail can be told from merely as many sectors. Those extents go to
+unwritten_on_end_truncated and unwritten_on_end_truncated_bytes;
+unwritten_on_end and unwritten_on_end_bytes count only the logged ones, so
+any increase there is worth a look.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 27 ++++++++++++++---
+ fs/btrfs/block-group.h | 5 ++--
+ fs/btrfs/fs.h | 9 ++++++
+ fs/btrfs/ordered-data.c | 66 +++++++++++++++++++++++++++++++++++++++--
+ 4 files changed, 99 insertions(+), 8 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index e59e3826d9bb8..27b7fb36361fa 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -2692,26 +2692,45 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
+ * write, error teardown) will not be written now. Marking it keeps a log
+ * settle from waiting for it forever, and a written sector is never padded,
+ * so a later partial write to the stripe reads it instead of zeroing it.
++ *
++ * Returns the number of allocated sectors that had not been written, and
++ * in @first_unwritten the logical address of the lowest of them (U64_MAX if
++ * there are none).
+ */
+-void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+- u64 start, u64 num_bytes)
++u32 btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
++ u64 start, u64 num_bytes,
++ u64 *first_unwritten)
+ {
+ struct btrfs_block_group *bg = run->bg;
+ const u32 bits = bg->fs_info->sectorsize_bits;
+ unsigned long flags;
+ u64 s = start;
+ u64 l = num_bytes;
++ u32 unwritten = 0;
+
++ *first_unwritten = U64_MAX;
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ ASSERT(run->inflight_bytes >= num_bytes);
+ run->inflight_bytes -= num_bytes;
+- if (run_written_range(run, &s, &l))
+- bitmap_set(run->written, (s - run->start) >> bits, l >> bits);
++ if (run_written_range(run, &s, &l)) {
++ const u32 first = (s - run->start) >> bits;
++ const u32 last = first + (l >> bits);
++
++ for (u32 i = first; i < last; i++) {
++ if (!test_bit(i, run->live) || test_bit(i, run->written))
++ continue;
++ if (!unwritten)
++ *first_unwritten = run->start + ((u64)i << bits);
++ unwritten++;
++ }
++ bitmap_set(run->written, first, l >> bits);
++ }
+ /* Under the lock: the run and the group may be gone after it. */
+ wake_up_var(&bg->open_stripe_runs);
+ if (open_stripe_run_drained(run) && !run->retained)
+ free_open_stripe_run(bg, run);
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ return unwritten;
+ }
+
+ /*
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 75775cb52ae8a..211dd5feaa27e 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -500,8 +500,9 @@ 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,
+ u64 num_bytes);
+-void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+- u64 start, u64 num_bytes);
++u32 btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
++ u64 start, u64 num_bytes,
++ u64 *first_unwritten);
+ void btrfs_open_stripe_write_done_bytenr(struct btrfs_fs_info *fs_info,
+ u64 start, u64 num_bytes);
+ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 69d33accd21ee..7186c62e8120c 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -977,6 +977,15 @@ struct btrfs_fs_info {
+ /* shared runs: frontier stripes sealed at log commit, bytes skipped */
+ atomic64_t log_seals;
+ atomic64_t log_seal_bytes;
++ /*
++ * ordered extents that ended with allocated sectors unwritten,
++ * other than exactly their truncated tail (these are logged)
++ */
++ atomic64_t unwritten_on_end;
++ atomic64_t unwritten_on_end_bytes;
++ /* ... whose unwritten sectors were exactly their truncated tail */
++ atomic64_t unwritten_on_end_truncated;
++ atomic64_t unwritten_on_end_truncated_bytes;
+ } stripe_run_stats;
+ /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
+ u32 stripe_rmw_prop;
+diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
+index 5bd8ff43f9d52..4fb0fd17a1f9d 100644
+--- a/fs/btrfs/ordered-data.c
++++ b/fs/btrfs/ordered-data.c
+@@ -401,6 +401,34 @@ static void finish_ordered_fn(struct btrfs_work *work)
+ btrfs_finish_ordered_io(ordered_extent);
+ }
+
++/*
++ * Whether the @unwritten sectors from @first_unwritten up are exactly the
++ * tail that truncation cut off @ordered, [disk_bytenr + truncated_len,
++ * disk_bytenr + disk_num_bytes): truncated folios that were never submitted,
++ * or a direct write that ended short. Only for an extent without a write
++ * error whose disk extent maps its file range one to one (not compressed).
++ */
++static bool ordered_unwritten_is_truncated_tail(
++ const struct btrfs_ordered_extent *ordered,
++ u32 unwritten, u64 first_unwritten)
++{
++ const struct btrfs_fs_info *fs_info = ordered->inode->root->fs_info;
++ u64 tail;
++
++ if (!test_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags) ||
++ test_bit(BTRFS_ORDERED_IOERR, &ordered->flags) ||
++ test_bit(BTRFS_ORDERED_COMPRESSED, &ordered->flags))
++ return false;
++ if (ordered->disk_num_bytes != ordered->num_bytes ||
++ ordered->truncated_len > ordered->num_bytes)
++ return false;
++ /* The sector holding the last byte kept was written with it. */
++ tail = ALIGN(ordered->truncated_len, fs_info->sectorsize);
++ return first_unwritten == ordered->disk_bytenr + tail &&
++ unwritten == (ordered->disk_num_bytes - tail) >>
++ fs_info->sectorsize_bits;
++}
++
+ /*
+ * Report this ordered extent's data IO to its open stripe run, exactly
+ * once. Called at IO completion, and as a catch-all when an ordered
+@@ -410,12 +438,46 @@ static void finish_ordered_fn(struct btrfs_work *work)
+ static void btrfs_ordered_stripe_write_done(struct btrfs_ordered_extent *ordered)
+ {
+ struct btrfs_open_stripe_run *run = ordered->stripe_run;
++ struct btrfs_fs_info *fs_info = ordered->inode->root->fs_info;
++ u64 first_unwritten;
++ u32 unwritten;
+
+ if (!run)
+ return;
+ ordered->stripe_run = NULL;
+- btrfs_open_stripe_write_done_run(run, ordered->disk_bytenr,
+- ordered->disk_num_bytes);
++ unwritten = btrfs_open_stripe_write_done_run(run, ordered->disk_bytenr,
++ ordered->disk_num_bytes,
++ &first_unwritten);
++ if (likely(!unwritten))
++ return;
++ /*
++ * Sectors this extent allocated that no write reached: a failed write,
++ * truncated folios, a short direct write or error teardown. They are
++ * now marked written so nothing waits for them.
++ *
++ * When they are exactly the truncated tail (a truncate or O_TRUNC
++ * racing writeback, or a direct write that ended short), nothing went
++ * wrong: count them apart and do not log them. Every other case is
++ * counted in unwritten_on_end and logged, to find out which paths
++ * produce it in practice.
++ */
++ if (ordered_unwritten_is_truncated_tail(ordered, unwritten,
++ first_unwritten)) {
++ atomic64_inc(&fs_info->stripe_run_stats.unwritten_on_end_truncated);
++ atomic64_add((u64)unwritten << fs_info->sectorsize_bits,
++ &fs_info->stripe_run_stats.unwritten_on_end_truncated_bytes);
++ return;
++ }
++ atomic64_inc(&fs_info->stripe_run_stats.unwritten_on_end);
++ atomic64_add((u64)unwritten << fs_info->sectorsize_bits,
++ &fs_info->stripe_run_stats.unwritten_on_end_bytes);
++ btrfs_info_rl(fs_info,
++"stripe_alloc: ordered extent ended with %u unwritten sectors: root %llu ino %llu file_offset %llu len %llu disk_bytenr %llu disk_num_bytes %llu truncated_len %lld flags 0x%lx",
++ unwritten, btrfs_root_id(ordered->inode->root),
++ btrfs_ino(ordered->inode), ordered->file_offset,
++ ordered->num_bytes, ordered->disk_bytenr,
++ ordered->disk_num_bytes, (s64)ordered->truncated_len,
++ ordered->flags);
+ }
+
+ static bool can_finish_ordered_extent(struct btrfs_ordered_extent *ordered,
+--
+2.47.3
+
+++ /dev/null
-From cbab48fd82cc6f288ad264a5afcad068e2343b03 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 20 Sep 2026 01:33:09 -0400
-Subject: [RFC PATCH 065/116] btrfs: stripe_meta: cover raid56 system chunks
-To: linux-btrfs@vger.kernel.org
-
-The chunk tree lives in system chunks, which carry no METADATA bit, so the
-whole-stripe rule that stripe_meta applies to raid56 tree blocks never
-applied to it: chunk tree blocks were placed by the clustered allocator,
-sharing stripes with chunk tree blocks committed earlier, and every chunk
-tree COW was a read-modify-write of such a stripe. The RMW audit measured
-it (meta_rmw_old over system chunks during chunk churn), and the mount
-warned about it. A torn parity rewrite there is the worst write hole the
-filesystem can take: with a member then lost, the committed chunk tree
-block that shared the stripe reconstructs wrong, the checksum rejects it,
-and nothing maps -- the degraded mount fails, and there is no second copy.
-
-Include system block groups in btrfs_is_stripe_meta_bg(). Everything
-downstream already keys on that predicate: the whole-stripe allocation in
-do_allocation_stripe(), the trapped-space accounting, the covered/uncovered
-decision in the RMW report and the audit. The four walks that select
-groups by space_info flags (the enable-time sweep, the unusable-space scan,
-the reclaim tick, the commit-time metadata run retirement) gain SYSTEM
-alongside DATA and METADATA, so system groups are armed, scanned, reclaimed
-when trapped, and have their runs closed after the commit's tree writes
-like metadata groups.
-
-reserve_chunk_space() sizes its request in tree blocks, but a chunk tree
-COW that needs a fresh run takes a whole stripe for its first block; the
-trapped bytes and the open run's remainder are already counted as used, so
-what is left is whole free stripes, and the check now demands one stripe
-of headroom beyond the request -- deciding when to allocate the next
-system chunk, without reserving the headroom -- or the chunk item for that
-very allocation could find no stripe to land in.
-
-The "does not cover raid56 system chunks" warning has nothing left to
-warn about and goes.
-
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/block-group.c | 76 +++++++++++++++++++++++-------------------
- fs/btrfs/extent-tree.c | 9 ++++-
- fs/btrfs/raid56.c | 6 ++--
- 3 files changed, 52 insertions(+), 39 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 9e4369b8b99f7..60fcfde839ba1 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2092,7 +2092,8 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
- int raid;
-
- if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
-- BTRFS_BLOCK_GROUP_METADATA)))
-+ BTRFS_BLOCK_GROUP_METADATA |
-+ BTRFS_BLOCK_GROUP_SYSTEM)))
- continue;
- /*
- * Metadata: the scan that maintains the stripe_meta margin
-@@ -2130,33 +2131,6 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
- }
- }
-
--/*
-- * stripe_alloc covers raid56 *data* block groups only. A filesystem whose
-- * metadata is also raid56 keeps the write hole there. The data guarantee is
-- * easy to read as a filesystem-wide one, so say once, when the policy turns
-- * on, what is not covered. That is btrfs_enable_stripe_alloc(): at mount the
-- * property applies after the block groups are read, so a report from
-- * btrfs_read_block_groups() would find the flag still clear. (Mixed block
-- * groups cannot get here: the property refuses them.)
-- */
--static void warn_stripe_alloc_uncovered(struct btrfs_fs_info *info)
--{
-- if (!btrfs_test_opt(info, STRIPE_ALLOC))
-- return;
--
-- /*
-- * raid56 metadata is covered now that the policy follows the chunk
-- * profile. System chunks are not: btrfs_is_stripe_meta_bg() tests
-- * the METADATA flag, and a system chunk does not carry it, so a
-- * raid56 system chunk keeps the legacy read-modify-write and its
-- * write hole. They are small and rewritten rarely, but say so
-- * rather than let the earlier "covered" message imply otherwise.
-- */
-- if (info->avail_system_alloc_bits & BTRFS_BLOCK_GROUP_RAID56_MASK)
-- btrfs_warn(info,
--"stripe_alloc does not cover raid56 system chunks: the write hole remains for them, consider converting to raid1c3/raid1c4");
--}
--
- /*
- * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
- * property on the top-level subvolume's root directory. Runs during mount
-@@ -2212,7 +2186,6 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
- if (live)
- set_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags);
- btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
-- warn_stripe_alloc_uncovered(fs_info);
- /*
- * Arm stripe_unusable accounting for raid56 data groups whose caches
- * loaded before the policy was enabled: block groups are read before
-@@ -2642,7 +2615,8 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
- bg = list_first_entry(&retire_list, struct btrfs_block_group,
- open_stripe_retire_list);
- list_del_init(&bg->open_stripe_retire_list);
-- if (!(bg->flags & BTRFS_BLOCK_GROUP_METADATA))
-+ if (!(bg->flags & (BTRFS_BLOCK_GROUP_METADATA |
-+ BTRFS_BLOCK_GROUP_SYSTEM)))
- continue;
-
- while (again) {
-@@ -2853,7 +2827,8 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- * both carry trapped free space. Mixed groups are refused.
- */
- if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
-- BTRFS_BLOCK_GROUP_METADATA)))
-+ BTRFS_BLOCK_GROUP_METADATA |
-+ BTRFS_BLOCK_GROUP_SYSTEM)))
- continue;
- down_read(&sinfo->groups_sem);
- for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-@@ -4949,7 +4924,8 @@ static void btrfs_stripe_reclaim_tick(struct btrfs_fs_info *fs_info)
- int raid;
-
- if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
-- BTRFS_BLOCK_GROUP_METADATA)))
-+ BTRFS_BLOCK_GROUP_METADATA |
-+ BTRFS_BLOCK_GROUP_SYSTEM)))
- continue;
- if (READ_ONCE(sinfo->bg_reclaim_threshold) <= 0)
- continue;
-@@ -7009,6 +6985,7 @@ static void reserve_chunk_space(struct btrfs_trans_handle *trans,
- {
- struct btrfs_fs_info *fs_info = trans->fs_info;
- struct btrfs_space_info *info;
-+ u64 headroom = 0;
- u64 left;
- bool want_system_chunk, need_system_chunk;
- int ret = 0;
-@@ -7023,12 +7000,41 @@ static void reserve_chunk_space(struct btrfs_trans_handle *trans,
- spin_lock(&info->lock);
- left = info->total_bytes - btrfs_space_info_used(info, true);
- want_system_chunk = info->total_bytes < system_space_target(info);
-- need_system_chunk = left < bytes;
- spin_unlock(&info->lock);
-
-+ /*
-+ * Under stripe_alloc a raid56 system chunk places its tree blocks by
-+ * whole stripes (btrfs_is_stripe_meta_bg()), and the bytes trapped in
-+ * partial stripes and the open run's remainder are already counted
-+ * as used above. What is left is whole free stripes, but the request
-+ * is sized in tree blocks: a chunk tree COW that needs a fresh run
-+ * takes a whole stripe for its first block, so demand one stripe of
-+ * headroom beyond the request, or the chunk item for the very system
-+ * chunk this would allocate finds no stripe to land in. The headroom
-+ * decides when to allocate; it is not reserved.
-+ */
-+ if (btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
-+ int raid;
-+
-+ down_read(&info->groups_sem);
-+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-+ struct btrfs_block_group *bg;
-+
-+ if (!(btrfs_raid_array[raid].bg_flag &
-+ BTRFS_BLOCK_GROUP_RAID56_MASK))
-+ continue;
-+ list_for_each_entry(bg, &info->block_groups[raid], list)
-+ headroom = max_t(u64, headroom,
-+ bg->full_stripe_len);
-+ }
-+ up_read(&info->groups_sem);
-+ }
-+
-+ need_system_chunk = left < bytes + headroom;
-+
- if (need_system_chunk && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
-- btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
-- left, bytes, type);
-+ btrfs_info(fs_info, "left=%llu, need=%llu, headroom=%llu, flags=%llu",
-+ left, bytes, headroom, type);
- btrfs_dump_space_info(info, 0, false);
- }
-
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index cb5c9c728e8d0..e9d83591baf30 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4243,11 +4243,18 @@ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
- * transaction rather than failing one write -- are the price of covering
- * raid56 metadata at all, and a filesystem that does not want them wants
- * raid1c3/raid1c4 metadata instead, which is the better answer anyway.
-+ *
-+ * System chunks are tree blocks too -- the chunk tree, without which nothing
-+ * maps -- and carry no METADATA bit, so they are named here explicitly. A
-+ * chunk tree block landing in a stripe with committed chunk tree blocks is
-+ * the worst possible write hole: a torn parity rewrite there costs the whole
-+ * filesystem on the next degraded mount, not one file.
- */
- bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg)
- {
- return btrfs_test_opt(bg->fs_info, STRIPE_ALLOC) &&
-- (bg->flags & BTRFS_BLOCK_GROUP_METADATA) &&
-+ (bg->flags & (BTRFS_BLOCK_GROUP_METADATA |
-+ BTRFS_BLOCK_GROUP_SYSTEM)) &&
- !(bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
- (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK);
- }
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 7a825b3507033..abfadfec54f5a 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -3248,9 +3248,9 @@ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
- * A raid56 metadata group under stripe_meta is covered: its
- * read-modify-writes are partial writes inside one transaction's
- * run, counted by the audit as meta_rmw_cur, and the audit warns
-- * by itself should one ever touch a committed block. Only system
-- * chunks and mixed groups are the uncovered case this message is
-- * about.
-+ * by itself should one ever touch a committed block. System chunks
-+ * are covered the same way. Only mixed groups are the uncovered case
-+ * this message is about.
- */
- bg = btrfs_lookup_block_group(fs_info, rbio->bioc->full_stripe_logical);
- if (bg) {
---
-2.47.3
-
+++ /dev/null
-From 6c7a6f089b7eacf99d6026721884742426ce0ff3 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Wed, 23 Sep 2026 01:47:12 -0400
-Subject: [RFC PATCH 066/116] btrfs: stripe_alloc: close dead nocow stripe runs
- at commit
-To: linux-btrfs@vger.kernel.org
-
-A nodatacow or preallocating inode gets a private BTRFS_STRIPE_RUN_NOCOW
-stripe run, and close_block_group_stripe_runs() deliberately skips those at
-commit: closing one per commit would burn a stripe per commit for a slowly
-appended nocow file. They close only when they fill up, or when the owning
-inode is evicted.
-
-That leaves them hoarding. Extents freed inside a live run's range return
-to the free space cache, but btrfs_stripe_run_range_usable() refuses to
-claim any range overlapping a live run, so the whole stripes freed there
-cannot be placed while the run object exists. fsstress fallocating
-thousands of files leaves thousands of cached inodes each holding a run;
-measured on a raid5 rig, ~99% of the free whole stripes in every read-write
-group sat inside one -- 73.4MB of 73.4MB in one group, behind 976 runs.
-The accounting side of this was already fixed, by reporting those stripes
-stranded rather than claimable so the admission gate stops admitting writes
-the allocator then refuses. The space itself stayed stranded until
-eviction.
-
-Give the runs a lifecycle instead. A run whose allocations have all been
-freed again is dead: it owns no data, so the write-hole invariants it exists
-to uphold have nothing left to protect, and it is pure hoarding. Close it
-on the normal commit path, which frees it and marks the group for the rescan
-that credits its stripes back.
-
-Two pieces:
-
- - btrfs_stripe_run_note_free(), called from btrfs_add_free_space(), clears
- the live bits of freed sectors inside a persistent run. The live map
- already means "this sector holds an allocation someone intends to
- write"; it was set at allocation and cleared on abandon, but never on
- the free of an extent that had been written, so it drifted permanently
- set. Only persistent runs are touched: every other class is closed and
- freed by its own commit, so its map is never read after its bytes could
- have been freed.
-
- - open_stripe_run_dead() reads that map. A run is dead when it handed out
- space (offset > start), has no bytes in flight, and has no live bit set.
- close_block_group_stripe_runs() now closes a persistent run that is
- dead, instead of skipping it.
-
-The invariant the skip exists for is preserved: a run with any live byte
-stays open. A slowly appended nocow file keeps its run across commits and
-still burns no stripe per commit. Only a run holding nothing at all is
-taken.
-
-Commit granularity is deliberate. The hoarding lasts across many commits
-today, so noticing the death at the next commit is enough, and it keeps the
-free path to a bitmap clear: no closing, no free space return, and no new
-lock ordering, since btrfs_stripe_run_note_free() takes only
-bg->stripe_run_lock and its callers hold no free space lock yet.
-
-The cost is one walk of the block group's open run list per free into a
-stripe_alloc group, with interrupts off. That is the same walk the
-allocation and IO completion paths already do, and this shortens the list
-they walk.
-
-A retired live map (live_nbits == 0, set when a run outgrows its map) leaves
-the run permanently undead. That is the safe direction: liveness unknown is
-never a licence to close.
-
-Unlink needs nothing extra: dropping the last link frees the inode's
-extents, which is exactly what makes its run dead. A partial truncate
-leaves live bytes and correctly keeps the run open.
-
-Counted in sysfs as stripe_run_stats::nocow_run_dead_closed. Directed test:
-nocow-dead-run-test.sh.
-
-Assisted-by: Claude:claude-opus-5
----
- fs/btrfs/block-group.c | 85 ++++++++++++++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 2 +
- fs/btrfs/free-space-cache.c | 1 +
- fs/btrfs/fs.h | 2 +
- fs/btrfs/sysfs.c | 6 ++-
- 5 files changed, 92 insertions(+), 4 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 60fcfde839ba1..4b821c9af73e9 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -664,6 +664,33 @@ 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 ever handed out has been freed again.
-+ *
-+ * The live map already answers this: a bit is set while its sector holds an
-+ * allocation someone still intends to write, and btrfs_stripe_run_note_free()
-+ * clears it when the extent is freed. A dead run owns no data at all, so the
-+ * write-hole invariants it exists to uphold have nothing left to protect --
-+ * it is pure hoarding, and the whole stripes freed inside its range stay
-+ * unclaimable (btrfs_stripe_run_range_usable()) until it is gone.
-+ *
-+ * Requires inflight_bytes == 0: bytes allocated but not yet reported have no
-+ * live bit of their own after an abandon, and an in-flight write must keep
-+ * its stripes. A retired live map (live_nbits == 0) means liveness is
-+ * unknown, which is never a licence to close. 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);
-+}
-+
- /*
- * A drained run may still be needed.
- *
-@@ -1251,6 +1278,50 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- 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 live stripe run's address range must not be re-claimed while the run
- * object still exists: an ENOSPC discard storm can return every byte of a
-@@ -2415,6 +2486,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;
-@@ -2441,8 +2513,17 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
- * (read-only, removal, unmount: seq == U64_MAX) still closes
- * persistent runs, as does the owning inode's eviction.
- */
-- if (run->persistent && seq != U64_MAX)
-- continue;
-+ if (run->persistent && seq != U64_MAX) {
-+ /*
-+ * ... unless nothing is left alive in it. A dead run
-+ * holds no data to protect and its stripes cannot be
-+ * reclaimed while it exists, so close it now rather
-+ * than waiting for the owner's eviction.
-+ */
-+ if (!open_stripe_run_dead(run))
-+ continue;
-+ atomic64_inc(&fs_info->stripe_run_stats.nocow_run_dead_closed);
-+ }
- /*
- * Metadata runs are still being filled at this point in the
- * commit and their tree blocks are not written until later;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 6a09ecc13f0c8..657b37c7f7fe5 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -493,6 +493,8 @@ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class);
- u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
- u64 nstripes);
-+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);
- /*
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index d01d480609b6a..2c3e32aea935c 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1626,6 +1626,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);
- }
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index bce5cc5b09740..50235cf99e1e9 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -922,6 +922,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;
- } stripe_run_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 786a6dbb02fe0..f367a0fc707a9 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1179,11 +1179,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);
-
---
-2.47.3
-
--- /dev/null
+From b8a1eee6f055ac803c5063beebc831789e0126ec Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sun, 25 Oct 2026 04:48:50 -0400
+Subject: [RFC PATCH 66/85] btrfs: stripe_alloc: log the space counters when
+ data writeback hits ENOSPC
+To: linux-btrfs@vger.kernel.org
+
+A data writeback allocation that fails with ENOSPC under stripe_alloc
+drops the buffered data in its range. The reservation margin is meant to
+make that impossible, so the warning is the only evidence that admission
+and the allocator disagreed, and today it names only the allocation size.
+A drop seen once in a long test cannot be explained afterwards.
+
+Log what admission decided on in the same line: the whole-stripe supply
+(claimable, the part dedicated to relocation, unmanaged free space), what
+is held against it (may_use, the outstanding extents' margin), the open,
+trapped and stranded bytes, reserved and total, and the margin unit. The
+"despite reservation margin" wording is kept, so existing log scanners
+still match it.
+
+On CONFIG_BTRFS_DEBUG builds, also log one line per block group with its
+full stripe length, claimable bytes, largest known claimable run, open
+remainder and trapped and stranded bytes. Unlike btrfs_dump_space_info()
+this walks no free space entries. It takes groups_sem for read and each
+group's lock, as the ENOSPC_DEBUG dump a few lines above already does at
+this call site, so it adds no lock ordering.
+
+The line and the walk share one rate limit, so a burst of failures cannot
+flood the log with group lines.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/extent-tree.c | 34 +++++++++++++++++++++++++++++-----
+ fs/btrfs/space-info.c | 39 +++++++++++++++++++++++++++++++++++++++
+ fs/btrfs/space-info.h | 1 +
+ 3 files changed, 69 insertions(+), 5 deletions(-)
+
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index cd945076a6d79..2fd40907cac62 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -5191,12 +5191,36 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ * 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.
++ * anyway the pages are dropped, so say so loudly, with the
++ * counters admission decided on (and, on debug builds, every
++ * group's view of its stripes): a drop seen once with nothing
++ * else logged cannot be explained afterwards.
+ */
+- 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);
++ if (is_data && delalloc && btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
++ static DEFINE_RATELIMIT_STATE(rs, DEFAULT_RATELIMIT_INTERVAL,
++ DEFAULT_RATELIMIT_BURST);
++ struct btrfs_space_info *sinfo;
++
++ sinfo = btrfs_find_space_info(fs_info, flags);
++ if (sinfo && __ratelimit(&rs)) {
++ btrfs_warn(fs_info,
++ "stripe_alloc: data writeback allocation of %llu bytes returned ENOSPC despite reservation margin; buffered data in this range will be dropped: claimable %llu claimable_reloc %llu open %llu trapped %llu stranded %llu may_use %llu margin %llu unmanaged_free %lld reserved %llu total %llu unit %llu",
++ num_bytes,
++ sinfo->bytes_stripe_claimable,
++ sinfo->bytes_stripe_claimable_reloc,
++ sinfo->bytes_stripe_open,
++ sinfo->bytes_stripe_unusable,
++ sinfo->bytes_stripe_stranded,
++ sinfo->bytes_may_use,
++ sinfo->bytes_stripe_margin,
++ (s64)atomic64_read(&sinfo->bytes_unmanaged_free),
++ sinfo->bytes_reserved,
++ sinfo->total_bytes,
++ READ_ONCE(fs_info->stripe_margin_unit));
++ if (IS_ENABLED(CONFIG_BTRFS_DEBUG))
++ btrfs_dump_stripe_groups(sinfo);
++ }
++ }
+ }
+
+ return ret;
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index f5e83f636b56e..2d9010624bbc0 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -1036,6 +1036,45 @@ void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
+ btrfs_info(fs_info, "%llu bytes available across all block groups", total_avail);
+ }
+
++/*
++ * One line per block group of what stripe_alloc's allocator sees: the
++ * stripe width, the whole-stripe supply and the largest run a claim may
++ * find, the open remainder and the trapped and stranded bytes. Cheap
++ * enough for a failed writeback allocation, unlike btrfs_dump_space_info()
++ * with its free space entries.
++ */
++void btrfs_dump_stripe_groups(struct btrfs_space_info *info)
++{
++ struct btrfs_fs_info *fs_info = info->fs_info;
++ const u64 reloc_bg = READ_ONCE(fs_info->data_reloc_bg);
++ struct btrfs_block_group *cache;
++ int index;
++
++ down_read(&info->groups_sem);
++ for (index = 0; index < BTRFS_NR_RAID_TYPES; index++) {
++ list_for_each_entry(cache, &info->block_groups[index], list) {
++ spin_lock(&cache->lock);
++ btrfs_info(fs_info,
++"stripe group %llu len %llu fsl %lu used %llu reserved %llu pinned %llu claimable %llu max_run %lld open_rem %llu trapped %llu stranded %llu cached %d%s%s%s",
++ cache->start, cache->length,
++ cache->full_stripe_len, cache->used,
++ cache->reserved, cache->pinned,
++ READ_ONCE(cache->stripe_claimable),
++ (s64)READ_ONCE(cache->max_claimable_run),
++ READ_ONCE(cache->stripe_open_remainder),
++ READ_ONCE(cache->stripe_unusable_ready) ?
++ READ_ONCE(cache->stripe_unusable) : 0,
++ READ_ONCE(cache->stripe_stranded),
++ cache->cached,
++ cache->ro ? " ro" : "",
++ cache->start == reloc_bg ? " reloc" : "",
++ btrfs_is_stripe_alloc_bg(cache) ? "" : " unmanaged");
++ spin_unlock(&cache->lock);
++ }
++ }
++ up_read(&info->groups_sem);
++}
++
+ static inline u64 calc_reclaim_items_nr(const struct btrfs_fs_info *fs_info,
+ u64 to_reclaim)
+ {
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index 3a8bda4471830..5e13008c688f5 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -393,6 +393,7 @@ struct btrfs_space_info *btrfs_find_space_info(const struct btrfs_fs_info *info,
+ void btrfs_clear_space_info_full(struct btrfs_fs_info *info);
+ void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
+ bool dump_block_groups);
++void btrfs_dump_stripe_groups(struct btrfs_space_info *info);
+ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
+ u64 orig_bytes,
+ enum btrfs_reserve_flush_enum flush);
+--
+2.47.3
+
--- /dev/null
+From fd2541deae3f19661fd8e5a03f1981574b6343b1 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sun, 25 Oct 2026 06:27:49 -0400
+Subject: [RFC PATCH 67/85] btrfs: stripe_alloc: do not count a writeback
+ ENOSPC drop's give-back as supply (debug part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: do not count a writeback ENOSPC
+drop's give-back as supply" (earlier in this series) that need code from
+"btrfs: stripe_alloc: log the space counters when data writeback hits
+ENOSPC", which comes after it in this series: they are applied here,
+once "btrfs: stripe_alloc: log the space counters when data writeback
+hits ENOSPC" is in, instead of with the rest of "btrfs: stripe_alloc: do
+not count a writeback ENOSPC drop's give-back as supply".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/extent-tree.c | 5 +++--
+ 1 file changed, 3 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 2fd40907cac62..cf54a9d35f1d1 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -5204,7 +5204,7 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ sinfo = btrfs_find_space_info(fs_info, flags);
+ if (sinfo && __ratelimit(&rs)) {
+ btrfs_warn(fs_info,
+- "stripe_alloc: data writeback allocation of %llu bytes returned ENOSPC despite reservation margin; buffered data in this range will be dropped: claimable %llu claimable_reloc %llu open %llu trapped %llu stranded %llu may_use %llu margin %llu unmanaged_free %lld reserved %llu total %llu unit %llu",
++ "stripe_alloc: data writeback allocation of %llu bytes returned ENOSPC despite reservation margin; buffered data in this range will be dropped: claimable %llu claimable_reloc %llu open %llu trapped %llu stranded %llu may_use %llu margin %llu unmanaged_free %lld reserved %llu total %llu unit %llu quarantine %llu",
+ num_bytes,
+ sinfo->bytes_stripe_claimable,
+ sinfo->bytes_stripe_claimable_reloc,
+@@ -5216,7 +5216,8 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ (s64)atomic64_read(&sinfo->bytes_unmanaged_free),
+ sinfo->bytes_reserved,
+ sinfo->total_bytes,
+- READ_ONCE(fs_info->stripe_margin_unit));
++ READ_ONCE(fs_info->stripe_margin_unit),
++ sinfo->bytes_stripe_quarantine);
+ if (IS_ENABLED(CONFIG_BTRFS_DEBUG))
+ btrfs_dump_stripe_groups(sinfo);
+ }
+--
+2.47.3
+
+++ /dev/null
-From fa5cdd7e9ffe41c2e15e670e59a8020924f641d5 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Wed, 23 Sep 2026 15:30:45 -0400
-Subject: [RFC PATCH 067/116] btrfs: stripe_alloc: do not round a full stripe
- with power-of-two macros
-To: linux-btrfs@vger.kernel.org
-
-full_stripe_len is nr_data_stripes * stripe_len. It is a power of two only
-when the data stripe count is: raid5 over 3 devices gives 128K and raid5
-over 5 gives 256K, but raid5 over 4 devices -- the common geometry, and the
-one the harness uses -- gives 3 * 64K = 192K, and 5, 6 and 7 data stripes
-are no better.
-
-round_down() and IS_ALIGNED() are mask operations, defined only for
-power-of-two moduli. Applied to 192K they do not round to a stripe at all,
-they clear whichever bits happen to sit under the mask:
-
- round_down(1179648, 196608) = 1179648 & ~196607 = 1048576
-
-which is a third of a stripe below the boundary it was asked for, and is not
-a stripe boundary at all. The error is silent and depends on the value: of
-the first eight stripe-aligned offsets in a group, four round correctly and
-four do not.
-
-The visible damage is in btrfs_stripe_nocow_writable(). It walks the
-stripes an in-place write would touch, starting at the stripe containing the
-extent. When the rounding lands low the walk starts one stripe early, in
-the PREVIOUS file's private nocow run, and the ownership test correctly
-refuses a run owned by another inode -- so the write is forced to COW. A
-preallocated file that is then overwritten therefore loses its
-preallocation and is rewritten elsewhere, wasting the space fallocate
-promised. Measured on raid5 over 4 devices with the prealloc waiver, half
-of a set of preallocated files COWed, and exactly the four of eight whose
-offsets the mask got wrong.
-
-Two more callers are affected. The nocow re-adoption hint in
-btrfs_alloc_from_inode_stripe_run() computes the wrong stripe, and
-btrfs_log_settle_stripes() both misjudges whether a run's filled length is
-stripe aligned and derives the wrong final partial stripe from it -- so a
-run that ends exactly on a stripe boundary can be treated as partial.
-
-Round by division instead, in one helper each for the round and the
-alignment test, so the next caller cannot reach for the mask again.
-
-Assisted-by: Claude:claude-opus-5
----
- fs/btrfs/block-group.c | 29 +++++++++++++++++++++++++----
- 1 file changed, 25 insertions(+), 4 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 4b821c9af73e9..c893d0f299f72 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -584,6 +584,27 @@ 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 (raid5 over 4 devices, or
-+ * raid6 over 5) gives 192K, and 5, 6 and 7 data stripes are no better. The
-+ * kernel's round_down() and IS_ALIGNED() are mask operations defined only for
-+ * power-of-two moduli: applied to 192K they silently return a value that is
-+ * not a stripe boundary at all (round_down(1179648, 196608) yields 1048576,
-+ * a third of a stripe low). Use division.
-+ */
-+static u64 stripe_round_down(u64 val, u64 fsl)
-+{
-+ return div64_u64(val, fsl) * fsl;
-+}
-+
-+static bool stripe_is_aligned(u64 val, u64 fsl)
-+{
-+ return stripe_round_down(val, fsl) == val;
-+}
-+
- /*
- * 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))
-@@ -1175,7 +1196,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- readopt_hint >= bg->start &&
- readopt_hint < bg->start + bg->length) {
- u64 stripe = bg->start +
-- round_down(readopt_hint - bg->start, fsl);
-+ stripe_round_down(readopt_hint - bg->start, fsl);
- u64 frontier = 0;
- u64 tlen;
-
-@@ -1653,7 +1674,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;
-@@ -2081,9 +2102,9 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- * to run->start is stripe alignment.
- */
- filled = run->offset - run->start;
-- if (!IS_ALIGNED(filled, bg->full_stripe_len)) {
-+ if (!stripe_is_aligned(filled, bg->full_stripe_len)) {
- ps_start = run->start +
-- round_down(filled, bg->full_stripe_len);
-+ stripe_round_down(filled, bg->full_stripe_len);
- ps_len = bg->full_stripe_len;
- }
- if (run->open) {
---
-2.47.3
-
+++ /dev/null
-From 378ae1181fb6c49489157587062078b9f8ca5769 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 24 Sep 2026 02:21:12 -0400
-Subject: [RFC PATCH 068/116] btrfs: stripe_alloc: do not wait for stripe runs
- to drain on an errored filesystem
-To: linux-btrfs@vger.kernel.org
-
-btrfs_retire_block_group_stripes() closes a read-only block group's stripe
-runs and waits for every byte allocated from them to be reported back,
-which normally happens when the ordered extents carrying those bytes
-complete. After a transaction abort that can never happen: the ordered
-extents still in flight are torn down at unmount, not before, so a run can
-stay undrained for the rest of the mount and the wait never returns.
-
-The caller that hit this is block group reclaim. On a degraded 5-member
-raid6 filesystem with raid6 metadata, the commit ran out of metadata space
-while freeing an extent (__btrfs_free_extent returned -ENOSPC from
-btrfs_run_delayed_refs) and forced the filesystem read-only, while the
-reclaim worker was in btrfs_inc_block_group_ro() for a data block group
-whose runs still had writes in flight. It sat in the retire wait holding
-reclaim_bgs_lock and sb_writers, reported by the hung task detector after
-327 seconds and never returned. (bhive, 2026-09-24, KASAN + lockdep clean
-otherwise; forensics in raid56-wh-harness.)
-
-End the wait when the filesystem has gone into error, and have
-__btrfs_handle_fs_error() wake every block group's drain waiters so a
-waiter already asleep sees it. The runs are left as they are: nothing can
-allocate from them now, and btrfs_free_open_stripe_runs() releases them at
-teardown, reporting any bytes still counted, which also names the path
-that failed to report. Do not start block group reclaim at all on an
-errored filesystem: relocation cannot proceed there.
-
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/block-group.c | 40 ++++++++++++++++++++++++++++++++++++++--
- fs/btrfs/block-group.h | 1 +
- fs/btrfs/messages.c | 3 +++
- 3 files changed, 42 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index c893d0f299f72..9fc41fe73cb06 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2610,14 +2610,45 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
- * prevent new allocations first (e.g. the block group is read-only),
- * otherwise this can wait forever. Membership in fs_info->open_stripe_bgs
- * is left for the next retire walk to collect.
-+ *
-+ * A filesystem that has gone into error ends the wait as well: after a
-+ * transaction abort the ordered extents holding a run's bytes in flight
-+ * may never complete (they are torn down at unmount), so a run can stay
-+ * undrained for the rest of the mount. Waiting for it there would block
-+ * the caller -- relocation, holding reclaim_bgs_lock and sb_writers --
-+ * forever. The runs are then left as they are; btrfs_free_open_stripe_runs()
-+ * releases them at teardown and reports the bytes still counted.
- */
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
- {
-+ struct btrfs_fs_info *fs_info = bg->fs_info;
-+
- close_block_group_stripe_runs(bg, U64_MAX);
- /* Parked partial-stripe rbios hold the very bios the wait drains. */
-- btrfs_flush_parked_rbios(bg->fs_info, bg->start, bg->length, false);
-+ btrfs_flush_parked_rbios(fs_info, bg->start, bg->length, false);
- wait_var_event(&bg->open_stripe_runs,
-- bg_open_stripes_settled(bg, U64_MAX));
-+ bg_open_stripes_settled(bg, U64_MAX) ||
-+ BTRFS_FS_ERROR(fs_info));
-+ if (BTRFS_FS_ERROR(fs_info) && !bg_open_stripes_settled(bg, U64_MAX))
-+ btrfs_warn(fs_info,
-+"block group %llu read-only with stripe runs still in flight after a filesystem error; not waiting for them",
-+ bg->start);
-+}
-+
-+/*
-+ * The filesystem has gone into error: wake every task waiting for a block
-+ * group's stripe runs to drain, so the waits that give up on an error
-+ * (btrfs_retire_block_group_stripes()) notice it. A run's own completion
-+ * reports may never arrive now.
-+ */
-+void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info)
-+{
-+ struct btrfs_block_group *bg;
-+
-+ spin_lock(&fs_info->open_stripe_lock);
-+ list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
-+ wake_up_var(&bg->open_stripe_runs);
-+ spin_unlock(&fs_info->open_stripe_lock);
- }
-
- /*
-@@ -4933,6 +4964,11 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- LIST_HEAD(retry_list);
- int reclaimed = 0;
-
-+ /* Relocation cannot proceed, and the stripe drain it starts with
-+ * would wait for IO that will not complete. */
-+ if (BTRFS_FS_ERROR(fs_info))
-+ return;
-+
- if (!btrfs_should_reclaim(fs_info))
- return;
-
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 657b37c7f7fe5..6c0b4ea723bb1 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -485,6 +485,7 @@ void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
- void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid);
- void btrfs_free_open_stripe_runs(struct btrfs_fs_info *fs_info);
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
-+void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
- bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
- struct extent_buffer *eb,
-diff --git a/fs/btrfs/messages.c b/fs/btrfs/messages.c
-index 0704be7be8719..785986c59ab6e 100644
---- a/fs/btrfs/messages.c
-+++ b/fs/btrfs/messages.c
-@@ -4,6 +4,7 @@
- #include "messages.h"
- #include "discard.h"
- #include "super.h"
-+#include "block-group.h"
-
- #ifdef CONFIG_PRINTK
-
-@@ -163,6 +164,8 @@ void __btrfs_handle_fs_error(struct btrfs_fs_info *fs_info, const char *function
- * send it down to the disk.
- */
- WRITE_ONCE(fs_info->fs_error, error);
-+ /* Waiters for stripe run drains give up on an error; tell them. */
-+ btrfs_wake_open_stripe_waiters(fs_info);
-
- /* Don't go through full error handling during mount. */
- if (!(sb->s_flags & SB_BORN))
---
-2.47.3
-
--- /dev/null
+From 6e3a00f579397c6232636f8f734f1c18db50aef7 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:58 -0400
+Subject: [RFC PATCH 68/85] btrfs: stripe_meta: allocate tree blocks by whole
+ stripes
+To: linux-btrfs@vger.kernel.org
+
+Metadata gets the placement rule data already has: tree blocks are handed
+out from runs of fully free stripes, and a stripe is never revisited once
+the transaction that filled it has written it. No separate mount option: the
+chunk profile already decides it. raid56 metadata has the same write hole
+as raid56 data, so it gets the same protection at the same time, and
+metadata on any other profile has no write hole to close -- the policy's
+RAID56_MASK test simply does not match it, so nothing changes there.
+
+It does cost a stranded stripe tail per commit, and a metadata allocation
+that fails aborts the transaction rather than failing one write. Those
+are the price of covering raid56 metadata at all rather than a reason to
+make it opt-in separately: a filesystem unwilling to pay them does not
+want raid56 metadata, and converting it to raid1c3/raid1c4 removes both
+the cost and the write hole.
+
+Only system chunks are left uncovered: btrfs_is_stripe_meta_bg() tests the
+METADATA flag and a system chunk does not carry it, so a raid56 system
+chunk keeps the legacy read-modify-write. The mount-time warning is
+narrowed to say exactly that instead of claiming metadata is uncovered,
+which it no longer is.
+
+The machinery is the data machinery, including the per-sector liveness
+map the previous patch gave it. Metadata needed three things of its own:
+
+ - A completion report. A run drains when every byte allocated from it
+ has been accounted for, and metadata had no equivalent of ordered
+ extent completion, so its runs could never drain -- the deadlock that
+ mixed block groups hit. end_bbio_meta_write() now reports, and
+ btrfs_open_stripe_write_abandoned() covers a tree block freed before
+ it was ever written (COWed twice in one transaction, say).
+
+ - A two-phase closure. btrfs_retire_open_stripes() runs before the
+ commit writes tree blocks, so it skips metadata runs; they are closed
+ and drained afterwards by btrfs_retire_meta_stripes(), once every block
+ is on disk. Closing earlier would strand blocks the commit has not
+ allocated yet, draining earlier would wait for writes it has not
+ issued. Metadata runs are also freed there rather than when their
+ counter reaches zero: a stripe's columns can be written by separate
+ rbios, and freeing on the first completion leaves the second with no
+ run to pad or merge against.
+
+ - Whole stripes per writeback pass. The opportunistic writeback passes
+ do not know about stripes and will happily write three tree blocks now
+ and five later; btrfs_defer_stripe_meta_write() leaves the blocks
+ dirty for the commit (or a WB_SYNC_ALL waiter) instead, the same shape
+ as the zoned write-pointer deferral.
+
+Two free paths bypass the usual completion reporting and must report the
+block abandoned themselves: btrfs_free_tree_block() can send a
+same-transaction unwritten block through the delayed-ref machinery when
+check_ref_cleanup() finds its ref head already processed, and
+clean_log_buffer() discards unwritten log tree blocks via
+btrfs_pin_reserved_extent() without ever visiting btrfs_free_tree_block().
+Either miss leaves the block counted as inflight forever: the run never
+drains, the block group reference never drops, and unmount asserts. Both
+were found by the dm-log-writes replay matrix, whose crash-recovery mounts
+exercise both paths routinely.
+
+Trapped free space is maintained for stripe_meta groups as for data: the
+disarm, rescan and commit-time scan accept them, the commit scan sums the
+METADATA space_info, and inc_block_group_ro() applies the trapped-bytes
+subtraction to metadata groups too. btrfs_update_global_block_rsv()
+compares the global reserve against the capacity minus the trapped bytes,
+so a metadata chunk is allocated while unallocated space remains, and a
+stripe_meta tree block allocation that fails with ENOSPC (which aborts the
+transaction) prints the stripe counters.
+
+btrfs_retire_meta_stripes() syncs the open-run remainder into the
+space_info after it closes the runs, as the data retirement does.
+report_uncovered_rmw() keeps its "not covered by stripe_alloc" message for
+what it was written for, system chunks and mixed groups, and no longer
+says it of a covered stripe_meta group. btrfs_free_tree_block() checks
+its block group lookup.
+
+A mount whose log replay fails after allocating tree blocks, and the
+unmount of an aborted filesystem, never commit again, so the commit-time
+retirement never releases their open runs and block group references:
+both release every open run before the block groups are freed, reporting
+any run that still counts bytes in flight.
+
+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 | 395 ++++++++++++++++++++++++++++--
+ fs/btrfs/block-group.h | 14 ++
+ fs/btrfs/block-rsv.c | 9 +-
+ fs/btrfs/disk-io.c | 2 +
+ fs/btrfs/extent-tree.c | 93 ++++++-
+ fs/btrfs/extent_io.c | 18 ++
+ fs/btrfs/free-space-cache.c | 8 +-
+ fs/btrfs/raid56.c | 17 ++
+ fs/btrfs/sysfs.c | 2 +-
+ fs/btrfs/tests/free-space-tests.c | 7 +
+ fs/btrfs/transaction.c | 18 ++
+ fs/btrfs/tree-log.c | 22 ++
+ 12 files changed, 572 insertions(+), 33 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 27b7fb36361fa..d29803e43bd56 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -500,6 +500,7 @@ struct btrfs_open_stripe_run {
+ u64 offset; /* next unallocated byte */
+ u64 inflight_bytes; /* reserved bytes with data IO pending */
+ u64 open_seq; /* fs_info->stripe_retire_seq at open */
++ u64 transid; /* fs_info->generation at open */
+ /*
+ * Private runs are found by (root, owner): root is the subvolume's
+ * root id, owner the inode number (LOG, NOCOW), a shared LOG key
+@@ -534,6 +535,60 @@ struct btrfs_open_stripe_run {
+ u32 live_nbits; /* sectors @live covers; caps growth */
+ };
+
++static void btrfs_dump_open_meta_runs(struct btrfs_block_group *bg)
++{
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (run->class != BTRFS_STRIPE_RUN_META)
++ continue;
++ btrfs_warn(bg->fs_info,
++" run %llu..%llu frontier %llu open %d inflight %llu transid %llu",
++ run->start, run->end, run->offset, run->open,
++ run->inflight_bytes, run->transid);
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++}
++
++static bool bg_has_undrained_meta_runs(struct btrfs_block_group *bg,
++ u64 transid)
++{
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ bool ret = false;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (run->class != BTRFS_STRIPE_RUN_META)
++ continue;
++ /*
++ * An open run here belongs to the running transaction: the
++ * retirer closed every run it is responsible for before its
++ * wait, so this one was opened while it waited, and drains
++ * when that transaction's own commit writes its tree blocks.
++ * Waiting on it would be waiting for writes this commit never
++ * issued.
++ */
++ if (run->open)
++ continue;
++ /*
++ * Likewise a run the running transaction opened and a band
++ * collision or eviction closed early: its blocks are written,
++ * and its stripes settled, by that transaction's own commit.
++ */
++ if (run->transid > transid)
++ continue;
++ if (run->inflight_bytes) {
++ ret = true;
++ break;
++ }
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ return ret;
++}
++
+ static bool open_stripe_run_drained(const struct btrfs_open_stripe_run *run)
+ {
+ return !run->open && run->inflight_bytes == 0;
+@@ -656,7 +711,27 @@ static bool open_stripe_run_dead(const struct btrfs_open_stripe_run *run)
+ return bitmap_empty(run->live, run->live_nbits);
+ }
+
+-/* Free a drained run. Caller holds bg->stripe_run_lock. */
++/*
++ * Whether a run is freed as soon as it drains. Two kinds must outlive the
++ * drain, because later writes to their stripes still need a covering run to
++ * park against or pad from:
++ *
++ * - Metadata runs: writeback may submit a stripe's tree blocks as separate
++ * rbios, so the run drains after the first one. They are freed by
++ * btrfs_retire_meta_stripes() once every tree block is on disk.
++ *
++ * - Relocation runs: relocation preallocates its destination extents (no
++ * IO, so the run drains at once) and writes them only after the commit
++ * that ends relocate_block_group(). They are retained until relocation
++ * releases them (btrfs_release_stripe_reloc_runs()). Meanwhile their
++ * stripes hold only relocation's own copies, and the closed run keeps its
++ * range unclaimable.
++ */
++static bool run_freed_on_drain(const struct btrfs_open_stripe_run *run)
++{
++ return run->class != BTRFS_STRIPE_RUN_META && !run->retained;
++}
++
+ static void free_open_stripe_run(struct btrfs_block_group *bg,
+ struct btrfs_open_stripe_run *run)
+ {
+@@ -678,6 +753,23 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
+ wake_up_var(&bg->open_stripe_runs);
+ }
+
++/*
++ * A run has drained. Free it if nothing needs it any more; otherwise
++ * (metadata or retained relocation runs) wake the waiters directly, since a
++ * report can arrive after btrfs_retire_meta_stripes() started waiting, e.g.
++ * when an unwritten tree block is freed.
++ */
++static void open_stripe_run_drain_reported(struct btrfs_block_group *bg,
++ struct btrfs_open_stripe_run *run)
++{
++ if (!open_stripe_run_drained(run))
++ return;
++ if (run_freed_on_drain(run))
++ free_open_stripe_run(bg, run);
++ else
++ wake_up_var(&bg->open_stripe_runs);
++}
++
+ /*
+ * Close a run: no further allocation may join it, and its unallocated tail
+ * must be returned to the free space cache by the caller (after dropping the
+@@ -786,6 +878,10 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ u64 *ret_offset, u64 *available)
+ {
+ struct btrfs_fs_info *fs_info = bg->fs_info;
++ const u64 transid = btrfs_get_fs_generation(fs_info);
++ u64 evict_start[BTRFS_STRIPE_RUN_NR_BANDS];
++ u64 evict_len[BTRFS_STRIPE_RUN_NR_BANDS];
++ int nr_evict = 0;
+ const u64 fsl = bg->full_stripe_len;
+ struct btrfs_open_stripe_run *new_run;
+ struct btrfs_open_stripe_run *run;
+@@ -813,6 +909,24 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+
+ if (!r)
+ continue;
++ /*
++ * Metadata runs are closed after the next transaction is
++ * already running (btrfs_retire_meta_stripes()), so a slot can
++ * still hold the previous transaction's run. Joining it would
++ * put two transactions' tree blocks in the same stripes, and
++ * the later one's writeback would read-modify-write parity
++ * over the earlier one's committed blocks: the write hole.
++ * Close it; its tail returns to the free space cache below.
++ */
++ if (class == BTRFS_STRIPE_RUN_META && r->transid != transid) {
++ bg->open_stripe[class][band] = NULL;
++ evict_len[nr_evict] =
++ close_open_stripe_run(bg, r,
++ &evict_start[nr_evict]);
++ if (evict_len[nr_evict])
++ nr_evict++;
++ continue;
++ }
+ rem = r->end - r->offset;
+ if (rem > *available)
+ *available = rem;
+@@ -834,10 +948,16 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ if (tail_len)
+ btrfs_add_free_space(bg, tail_start, tail_len);
++ for (int i = 0; i < nr_evict; i++)
++ btrfs_add_free_space(bg, evict_start[i], evict_len[i]);
+ stripe_open_remainder_sync(bg);
+ return 0;
+ }
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ for (int i = 0; i < nr_evict; i++)
++ btrfs_add_free_space(bg, evict_start[i], evict_len[i]);
++ if (nr_evict)
++ stripe_open_remainder_sync(bg);
+
+ /* Zeroed, so the error paths can free ->live and ->written. */
+ new_run = kzalloc(sizeof(*new_run), GFP_NOFS);
+@@ -909,6 +1029,9 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+
+ if (!r || r->end != start)
+ continue;
++ /* Never grow another transaction's run (see the scan above). */
++ if (class == BTRFS_STRIPE_RUN_META && r->transid != transid)
++ continue;
+ /*
+ * Only grow as far as the run's liveness map reaches; it
+ * cannot be reallocated here (see alloc_run_live_map()).
+@@ -951,6 +1074,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ if (new_run->retained)
+ atomic64_inc(&fs_info->stripe_run_stats.reloc_run_retained);
+ new_run->owner = 0;
++ new_run->transid = transid;
+ new_run->start = start;
+ new_run->end = start + len;
+ new_run->offset = start + num_bytes;
+@@ -2274,15 +2398,20 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
+ */
+ static void warn_stripe_alloc_uncovered(struct btrfs_fs_info *info)
+ {
+- const u64 meta_bits = info->avail_metadata_alloc_bits |
+- info->avail_system_alloc_bits;
+-
+ if (!btrfs_test_opt(info, STRIPE_ALLOC))
+ return;
+
+- if (meta_bits & BTRFS_BLOCK_GROUP_RAID56_MASK)
++ /*
++ * raid56 metadata is covered now that the policy follows the chunk
++ * profile. System chunks are not: btrfs_is_stripe_meta_bg() tests
++ * the METADATA flag, and a system chunk does not carry it, so a
++ * raid56 system chunk keeps the legacy read-modify-write and its
++ * write hole. They are small and rewritten rarely, but say so
++ * rather than let the earlier "covered" message imply otherwise.
++ */
++ if (info->avail_system_alloc_bits & BTRFS_BLOCK_GROUP_RAID56_MASK)
+ btrfs_warn(info,
+-"stripe_alloc does not cover raid56 metadata: the write hole remains for metadata, consider converting it to raid1c3/raid1c4");
++"stripe_alloc does not cover raid56 system chunks: the write hole remains for them, consider converting to raid1c3/raid1c4");
+ }
+
+ /*
+@@ -2593,8 +2722,7 @@ void btrfs_open_stripe_write_abandoned(struct btrfs_block_group *bg, u64 start,
+ ASSERT(run->inflight_bytes >= num_bytes);
+ run_live_set(run, start, num_bytes, false);
+ run->inflight_bytes -= num_bytes;
+- if (open_stripe_run_drained(run) && !run->retained)
+- free_open_stripe_run(bg, run);
++ open_stripe_run_drain_reported(bg, run);
+ break;
+ }
+ }
+@@ -2619,8 +2747,7 @@ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
+ ASSERT(start + num_bytes <= run->offset);
+ ASSERT(run->inflight_bytes >= num_bytes);
+ run->inflight_bytes -= num_bytes;
+- if (open_stripe_run_drained(run) && !run->retained)
+- free_open_stripe_run(bg, run);
++ open_stripe_run_drain_reported(bg, run);
+ break;
+ }
+ }
+@@ -2727,8 +2854,7 @@ u32 btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
+ }
+ /* Under the lock: the run and the group may be gone after it. */
+ wake_up_var(&bg->open_stripe_runs);
+- if (open_stripe_run_drained(run) && !run->retained)
+- free_open_stripe_run(bg, run);
++ open_stripe_run_drain_reported(bg, run);
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ return unwritten;
+ }
+@@ -2770,6 +2896,13 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
+ continue;
+ atomic64_inc(&fs_info->stripe_run_stats.nocow_run_dead_closed);
+ }
++ /*
++ * Metadata runs are still being filled at this point in the
++ * commit and their tree blocks are not written until later;
++ * btrfs_retire_meta_stripes() closes them once they are.
++ */
++ if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
++ continue;
+ 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)
+@@ -2815,6 +2948,9 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
+ if (run->retained && open_stripe_run_drained(run) &&
+ seq != U64_MAX)
+ continue;
++ /* Metadata drains after tree writeback, not here. */
++ if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
++ continue;
+ if (run->open_seq < seq) {
+ ret = false;
+ break;
+@@ -2912,16 +3048,204 @@ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info)
+ }
+
+ /*
+- * Commit-time retirement: close every stripe run opened before this call
+- * and wait for all data IO into the stripes of those runs to complete.
+- * Must run while the committing transaction still accepts joins (before
+- * TRANS_STATE_COMMIT_DOING): tasks holding unreported run bytes can block
+- * on a join (e.g. a chunk allocation mid-delalloc), and this drain waits
+- * for their IO. Records the bumped sequence in @trans; ordered extents
+- * from runs with open_seq >= it defer their file extents to the next
+- * transaction, closing the fast-completion window this placement opens.
+- * Calls are serialized by the transaction commit; @trans may be NULL for
+- * the final cleanup call.
++ * Teardown: free every remaining stripe run and drop each group's
++ * membership reference. Needed when no final commit retired them: a mount
++ * that fails after log replay allocated tree blocks, or an unmount after a
++ * transaction abort. IO is quiesced by now, so a run still counting
++ * inflight bytes is reported and freed anyway.
++ *
++ * Ordered extents point at their runs (ordered->stripe_run), so this relies
++ * on none being left: at unmount every inode, and with it every ordered
++ * extent, is gone before close_ctree() runs, delayed iputs are drained, and
++ * on both paths the workers that complete ordered extents are stopped first.
++ */
++void btrfs_free_open_stripe_runs(struct btrfs_fs_info *fs_info)
++{
++ LIST_HEAD(bgs);
++ struct btrfs_block_group *bg, *tmp_bg;
++ unsigned long flags;
++
++ spin_lock(&fs_info->open_stripe_lock);
++ list_splice_init(&fs_info->open_stripe_bgs, &bgs);
++ spin_unlock(&fs_info->open_stripe_lock);
++
++ list_for_each_entry_safe(bg, tmp_bg, &bgs, open_stripe_bg_list) {
++ struct btrfs_open_stripe_run *run, *tmp;
++
++ list_del_init(&bg->open_stripe_bg_list);
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry_safe(run, tmp, &bg->open_stripe_runs, list) {
++ if (run->inflight_bytes)
++ btrfs_warn(fs_info,
++"stripe run %llu-%llu in block group %llu released at teardown with %llu bytes still in flight",
++ run->start, run->end, bg->start,
++ run->inflight_bytes);
++ list_del(&run->list);
++ bitmap_free(run->live);
++ kfree(run);
++ }
++ memset(bg->open_stripe, 0, sizeof(bg->open_stripe));
++ bg->stripe_open_remainder = 0;
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ stripe_open_remainder_sync(bg);
++ btrfs_put_block_group(bg);
++ }
++}
++
++/*
++ * Close and drain the metadata stripe runs once every tree block this
++ * transaction allocated has reached the disk.
++ *
++ * btrfs_retire_open_stripes() runs earlier in the commit and skips these
++ * runs, so they stay open for the commit's own tree block allocations.
++ * Closing earlier would strand blocks the commit has yet to allocate;
++ * draining earlier would wait for writes the commit has yet to issue.
++ */
++void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
++{
++ struct btrfs_block_group *bg;
++ LIST_HEAD(retire_list);
++ unsigned long flags;
++
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return;
++
++ spin_lock(&fs_info->open_stripe_lock);
++ list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
++ list_add_tail(&bg->open_stripe_retire_list, &retire_list);
++ spin_unlock(&fs_info->open_stripe_lock);
++
++ while (!list_empty(&retire_list)) {
++ struct btrfs_open_stripe_run *run;
++ bool again = true;
++
++ bg = list_first_entry(&retire_list, struct btrfs_block_group,
++ open_stripe_retire_list);
++ list_del_init(&bg->open_stripe_retire_list);
++ if (!(bg->flags & BTRFS_BLOCK_GROUP_METADATA))
++ continue;
++
++ while (again) {
++ u64 tail_start;
++ u64 tail_len = 0;
++
++ again = false;
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (run->class != BTRFS_STRIPE_RUN_META ||
++ !run->open)
++ continue;
++ /*
++ * The running transaction's runs are not ours
++ * to close: their tree blocks are written, and
++ * their stripes settled, by that transaction's
++ * own commit.
++ */
++ if (run->transid > transid)
++ continue;
++ for (int band = 0;
++ band < BTRFS_STRIPE_RUN_NR_BANDS; band++)
++ if (bg->open_stripe[BTRFS_STRIPE_RUN_META][band] == run)
++ bg->open_stripe[BTRFS_STRIPE_RUN_META][band] = NULL;
++ tail_len = close_open_stripe_run(bg, run, &tail_start);
++ again = true;
++ break;
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ if (tail_len)
++ btrfs_add_free_space(bg, tail_start, tail_len);
++ }
++ /*
++ * The closes above shrank the group's open-run remainder;
++ * fold the delta into the space_info now. While the policy
++ * is on the next allocation from this group would carry it,
++ * but after a runtime disable nothing allocates here again
++ * and the stale remainder holds metadata back for good.
++ */
++ stripe_open_remainder_sync(bg);
++
++ /*
++ * Every tree block is on disk, so end_bbio_meta_write() has
++ * reported all of them and this normally does not wait. The
++ * timeout guards against a path that frees a tree block
++ * without reporting it to its run: warn and keep the run,
++ * which costs space, rather than hang the commit.
++ */
++ if (!wait_var_event_timeout(&bg->open_stripe_runs,
++ !bg_has_undrained_meta_runs(bg, transid),
++ 60 * HZ)) {
++ btrfs_warn(fs_info,
++"metadata stripe runs in block group %llu did not drain; a tree block was freed without reporting to its run",
++ bg->start);
++ btrfs_dump_open_meta_runs(bg);
++ }
++
++ /* Drained and no longer needed for padding or merging. */
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ while (true) {
++ struct btrfs_open_stripe_run *next = NULL;
++
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (run->class == BTRFS_STRIPE_RUN_META &&
++ open_stripe_run_drained(run)) {
++ next = run;
++ break;
++ }
++ }
++ if (!next)
++ break;
++ free_open_stripe_run(bg, next);
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ }
++}
++
++/*
++ * Should this tree block be left dirty for the transaction commit to write?
++ *
++ * A stripe of tree blocks goes out as one full-stripe write only if all of
++ * its blocks are written in the same pass. Opportunistic writeback (memory
++ * reclaim, the periodic timer) does not know about stripes and would split
++ * it into read-modify-writes, so it is declined here, as zoned mode does in
++ * btrfs_check_meta_write_pointer(), and a commit is requested instead.
++ * WB_SYNC_ALL is never deferred, so a caller that needs the pages written
++ * can always get them written.
++ */
++bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
++ struct extent_buffer *eb,
++ const struct writeback_control *wbc)
++{
++ struct btrfs_block_group *bg;
++ bool defer;
++
++ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
++ return false;
++ if (wbc->sync_mode == WB_SYNC_ALL)
++ return false;
++
++ bg = btrfs_lookup_block_group(fs_info, eb->start);
++ if (!bg)
++ return false;
++ defer = btrfs_is_stripe_meta_bg(bg);
++ btrfs_put_block_group(bg);
++
++ if (defer) {
++ set_bit(BTRFS_FS_NEED_TRANS_COMMIT, &fs_info->flags);
++ wake_up_process(fs_info->transaction_kthread);
++ }
++ return defer;
++}
++
++/*
++ * Commit-time retirement: close every data stripe run opened before this
++ * call and wait for its IO to complete. Metadata runs are retired later by
++ * btrfs_retire_meta_stripes(), and persistent NOCOW runs survive. Must run
++ * while the committing transaction still accepts joins (before
++ * TRANS_STATE_COMMIT_DOING): tasks holding unreported run bytes can block on
++ * a join, and this drain waits for their IO. Records the bumped sequence in
++ * @trans; ordered extents from runs with open_seq >= it defer their file
++ * extents to the next transaction. Calls are serialized by the transaction
++ * commit; @trans is NULL for the final cleanup call.
+ */
+ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
+ struct btrfs_transaction *trans)
+@@ -3006,7 +3330,13 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ u64 total_stranded = 0;
+ int raid;
+
+- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
++ /*
++ * Data groups under stripe_alloc and metadata groups under
++ * stripe_meta both place extents in whole stripes only, so
++ * both carry trapped free space. Mixed groups are refused.
++ */
++ if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
++ BTRFS_BLOCK_GROUP_METADATA)))
+ continue;
+ down_read(&sinfo->groups_sem);
+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
+@@ -3126,7 +3456,14 @@ void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
+ bg = btrfs_lookup_block_group(fs_info, full_stripe_start);
+ if (!bg)
+ return;
+- if (!btrfs_is_stripe_alloc_bg(bg) ||
++ /*
++ * Metadata is checked on the same terms once stripe_meta places it:
++ * its runs stay open across the commit's tree building but are closed
++ * and drained before the commit ends, so a tree block write outside
++ * every live run means a stripe was revisited after the transaction
++ * that filled it finished -- the same violation as for data.
++ */
++ if ((!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg)) ||
+ test_bit(BLOCK_GROUP_FLAG_STRIPE_RELOC_USED, &bg->runtime_flags) ||
+ test_bit(BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED, &bg->runtime_flags))
+ goto out;
+@@ -4283,8 +4620,16 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
+ * btrfs_can_overcommit check here, and we need to pass in
+ * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
+ * leeway to allow us to mark this block group as read only.
++ *
++ * As for data above: a stripe_meta group's trapped bytes are
++ * already in the space_info total, do not re-provide them.
+ */
+- if (btrfs_can_overcommit(sinfo, num_bytes, BTRFS_RESERVE_NO_FLUSH))
++ u64 trapped = 0;
++
++ if (READ_ONCE(cache->stripe_unusable_ready))
++ trapped = min(READ_ONCE(cache->stripe_unusable), num_bytes);
++ if (btrfs_can_overcommit(sinfo, num_bytes - trapped,
++ BTRFS_RESERVE_NO_FLUSH))
+ ret = 0;
+ }
+
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index 211dd5feaa27e..b1cbc08ce058d 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -47,6 +47,14 @@ enum btrfs_stripe_run_class {
+ * blast radius to the owning file alone.
+ */
+ BTRFS_STRIPE_RUN_NOCOW,
++ /*
++ * Tree blocks. Kept out of the commit-time drain that settles the
++ * classes above, because metadata writeback happens later in the same
++ * commit than that drain runs: these are sealed against further
++ * allocation and drained separately once the tree blocks are on disk
++ * (see btrfs_retire_meta_stripes()).
++ */
++ BTRFS_STRIPE_RUN_META,
+ BTRFS_STRIPE_RUN_NR_CLASSES,
+ };
+
+@@ -509,9 +517,14 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
+ struct btrfs_fs_info *fs_info, u64 bytenr, u64 num_bytes,
+ u64 *open_seq);
+ void btrfs_close_bg_open_stripes(struct btrfs_block_group *bg);
++void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid);
++void btrfs_free_open_stripe_runs(struct btrfs_fs_info *fs_info);
+ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg);
+ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info);
+ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
++bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
++ struct extent_buffer *eb,
++ const struct writeback_control *wbc);
+ void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
+ u64 len);
+ bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
+@@ -585,6 +598,7 @@ void btrfs_clear_data_reloc_bg(struct btrfs_block_group *bg);
+ void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info);
+ bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr);
+ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg);
++bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg);
+ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force);
+ void btrfs_stripe_alloc_enable_work(struct work_struct *work);
+ #ifdef CONFIG_BTRFS_DEBUG
+diff --git a/fs/btrfs/block-rsv.c b/fs/btrfs/block-rsv.c
+index fd604631b9ca8..d78ae83bd00d0 100644
+--- a/fs/btrfs/block-rsv.c
++++ b/fs/btrfs/block-rsv.c
+@@ -400,7 +400,14 @@ void btrfs_update_global_block_rsv(struct btrfs_fs_info *fs_info)
+
+ block_rsv->full = (block_rsv->reserved == block_rsv->size);
+
+- if (block_rsv->size >= sinfo->total_bytes)
++ /*
++ * The global reserve must be backed by space a tree block can
++ * actually land in. Under stripe_meta that excludes the bytes
++ * trapped in partially used stripes, so compare against the usable
++ * capacity, not the raw total, and force a chunk allocation as soon
++ * as the reserve would not fit in it.
++ */
++ if (block_rsv->size >= sinfo->total_bytes - sinfo->bytes_stripe_unusable)
+ sinfo->force_alloc = CHUNK_ALLOC_FORCE;
+ spin_unlock(&block_rsv->lock);
+ spin_unlock(&sinfo->lock);
+diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
+index ad4046b12d011..a7339ea5b0028 100644
+--- a/fs/btrfs/disk-io.c
++++ b/fs/btrfs/disk-io.c
+@@ -3853,6 +3853,7 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
+ fail_sb_buffer:
+ btrfs_stop_parked_rbios(fs_info);
+ btrfs_stop_all_workers(fs_info);
++ btrfs_free_open_stripe_runs(fs_info);
+ btrfs_free_block_groups(fs_info);
+ fail_alloc:
+ btrfs_mapping_tree_free(fs_info);
+@@ -4625,6 +4626,7 @@ void __cold close_ctree(struct btrfs_fs_info *fs_info)
+ * accounting appear to be wrong because there's pending reserved bytes,
+ * so make sure we do the block group cleanup afterwards.
+ */
++ btrfs_free_open_stripe_runs(fs_info);
+ btrfs_free_block_groups(fs_info);
+
+ iput(fs_info->btree_inode);
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index cf54a9d35f1d1..25a339856b07e 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -3667,6 +3667,23 @@ int btrfs_free_tree_block(struct btrfs_trans_handle *trans,
+ if (btrfs_header_generation(buf) != trans->transid)
+ return 0;
+
++ /*
++ * A tree block this transaction allocated and never wrote gets no
++ * writeback completion to report it to its stripe run, so report it
++ * here, before the free paths diverge: if its delayed ref head already
++ * ran, the free goes through __btrfs_free_extent() and the pin
++ * machinery, which know nothing of stripe runs.
++ */
++ if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
++ bg = btrfs_lookup_block_group(fs_info, buf->start);
++ if (bg) {
++ if (btrfs_is_stripe_meta_bg(bg))
++ btrfs_open_stripe_write_abandoned(bg, buf->start,
++ buf->len);
++ btrfs_put_block_group(bg);
++ }
++ }
++
+ if (root_id != BTRFS_TREE_LOG_OBJECTID) {
+ ret = check_ref_cleanup(trans, buf->start);
+ if (!ret)
+@@ -4222,6 +4239,30 @@ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
+ !test_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &bg->runtime_flags);
+ }
+
++/*
++ * Should this block group allocate tree blocks by whole stripes?
++ *
++ * The same rule data follows: only fully free stripes are claimed, and the
++ * partial stripe left at the end of a commit is padded out rather than
++ * revisited, so no tree block write ever lands in a stripe holding earlier
++ * committed data. Not separately gated: the chunk profile already decides
++ * it. raid56 metadata has the same write hole as raid56 data and gets the
++ * same protection at the same time; metadata on any other profile has no
++ * write hole to close, and the RAID56_MASK test below means the policy
++ * simply does not apply to it. The costs metadata brings -- a stranded
++ * stripe tail per commit, and an allocation failure that aborts the
++ * transaction rather than failing one write -- are the price of covering
++ * raid56 metadata at all, and a filesystem that does not want them wants
++ * raid1c3/raid1c4 metadata instead, which is the better answer anyway.
++ */
++bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg)
++{
++ return btrfs_test_opt(bg->fs_info, STRIPE_ALLOC) &&
++ (bg->flags & BTRFS_BLOCK_GROUP_METADATA) &&
++ !(bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
++ (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
+@@ -4273,6 +4314,30 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
+ bool skip = false;
+ int ret;
+
++ /*
++ * Tree blocks take the same path as data -- whole free stripes, a
++ * frontier that padding can complete -- in their own class, and none
++ * of the steering below applies to them: there is no inode to steer
++ * by, metadata is always COW, and relocation moves tree blocks
++ * through the normal metadata allocator.
++ */
++ if (btrfs_is_stripe_meta_bg(block_group)) {
++ ret = btrfs_alloc_from_open_stripe(block_group,
++ ffe_ctl->num_bytes,
++ BTRFS_STRIPE_RUN_META,
++ &offset, &available);
++ if (ret == -ENOMEM)
++ return ret;
++ if (ret) {
++ if (available > ffe_ctl->max_extent_size)
++ ffe_ctl->max_extent_size = available;
++ return 1;
++ }
++ ffe_ctl->found_offset = offset;
++ ffe_ctl->search_start = offset;
++ return 0;
++ }
++
+ /*
+ * Soft dedication of one block group to relocation, mirroring the
+ * zoned data_reloc_bg rule: it keeps relocation's prealloc-then-
+@@ -4381,7 +4446,8 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
+ static void undo_stripe_allocation(struct btrfs_block_group *block_group,
+ struct find_free_extent_ctl *ffe_ctl)
+ {
+- if (btrfs_is_stripe_alloc_bg(block_group))
++ if (btrfs_is_stripe_alloc_bg(block_group) ||
++ btrfs_is_stripe_meta_bg(block_group))
+ btrfs_open_stripe_write_abandoned(block_group,
+ ffe_ctl->found_offset,
+ ffe_ctl->num_bytes);
+@@ -4393,7 +4459,8 @@ static int do_allocation(struct btrfs_block_group *block_group,
+ {
+ switch (ffe_ctl->policy) {
+ case BTRFS_EXTENT_ALLOC_CLUSTERED:
+- if (btrfs_is_stripe_alloc_bg(block_group))
++ if (btrfs_is_stripe_alloc_bg(block_group) ||
++ btrfs_is_stripe_meta_bg(block_group))
+ return do_allocation_stripe(block_group, ffe_ctl,
+ bg_ret);
+ return do_allocation_clustered(block_group, ffe_ctl, bg_ret);
+@@ -5222,6 +5289,28 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ btrfs_dump_stripe_groups(sinfo);
+ }
+ }
++ /*
++ * Tree block reservations are admitted against the
++ * whole-stripe supply, so a stripe_meta tree block should
++ * always find a whole stripe or an open run. If not, the
++ * transaction aborts: log the counters.
++ */
++ if (!is_data && btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
++ (flags & BTRFS_BLOCK_GROUP_RAID56_MASK)) {
++ struct btrfs_space_info *sinfo;
++
++ sinfo = btrfs_find_space_info(fs_info, flags);
++ if (sinfo)
++ btrfs_warn_rl(fs_info,
++ "stripe_meta: tree block allocation of %llu bytes returned ENOSPC: claimable %llu open %llu trapped %llu may_use %llu reserved %llu total %llu",
++ num_bytes,
++ sinfo->bytes_stripe_claimable,
++ sinfo->bytes_stripe_open,
++ sinfo->bytes_stripe_unusable,
++ sinfo->bytes_may_use,
++ sinfo->bytes_reserved,
++ sinfo->total_bytes);
++ }
+ }
+
+ return ret;
+diff --git a/fs/btrfs/extent_io.c b/fs/btrfs/extent_io.c
+index 5ff630630490e..188e167848f91 100644
+--- a/fs/btrfs/extent_io.c
++++ b/fs/btrfs/extent_io.c
+@@ -2392,6 +2392,16 @@ static void end_bbio_meta_write(struct btrfs_bio *bbio)
+ if (bbio->bio.bi_status != BLK_STS_OK)
+ set_btree_ioerr(eb);
+
++ /*
++ * Tell the stripe run this tree block is written. Data reports the
++ * same thing from ordered extent completion; metadata has no ordered
++ * extent, so without this the run's inflight bytes would never come
++ * back down and nothing waiting on it could ever proceed. Reported
++ * on error too: the bytes will not be written again, and a run that
++ * cannot drain is worse than one that drains after a failed write.
++ */
++ btrfs_open_stripe_write_done_bytenr(eb->fs_info, eb->start, eb->len);
++
+ /*
+ * Clear writeback on the buffer's own folios. The bio may carry the
+ * shared zero page instead (EXTENT_BUFFER_ZONED_ZEROOUT), so iterate
+@@ -2653,6 +2663,14 @@ int btree_writepages(struct address_space *mapping, struct writeback_control *wb
+ while ((eb = eb_batch_next(&batch)) != NULL) {
+ ctx.eb = eb;
+
++ /*
++ * Leave it dirty for the commit, so its stripe goes
++ * out in one piece instead of once per writeback
++ * pass.
++ */
++ if (btrfs_defer_stripe_meta_write(fs_info, eb, wbc))
++ continue;
++
+ ret = write_meta_extent_buffer(&ctx, wbc);
+ if (ret == -EBUSY) {
+ ret = 0;
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index eaed680e362dc..362e31f8be3d5 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -1687,7 +1687,7 @@ static void stripe_trim_claimable(struct btrfs_block_group *bg, u64 bytenr,
+ {
+ s64 delta;
+
+- if (!btrfs_is_stripe_alloc_bg(bg))
++ if (!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg))
+ return;
+ if (!READ_ONCE(bg->stripe_unusable_ready) || !size)
+ return;
+@@ -2348,7 +2348,7 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
+ u64 trapped, claimable, nstripes;
+ u32 *freep;
+
+- if (!btrfs_is_stripe_alloc_bg(bg))
++ if (!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg))
+ return;
+ if (READ_ONCE(bg->stripe_unusable_ready))
+ return;
+@@ -2395,7 +2395,7 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+ u64 trapped;
+ u64 claimable;
+
+- if (!btrfs_is_stripe_alloc_bg(bg))
++ if (!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg))
+ return;
+
+ spin_lock(&ctl->tree_lock);
+@@ -2568,7 +2568,7 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
+ u64 nstripes;
+ u32 *freep;
+
+- if (!btrfs_is_stripe_alloc_bg(bg))
++ if (!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg))
+ return;
+
+ nstripes = stripe_unusable_nstripes(bg);
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index e1fee64396457..c2ba1f3e7a25c 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -3581,6 +3581,8 @@ static bool need_read_stripe_sectors(struct btrfs_raid_bio *rbio)
+ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
+ {
+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ struct btrfs_block_group *bg;
++ bool covered = false;
+
+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
+ return;
+@@ -3590,6 +3592,21 @@ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
+ return;
+
+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw);
++ /*
++ * A raid56 metadata group under stripe_meta is covered: its
++ * read-modify-writes are partial writes inside one transaction's
++ * run, counted by the audit as meta_rmw_cur, and the audit warns
++ * by itself should one ever touch a committed block. Only system
++ * chunks and mixed groups are the uncovered case this message is
++ * about.
++ */
++ bg = btrfs_lookup_block_group(fs_info, rbio->bioc->full_stripe_logical);
++ if (bg) {
++ covered = btrfs_is_stripe_meta_bg(bg);
++ btrfs_put_block_group(bg);
++ }
++ if (covered)
++ return;
+ btrfs_warn_rl(fs_info,
+ "read-modify-write of full stripe %llu: this block group is not covered by stripe_alloc, the raid56 write hole applies to it",
+ rbio->bioc->full_stripe_logical);
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 609e3e4462a1c..1812ba343ca14 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1188,7 +1188,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
+ /* Indexed by enum btrfs_stripe_run_class. */
+ static const char * const class_names[] = {
+- "cow", "reloc", "log", "nocow",
++ "cow", "reloc", "log", "nocow", "meta",
+ };
+ int live_by_class[BTRFS_STRIPE_RUN_NR_CLASSES];
+ int open_runs[BTRFS_STRIPE_RUN_NR_CLASSES];
+diff --git a/fs/btrfs/tests/free-space-tests.c b/fs/btrfs/tests/free-space-tests.c
+index 5da244e148321..10fd9d6b344b3 100644
+--- a/fs/btrfs/tests/free-space-tests.c
++++ b/fs/btrfs/tests/free-space-tests.c
+@@ -1478,6 +1478,13 @@ static int test_open_stripe(struct btrfs_block_group *cache, u32 sectorsize)
+ }
+ ret = 0;
+ out:
++ /*
++ * The relocation run is retained after retirement, as it is until
++ * relocation ends, and keeps the group on fs_info->open_stripe_bgs.
++ * Nothing here ends a relocation, so free what is left as unmount
++ * does, or the run and the group's reference leak.
++ */
++ btrfs_free_open_stripe_runs(fs_info);
+ cache->full_stripe_len = orig_fsl;
+ return ret;
+ }
+diff --git a/fs/btrfs/transaction.c b/fs/btrfs/transaction.c
+index 6bbcf42121461..aa251b32b1dcf 100644
+--- a/fs/btrfs/transaction.c
++++ b/fs/btrfs/transaction.c
+@@ -23,6 +23,7 @@
+ #include "dev-replace.h"
+ #include "qgroup.h"
+ #include "block-group.h"
++#include "free-space-cache.h"
+ #include "raid56.h"
+ #include "space-info.h"
+ #include "fs.h"
+@@ -1346,6 +1347,13 @@ static int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans)
+ blk_start_plug(&plug);
+ ret = btrfs_write_marked_extents(fs_info, dirty_pages, EXTENT_DIRTY);
+ blk_finish_plug(&plug);
++ /*
++ * Everything this commit is going to submit has been submitted, so any
++ * rbio still parked waiting for a sibling is waiting for one that will
++ * never come. Kick them down now rather than let the wait below sit
++ * out their park deadline.
++ */
++ btrfs_flush_parked_rbios(fs_info, 0, U64_MAX, true);
+ ret2 = btrfs_wait_extents(fs_info, dirty_pages);
+
+ if (ret)
+@@ -2664,6 +2672,16 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
+ goto scrub_continue;
+ }
+
++ /*
++ * Every tree block this transaction allocated is now on disk, so its
++ * metadata stripe runs can be closed and drained. This is the point
++ * the earlier btrfs_retire_open_stripes() deliberately left them
++ * alone for: closing before here would strand blocks the commit had
++ * not allocated yet, draining before here would wait on writes it had
++ * not issued.
++ */
++ btrfs_retire_meta_stripes(fs_info, cur_trans->transid);
++
+ ret = write_all_supers(trans);
+ /*
+ * the super is written, we can safely allow the tree-loggers
+diff --git a/fs/btrfs/tree-log.c b/fs/btrfs/tree-log.c
+index d902d169680a4..3a2391b616694 100644
+--- a/fs/btrfs/tree-log.c
++++ b/fs/btrfs/tree-log.c
+@@ -2938,6 +2938,28 @@ static int clean_log_buffer(struct btrfs_trans_handle *trans,
+ wait_on_extent_buffer_writeback(eb);
+ btrfs_tree_unlock(eb);
+
++ /*
++ * A log tree block discarded before it was ever written has no
++ * writeback completion coming: nothing else will report it to its
++ * stripe run, and an unreported allocation keeps the run's inflight
++ * count from ever draining. Report it abandoned here. Written
++ * blocks were already reported by their write endio (the writeback
++ * wait above means no submission is still in flight), and log blocks
++ * from a previous mount walked during log replay carry the WRITTEN
++ * flag on disk, so both are excluded.
++ */
++ if (!btrfs_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN)) {
++ struct btrfs_block_group *stripe_bg;
++
++ stripe_bg = btrfs_lookup_block_group(fs_info, eb->start);
++ if (stripe_bg) {
++ if (btrfs_is_stripe_meta_bg(stripe_bg))
++ btrfs_open_stripe_write_abandoned(stripe_bg,
++ eb->start, eb->len);
++ btrfs_put_block_group(stripe_bg);
++ }
++ }
++
+ if (trans) {
+ int ret;
+
+--
+2.47.3
+
+++ /dev/null
-From 40ab3d57819b5a60d8a52de1c2eb33932ddf8f4e Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 24 Sep 2026 07:55:39 -0400
-Subject: [RFC PATCH 069/116] btrfs: stripe_alloc: end the commit-time and log
- drains on an errored filesystem too
-To: linux-btrfs@vger.kernel.org
-
-The previous change let btrfs_retire_block_group_stripes() give up its
-drain wait when the filesystem has gone into error, because the ordered
-extents holding a run's bytes in flight are not torn down until unmount
-and the wait would otherwise never return.
-
-btrfs_retire_open_stripes() has the same wait with the same exposure, in
-two worse places: the transaction commit, where it would park the
-transaction kthread, and the final cleanup call from close_ctree(), where
-it would wedge the unmount on its own account. The unmount that hung on
-2026-09-23 had cancel_work_sync() waiting on the parked reclaim worker,
-but this wait would have held it just the same. A directed reproducer
-that stalled writeback under a balance found the balance sitting in this
-function, not in the per-block-group one. The wake added to
-__btrfs_handle_fs_error() does not help by itself: wait_var_event()
-re-evaluates its condition, which did not know about the error.
-
-The fsync carry path's wait in btrfs_log_settle_stripes() is the third
-instance; the log commit is going to fail on an errored filesystem in any
-case, so do not sleep for IO first.
-
-Add the error term to both, and warn at retirement when runs are left in
-flight, as the per-block-group path does.
-
-Assisted-by: Claude:claude-fable-5-1
----
- fs/btrfs/block-group.c | 16 ++++++++++++++--
- 1 file changed, 14 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 9fc41fe73cb06..289ec278ac4f8 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2131,7 +2131,8 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- if (flush_len) {
- btrfs_flush_parked_rbios(fs_info, flush_start, flush_len, false);
- wait_var_event(&bg->open_stripe_runs,
-- stripe_log_range_settled(bg, bytenr));
-+ stripe_log_range_settled(bg, bytenr) ||
-+ BTRFS_FS_ERROR(fs_info));
- }
- btrfs_put_block_group(bg);
- }
-@@ -2909,8 +2910,19 @@ void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
- while (!list_empty(&retire_list)) {
- bg = list_first_entry(&retire_list, struct btrfs_block_group,
- open_stripe_retire_list);
-+ /*
-+ * Same escape as btrfs_retire_block_group_stripes(): on an
-+ * errored filesystem the bytes in flight may never be
-+ * reported, and this wait sits in the transaction commit and
-+ * in the teardown call from close_ctree().
-+ */
- wait_var_event(&bg->open_stripe_runs,
-- bg_open_stripes_settled(bg, seq));
-+ bg_open_stripes_settled(bg, seq) ||
-+ BTRFS_FS_ERROR(fs_info));
-+ if (BTRFS_FS_ERROR(fs_info) && !bg_open_stripes_settled(bg, seq))
-+ btrfs_warn(fs_info,
-+"block group %llu has stripe runs still in flight at retirement after a filesystem error; not waiting for them",
-+ bg->start);
- list_del_init(&bg->open_stripe_retire_list);
-
- /* Drop the membership if the group has no runs left. */
---
-2.47.3
-
--- /dev/null
+From aa8b778a51434b49ca822ad7c66f8e0e5eeb2bef Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 1 Oct 2026 12:14:49 -0400
+Subject: [RFC PATCH 69/85] btrfs: stripe_alloc: keep a stripe in the rbio
+ cache until its run has written all of it (stripe_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: keep a stripe in the rbio cache until
+its run has written all of it" (earlier in this series) that need code
+from "btrfs: stripe_meta: allocate tree blocks by whole stripes", which
+comes after it in this series: they are applied here, once "btrfs:
+stripe_meta: allocate tree blocks by whole stripes" is in, instead of
+with the rest of "btrfs: stripe_alloc: keep a stripe in the rbio cache
+until its run has written all of it".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index d29803e43bd56..45a09c6b6fdfd 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -3082,6 +3082,7 @@ void btrfs_free_open_stripe_runs(struct btrfs_fs_info *fs_info)
+ run->inflight_bytes);
+ list_del(&run->list);
+ bitmap_free(run->live);
++ bitmap_free(run->written);
+ kfree(run);
+ }
+ memset(bg->open_stripe, 0, sizeof(bg->open_stripe));
+--
+2.47.3
+
+++ /dev/null
-From bda94d6e75730c4a28cbfcf5004ac9c16c644626 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 29 Sep 2026 05:29:38 -0400
-Subject: [RFC PATCH 070/116] btrfs: stripe_alloc: compact mostly live groups
- instead of skipping them
-To: linux-btrfs@vger.kernel.org
-
-Reclaim only takes a stripe_alloc / stripe_meta group whose live data is
-below bg_reclaim_threshold: moving everything out of a fuller group costs
-nearly a group's worth of writes and needs that much claimable space
-elsewhere. But trapped free space is not confined to emptyish groups.
-Under steady COW churn the metadata groups stay mostly live while every
-commit leaves partially used stripes behind, and on a raid6 metadata fill
-the trapped share of the metadata free space reached 88% with no group
-ever falling below the threshold: reclaim never ran, and the space never
-came back.
-
-A group like that does not need all of its data moved. The trapped space
-is in its partially used stripes; moving only the extents in those
-stripes makes them whole again. An extent spanning several stripes frees
-its bytes in all of them when it moves, so the stripes it shares with
-others must move too, transitively: the selection is the closure of the
-partial stripes under "shares an extent with". A tree block never spans a
-stripe, so for a metadata group it is just the partial stripes.
-
-Compaction runs from the reclaim worker, for a group whose live data does
-not fall below the threshold, once its trapped space reaches
-stripe_compact percent of the whole group. (The test whole relocation
-uses, trapped share of the FREE space, never admits a mostly live group:
-its little free space is mostly whole stripes.)
-
- - The group goes read-only as for relocation. After a commit, so the
- free space cache and the extent tree's commit root agree, the partial
- stripes are read from the free space cache and the closure is found
- with a union-find over the group's stripes in one pass over its extent
- items, each union carrying the live bytes of its extents.
-
- - If the closure would move more than half the group's live bytes, the
- group is relocated whole and removed instead: that costs about the
- same and also gives back the group's raw space.
-
- - Otherwise relocation runs with find_next_extent() skipping every
- extent outside the selection, through both data stages, and the group
- is committed (so what moved out is unpinned) and made writable again
- instead of removed. replace_file_extents() rewrites only the pointers
- to selected extents: the others did not move and have no new location
- (a leaf referencing both kinds is common).
-
-Balance, device shrink and removal still relocate whole groups
-(btrfs_relocate_chunk() is unchanged; btrfs_compact_chunk() is the new
-entry point). sysfs stripe_compact is the trapped percent of a group's
-length that makes it a candidate (default 10; 0 turns compaction off),
-and stripe_run_stats counts compaction passes, fallbacks to whole
-relocation, stripes evacuated and bytes moved.
-
-The destination is ordinary relocation's: the moved extents need whole
-claimable stripes in other groups, and a commit during the pass can leave
-a partial stripe at the tail of a relocation run there. The admission
-test for compaction therefore asks for half the group's live bytes
-claimable elsewhere, the most a compaction can move.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 42 +++++-
- fs/btrfs/disk-io.c | 1 +
- fs/btrfs/free-space-cache.c | 141 ++++++++++++++----
- fs/btrfs/free-space-cache.h | 3 +
- fs/btrfs/fs.h | 14 ++
- fs/btrfs/relocation.c | 276 +++++++++++++++++++++++++++++++++++-
- fs/btrfs/relocation.h | 2 +-
- fs/btrfs/sysfs.c | 44 +++++-
- fs/btrfs/volumes.c | 28 +++-
- fs/btrfs/volumes.h | 2 +
- 10 files changed, 511 insertions(+), 42 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 289ec278ac4f8..e39f266016306 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -4802,6 +4802,7 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- u64 reserved;
- u64 old_total;
- int ret = 0;
-+ bool compact = false;
-
- /*
- * A stripe_alloc / stripe_meta group's live extents can only move into
-@@ -4815,9 +4816,13 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- */
- if (btrfs_is_stripe_alloc_bg(bg) || btrfs_is_stripe_meta_bg(bg)) {
- u64 elsewhere = READ_ONCE(space_info->bytes_stripe_claimable);
-+ u64 need = READ_ONCE(bg->used);
-
-+ /* Compaction moves at most half of it. */
-+ if (btrfs_stripe_bg_wants_compaction(bg))
-+ need /= 2;
- elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
-- if (elsewhere < READ_ONCE(bg->used)) {
-+ if (elsewhere < need) {
- struct btrfs_trans_handle *trans;
-
- trans = btrfs_join_transaction(fs_info->tree_root);
-@@ -4889,10 +4894,19 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- * the first place.
- */
- if (!should_reclaim_block_group(bg, bg->length)) {
-- spin_unlock(&bg->lock);
-- spin_unlock(&space_info->lock);
-- up_write(&space_info->groups_sem);
-- return 0;
-+ /*
-+ * Too full to relocate whole. A stripe_alloc / stripe_meta
-+ * group whose free space is trapped in partially used stripes
-+ * can still be compacted: only the extents in those stripes
-+ * move.
-+ */
-+ compact = btrfs_stripe_bg_wants_compaction(bg);
-+ if (!compact) {
-+ spin_unlock(&bg->lock);
-+ spin_unlock(&space_info->lock);
-+ up_write(&space_info->groups_sem);
-+ return 0;
-+ }
- }
-
- spin_unlock(&bg->lock);
-@@ -4940,7 +4954,23 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- spin_unlock(&bg->lock);
-
- trace_btrfs_reclaim_block_group(bg);
-- ret = btrfs_relocate_chunk(fs_info, bg->start, false);
-+ if (compact) {
-+ bool compacted;
-+
-+ ret = btrfs_compact_chunk(fs_info, bg->start, &compacted);
-+ /*
-+ * Compacted, the group stays: drop our read-only hold. It
-+ * gave back trapped space, not a chunk; what moved is counted
-+ * in stripe_run_stats.
-+ */
-+ if (!ret && compacted) {
-+ btrfs_dec_block_group_ro(bg);
-+ used = 0;
-+ reserved = 0;
-+ }
-+ } else {
-+ ret = btrfs_relocate_chunk(fs_info, bg->start, false);
-+ }
- if (btrfs_is_zoned(fs_info) && ret == -EAGAIN) {
- btrfs_dec_block_group_ro(bg);
- btrfs_debug(fs_info, "deferring reclaim of chunk %llu", bg->start);
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index 8c5070a598750..3d3a51cd963d0 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -2806,6 +2806,7 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
- INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
- INIT_WORK(&fs_info->stripe_alloc_enable_work, btrfs_stripe_alloc_enable_work);
- fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
-+ fs_info->stripe_compact = 10;
- fs_info->stripe_park_sync_timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
- spin_lock_init(&fs_info->open_stripe_lock);
- spin_lock_init(&fs_info->delalloc_root_lock);
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 2c3e32aea935c..f0c3187554deb 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2048,26 +2048,18 @@ static u64 stripe_unusable_nstripes(const struct btrfs_block_group *bg)
- }
-
- /*
-- * Total trapped free bytes (free space in partially filled stripes) over the
-- * whole block group -- the authoritative definition of stripe_unusable,
-- * recomputed at cache-in and after each commit that changed the group's free
-- * space. Every free byte is accumulated into a per-stripe array (so a stripe
-- * whose total free is neither zero nor a whole stripe is partially filled, and
-- * its free bytes are trapped). @freep is a zeroed array of stripe_unusable_
-- * nstripes() u32 entries the caller allocates before taking the tree lock (it
-- * can be large); this runs with ctl->tree_lock held.
-+ * Accumulate every free byte of @bg into its stripe's slot of @freep (a zeroed
-+ * array of stripe_unusable_nstripes() entries). Returns the bytes counted.
-+ * Caller holds ctl->tree_lock.
- */
--static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
-- u64 nstripes)
-+static u64 stripe_free_walk(struct btrfs_block_group *bg, u32 *freep)
- {
- struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
- const u32 unit = bg->fs_info->sectorsize;
- const u64 fsl = bg->full_stripe_len;
- const u64 bg_start = bg->start;
- u64 counted = 0;
-- u64 trapped = 0;
- struct rb_node *n;
-- u64 i;
-
- lockdep_assert_held(&ctl->tree_lock);
-
-@@ -2096,6 +2088,29 @@ static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
- e->offset + e->bytes, &counted);
- }
- }
-+ return counted;
-+}
-+
-+/*
-+ * Total trapped free bytes (free space in partially filled stripes) over the
-+ * whole block group -- the authoritative definition of stripe_unusable,
-+ * recomputed at cache-in and after each commit that changed the group's free
-+ * space. Every free byte is accumulated into a per-stripe array (so a stripe
-+ * whose total free is neither zero nor a whole stripe is partially filled, and
-+ * its free bytes are trapped). @freep is a zeroed array of stripe_unusable_
-+ * nstripes() u32 entries the caller allocates before taking the tree lock (it
-+ * can be large); this runs with ctl->tree_lock held.
-+ */
-+static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
-+ u64 nstripes)
-+{
-+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-+ const u64 fsl = bg->full_stripe_len;
-+ u64 counted;
-+ u64 trapped = 0;
-+ u64 i;
-+
-+ counted = stripe_free_walk(bg, freep);
-
- /* Every free byte was distributed to exactly one stripe (debug check). */
- ASSERT(counted == ctl->free_space,
-@@ -2115,6 +2130,38 @@ static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
- return trapped;
- }
-
-+/*
-+ * For compaction: set in @map (@nstripes bits, zeroed by the caller) every
-+ * stripe of @bg that holds free space but not a whole stripe of it. Returns
-+ * how many, or a negative errno.
-+ */
-+s64 btrfs_stripe_partial_map(struct btrfs_block_group *bg, unsigned long *map,
-+ u64 nstripes)
-+{
-+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-+ const u64 fsl = bg->full_stripe_len;
-+ s64 found = 0;
-+ u32 *freep;
-+ u64 i;
-+
-+ if (nstripes != stripe_unusable_nstripes(bg))
-+ return -EINVAL;
-+ freep = kvcalloc(nstripes, sizeof(*freep), GFP_NOFS);
-+ if (!freep)
-+ return -ENOMEM;
-+ spin_lock(&ctl->tree_lock);
-+ stripe_free_walk(bg, freep);
-+ spin_unlock(&ctl->tree_lock);
-+ for (i = 0; i < nstripes; i++) {
-+ if (freep[i] && freep[i] < fsl) {
-+ set_bit(i, map);
-+ found++;
-+ }
-+ }
-+ kvfree(freep);
-+ return found;
-+}
-+
- /*
- * The legacy allocator parks a group's free space in an allocation cluster
- * (for a metadata group, its whole initial extent), where the group's own
-@@ -2234,18 +2281,26 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
- * zoned's zone_unusable reclaim: once enough of the group's FREE space is
- * trapped in partially used stripes (zoned compares with the capacity, but a
- * stripe group also holds claimable whole stripes), relocation packs the live
-- * extents into whole stripes elsewhere and frees the group. Only groups
-- * whose live data is below the same threshold are cheap enough to move, and
-+ * extents into whole stripes elsewhere. A group whose live data is below the
-+ * same threshold is cheap enough to move whole and free; a fuller one is
-+ * compacted instead (btrfs_compact_chunk()): only the extents in its partial
-+ * stripes move, at most half its live bytes, and the group stays. Either way
- * only when that data fits in the claimable supply of the OTHER groups:
- * relocation needs whole stripes too, and a group queued while there is
- * nowhere to move it starves writers with read-only transitions and fails
-- * each time at the fill edge. The worker re-checks with
-- * should_reclaim_block_group(). Reads the counters without locks; the
-- * commit-time rescan calls it with fresh values, the cleaner's periodic
-- * re-evaluation with slightly stale ones, and either error is caught by
-- * the worker.
-+ * each time at the fill edge. The worker re-checks. Reads the counters
-+ * without locks; the commit-time rescan calls it with fresh values, the
-+ * cleaner's periodic re-evaluation with slightly stale ones, and either
-+ * error is caught by the worker.
- */
--bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
-+enum stripe_reclaim_kind {
-+ STRIPE_RECLAIM_NONE,
-+ STRIPE_RECLAIM_RELOCATE,
-+ STRIPE_RECLAIM_COMPACT,
-+};
-+
-+static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
-+ bool check_room)
- {
- struct btrfs_space_info *sinfo = bg->space_info;
- const int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
-@@ -2257,21 +2312,55 @@ bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
- * relocating the group would only force that.
- */
- const u64 trapped = unusable - min(unusable, READ_ONCE(bg->stripe_stranded));
-+ enum stripe_reclaim_kind kind = STRIPE_RECLAIM_RELOCATE;
-+ u64 need = used;
- u64 elsewhere;
- u64 promised;
-
- if (thresh <= 0 || bg->ro || !READ_ONCE(bg->stripe_unusable_ready))
-- return false;
-- if (trapped < mult_perc(bg->length - min(used, bg->length), thresh))
-- return false;
-- if (used >= mult_perc(bg->length, thresh))
-- return false;
-+ return STRIPE_RECLAIM_NONE;
-+ if (used >= mult_perc(bg->length, thresh)) {
-+ /*
-+ * Too full to move whole: compact it once its trapped space is
-+ * stripe_compact percent of the whole group. Measured against
-+ * the free space, as for a whole relocation below, a mostly
-+ * live group never qualified: its little free space is mostly
-+ * whole stripes, so the trapped share of it stays small while
-+ * the trapped bytes grow.
-+ */
-+ const u32 pct = READ_ONCE(bg->fs_info->stripe_compact);
-+
-+ if (!pct || trapped < mult_perc(bg->length, pct))
-+ return STRIPE_RECLAIM_NONE;
-+ kind = STRIPE_RECLAIM_COMPACT;
-+ need = used / 2;
-+ } else if (trapped < mult_perc(bg->length - min(used, bg->length),
-+ thresh)) {
-+ return STRIPE_RECLAIM_NONE;
-+ }
-+ if (!check_room)
-+ return kind;
- elsewhere = READ_ONCE(sinfo->bytes_stripe_claimable);
- promised = READ_ONCE(sinfo->bytes_may_use) +
- READ_ONCE(sinfo->bytes_stripe_margin);
- elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
- elsewhere -= min(elsewhere, promised);
-- return elsewhere >= used;
-+ return elsewhere >= need ? kind : STRIPE_RECLAIM_NONE;
-+}
-+
-+bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
-+{
-+ return stripe_bg_reclaim_kind(bg, true) != STRIPE_RECLAIM_NONE;
-+}
-+
-+/*
-+ * For the reclaim worker, about a group it took: compact it rather than
-+ * relocate it whole. Room is not re-checked; the worker makes room first,
-+ * and relocation fails cleanly without it.
-+ */
-+bool btrfs_stripe_bg_wants_compaction(struct btrfs_block_group *bg)
-+{
-+ return stripe_bg_reclaim_kind(bg, false) == STRIPE_RECLAIM_COMPACT;
- }
-
- /*
-diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
-index 330bb988f9592..09c41eeb48854 100644
---- a/fs/btrfs/free-space-cache.h
-+++ b/fs/btrfs/free-space-cache.h
-@@ -119,6 +119,9 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *block_grou
- void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
- void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
- bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg);
-+bool btrfs_stripe_bg_wants_compaction(struct btrfs_block_group *bg);
-+s64 btrfs_stripe_partial_map(struct btrfs_block_group *bg, unsigned long *map,
-+ u64 nstripes);
- void btrfs_dump_free_space(struct btrfs_block_group *block_group,
- u64 bytes);
- int btrfs_find_space_cluster(struct btrfs_block_group *block_group,
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 50235cf99e1e9..aa0cc290a753a 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -924,10 +924,24 @@ struct btrfs_fs_info {
- atomic64_t strand_rescan_marks;
- /* persistent nocow runs closed at commit for being dead */
- atomic64_t nocow_run_dead_closed;
-+ /* compaction passes that kept their group */
-+ atomic64_t compact_runs;
-+ /* compaction plans over the cap, relocated whole instead */
-+ atomic64_t compact_fallbacks;
-+ /* stripes evacuated by compaction (closure included) */
-+ atomic64_t compact_stripes;
-+ /* live bytes compaction moved */
-+ atomic64_t compact_bytes;
- } stripe_run_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
- u32 stripe_rmw_prop;
-+ /*
-+ * Reclaim compacts a mostly live stripe_alloc / stripe_meta group once
-+ * this percent of its length is trapped; 0 = never (sysfs
-+ * stripe_compact, default 10). See btrfs_compact_chunk().
-+ */
-+ u32 stripe_compact;
- /*
- * Parking deadlines in ms, tunable through sysfs so the constants
- * can be swept against a workload instead of rebuilt for each
-diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
-index ed44c1cd99f6a..d9f218e128f6c 100644
---- a/fs/btrfs/relocation.c
-+++ b/fs/btrfs/relocation.c
-@@ -180,8 +180,41 @@ struct reloc_control {
- bool found_file_extent;
-
- refcount_t refs;
-+
-+ /*
-+ * Compaction: the stripes whose extents are relocated (compact_plan());
-+ * NULL relocates the whole group.
-+ */
-+ unsigned long *compact_map;
-+ u64 compact_fsl;
- };
-
-+/*
-+ * Stripe compaction. A stripe_alloc / stripe_meta group whose free space is
-+ * trapped in partially used stripes, but whose live data mostly fills whole
-+ * ones, does not need all of that data moved to get the space back: only the
-+ * extents in the partial stripes, and -- since moving an extent frees its
-+ * bytes in every stripe it spans -- the extents sharing a stripe with those,
-+ * transitively. compact_plan() selects that closure, find_next_extent()
-+ * skips every extent outside it, and the group is kept and made writable
-+ * again instead of removed. A tree block never spans a stripe, so for a
-+ * metadata group the closure is the partial stripes themselves.
-+ */
-+static bool compact_selected(const struct reloc_control *rc, u64 start, u64 len)
-+{
-+ const struct btrfs_block_group *bg = rc->block_group;
-+ u64 first, last;
-+
-+ if (!rc->compact_map)
-+ return true;
-+ if (start < bg->start || !len)
-+ return false;
-+ first = div64_u64(start - bg->start, rc->compact_fsl);
-+ last = div64_u64(min(start + len, bg->start + bg->length) - 1 - bg->start,
-+ rc->compact_fsl);
-+ return find_next_bit(rc->compact_map, last + 1, first) <= last;
-+}
-+
- static struct reloc_control *get_reloc_control(struct btrfs_fs_info *fs_info)
- {
- struct reloc_control *rc;
-@@ -226,6 +259,7 @@ static void put_reloc_control(struct reloc_control *rc)
- if (rc->block_group)
- btrfs_put_block_group(rc->block_group);
-
-+ bitmap_free(rc->compact_map);
- kfree(rc);
- }
- }
-@@ -974,8 +1008,14 @@ int replace_file_extents(struct btrfs_trans_handle *trans,
- num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
- if (bytenr == 0)
- continue;
-+ /*
-+ * Only the extents that moved have a new location: under
-+ * compaction that is the selected ones, not every extent in
-+ * the group.
-+ */
- if (!in_range(bytenr, rc->block_group->start,
-- rc->block_group->length))
-+ rc->block_group->length) ||
-+ !compact_selected(rc, bytenr, num_bytes))
- continue;
-
- /*
-@@ -3537,6 +3577,11 @@ int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
- else
- rc->search_start = key.objectid +
- fs_info->nodesize;
-+ if (!compact_selected(rc, key.objectid,
-+ rc->search_start - key.objectid)) {
-+ path->slots[0]++;
-+ goto next;
-+ }
- memcpy(extent_key, &key, sizeof(key));
- return 0;
- }
-@@ -5426,18 +5471,210 @@ static int do_nonremap_reloc(struct btrfs_fs_info *fs_info, bool verbose,
- rc->extents_found, stage_to_string(finishes_stage));
- }
-
-- WARN_ON(rc->block_group->pinned > 0);
-- WARN_ON(rc->block_group->reserved > 0);
-- WARN_ON(rc->block_group->used > 0);
-+ /* A compacted group keeps the extents it was not asked to move. */
-+ if (!rc->compact_map) {
-+ WARN_ON(rc->block_group->pinned > 0);
-+ WARN_ON(rc->block_group->reserved > 0);
-+ WARN_ON(rc->block_group->used > 0);
-+ }
-
- return 0;
- }
-
-+static u32 compact_root(u32 *parent, u32 x)
-+{
-+ while (parent[x] != x) {
-+ parent[x] = parent[parent[x]];
-+ x = parent[x];
-+ }
-+ return x;
-+}
-+
-+/*
-+ * Select the stripes to evacuate: the partially used ones, and every stripe
-+ * joined to one of them through an extent spanning both. A union-find over
-+ * the group's stripes, in one pass over its extent items in the commit root,
-+ * each union carrying the live bytes of its extents. Sets rc->compact_map;
-+ * returns the live bytes the selection moves in @moved and the number of
-+ * stripes selected in @nsel.
-+ */
-+static int compact_plan(struct reloc_control *rc, u64 *moved, u64 *nsel)
-+{
-+ struct btrfs_block_group *bg = rc->block_group;
-+ struct btrfs_fs_info *fs_info = bg->fs_info;
-+ const u64 fsl = bg->full_stripe_len;
-+ const u64 end = bg->start + bg->length;
-+ BTRFS_PATH_AUTO_FREE(path);
-+ struct btrfs_key key;
-+ unsigned long *map = NULL;
-+ unsigned long *sel = NULL;
-+ u32 *parent = NULL;
-+ u64 *bytes = NULL;
-+ u64 nstripes;
-+ s64 npartial;
-+ u64 i;
-+ int ret;
-+
-+ *moved = 0;
-+ *nsel = 0;
-+ if (!fsl)
-+ return -EINVAL;
-+ nstripes = div64_u64(bg->length + fsl - 1, fsl);
-+ if (nstripes > U32_MAX)
-+ return -EINVAL;
-+
-+ path = btrfs_alloc_path();
-+ map = bitmap_zalloc(nstripes, GFP_NOFS);
-+ sel = bitmap_zalloc(nstripes, GFP_NOFS);
-+ parent = kvmalloc_array(nstripes, sizeof(*parent), GFP_NOFS);
-+ bytes = kvcalloc(nstripes, sizeof(*bytes), GFP_NOFS);
-+ if (!path || !map || !sel || !parent || !bytes) {
-+ ret = -ENOMEM;
-+ goto out;
-+ }
-+ npartial = btrfs_stripe_partial_map(bg, map, nstripes);
-+ if (npartial < 0) {
-+ ret = npartial;
-+ goto out;
-+ }
-+ for (i = 0; i < nstripes; i++)
-+ parent[i] = i;
-+
-+ path->search_commit_root = true;
-+ path->skip_locking = true;
-+ path->need_commit_sem = true;
-+ key.objectid = bg->start;
-+ key.type = 0;
-+ key.offset = 0;
-+ ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
-+ if (ret < 0)
-+ goto out;
-+ while (1) {
-+ struct extent_buffer *leaf = path->nodes[0];
-+ u64 len;
-+ u32 a, b, r;
-+
-+ if (path->slots[0] >= btrfs_header_nritems(leaf)) {
-+ ret = btrfs_next_leaf(rc->extent_root, path);
-+ if (ret < 0)
-+ goto out;
-+ if (ret > 0)
-+ break;
-+ cond_resched();
-+ continue;
-+ }
-+ btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
-+ path->slots[0]++;
-+ if (key.objectid >= end)
-+ break;
-+ if (key.type == BTRFS_EXTENT_ITEM_KEY)
-+ len = key.offset;
-+ else if (key.type == BTRFS_METADATA_ITEM_KEY)
-+ len = fs_info->nodesize;
-+ else
-+ continue;
-+ if (key.objectid < bg->start || !len)
-+ continue;
-+ a = div64_u64(key.objectid - bg->start, fsl);
-+ b = div64_u64(min(key.objectid + len, end) - 1 - bg->start, fsl);
-+ r = compact_root(parent, a);
-+ for (u32 s = a + 1; s <= b; s++) {
-+ u32 t = compact_root(parent, s);
-+
-+ if (t != r) {
-+ parent[t] = r;
-+ bytes[r] += bytes[t];
-+ }
-+ }
-+ bytes[r] += len;
-+ }
-+ ret = 0;
-+
-+ /* Select every union holding a partial stripe... */
-+ for_each_set_bit(i, map, nstripes) {
-+ u32 r = compact_root(parent, i);
-+
-+ if (!__test_and_set_bit(r, sel))
-+ *moved += bytes[r];
-+ }
-+ /* ...and evacuate all of its stripes. */
-+ for (i = 0; i < nstripes; i++) {
-+ if (test_bit(compact_root(parent, i), sel)) {
-+ __set_bit(i, map);
-+ (*nsel)++;
-+ }
-+ }
-+ rc->compact_map = map;
-+ rc->compact_fsl = fsl;
-+ map = NULL;
-+out:
-+ bitmap_free(map);
-+ bitmap_free(sel);
-+ kvfree(parent);
-+ kvfree(bytes);
-+ return ret;
-+}
-+
-+/*
-+ * Plan the compaction of a read-only group. Returns 1 to compact
-+ * (rc->compact_map set), 0 to relocate the whole group instead -- the
-+ * closure would move more than half its live bytes, most of the cost of
-+ * moving all of them, which also gets the group's raw space back -- or a
-+ * negative errno.
-+ */
-+static int compact_prepare(struct reloc_control *rc)
-+{
-+ struct btrfs_block_group *bg = rc->block_group;
-+ struct btrfs_fs_info *fs_info = bg->fs_info;
-+ struct btrfs_trans_handle *trans;
-+ u64 moved, nsel, used;
-+ int ret;
-+
-+ /*
-+ * Settle first: what the group freed stays pinned until a commit, and
-+ * the plan reads the free space cache and the commit root, which then
-+ * agree.
-+ */
-+ trans = btrfs_join_transaction(rc->extent_root);
-+ if (IS_ERR(trans))
-+ return PTR_ERR(trans);
-+ ret = btrfs_commit_transaction(trans);
-+ if (ret)
-+ return ret;
-+ ret = btrfs_cache_block_group(bg, true);
-+ if (ret)
-+ return ret;
-+ ret = compact_plan(rc, &moved, &nsel);
-+ if (ret)
-+ return ret;
-+
-+ spin_lock(&bg->lock);
-+ used = bg->used;
-+ spin_unlock(&bg->lock);
-+ if (moved > used / 2) {
-+ bitmap_free(rc->compact_map);
-+ rc->compact_map = NULL;
-+ atomic64_inc(&fs_info->stripe_run_stats.compact_fallbacks);
-+ return 0;
-+ }
-+ atomic64_inc(&fs_info->stripe_run_stats.compact_runs);
-+ atomic64_add(nsel, &fs_info->stripe_run_stats.compact_stripes);
-+ atomic64_add(moved, &fs_info->stripe_run_stats.compact_bytes);
-+ btrfs_info(fs_info,
-+ "compacting block group %llu: %llu stripes, %llu of %llu live bytes",
-+ bg->start, nsel, moved, used);
-+ return 1;
-+}
-+
- /*
- * function to relocate all extents in a block group.
-+ *
-+ * @compact: NULL relocates the whole group. Pointing at true, the group is
-+ * compacted if that moves at most half its live bytes and relocated whole
-+ * otherwise; on return it says which. A compacted group is left writable.
- */
- int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
-- bool verbose)
-+ bool verbose, bool *compact)
- {
- struct btrfs_block_group *bg;
- struct btrfs_root *extent_root = btrfs_extent_root(fs_info, group_start);
-@@ -5446,6 +5683,7 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
- struct btrfs_path *path = NULL;
- int ret;
- bool bg_is_ro = false;
-+ bool compacting = false;
-
- if (unlikely(!extent_root)) {
- btrfs_err(fs_info,
-@@ -5543,6 +5781,18 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
- ret = btrfs_zone_finish(rc->block_group);
- WARN_ON(ret && ret != -EAGAIN);
-
-+ /* Compaction is for the relocation that moves extents, not remapping. */
-+ if (compact && *compact && should_relocate_using_remap_tree(bg))
-+ *compact = false;
-+ if (compact && *compact) {
-+ ret = compact_prepare(rc);
-+ if (ret < 0)
-+ goto out;
-+ compacting = ret;
-+ *compact = compacting;
-+ ret = 0;
-+ }
-+
- if (should_relocate_using_remap_tree(bg)) {
- if (bg->remap_bytes != 0) {
- ret = move_existing_remaps(fs_info, bg, path);
-@@ -5562,6 +5812,22 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
- ret = do_nonremap_reloc(fs_info, verbose, rc);
- }
-
-+ if (!ret && compacting) {
-+ struct btrfs_trans_handle *trans;
-+
-+ /*
-+ * The group stays. Commit, so what moved out of it is unpinned
-+ * and its stripes are whole again before it is writable.
-+ */
-+ trans = btrfs_join_transaction(rc->extent_root);
-+ if (IS_ERR(trans))
-+ ret = PTR_ERR(trans);
-+ else
-+ ret = btrfs_commit_transaction(trans);
-+ btrfs_dec_block_group_ro(rc->block_group);
-+ bg_is_ro = false;
-+ }
-+
- out:
- if (ret && bg_is_ro)
- btrfs_dec_block_group_ro(rc->block_group);
-diff --git a/fs/btrfs/relocation.h b/fs/btrfs/relocation.h
-index bb7a86e7dbe3a..e9f95976aae4b 100644
---- a/fs/btrfs/relocation.h
-+++ b/fs/btrfs/relocation.h
-@@ -24,7 +24,7 @@ static inline bool should_relocate_using_remap_tree(const struct btrfs_block_gro
- }
-
- int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
-- bool verbose);
-+ bool verbose, bool *compact);
- int btrfs_init_reloc_root(struct btrfs_trans_handle *trans, struct btrfs_root *root);
- int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
- struct btrfs_root *root);
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index f367a0fc707a9..1f14e9a16f5bc 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1180,12 +1180,20 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- "claim_refused_live_run %lld\n"
- "strand_scan_bytes %lld\n"
- "strand_rescan_marks %lld\n"
-- "nocow_run_dead_closed %lld\n",
-+ "nocow_run_dead_closed %lld\n"
-+ "compact_runs %lld\n"
-+ "compact_fallbacks %lld\n"
-+ "compact_stripes %lld\n"
-+ "compact_bytes %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.nocow_run_dead_closed));
-+ atomic64_read(&fs_info->stripe_run_stats.nocow_run_dead_closed),
-+ atomic64_read(&fs_info->stripe_run_stats.compact_runs),
-+ atomic64_read(&fs_info->stripe_run_stats.compact_fallbacks),
-+ atomic64_read(&fs_info->stripe_run_stats.compact_stripes),
-+ atomic64_read(&fs_info->stripe_run_stats.compact_bytes));
- }
- BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
-
-@@ -1224,6 +1232,37 @@ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_sync_timeout_ms, stripe_park_sync_timeout_ms);
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_congestion, stripe_park_congestion);
-
-+/*
-+ * Reclaim compacts a mostly live stripe group once this percent of its length
-+ * is trapped (btrfs_compact_chunk()); 0 turns compaction off.
-+ */
-+static ssize_t btrfs_stripe_compact_show(struct kobject *kobj,
-+ struct kobj_attribute *a, char *buf)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+
-+ return sysfs_emit(buf, "%u\n", READ_ONCE(fs_info->stripe_compact));
-+}
-+
-+static ssize_t btrfs_stripe_compact_store(struct kobject *kobj,
-+ struct kobj_attribute *a,
-+ const char *buf, size_t len)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+ unsigned int val;
-+ int ret;
-+
-+ ret = kstrtouint(buf, 10, &val);
-+ if (ret)
-+ return ret;
-+ if (val > 100)
-+ return -EINVAL;
-+ WRITE_ONCE(fs_info->stripe_compact, val);
-+ return len;
-+}
-+BTRFS_ATTR_RW(, stripe_compact, btrfs_stripe_compact_show,
-+ btrfs_stripe_compact_store);
-+
-
-
- static ssize_t btrfs_clone_alignment_show(struct kobject *kobj,
-@@ -1597,6 +1636,7 @@ static const struct attribute *btrfs_attrs[] = {
- BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
- BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
- BTRFS_ATTR_PTR(, stripe_park_congestion),
-+ BTRFS_ATTR_PTR(, stripe_compact),
- BTRFS_ATTR_PTR(, temp_fsid),
- NULL,
- };
-diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
-index ce78a9441c64f..6e7419b87ddcd 100644
---- a/fs/btrfs/volumes.c
-+++ b/fs/btrfs/volumes.c
-@@ -3737,7 +3737,8 @@ static int btrfs_relocate_chunk_finish(struct btrfs_fs_info *fs_info,
- return ret;
- }
-
--int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool verbose)
-+static int relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
-+ bool verbose, bool *compact)
- {
- struct btrfs_block_group *block_group;
- int ret;
-@@ -3764,7 +3765,7 @@ int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool v
-
- /* step one, relocate all the extents inside this chunk */
- btrfs_scrub_pause(fs_info);
-- ret = btrfs_relocate_block_group(fs_info, chunk_offset, verbose);
-+ ret = btrfs_relocate_block_group(fs_info, chunk_offset, verbose, compact);
- btrfs_scrub_continue(fs_info);
- if (ret) {
- /*
-@@ -3776,6 +3777,10 @@ int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool v
- return ret;
- }
-
-+ /* Compacted: the group keeps the rest of its live extents. */
-+ if (compact && *compact)
-+ return 0;
-+
- block_group = btrfs_lookup_block_group(fs_info, chunk_offset);
- if (!block_group)
- return -ENOENT;
-@@ -3791,6 +3796,25 @@ int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool v
- return ret;
- }
-
-+int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool verbose)
-+{
-+ return relocate_chunk(fs_info, chunk_offset, verbose, NULL);
-+}
-+
-+/*
-+ * Compact a stripe_alloc / stripe_meta group: relocate only the extents in
-+ * its partially used stripes (and those sharing a stripe with them) and keep
-+ * it. When that would move more than half its live bytes the group is
-+ * relocated and removed as by btrfs_relocate_chunk() instead; @compacted
-+ * says which happened.
-+ */
-+int btrfs_compact_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
-+ bool *compacted)
-+{
-+ *compacted = true;
-+ return relocate_chunk(fs_info, chunk_offset, false, compacted);
-+}
-+
- static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
- {
- struct btrfs_root *chunk_root = fs_info->chunk_root;
-diff --git a/fs/btrfs/volumes.h b/fs/btrfs/volumes.h
-index 75b1179776c80..982d88264ca5a 100644
---- a/fs/btrfs/volumes.h
-+++ b/fs/btrfs/volumes.h
-@@ -787,6 +787,8 @@ int btrfs_recover_balance(struct btrfs_fs_info *fs_info);
- int btrfs_pause_balance(struct btrfs_fs_info *fs_info);
- int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
- bool verbose);
-+int btrfs_compact_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset,
-+ bool *compacted);
- int btrfs_cancel_balance(struct btrfs_fs_info *fs_info);
- bool btrfs_chunk_writeable(struct btrfs_fs_info *fs_info, u64 chunk_offset);
- void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index);
---
-2.47.3
-
--- /dev/null
+From 9e00bb532a627618364cd9b43a1c833dbd3d0da9 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 10 Oct 2026 00:19:18 -0400
+Subject: [RFC PATCH 70/85] btrfs: stripe_alloc: skip RAID5/6 groups that are
+ mapped as RAID1/RAID1C3 (stripe_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: skip RAID5/6 groups that are mapped
+as RAID1/RAID1C3" (earlier in this series) that need code from "btrfs:
+stripe_meta: allocate tree blocks by whole stripes", which comes after
+it in this series: they are applied here, once "btrfs: stripe_meta:
+allocate tree blocks by whole stripes" is in, instead of with the rest
+of "btrfs: stripe_alloc: skip RAID5/6 groups that are mapped as
+RAID1/RAID1C3".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/extent-tree.c | 3 ++-
+ 1 file changed, 2 insertions(+), 1 deletion(-)
+
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 25a339856b07e..8fce8a5568222 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4260,7 +4260,8 @@ bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg)
+ return btrfs_test_opt(bg->fs_info, STRIPE_ALLOC) &&
+ (bg->flags & BTRFS_BLOCK_GROUP_METADATA) &&
+ !(bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
+- (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK);
++ (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
++ !test_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &bg->runtime_flags);
+ }
+
+ /*
+--
+2.47.3
+
+++ /dev/null
-From 81b9d74a3c498c8df94b99b9d6c72c68f077ce04 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Wed, 30 Sep 2026 18:07:52 -0400
-Subject: [RFC PATCH 071/116] btrfs: stripe_alloc: attribute each data
- read-modify-write to why padding declined
-To: linux-btrfs@vger.kernel.org
-
-data_rmw counts read-modify-writes, and the pad_decline_* counters count
-the pad oracle's refusals, but a refusal does not always lead to a read
-(a full stripe or a cached one does not read), so the two cannot be
-subtracted: nothing says which RMWs the allocator explains. With
-allow_rmw empty, a data RMW in a stripe_alloc group is expected in two
-places only:
-
- - at the open run's own frontier (the pad verdict UNCOVERED): the
- sectors it reads belong to the same run, in the same transaction,
- and are not durable yet;
-
- - from relocation writing into its own preallocated extents, which no
- root but the data reloc tree references until relocation moves the
- pointers after writeback.
-
-Record the pad oracle's verdict on the rbio (rmw_try_pad_full()) and,
-at the RMW site, split data_rmw by it (data_rmw_<reason>, with
-data_rmw_not_tried when the oracle was not consulted and
-data_rmw_pad_ok_nomem when it agreed but the zero pages could not be
-allocated). NO_RUN is the oracle's catch-all exit, so split it further
-by the exit taken (data_rmw_norun_*) and count those in a read-only
-group (data_rmw_norun_bg_ro). Count the data RMWs written by the data
-reloc inode outside the frontier (data_rmw_reloc_writer, disjoint from
-data_rmw_uncovered). All in stripe_park_stats.
-
-A test can then assert that data_rmw - data_rmw_uncovered -
-data_rmw_reloc_writer is zero on a stripe_alloc filesystem, on a
-production kernel, with reclaim relocating during the run -- which it
-could not do from the totals alone.
-
-The cost is a byte of state per rbio and a few counter increments per
-RMW, plus one block group lookup for NO_RUN RMWs.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 17 +++++++++--
- fs/btrfs/block-group.h | 17 +++++++++++
- fs/btrfs/fs.h | 15 +++++++++
- fs/btrfs/raid56.c | 69 ++++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/raid56.h | 9 ++++++
- fs/btrfs/sysfs.c | 28 +++++++++++++++++
- 6 files changed, 153 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index e39f266016306..9c032d762b8f4 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1792,13 +1792,19 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
-
- if (list_empty_careful(&fs_info->open_stripe_bgs)) {
- atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
-+ if (info)
-+ info->norun = BTRFS_STRIPE_NORUN_NO_BGS;
- return false;
- }
- bg = btrfs_lookup_block_group(fs_info, stripe_start);
- if (!bg) {
- atomic64_inc(&fs_info->stripe_park_stats.pad_decline_no_run);
-+ if (info)
-+ info->norun = BTRFS_STRIPE_NORUN_NO_BG;
- return false;
- }
-+ if (info)
-+ info->norun = BTRFS_STRIPE_NORUN_NO_COVER;
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-@@ -1811,6 +1817,7 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
- info->run_end = run->end;
- info->run_offset = run->offset;
- info->inflight_bytes = run->inflight_bytes;
-+ info->norun = BTRFS_STRIPE_NORUN_NO_LIVE;
- }
- if (!run->live || !run->live_nbits)
- break;
-@@ -1824,8 +1831,11 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
- * needs to pad. An open run's end is stripe aligned, so
- * overhang there means a stripe the run does not own.
- */
-- if (stripe_start + stripe_len > run->end && run->open)
-+ if (stripe_start + stripe_len > run->end && run->open) {
-+ if (info)
-+ info->norun = BTRFS_STRIPE_NORUN_OVERHANG;
- break;
-+ }
-
- first = (stripe_start - run->start) >> bits;
- /*
-@@ -1834,8 +1844,11 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
- * which sectors are dead, and padding acts on that by
- * overwriting them.
- */
-- if (first + nsectors > run->live_nbits)
-+ if (first + nsectors > run->live_nbits) {
-+ if (info)
-+ info->norun = BTRFS_STRIPE_NORUN_PAST_MAP;
- break;
-+ }
- bitmap_zero(dead, nsectors);
- for (u32 i = 0; i < nsectors; i++)
- if (!test_bit(first + i, run->live))
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 6c0b4ea723bb1..8abfc3e47d17f 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -510,6 +510,22 @@ enum btrfs_stripe_pad_reason {
- BTRFS_STRIPE_PAD_LIVE, /* frontier past the stripe: all allocated */
- BTRFS_STRIPE_PAD_UNALLOCATED, /* frontier has not reached the stripe */
- BTRFS_STRIPE_PAD_UNCOVERED, /* a sector below the frontier is not covered */
-+ BTRFS_STRIPE_PAD_NR_REASONS,
-+};
-+
-+/*
-+ * Which exit of btrfs_stripe_run_pad_mask() gave BTRFS_STRIPE_PAD_NO_RUN: a
-+ * catch-all for every refusal, including "a run covers the stripe but its
-+ * map cannot answer for it".
-+ */
-+enum btrfs_stripe_pad_norun {
-+ BTRFS_STRIPE_NORUN_NO_BGS = 0, /* no block group has open runs */
-+ BTRFS_STRIPE_NORUN_NO_BG, /* block group lookup failed */
-+ BTRFS_STRIPE_NORUN_NO_COVER, /* no run's span covers the stripe */
-+ BTRFS_STRIPE_NORUN_NO_LIVE, /* covering run has no live map */
-+ BTRFS_STRIPE_NORUN_OVERHANG, /* open run's end cuts the stripe */
-+ BTRFS_STRIPE_NORUN_PAST_MAP, /* stripe runs past the live map */
-+ BTRFS_STRIPE_NORUN_NR,
- };
-
- struct btrfs_stripe_pad_info {
-@@ -518,6 +534,7 @@ struct btrfs_stripe_pad_info {
- u64 run_offset; /* the allocation frontier */
- u64 inflight_bytes;
- u8 reason;
-+ u8 norun; /* enum btrfs_stripe_pad_norun */
- };
-
- u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index aa0cc290a753a..6e8119e073a9e 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -894,6 +894,21 @@ struct btrfs_fs_info {
- * frontier is not covered by this write: another
- * allocation shares the stripe. */
- atomic64_t pad_decline_uncovered;
-+ /*
-+ * data_rmw split by why padding declined for the rbio that
-+ * did it: 0..4 are enum btrfs_stripe_pad_reason (0: the pad
-+ * oracle agreed but the data page allocation failed), 5: not
-+ * tried (stripe_alloc off, or no memory for the bitmap).
-+ * data_rmw_norun splits the NO_RUN entry by enum
-+ * btrfs_stripe_pad_norun; norun_ro counts those in a
-+ * read-only (relocating) group. reloc_writer counts data RMWs
-+ * written by the data reloc inode outside the open run's
-+ * frontier, disjoint from data_rmw_by[UNCOVERED].
-+ */
-+ atomic64_t data_rmw_by[6];
-+ atomic64_t data_rmw_norun[6];
-+ atomic64_t data_rmw_norun_ro;
-+ atomic64_t data_rmw_reloc_writer;
- atomic64_t meta_rmw;
- /*
- * Breakdown of what a metadata read-modify-write found in the
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index abfadfec54f5a..1195f667784ca 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -22,6 +22,7 @@
- #include "file-item.h"
- #include "btrfs_inode.h"
- #include "block-group.h"
-+#include "bio.h"
-
- /* set when additional merges to this rbio are not allowed */
- #define RBIO_RMW_LOCKED_BIT 1
-@@ -66,6 +67,9 @@
- /* Set at park time and never cleared: this rbio once parked (stats). */
- #define RBIO_WAS_PARKED_BIT 7
-
-+/* rbio->pad_reason when rmw_try_pad_full() did not consult the pad oracle. */
-+#define RBIO_PAD_NOT_TRIED 0xff
-+
- /*
- * Set when a parked rbio carries (or merged) a REQ_SYNC bio: a waiter
- * is blocked on it, so deadlines stay authoritative and neither the
-@@ -2871,6 +2875,65 @@ static void submit_write_bios(struct btrfs_raid_bio *rbio,
- }
- }
-
-+static void rbio_record_pad(struct btrfs_raid_bio *rbio,
-+ const struct btrfs_stripe_pad_info *info)
-+{
-+ rbio->pad_reason = info->reason;
-+ rbio->pad_norun = info->norun;
-+}
-+
-+static_assert(BTRFS_STRIPE_PAD_NR_REASONS + 1 ==
-+ ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_park_stats.data_rmw_by));
-+static_assert(BTRFS_STRIPE_NORUN_NR ==
-+ ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_park_stats.data_rmw_norun));
-+
-+/*
-+ * Attribute a read-modify-write to why padding declined for this rbio. With
-+ * allow_rmw empty, a data RMW in a stripe_alloc group is expected in two
-+ * places only: at the open run's own frontier (UNCOVERED: the sectors it
-+ * reads are the same run's, in the same transaction, not yet durable), and
-+ * from relocation writing into its own preallocated extents, which nothing
-+ * but the data reloc inode references until relocation moves the pointers
-+ * after writeback. Any other data RMW in a covered group is unexplained.
-+ */
-+static void rbio_count_rmw_reason(struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ u8 idx = rbio->pad_reason;
-+ bool reloc_writer = false;
-+ struct bio *bio;
-+
-+ if (idx >= BTRFS_STRIPE_PAD_NR_REASONS)
-+ idx = BTRFS_STRIPE_PAD_NR_REASONS; /* not tried */
-+ atomic64_inc(&fs_info->stripe_park_stats.data_rmw_by[idx]);
-+ if (!(rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA))
-+ return;
-+
-+ if (idx == BTRFS_STRIPE_PAD_NO_RUN) {
-+ struct btrfs_block_group *bg;
-+
-+ if (rbio->pad_norun < BTRFS_STRIPE_NORUN_NR)
-+ atomic64_inc(&fs_info->stripe_park_stats.data_rmw_norun[rbio->pad_norun]);
-+ bg = btrfs_lookup_block_group(fs_info,
-+ rbio->bioc->full_stripe_logical);
-+ if (bg) {
-+ if (data_race(bg->ro))
-+ atomic64_inc(&fs_info->stripe_park_stats.data_rmw_norun_ro);
-+ btrfs_put_block_group(bg);
-+ }
-+ }
-+
-+ /* The writer: the first bio's inode. */
-+ spin_lock(&rbio->bio_list_lock);
-+ bio = bio_list_peek(&rbio->bio_list);
-+ if (bio && btrfs_bio(bio)->inode)
-+ reloc_writer = btrfs_is_data_reloc_root(btrfs_bio(bio)->inode->root);
-+ spin_unlock(&rbio->bio_list_lock);
-+ /* Disjoint from the frontier count, so the two can be summed. */
-+ if (reloc_writer && idx != BTRFS_STRIPE_PAD_UNCOVERED)
-+ atomic64_inc(&fs_info->stripe_park_stats.data_rmw_reloc_writer);
-+}
-+
- /*
- * Try to avoid the RMW read phase of a sub-stripe write by zero-filling
- * the uncovered data sectors. Legal only where the stripe's run says the
-@@ -2892,6 +2955,7 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- bool ok = false;
- int i;
-
-+ rbio->pad_reason = RBIO_PAD_NOT_TRIED;
- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
- return false;
-
-@@ -2900,6 +2964,7 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- return false;
- if (!btrfs_stripe_run_pad_mask(fs_info, stripe_start, stripe_len, dead,
- &info)) {
-+ rbio_record_pad(rbio, &info);
- trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
- stripe_len, 0, 0, nsectors,
- info.run_start, info.run_end,
-@@ -2929,6 +2994,7 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- if (!test_bit(i, dead)) {
- atomic64_inc(&fs_info->stripe_park_stats.pad_decline_uncovered);
- info.reason = BTRFS_STRIPE_PAD_UNCOVERED;
-+ rbio_record_pad(rbio, &info);
- trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
- stripe_len, 0, covered,
- nsectors,
-@@ -2946,6 +3012,8 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- if (!ok)
- return false;
-
-+ /* The oracle agreed: only a page allocation failure refuses now. */
-+ rbio->pad_reason = BTRFS_STRIPE_PAD_OK;
- if (alloc_rbio_data_pages(rbio) < 0)
- return false;
-
-@@ -3315,6 +3383,7 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- * count that should be zero.
- */
- atomic64_inc(&fs_info->stripe_park_stats.data_rmw);
-+ rbio_count_rmw_reason(rbio);
- /* A parked-then-flushed write that still had to read. */
- if (test_bit(RBIO_WAS_PARKED_BIT, &rbio->flags))
- atomic64_inc(&fs_info->stripe_park_stats.rmw_reads);
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index 11b843095903e..56e0e9790473a 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -144,6 +144,15 @@ struct btrfs_raid_bio {
- /* Flags that tell us if it is safe to merge with this bio. */
- unsigned long flags;
-
-+ /*
-+ * Why the last rmw_try_pad_full() on this rbio did not pad, so the
-+ * read-modify-write it leads to can be attributed: enum
-+ * btrfs_stripe_pad_reason (OK here means the data page allocation
-+ * failed), or RBIO_PAD_NOT_TRIED; and for NO_RUN, which exit.
-+ */
-+ u8 pad_reason;
-+ u8 pad_norun;
-+
- /*
- * Set if we're doing a parity rebuild for a read from higher up, which
- * is handled differently from a parity rebuild as part of RMW.
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 1f14e9a16f5bc..eefb17551e594 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1139,6 +1139,20 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "pad_decline_no_run %lld\n"
- "pad_decline_unallocated %lld\n"
- "pad_decline_uncovered %lld\n"
-+ "data_rmw_pad_ok_nomem %lld\n"
-+ "data_rmw_no_run %lld\n"
-+ "data_rmw_live %lld\n"
-+ "data_rmw_unallocated %lld\n"
-+ "data_rmw_uncovered %lld\n"
-+ "data_rmw_not_tried %lld\n"
-+ "data_rmw_norun_no_bgs %lld\n"
-+ "data_rmw_norun_no_bg %lld\n"
-+ "data_rmw_norun_no_cover %lld\n"
-+ "data_rmw_norun_no_live %lld\n"
-+ "data_rmw_norun_overhang %lld\n"
-+ "data_rmw_norun_past_map %lld\n"
-+ "data_rmw_norun_bg_ro %lld\n"
-+ "data_rmw_reloc_writer %lld\n"
- "meta_rmw %lld\n"
- "meta_rmw_cur %lld\n"
- "meta_rmw_old %lld\n"
-@@ -1160,6 +1174,20 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.pad_decline_no_run),
- atomic64_read(&fs_info->stripe_park_stats.pad_decline_unallocated),
- atomic64_read(&fs_info->stripe_park_stats.pad_decline_uncovered),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[0]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[1]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[2]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[3]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[4]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[5]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[0]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[1]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[2]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[3]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[4]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[5]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun_ro),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_reloc_writer),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
---
-2.47.3
-
--- /dev/null
+From f338d88054a75420a22b7013958b392a3103a579 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 22 Oct 2026 16:47:05 -0400
+Subject: [RFC PATCH 71/85] btrfs: stripe_meta: extend stripe reclaim to
+ metadata block groups
+To: linux-btrfs@vger.kernel.org
+
+The stripe reclaim of the reclaim subtopic handles stripe_alloc data block
+groups only. stripe_meta allocates tree blocks in whole stripes too, so
+its block groups trap free space in partially used stripes the same way,
+and that space comes back only by moving the live tree blocks out of those
+stripes. Metadata needs it more than data: a metadata reservation that
+finds no claimable stripe aborts the transaction instead of failing one
+write, so trapped metadata space that is never reclaimed ends in a forced
+read-only filesystem.
+
+Extend each reclaim mechanism to stripe_meta block groups:
+
+ - btrfs_reclaim_block_group(): allocate a chunk to relocate into when the
+ other groups' claimable stripes cannot take the group's live bytes, and
+ relocate the group even while it has reserved or pinned bytes. Under
+ COW, a metadata group always has tree blocks reserved or pinned, so the
+ generic bail-out would defer it forever.
+
+ - The cleaner's periodic re-evaluation scans the metadata space_info as
+ well as the data one.
+
+ - Compaction counts metadata extent items: a tree block is nodesize long
+ and never spans a stripe, so for a metadata group the closure is the
+ partial stripes themselves.
+
+ - stripe_reclaim_now accepts stripe_meta block groups, for one group or
+ for all of them.
+
+The comments that name the groups reclaim handles now name both.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 26 +++++++++++++++-----------
+ fs/btrfs/free-space-cache.c | 2 +-
+ fs/btrfs/fs.h | 2 +-
+ fs/btrfs/relocation.c | 8 ++++++--
+ fs/btrfs/sysfs.c | 2 +-
+ fs/btrfs/volumes.c | 2 +-
+ 6 files changed, 25 insertions(+), 17 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 45a09c6b6fdfd..cd6fe47d6b0f4 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -5168,14 +5168,14 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ bool compacted = false;
+
+ /*
+- * A stripe_alloc group's live extents can only move into
++ * A stripe_alloc / stripe_meta group's live extents can only move into
+ * whole free stripes. When the rest of the space_info has too few
+ * claimable bytes for them, allocate a chunk to relocate into, once per
+ * attempt. Done here rather than in the reservation path so that a
+ * device shrink, which relocates without spare room by design, still
+ * fails cleanly.
+ */
+- if (btrfs_is_stripe_alloc_bg(bg)) {
++ if (btrfs_is_stripe_alloc_bg(bg) || btrfs_is_stripe_meta_bg(bg)) {
+ u64 elsewhere = READ_ONCE(space_info->bytes_stripe_claimable);
+ u64 need = READ_ONCE(bg->used);
+
+@@ -5208,14 +5208,15 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ bg->stripe_reclaim_forced = STRIPE_RECLAIM_NONE;
+ if (bg->ro ||
+ ((bg->reserved || bg->pinned) &&
+- !btrfs_is_stripe_alloc_bg(bg))) {
++ !btrfs_is_stripe_alloc_bg(bg) &&
++ !btrfs_is_stripe_meta_bg(bg))) {
+ /*
+ * We want to bail if we made new allocations or have
+ * outstanding allocations in this block group. We do
+ * the ro check in case balance is currently acting on
+ * this block group.
+ *
+- * Not for a stripe_alloc group: under
++ * Not for a stripe_alloc or stripe_meta group: under
+ * COW churn it always has blocks reserved or pinned,
+ * so the bail-out would defer it forever, while the
+ * trapped free space it was queued for only grows.
+@@ -5262,7 +5263,7 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
+ compact = (forced == STRIPE_RECLAIM_COMPACT);
+ } else if (!should_reclaim_block_group(bg, bg->length)) {
+ /*
+- * Too full to relocate whole. A stripe_alloc
++ * Too full to relocate whole. A stripe_alloc / stripe_meta
+ * group whose free space is trapped in partially used stripes
+ * can still be compacted: only the extents in those stripes
+ * move.
+@@ -5554,7 +5555,7 @@ void btrfs_reclaim_bgs_work(struct work_struct *work)
+ }
+
+ /*
+- * Periodic re-evaluation of stripe_alloc groups from the
++ * Periodic re-evaluation of stripe_alloc / stripe_meta groups from the
+ * cleaner. The commit-time rescan only sees groups whose free space changed
+ * in that transaction, and only when there is a transaction: a mark that
+ * did not land (the group was on another list) or a group the worker dropped
+@@ -5571,7 +5572,8 @@ static void btrfs_stripe_reclaim_tick(struct btrfs_fs_info *fs_info)
+ list_for_each_entry(sinfo, &fs_info->space_info, list) {
+ int raid;
+
+- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
++ if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
++ BTRFS_BLOCK_GROUP_METADATA)))
+ continue;
+ if (READ_ONCE(sinfo->bg_reclaim_threshold) <= 0)
+ continue;
+@@ -5671,7 +5673,7 @@ static bool stripe_reclaim_now_queue(struct btrfs_block_group *bg,
+ }
+
+ /*
+- * /sys/fs/btrfs/<uuid>/stripe_reclaim_now: reclaim stripe_alloc
++ * /sys/fs/btrfs/<uuid>/stripe_reclaim_now: reclaim stripe_alloc / stripe_meta
+ * raid56 block groups now, e.g. from an idle-time job, rather than waiting
+ * for the commit-time rescan and its five-minute hysteresis. The threshold
+ * is the space_info's bg_reclaim_threshold, or BTRFS_DEFAULT_RECLAIM_THRESH
+@@ -5684,7 +5686,7 @@ static bool stripe_reclaim_now_queue(struct btrfs_block_group *bg,
+ * Otherwise @start names one group (its logical start): it is reclaimed
+ * whatever the trapped minimums say, compacted if it is above the threshold
+ * and has trapped stripes, relocated otherwise. -ENOENT: no group starts
+- * there; -EINVAL: not a stripe_alloc raid56 group (relocate
++ * there; -EINVAL: not a stripe_alloc / stripe_meta raid56 group (relocate
+ * any other group with balance's vrange filter); -EBUSY: the group is
+ * read-only (balance or scrub hold it); -EAGAIN: it is already on a list
+ * (queued, unused or new); -ENOSPC: the other groups' claimable stripes plus
+@@ -5722,7 +5724,8 @@ int btrfs_stripe_reclaim_now(struct btrfs_fs_info *fs_info, bool all, u64 start)
+ return -ENOENT;
+ if (bg->start != start) {
+ ret = -ENOENT;
+- } else if (!btrfs_is_stripe_alloc_bg(bg)) {
++ } else if (!btrfs_is_stripe_alloc_bg(bg) &&
++ !btrfs_is_stripe_meta_bg(bg)) {
+ ret = -EINVAL;
+ } else if (READ_ONCE(bg->ro)) {
+ ret = -EBUSY;
+@@ -5757,7 +5760,8 @@ int btrfs_stripe_reclaim_now(struct btrfs_fs_info *fs_info, bool all, u64 start)
+ BTRFS_BLOCK_GROUP_RAID56_MASK))
+ continue;
+ list_for_each_entry(bg, &sinfo->block_groups[raid], list) {
+- if (!btrfs_is_stripe_alloc_bg(bg))
++ if (!btrfs_is_stripe_alloc_bg(bg) &&
++ !btrfs_is_stripe_meta_bg(bg))
+ continue;
+ kind = btrfs_stripe_bg_reclaim_now_kind(bg, thresh,
+ false, stripe_reclaim_chunk_room(bg));
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 362e31f8be3d5..1117b14e23d53 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -2421,7 +2421,7 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
+
+
+ /*
+- * Does this stripe_alloc group want the reclaim worker? As
++ * Does this stripe_alloc / stripe_meta group want the reclaim worker? As
+ * with zoned's zone_unusable, reclaim once enough of the group's free space
+ * is trapped. A group whose live data is below the threshold is relocated
+ * whole; a fuller one is compacted (btrfs_compact_chunk()), moving only the
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 7186c62e8120c..686494b85d3e4 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -990,7 +990,7 @@ struct btrfs_fs_info {
+ /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
+ u32 stripe_rmw_prop;
+ /*
+- * Reclaim compacts a mostly live stripe_alloc group once
++ * Reclaim compacts a mostly live stripe_alloc / stripe_meta group once
+ * this percent of its length is trapped; 0 = never (sysfs
+ * stripe_compact, default 10). See btrfs_compact_chunk().
+ */
+diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
+index 79e65dfd9d14b..89a915b46e727 100644
+--- a/fs/btrfs/relocation.c
++++ b/fs/btrfs/relocation.c
+@@ -190,14 +190,15 @@ struct reloc_control {
+ };
+
+ /*
+- * Stripe compaction. A stripe_alloc group whose free space is
++ * Stripe compaction. A stripe_alloc / stripe_meta group whose free space is
+ * trapped in partially used stripes, but whose live data mostly fills whole
+ * ones, does not need all of that data moved to get the space back: only the
+ * extents in the partial stripes, and -- since moving an extent frees its
+ * bytes in every stripe it spans -- the extents sharing a stripe with those,
+ * transitively. compact_plan() selects that closure, find_next_extent()
+ * skips every extent outside it, and the group is kept and made writable
+- * again instead of removed.
++ * again instead of removed. A tree block never spans a stripe, so for a
++ * metadata group the closure is the partial stripes themselves.
+ */
+ static bool compact_selected(const struct reloc_control *rc, u64 start, u64 len)
+ {
+@@ -5498,6 +5499,7 @@ static u32 compact_root(u32 *parent, u32 x)
+ static int compact_plan(struct reloc_control *rc, u64 *moved, u64 *nsel)
+ {
+ struct btrfs_block_group *bg = rc->block_group;
++ struct btrfs_fs_info *fs_info = bg->fs_info;
+ const u64 fsl = bg->full_stripe_len;
+ const u64 end = bg->start + bg->length;
+ BTRFS_PATH_AUTO_FREE(path);
+@@ -5565,6 +5567,8 @@ static int compact_plan(struct reloc_control *rc, u64 *moved, u64 *nsel)
+ break;
+ if (key.type == BTRFS_EXTENT_ITEM_KEY)
+ len = key.offset;
++ else if (key.type == BTRFS_METADATA_ITEM_KEY)
++ len = fs_info->nodesize;
+ else
+ continue;
+ if (key.objectid < bg->start || !len)
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 1812ba343ca14..60bf7da1790b4 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1371,7 +1371,7 @@ BTRFS_ATTR_RW(, stripe_compact, btrfs_stripe_compact_show,
+ btrfs_stripe_compact_store);
+
+ /*
+- * Reclaim stripe_alloc raid56 block groups now: "all" (or "1")
++ * Reclaim stripe_alloc / stripe_meta raid56 block groups now: "all" (or "1")
+ * queues every group the reclaim predicate picks, a block group's logical
+ * start forces that group. See btrfs_stripe_reclaim_now().
+ */
+diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
+index c9f81b0975fe0..9f689c4c9d7f8 100644
+--- a/fs/btrfs/volumes.c
++++ b/fs/btrfs/volumes.c
+@@ -3802,7 +3802,7 @@ int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset, bool v
+ }
+
+ /*
+- * Compact a stripe_alloc group: relocate only the extents in
++ * Compact a stripe_alloc / stripe_meta group: relocate only the extents in
+ * its partially used stripes (and those sharing a stripe with them) and keep
+ * it. When that would move more than half its live bytes the group is
+ * relocated and removed as by btrfs_relocate_chunk() instead; @compacted
+--
+2.47.3
+
+++ /dev/null
-From db1269b9f63e72b7581f48836f4919c8607d28f3 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Wed, 30 Sep 2026 18:07:56 -0400
-Subject: [RFC PATCH 072/116] btrfs: stripe_alloc: optionally audit data
- read-modify-writes against the committed extent tree
-To: linux-btrfs@vger.kernel.org
-
-The attribution counters say which RMWs the allocator's design explains;
-they do not show that an RMW put nothing at risk. That depends on what
-the uncovered sectors hold: an RMW recomputes parity under them while
-they stay put, so a crash mid-write can tear them, and that matters
-only if a committed transaction references them and the owner is not
-relocation's own orphaned copy.
-
-Add an audit that answers it from the tree. For every data RMW, walk
-the commit root of the extent tree (no locking, as
-rmw_block_referenced() does) for extents overlapping the stripe's
-uncovered sectors, and read each one's data backrefs, inline and keyed.
-An extent owned only by the data reloc tree counts as relocation's
-(data_rmw_hole_reloc_only); any other owner, a shared ref (owner
-unknown), or no ref at all is foreign and counts as a write hole
-(data_rmw_hole_no_run / _uncovered / _other, by pad verdict). Log the
-writer of every foreign hole and of every NO_RUN RMW, rate-limited from
-separate call sites so a flood of the second cannot starve the first:
-root, inode, file offset, ordered extent flags, disk bytenr, stripe run
-sequence, and the covering run as the pad oracle saw it. The commit
-root switches just before the super lands, so the check can report a
-hole early, never hide one.
-
-A tree search per RMW is not free (a stock raid5 filesystem does
-thousands a minute), so the audit is built only with CONFIG_BTRFS_DEBUG
-and runs only while /sys/fs/btrfs/<uuid>/debug/stripe_rmw_audit is set,
-which it is not by default. Its counters are in
-debug/stripe_rmw_audit_stats, with data_rmw_audited so a reader can
-tell an audit that found nothing from one that never ran.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 2 +
- fs/btrfs/block-group.h | 2 +
- fs/btrfs/fs.h | 21 +++
- fs/btrfs/raid56.c | 306 +++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/raid56.h | 8 ++
- fs/btrfs/sysfs.c | 63 +++++++++
- 6 files changed, 402 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 9c032d762b8f4..e63ca269e6721 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1817,6 +1817,8 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
- info->run_end = run->end;
- info->run_offset = run->offset;
- info->inflight_bytes = run->inflight_bytes;
-+ info->run_open = run->open;
-+ info->run_class = run->class;
- info->norun = BTRFS_STRIPE_NORUN_NO_LIVE;
- }
- if (!run->live || !run->live_nbits)
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 8abfc3e47d17f..c8724effe36ca 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -535,6 +535,8 @@ struct btrfs_stripe_pad_info {
- u64 inflight_bytes;
- u8 reason;
- u8 norun; /* enum btrfs_stripe_pad_norun */
-+ u8 run_open; /* the covering run was open */
-+ u8 run_class; /* and its class */
- };
-
- u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 6e8119e073a9e..4ed55f974ea24 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -923,6 +923,27 @@ struct btrfs_fs_info {
- atomic64_t meta_rmw_free;
- atomic64_t congestion_short;
- } stripe_park_stats;
-+
-+#ifdef CONFIG_BTRFS_DEBUG
-+ /*
-+ * Audit of each data read-modify-write against the committed extent
-+ * tree (raid56.c), off unless enabled through
-+ * /sys/fs/btrfs/<uuid>/debug/stripe_rmw_audit. hole_by counts RMWs
-+ * whose uncovered sectors hold committed extents that some root other
-+ * than the data reloc tree owns (a real write hole), split like
-+ * data_rmw_by; hole_reloc_only counts those owned by relocation alone.
-+ */
-+ bool stripe_rmw_audit;
-+ struct {
-+ atomic64_t audited;
-+ atomic64_t hole_by[6];
-+ atomic64_t hole_sectors;
-+ atomic64_t hole_reloc_only;
-+ atomic64_t hole_reloc_sectors;
-+ atomic64_t reloc_writer_foreign;
-+ atomic64_t audit_err;
-+ } stripe_rmw_audit_stats;
-+#endif
- /*
- * Stripe run lifecycle observability: lifetime counters exposed
- * through sysfs stripe_run_stats, so a test can show it exercised
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 1195f667784ca..865ecb86b9ead 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -23,6 +23,7 @@
- #include "btrfs_inode.h"
- #include "block-group.h"
- #include "bio.h"
-+#include "ordered-data.h"
-
- /* set when additional merges to this rbio are not allowed */
- #define RBIO_RMW_LOCKED_BIT 1
-@@ -2880,6 +2881,13 @@ static void rbio_record_pad(struct btrfs_raid_bio *rbio,
- {
- rbio->pad_reason = info->reason;
- rbio->pad_norun = info->norun;
-+#ifdef CONFIG_BTRFS_DEBUG
-+ rbio->pad_run_open = info->run_open;
-+ rbio->pad_run_class = info->run_class;
-+ rbio->pad_run_start = info->run_start;
-+ rbio->pad_run_end = info->run_end;
-+ rbio->pad_run_offset = info->run_offset;
-+#endif
- }
-
- static_assert(BTRFS_STRIPE_PAD_NR_REASONS + 1 ==
-@@ -2887,6 +2895,302 @@ static_assert(BTRFS_STRIPE_PAD_NR_REASONS + 1 ==
- static_assert(BTRFS_STRIPE_NORUN_NR ==
- ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_park_stats.data_rmw_norun));
-
-+#ifdef CONFIG_BTRFS_DEBUG
-+/* What the audit found under one RMW's uncovered sectors. */
-+struct rmw_audit {
-+ int foreign; /* sectors under extents another root owns */
-+ int reloc; /* sectors under extents only relocation owns */
-+ u64 min_gen;
-+ u64 max_gen;
-+ u64 first; /* first foreign extent */
-+ u64 first_root; /* one other root referencing it (0: shared ref) */
-+};
-+
-+/* One extent being classified: its uncovered sectors and its owners. */
-+struct rmw_audit_ext {
-+ u64 bytenr;
-+ u64 gen;
-+ int sectors;
-+ int reloc_refs;
-+ int other_refs; /* includes shared refs: owner unknown, so foreign */
-+ u64 other_root;
-+};
-+
-+static void rmw_audit_ext_ref(struct rmw_audit_ext *e, u64 root)
-+{
-+ if (root == BTRFS_DATA_RELOC_TREE_OBJECTID) {
-+ e->reloc_refs++;
-+ } else {
-+ e->other_refs++;
-+ if (!e->other_root)
-+ e->other_root = root;
-+ }
-+}
-+
-+static void rmw_audit_ext_done(struct rmw_audit *a, struct rmw_audit_ext *e)
-+{
-+ if (!e->sectors)
-+ goto out;
-+ /* No ref seen at all: be conservative and call it foreign. */
-+ if (e->other_refs || !e->reloc_refs) {
-+ if (!a->foreign) {
-+ a->first = e->bytenr;
-+ a->first_root = e->other_root;
-+ }
-+ a->foreign += e->sectors;
-+ a->min_gen = min(a->min_gen, e->gen);
-+ a->max_gen = max(a->max_gen, e->gen);
-+ } else {
-+ a->reloc += e->sectors;
-+ }
-+out:
-+ memset(e, 0, sizeof(*e));
-+}
-+
-+/*
-+ * Classify the data sectors of this rbio's stripe that the write does NOT
-+ * cover by the COMMITTED extent under them and that extent's owners. Those
-+ * are the sectors a torn RMW can destroy after a crash. An extent owned only
-+ * by the data reloc tree is relocation's own orphaned copy, discarded by
-+ * orphan cleanup if a crash comes before its pointers move; any other owner
-+ * is a real write hole. Commit root, no locking, as in
-+ * rmw_block_referenced(). Returns -1 when the lookup cannot answer.
-+ *
-+ * The commit root is switched shortly before the super lands, so an extent
-+ * of the transaction committing right now can count early: this errs towards
-+ * reporting a hole, never towards hiding one.
-+ */
-+static int rmw_committed_uncovered(struct btrfs_raid_bio *rbio,
-+ struct rmw_audit *a)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ const u64 stripe_start = rbio->bioc->full_stripe_logical;
-+ const u64 stripe_end = stripe_start +
-+ (u64)rbio->nr_data * rbio->bioc->stripe_len;
-+ const u32 bits = fs_info->sectorsize_bits;
-+ struct btrfs_root *extent_root = btrfs_extent_root(fs_info, stripe_start);
-+ struct rmw_audit_ext e = { 0 };
-+ struct btrfs_path *path;
-+ struct btrfs_key key;
-+ int ret;
-+
-+ memset(a, 0, sizeof(*a));
-+ a->min_gen = U64_MAX;
-+ path = btrfs_alloc_path();
-+ if (!path)
-+ return -1;
-+ path->search_commit_root = 1;
-+ path->skip_locking = 1;
-+
-+ down_read(&fs_info->commit_root_sem);
-+ key.objectid = stripe_start;
-+ key.type = BTRFS_EXTENT_ITEM_KEY;
-+ key.offset = 0;
-+ ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
-+ if (ret < 0)
-+ goto fail;
-+ /* An extent starting below the stripe may reach into it. */
-+ ret = btrfs_previous_extent_item(extent_root, path,
-+ stripe_start > SZ_1G ? stripe_start - SZ_1G : 0);
-+ if (ret < 0)
-+ goto fail;
-+ if (ret > 0) {
-+ btrfs_release_path(path);
-+ ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
-+ if (ret < 0)
-+ goto fail;
-+ }
-+ while (1) {
-+ struct extent_buffer *leaf = path->nodes[0];
-+ const int slot = path->slots[0];
-+ struct btrfs_extent_item *ei;
-+ unsigned long ptr, end;
-+ u64 lo, hi;
-+
-+ if (slot >= btrfs_header_nritems(leaf)) {
-+ ret = btrfs_next_leaf(extent_root, path);
-+ if (ret < 0)
-+ goto fail;
-+ if (ret > 0)
-+ break;
-+ continue;
-+ }
-+ btrfs_item_key_to_cpu(leaf, &key, slot);
-+
-+ /* Keyed backrefs of the extent being classified. */
-+ if (e.sectors && key.objectid == e.bytenr) {
-+ if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
-+ struct btrfs_extent_data_ref *dref;
-+
-+ dref = btrfs_item_ptr(leaf, slot,
-+ struct btrfs_extent_data_ref);
-+ rmw_audit_ext_ref(&e, btrfs_extent_data_ref_root(leaf, dref));
-+ } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
-+ e.other_refs++;
-+ }
-+ path->slots[0]++;
-+ continue;
-+ }
-+ if (key.type != BTRFS_EXTENT_ITEM_KEY) {
-+ if (key.objectid >= stripe_end)
-+ break;
-+ path->slots[0]++;
-+ continue;
-+ }
-+ rmw_audit_ext_done(a, &e);
-+ if (key.objectid >= stripe_end)
-+ break;
-+ if (key.objectid + key.offset <= stripe_start) {
-+ path->slots[0]++;
-+ continue;
-+ }
-+ ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
-+ lo = max(key.objectid, stripe_start);
-+ hi = min(key.objectid + key.offset, stripe_end);
-+ for (u64 b = lo; b < hi; b += fs_info->sectorsize)
-+ if (rbio->bio_paddrs[((b - stripe_start) >> bits) * rbio->sector_nsteps] == INVALID_PADDR)
-+ e.sectors++;
-+ if (!e.sectors) {
-+ path->slots[0]++;
-+ continue;
-+ }
-+ e.bytenr = key.objectid;
-+ e.gen = btrfs_extent_generation(leaf, ei);
-+ /* Inline backrefs: data extents carry no tree_block_info. */
-+ ptr = (unsigned long)(ei + 1);
-+ end = (unsigned long)ei + btrfs_item_size(leaf, slot);
-+ while (ptr < end) {
-+ struct btrfs_extent_inline_ref *iref = (void *)ptr;
-+ const int type = btrfs_extent_inline_ref_type(leaf, iref);
-+ const u32 size = btrfs_extent_inline_ref_size(type);
-+
-+ if (type == BTRFS_EXTENT_DATA_REF_KEY) {
-+ struct btrfs_extent_data_ref *dref =
-+ (void *)&iref->offset;
-+
-+ rmw_audit_ext_ref(&e, btrfs_extent_data_ref_root(leaf, dref));
-+ } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
-+ e.other_refs++;
-+ } else if (type != BTRFS_EXTENT_OWNER_REF_KEY) {
-+ /* Not a data ref we understand: foreign. */
-+ e.other_refs++;
-+ break;
-+ }
-+ if (!size)
-+ break;
-+ ptr += size;
-+ }
-+ path->slots[0]++;
-+ }
-+ rmw_audit_ext_done(a, &e);
-+ up_read(&fs_info->commit_root_sem);
-+ btrfs_free_path(path);
-+ return a->foreign + a->reloc;
-+fail:
-+ up_read(&fs_info->commit_root_sem);
-+ btrfs_free_path(path);
-+ return -1;
-+}
-+
-+/*
-+ * With /sys/fs/btrfs/<uuid>/debug/stripe_rmw_audit set: prove from the
-+ * committed extent tree, not from the allocator's design, that a data RMW put
-+ * no other owner's committed data at risk, and log the writer of any that
-+ * did (and of every NO_RUN RMW, the class the allocator cannot explain by
-+ * construction). @idx is the RMW's data_rmw_by index.
-+ */
-+static void rbio_audit_rmw(struct btrfs_raid_bio *rbio, u8 idx)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ const u64 stripe_start = rbio->bioc->full_stripe_logical;
-+ struct btrfs_block_group *bg;
-+ struct rmw_audit a;
-+ u64 root_id = 0, ino = 0, foff = 0, oflags = 0, oseq = 0, odisk = 0;
-+ u64 bg_flags = 0;
-+ bool orun = false;
-+ int nbios = 0;
-+ int ro = -1;
-+ int ret;
-+ struct bio *bio;
-+
-+ if (!READ_ONCE(fs_info->stripe_rmw_audit))
-+ return;
-+ atomic64_inc(&fs_info->stripe_rmw_audit_stats.audited);
-+
-+ spin_lock(&rbio->bio_list_lock);
-+ bio_list_for_each(bio, &rbio->bio_list) {
-+ struct btrfs_bio *bbio = btrfs_bio(bio);
-+
-+ if (nbios++)
-+ continue;
-+ if (!bbio->inode ||
-+ btrfs_ino(bbio->inode) == BTRFS_BTREE_INODE_OBJECTID)
-+ continue;
-+ root_id = btrfs_root_id(bbio->inode->root);
-+ ino = btrfs_ino(bbio->inode);
-+ foff = bbio->file_offset;
-+ if (bbio->ordered) {
-+ oflags = bbio->ordered->flags;
-+ oseq = bbio->ordered->stripe_seq;
-+ odisk = bbio->ordered->disk_bytenr;
-+ orun = bbio->ordered->stripe_run != NULL;
-+ }
-+ }
-+ spin_unlock(&rbio->bio_list_lock);
-+
-+ /* The audit needs bio sectors mapped; idempotent. */
-+ index_rbio_pages(rbio);
-+ ret = rmw_committed_uncovered(rbio, &a);
-+ if (ret < 0) {
-+ atomic64_inc(&fs_info->stripe_rmw_audit_stats.audit_err);
-+ } else if (a.foreign) {
-+ atomic64_inc(&fs_info->stripe_rmw_audit_stats.hole_by[idx]);
-+ atomic64_add(a.foreign, &fs_info->stripe_rmw_audit_stats.hole_sectors);
-+ if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
-+ atomic64_inc(&fs_info->stripe_rmw_audit_stats.reloc_writer_foreign);
-+ } else if (a.reloc) {
-+ atomic64_inc(&fs_info->stripe_rmw_audit_stats.hole_reloc_only);
-+ }
-+ if (ret > 0)
-+ atomic64_add(a.reloc, &fs_info->stripe_rmw_audit_stats.hole_reloc_sectors);
-+
-+ if (idx == BTRFS_STRIPE_PAD_NO_RUN) {
-+ bg = btrfs_lookup_block_group(fs_info, stripe_start);
-+ if (bg) {
-+ ro = data_race(bg->ro);
-+ bg_flags = bg->flags;
-+ btrfs_put_block_group(bg);
-+ }
-+ }
-+
-+ /*
-+ * Separate call sites, so separate rate limits: a flood of NO_RUN
-+ * lines cannot starve the hole lines.
-+ */
-+ if (ret > 0 && a.foreign)
-+ btrfs_warn_rl(fs_info,
-+"rmw audit: write hole: stripe %llu reason %u norun %u foreign %d reloc %d gen %llu..%llu first %llu first_root %lld fsgen %llu committed %llu writer root %lld ino %llu foff %llu oe_flags 0x%llx oe_disk %llu oe_seq %llu oe_run %d nbios %d",
-+ stripe_start, idx, rbio->pad_norun, a.foreign,
-+ a.reloc, a.min_gen, a.max_gen, a.first,
-+ (s64)a.first_root, btrfs_get_fs_generation(fs_info),
-+ btrfs_get_last_trans_committed(fs_info),
-+ (s64)root_id, ino, foff, oflags, odisk, oseq, orun,
-+ nbios);
-+ else if (idx == BTRFS_STRIPE_PAD_NO_RUN)
-+ btrfs_info_rl(fs_info,
-+"rmw audit: no_run RMW stripe %llu norun %u bg_ro %d bg_flags 0x%llx run %llu..%llu off %llu open %u class %u reloc_sectors %d fsgen %llu committed %llu writer root %lld ino %llu foff %llu oe_flags 0x%llx oe_seq %llu oe_run %d nbios %d",
-+ stripe_start, rbio->pad_norun, ro, bg_flags,
-+ rbio->pad_run_start, rbio->pad_run_end,
-+ rbio->pad_run_offset, rbio->pad_run_open,
-+ rbio->pad_run_class, ret > 0 ? a.reloc : 0,
-+ btrfs_get_fs_generation(fs_info),
-+ btrfs_get_last_trans_committed(fs_info),
-+ (s64)root_id, ino, foff, oflags, oseq, orun, nbios);
-+}
-+#else
-+static void rbio_audit_rmw(struct btrfs_raid_bio *rbio, u8 idx) { }
-+#endif
-+
- /*
- * Attribute a read-modify-write to why padding declined for this rbio. With
- * allow_rmw empty, a data RMW in a stripe_alloc group is expected in two
-@@ -2932,6 +3236,8 @@ static void rbio_count_rmw_reason(struct btrfs_raid_bio *rbio)
- /* Disjoint from the frontier count, so the two can be summed. */
- if (reloc_writer && idx != BTRFS_STRIPE_PAD_UNCOVERED)
- atomic64_inc(&fs_info->stripe_park_stats.data_rmw_reloc_writer);
-+
-+ rbio_audit_rmw(rbio, idx);
- }
-
- /*
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index 56e0e9790473a..8a618b86a5f18 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -152,6 +152,14 @@ struct btrfs_raid_bio {
- */
- u8 pad_reason;
- u8 pad_norun;
-+#ifdef CONFIG_BTRFS_DEBUG
-+ /* The covering run as the pad oracle saw it, for the RMW audit's log. */
-+ u8 pad_run_open;
-+ u8 pad_run_class;
-+ u64 pad_run_start;
-+ u64 pad_run_end;
-+ u64 pad_run_offset;
-+#endif
-
- /*
- * Set if we're doing a parity rebuild for a read from higher up, which
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index eefb17551e594..8895a53668415 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -525,7 +525,70 @@ static const struct attribute *discard_attrs[] = {
- *
- * Path: /sys/fs/btrfs/UUID/debug/
- */
-+/*
-+ * Audit every data read-modify-write against the committed extent tree
-+ * (raid56.c): a tree search per RMW, so off by default.
-+ */
-+static ssize_t btrfs_stripe_rmw_audit_show(struct kobject *kobj,
-+ struct kobj_attribute *a, char *buf)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
-+
-+ return sysfs_emit(buf, "%d\n", READ_ONCE(fs_info->stripe_rmw_audit));
-+}
-+
-+static ssize_t btrfs_stripe_rmw_audit_store(struct kobject *kobj,
-+ struct kobj_attribute *a,
-+ const char *buf, size_t len)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
-+ bool val;
-+ int ret;
-+
-+ ret = kstrtobool(buf, &val);
-+ if (ret)
-+ return ret;
-+ WRITE_ONCE(fs_info->stripe_rmw_audit, val);
-+ return len;
-+}
-+BTRFS_ATTR_RW(debug_mount, stripe_rmw_audit, btrfs_stripe_rmw_audit_show,
-+ btrfs_stripe_rmw_audit_store);
-+
-+static ssize_t btrfs_stripe_rmw_audit_stats_show(struct kobject *kobj,
-+ struct kobj_attribute *a,
-+ char *buf)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(get_btrfs_kobj(kobj));
-+
-+ return sysfs_emit(buf,
-+ "data_rmw_audited %lld\n"
-+ "data_rmw_hole_no_run %lld\n"
-+ "data_rmw_hole_uncovered %lld\n"
-+ "data_rmw_hole_other %lld\n"
-+ "data_rmw_hole_sectors %lld\n"
-+ "data_rmw_hole_reloc_only %lld\n"
-+ "data_rmw_hole_reloc_sectors %lld\n"
-+ "data_rmw_reloc_writer_foreign %lld\n"
-+ "data_rmw_audit_err %lld\n",
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.audited),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[1]),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[4]),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[0]) +
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[2]) +
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[3]) +
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[5]),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_sectors),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_reloc_only),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_reloc_sectors),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.reloc_writer_foreign),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.audit_err));
-+}
-+BTRFS_ATTR(debug_mount, stripe_rmw_audit_stats,
-+ btrfs_stripe_rmw_audit_stats_show);
-+
- static const struct attribute *btrfs_debug_mount_attrs[] = {
-+ BTRFS_ATTR_PTR(debug_mount, stripe_rmw_audit),
-+ BTRFS_ATTR_PTR(debug_mount, stripe_rmw_audit_stats),
- NULL,
- };
-
---
-2.47.3
-
--- /dev/null
+From 5caf207efa50dc5d51f7e0a120f22301e3329f2c Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:12 -0400
+Subject: [RFC PATCH 72/85] btrfs: stripe_meta: hold back whole stripes so tree
+ blocks always land and trapped groups can be reclaimed
+To: linux-btrfs@vger.kernel.org
+
+Two failures at the metadata fill edge under stripe_meta, both seen
+with the tiny-file fill test on raid5 metadata.
+
+The first is a transaction abort. A tree block is reserved in bytes
+and admitted while claimable whole stripes cover the outstanding
+reservations, but it is placed in whole stripes: the open run it would
+have joined is closed at the transaction boundary, so every group
+claims at least one fresh full stripe per transaction. The last few
+megabytes of claimable supply go to those claims, made for reservations
+admitted earlier, and the next admitted tree block finds no stripe at
+all ("stripe_meta: tree block allocation of 16384 bytes returned
+ENOSPC: claimable 0 open 1622016 trapped 1614266368"), which aborts the
+transaction. Pre-pay two transactions' worth of claims -- twice the
+number of writable groups times the widest full stripe -- in the
+space_info's stripe margin, recomputed at each commit scan. Best-fit
+run selection opens a fresh run only when a group's runs are full, so
+this is a few megabytes, not a fraction of the space_info.
+
+The second is a filesystem that quietly runs out at half capacity.
+COW frees trap stripes rather than free them: a stripe is claimable
+again only once every tree block in it is dead, which random deaths in
+a sixteen-block stripe essentially never achieve, so the METADATA
+space_info settles around half used, half trapped and no claimable
+stripe left (3.04 GiB metadata, 49% used, fs not writable, deletes
+included). Only relocation packs live tree blocks back into whole
+stripes, and it needs the moved group's live bytes claimable elsewhere
+before it starts -- by the time the trigger fires there is nothing
+left. Hold back a reserve of whole stripes -- the largest writable
+group's length, capped at a quarter of the space_info, nothing with a
+single group -- from every metadata reservation except those made by
+the relocation task, identified by a task pointer that reloc_ctl
+already implies. Reservations admitted against the reserve reach the
+same tickets, so the flag travels with the ticket. The reserve is an
+accounting hold-back, not a partition: a committing transaction still
+allocates from those stripes when it must, and the next scan restates
+the reserve from what remains. Both counters are cleared when
+stripe_alloc is turned off, since the scan that maintains them stops
+with it.
+
+The reserve is reported through sysfs as bytes_stripe_reserve and in
+the space_info dump, whose stripe_claimable and stripe_margin values
+were printed under each other's label.
+
+The reserve belongs to the whole of btrfs_relocate_block_group(), not
+only the stretches where reloc_ctl is set: relocation reserves metadata
+before its first stage (create_reloc_inode() starts a transaction for
+six items), and that reservation, made as an ordinary user, fails with
+-ENOSPC exactly when relocation is needed -- once the claimable supply
+has fallen below the reserve. fs_info->reloc_owner records the task
+for the whole run (reloc_chunk_start() serializes it) and counts as
+relocation here.
+
+Who may draw on the reserve:
+
+- Relocation, for the whole of btrfs_relocate_block_group(), which
+ reloc_chunk_start() serializes: the reservation create_reloc_inode()
+ makes before the first stage must not stay behind the reserve, or every
+ metadata relocation fails exactly when the supply is below it (511 of
+ 536 failed relocations of a raid6/raid6 octopus run ended so). Making a
+ group read-only, relocation's first step, draws on it too.
+
+- The transaction machinery's own reservations, NO_FLUSH, FLUSH_LIMIT and
+ EMERGENCY: the reserve holds back user operations so relocation and the
+ commit after it have room, and must not hold back the commit (an
+ extent tree COW freeing deleted leaves aborted the transaction with
+ 163 MiB of whole stripes unused). User reservations (FLUSH_ALL,
+ ALL_STEAL, EVICT, DATA) still stop at it.
+
+- The global reserve steal is refused once the claimable supply is down
+ to the reserve plus the claim margin: an inline unlink frees no stripe
+ and each transaction of unlinks takes fresh ones, so stolen
+ reservations end in an abort. The unlink fails with ENOSPC instead.
+ The orphan cleanup at mount and ro->rw remount (the task is recorded in
+ btrfs_start_pre_rw_mount()) steals regardless: a failed eviction there
+ fails the read-write mount, and a filesystem that cannot be mounted
+ read-write can never run the relocation the reserve is for.
+
+The reserve is a multiple of the metadata full stripe (stripe_round_up(),
+not round_up(): the widths are not powers of two).
+
+Raid56 metadata groups go through a runtime enable or disable too: the
+arm and disarm sweep covers METADATA space_infos, the commit-time
+metadata retirement runs whether or not the policy is on (so a disable
+does not leave the running transaction's metadata runs and their group
+references until unmount), and the enable drain commits the running
+transaction before arming the write-hole check, since tree blocks the
+legacy allocator placed in it are written by that commit into partly used
+stripes. That one commit's exposure is inherent.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+Assisted-by: Claude:claude-fable-5-1
+---
+ fs/btrfs/block-group.c | 98 ++++++++++++++++++++++++++++++++++---
+ fs/btrfs/disk-io.c | 7 ++-
+ fs/btrfs/free-space-cache.c | 2 +-
+ fs/btrfs/fs.h | 24 +++++++++
+ fs/btrfs/relocation.c | 4 ++
+ fs/btrfs/space-info.c | 71 ++++++++++++++++++++++++---
+ fs/btrfs/space-info.h | 28 ++++++-----
+ fs/btrfs/sysfs.c | 2 +
+ 8 files changed, 210 insertions(+), 26 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index cd6fe47d6b0f4..73c7b5575c39d 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -607,6 +607,11 @@ static u64 stripe_round_down(u64 val, u64 fsl)
+ return div64_u64(val, fsl) * fsl;
+ }
+
++static u64 stripe_round_up(u64 val, u64 fsl)
++{
++ return stripe_round_down(val + fsl - 1, fsl);
++}
++
+ static bool stripe_is_aligned(u64 val, u64 fsl)
+ {
+ return stripe_round_down(val, fsl) == val;
+@@ -2349,8 +2354,9 @@ int btrfs_stripe_alloc_check_support(struct btrfs_fs_info *fs_info)
+ }
+
+ /*
+- * Arm or disarm stripe_unusable accounting across all raid56 data block
+- * groups whose caches are loaded. Same walk as the commit-time rescan.
++ * Arm or disarm stripe_unusable accounting across all raid56 data and
++ * metadata block groups whose caches are loaded. Same walk as the
++ * commit-time rescan.
+ */
+ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
+ {
+@@ -2359,8 +2365,26 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
+ list_for_each_entry(sinfo, &fs_info->space_info, list) {
+ int raid;
+
+- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA))
++ if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
++ BTRFS_BLOCK_GROUP_METADATA)))
+ continue;
++ /*
++ * Metadata: the scan that maintains the stripe_meta margin
++ * and reserve stops with the option, so clear them here or
++ * they hold metadata back forever. The groups themselves
++ * are armed and disarmed below like data groups: raid56
++ * metadata places tree blocks in whole stripes from the
++ * moment the option is on, so its trapped and claimable
++ * bytes count from that moment and stop counting when it
++ * goes off.
++ */
++ if (!arm && (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)) {
++ spin_lock(&sinfo->lock);
++ sinfo->bytes_stripe_margin = 0;
++ sinfo->bytes_stripe_reserve = 0;
++ btrfs_try_granting_tickets(sinfo);
++ spin_unlock(&sinfo->lock);
++ }
+ /* The writeback quarantine is the gate's; it goes with it. */
+ if (!arm && (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)) {
+ spin_lock(&sinfo->lock);
+@@ -2427,6 +2451,13 @@ void btrfs_stripe_alloc_enable_work(struct work_struct *work)
+
+ btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
+ btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
++ /*
++ * Tree blocks the legacy allocator placed in the transaction running at
++ * the flip are written into partly used stripes by that transaction's
++ * commit. Wait for it before arming the check, which would otherwise
++ * report those writes as violations.
++ */
++ btrfs_commit_current_transaction(fs_info->tree_root);
+ clear_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags);
+ btrfs_info(fs_info,
+ "stripe_alloc: writes placed before the policy was enabled have landed");
+@@ -3108,9 +3139,13 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
+ LIST_HEAD(retire_list);
+ unsigned long flags;
+
+- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
+- return;
+-
++ /*
++ * No option test: a runtime disable leaves the running transaction's
++ * metadata runs open, and the commit that follows still has to close
++ * and drain them or their block groups never drop their references.
++ * The list is empty when nothing is open, so this costs nothing on a
++ * filesystem that never had the policy.
++ */
+ spin_lock(&fs_info->open_stripe_lock);
+ list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
+ list_add_tail(&bg->open_stripe_retire_list, &retire_list);
+@@ -3329,6 +3364,9 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ u64 total_claimable = 0;
+ u64 total_claimable_reloc = 0;
+ u64 total_stranded = 0;
++ u64 largest = 0;
++ u64 unit = 0;
++ u32 nr_rw = 0;
+ int raid;
+
+ /*
+@@ -3388,7 +3426,10 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ if (bg->start == READ_ONCE(fs_info->data_reloc_bg))
+ total_claimable_reloc +=
+ bg->stripe_claimable;
++ nr_rw++;
++ largest = max(largest, bg->length);
+ }
++ unit = max(unit, bg->full_stripe_len);
+ }
+ }
+ up_read(&sinfo->groups_sem);
+@@ -3397,6 +3438,42 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ sinfo->bytes_stripe_claimable = total_claimable;
+ sinfo->bytes_stripe_claimable_reloc = total_claimable_reloc;
+ sinfo->bytes_stripe_stranded = total_stranded;
++ /*
++ * Not if the option went off since the check above: the
++ * disable path has cleared the margin and reserve, and no
++ * later scan would clear them again.
++ */
++ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA) &&
++ btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
++ u64 reserve = 0;
++
++ /*
++ * stripe_meta. A tree block is reserved in bytes but
++ * placed in whole stripes: the run it would join is
++ * closed at the transaction boundary, so each group
++ * claims at least one fresh stripe per transaction.
++ * Pre-pay two transactions' worth of such claims, or
++ * the last claimable stripes go to claims made for
++ * reservations admitted earlier and an admitted tree
++ * block finds none, which aborts the transaction.
++ */
++ sinfo->bytes_stripe_margin = 2ULL * nr_rw * unit;
++ /*
++ * COW frees trap stripes (a stripe is claimable only
++ * once every block in it is dead), and only relocation
++ * packs live blocks back into whole stripes, which
++ * needs room elsewhere for the moved group. With more
++ * than one group, hold back one group's worth, capped
++ * at a quarter of the space_info, from all but
++ * relocation. Accounting only: a committing
++ * transaction may still allocate here.
++ */
++ if (nr_rw > 1 && unit)
++ reserve = stripe_round_up(min(largest,
++ sinfo->total_bytes / 4),
++ unit);
++ sinfo->bytes_stripe_reserve = reserve;
++ }
+ /*
+ * The rescan usually lowers the counter (mid-transaction
+ * incremental adds overcount conservatively); admission
+@@ -4629,8 +4706,15 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
+
+ if (READ_ONCE(cache->stripe_unusable_ready))
+ trapped = min(READ_ONCE(cache->stripe_unusable), num_bytes);
++ /*
++ * The stripe_meta reserve is the room a group's live blocks
++ * move into when it is relocated, and going read-only is the
++ * first step of exactly that: count the reserve as available
++ * here, or the guard refuses every relocation at the edge by
++ * the width of the reserve.
++ */
+ if (btrfs_can_overcommit(sinfo, num_bytes - trapped,
+- BTRFS_RESERVE_NO_FLUSH))
++ BTRFS_RESERVE_NO_FLUSH, true))
+ ret = 0;
+ }
+
+diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
+index a7339ea5b0028..d4b6de361fb3c 100644
+--- a/fs/btrfs/disk-io.c
++++ b/fs/btrfs/disk-io.c
+@@ -3148,17 +3148,22 @@ int btrfs_start_pre_rw_mount(struct btrfs_fs_info *fs_info)
+ if (ret)
+ return ret;
+
++ WRITE_ONCE(fs_info->mount_cleanup_task, current);
+ ret = btrfs_cleanup_fs_roots(fs_info);
+- if (ret)
++ if (ret) {
++ WRITE_ONCE(fs_info->mount_cleanup_task, NULL);
+ return ret;
++ }
+
+ down_read(&fs_info->cleanup_work_sem);
+ if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
+ (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
+ up_read(&fs_info->cleanup_work_sem);
++ WRITE_ONCE(fs_info->mount_cleanup_task, NULL);
+ return ret;
+ }
+ up_read(&fs_info->cleanup_work_sem);
++ WRITE_ONCE(fs_info->mount_cleanup_task, NULL);
+
+ mutex_lock(&fs_info->cleaner_mutex);
+ ret = btrfs_recover_relocation(fs_info);
+diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
+index 1117b14e23d53..2106eec097812 100644
+--- a/fs/btrfs/free-space-cache.c
++++ b/fs/btrfs/free-space-cache.c
+@@ -2452,7 +2452,7 @@ static bool stripe_reclaim_meta_room(struct btrfs_fs_info *fs_info)
+ return true;
+ spin_lock(&meta->lock);
+ ok = btrfs_space_info_used(meta, true) + bytes <= meta->total_bytes ||
+- btrfs_can_overcommit(meta, bytes, BTRFS_RESERVE_FLUSH_ALL);
++ btrfs_can_overcommit(meta, bytes, BTRFS_RESERVE_FLUSH_ALL, true);
+ spin_unlock(&meta->lock);
+ return ok;
+ }
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 686494b85d3e4..a21750342d1e5 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -789,6 +789,30 @@ struct btrfs_fs_info {
+ struct btrfs_space_info *data_sinfo;
+
+ struct reloc_control *reloc_ctl;
++ /*
++ * The task running relocation while reloc_ctl is set. Under
++ * stripe_meta it alone may reserve metadata out of the whole stripes
++ * held back in bytes_stripe_reserve, so that a trapped metadata
++ * group can always be relocated (see btrfs_can_overcommit()).
++ */
++ struct task_struct *reloc_task;
++ /*
++ * The task inside btrfs_relocate_block_group(), for its whole run
++ * (relocation is serialized by reloc_chunk_start()). reloc_task only
++ * covers the stretches where reloc_ctl is set; the reservations made
++ * before and between them -- creating the data reloc inode first of
++ * all -- are relocation's too, and may draw on the same reserve.
++ */
++ struct task_struct *reloc_owner;
++ /*
++ * The task running the mount-time (and ro->rw remount) orphan
++ * cleanup in btrfs_start_pre_rw_mount(). Its evictions may steal
++ * from the global reserve even below the stripe_meta reserve: a
++ * mount that cannot finish orphan cleanup fails, and a filesystem
++ * that cannot be mounted read-write can never run the relocation
++ * the reserve is held back for.
++ */
++ struct task_struct *mount_cleanup_task;
+
+ /* data_alloc_cluster is only used in ssd_spread mode */
+ struct btrfs_free_cluster data_alloc_cluster;
+diff --git a/fs/btrfs/relocation.c b/fs/btrfs/relocation.c
+index 89a915b46e727..d9f218e128f6c 100644
+--- a/fs/btrfs/relocation.c
++++ b/fs/btrfs/relocation.c
+@@ -3598,6 +3598,7 @@ static void set_reloc_control(struct reloc_control *rc)
+ spin_lock(&fs_info->reloc_ctl_lock);
+ fs_info->reloc_ctl = rc;
+ spin_unlock(&fs_info->reloc_ctl_lock);
++ WRITE_ONCE(fs_info->reloc_task, current);
+ mutex_unlock(&fs_info->reloc_mutex);
+ }
+
+@@ -3609,6 +3610,7 @@ static void unset_reloc_control(struct reloc_control *rc)
+ spin_lock(&fs_info->reloc_ctl_lock);
+ fs_info->reloc_ctl = NULL;
+ spin_unlock(&fs_info->reloc_ctl_lock);
++ WRITE_ONCE(fs_info->reloc_task, NULL);
+ mutex_unlock(&fs_info->reloc_mutex);
+ }
+
+@@ -5736,6 +5738,7 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
+ ret = reloc_chunk_start(fs_info);
+ if (ret < 0)
+ goto out_put_rc;
++ WRITE_ONCE(fs_info->reloc_owner, current);
+
+ ret = btrfs_inc_block_group_ro(rc->block_group, true);
+ if (ret)
+@@ -5837,6 +5840,7 @@ int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
+ if (!btrfs_is_zoned(fs_info))
+ btrfs_release_data_reloc_bg(fs_info);
+ btrfs_free_path(path);
++ WRITE_ONCE(fs_info->reloc_owner, NULL);
+ reloc_chunk_end(fs_info);
+ out_put_rc:
+ put_reloc_control(rc);
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index 2d9010624bbc0..563a8832732bb 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -187,6 +187,10 @@ struct reserve_ticket {
+ u64 bytes;
+ int error;
+ bool steal;
++ /* Made by the relocation task: may draw on bytes_stripe_reserve. */
++ bool reloc;
++ /* Made by the mount-time orphan cleanup: may steal regardless. */
++ bool mount_cleanup;
+ /*
+ * A preallocation: one whole stripe of collateral is charged into
+ * bytes_stripe_margin in the same critical section that grants the
+@@ -684,7 +688,7 @@ static inline bool can_overcommit(const struct btrfs_space_info *space_info,
+ }
+
+ bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
+- enum btrfs_reserve_flush_enum flush)
++ enum btrfs_reserve_flush_enum flush, bool reloc)
+ {
+ u64 used;
+
+@@ -693,6 +697,13 @@ bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
+ return false;
+
+ used = btrfs_space_info_used(space_info, true);
++ /*
++ * The stripe_meta reserve exists for relocation: it is the room in
++ * which the live tree blocks of a trapped group are packed into whole
++ * stripes. Everyone else sees it as used.
++ */
++ if (reloc)
++ used -= min(used, space_info->bytes_stripe_reserve);
+
+ return check_can_overcommit(space_info, used, bytes, flush);
+ }
+@@ -924,13 +935,26 @@ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info)
+ while (!list_empty(head)) {
+ struct reserve_ticket *ticket;
+ u64 used_after;
++ u64 tused;
+
+ ticket = list_first_entry(head, struct reserve_ticket, list);
+ used_after = used + ticket->bytes;
++ /*
++ * Relocation's tickets may draw on the stripe_meta reserve: for
++ * this ticket only, the tickets after it still see it as used.
++ */
++ tused = used;
++ if (ticket->reloc)
++ tused -= min(tused, space_info->bytes_stripe_reserve);
+
+- /* 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)) &&
++ /*
++ * Check and see if our ticket can be satisfied now. The
++ * gate's relocation rule is for FLUSH_DATA_RELOC, which never
++ * waits on a ticket (can_ticket()); ticket->reloc is the
++ * stripe_meta reserve's eligibility, a different question.
++ */
++ if ((tused + ticket->bytes <= space_info->total_bytes ||
++ can_overcommit(space_info, tused, 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);
+@@ -983,13 +1007,13 @@ 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 stripe_unusable=%llu stripe_open=%llu stripe_margin=%llu stripe_claimable=%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_claimable=%llu stripe_margin=%llu stripe_reserve=%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_stripe_unusable, info->bytes_stripe_open,
+ info->bytes_stripe_claimable,
+- info->bytes_stripe_margin);
++ info->bytes_stripe_margin, info->bytes_stripe_reserve);
+ }
+
+ void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
+@@ -1482,6 +1506,22 @@ static bool steal_from_global_rsv(struct btrfs_space_info *space_info,
+ if (global_rsv->space_info != space_info)
+ return false;
+
++ /*
++ * stripe_meta: the global reserve is refilled at every commit, but its
++ * bytes are only as real as the whole stripes behind them. Once the
++ * claimable supply is down to the relocation reserve, a stolen
++ * reservation lets a transaction consume fresh stripes through COW
++ * while its frees come back trapped, until a tree block finds no stripe
++ * and the commit aborts. Refuse the steal: -ENOSPC is recoverable and
++ * an abort is not. Mount-time orphan cleanup is exempt: it is bounded,
++ * and failing it fails the mount, leaving no way to relocate.
++ */
++ if (space_info->bytes_stripe_reserve && !ticket->mount_cleanup &&
++ space_info->bytes_stripe_claimable <
++ space_info->bytes_stripe_reserve + space_info->bytes_stripe_margin +
++ ticket->bytes)
++ return false;
++
+ spin_lock(&global_rsv->lock);
+ min_bytes = mult_perc(global_rsv->size, 10);
+ if (global_rsv->reserved < min_bytes + ticket->bytes) {
+@@ -2176,6 +2216,20 @@ static int __reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
+ u64 used;
+ int ret = -ENOSPC;
+ bool pending_tickets;
++ /*
++ * Who may draw on the stripe_meta reserve (bytes_stripe_reserve):
++ * the relocation task, which is what the reserve is for, and the
++ * transaction machinery's own bounded reservations -- NO_FLUSH from
++ * btrfs_use_block_rsv() when a handle's reserve runs dry mid-COW,
++ * FLUSH_LIMIT for delayed refs and delayed inodes, EMERGENCY -- which
++ * a committing transaction cannot fail without aborting. User
++ * operations (FLUSH_ALL, ALL_STEAL, EVICT, DATA) stay behind it.
++ */
++ const bool reloc = (READ_ONCE(fs_info->reloc_task) == current) ||
++ (READ_ONCE(fs_info->reloc_owner) == current) ||
++ flush == BTRFS_RESERVE_NO_FLUSH ||
++ flush == BTRFS_RESERVE_FLUSH_LIMIT ||
++ flush == BTRFS_RESERVE_FLUSH_EMERGENCY;
+
+ ASSERT(orig_bytes, "orig_bytes=%llu", orig_bytes);
+ /*
+@@ -2215,6 +2269,8 @@ static int __reserve_bytes(struct btrfs_space_info *space_info, u64 orig_bytes,
+ * Carry on if we have enough space (short-circuit) OR call
+ * can_overcommit() to ensure we can overcommit to continue.
+ */
++ if (reloc)
++ used -= min(used, space_info->bytes_stripe_reserve);
+ if (!pending_tickets &&
+ ((used + orig_bytes <= space_info->total_bytes) ||
+ can_overcommit(space_info, used, orig_bytes, flush)) &&
+@@ -2253,6 +2309,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.reloc = reloc;
++ ticket.mount_cleanup =
++ READ_ONCE(fs_info->mount_cleanup_task) == current;
+ ticket.hold_stripe = held != NULL;
+ ticket.held = 0;
+ ticket.stripe_margin = stripe_margin;
+diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
+index 5e13008c688f5..a38a36362e9bc 100644
+--- a/fs/btrfs/space-info.h
++++ b/fs/btrfs/space-info.h
+@@ -192,16 +192,21 @@ 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 bytes_stripe_margin; /* data: one full stripe per
++ outstanding delalloc extent or
++ preallocation in flight, pre-paying
++ the sub-stripe tail a commit can trap
++ before writeback (see
++ btrfs_stripe_margin_mod()).
++ stripe_meta metadata: two
++ transactions' worth of stripe claims,
++ set at each commit scan. */
++ u64 bytes_stripe_reserve; /* stripe_meta: whole stripes held back
++ for relocation (and the transaction
++ machinery's own reservations), so a
++ trapped metadata group can always be
++ moved. Counted as used; recomputed
++ at each commit scan. */
+ u64 bytes_stripe_quarantine; /* data: what buffered writeback that
+ failed with ENOSPC released, held
+ out of the admission supply until
+@@ -370,6 +375,7 @@ static inline u64 btrfs_space_info_used(const struct btrfs_space_info *s_info,
+ s_info->bytes_zone_unusable +
+ s_info->bytes_stripe_unusable + s_info->bytes_stripe_open +
+ s_info->bytes_stripe_margin +
++ s_info->bytes_stripe_reserve +
+ (may_use_included ? s_info->bytes_may_use : 0);
+ }
+
+@@ -399,7 +405,7 @@ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
+ enum btrfs_reserve_flush_enum flush);
+ void btrfs_try_granting_tickets(struct btrfs_space_info *space_info);
+ bool btrfs_can_overcommit(const struct btrfs_space_info *space_info, u64 bytes,
+- enum btrfs_reserve_flush_enum flush);
++ enum btrfs_reserve_flush_enum flush, bool reloc);
+
+ static inline void btrfs_space_info_free_bytes_may_use(
+ struct btrfs_space_info *space_info,
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 60bf7da1790b4..48b10f03e8092 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -883,6 +883,7 @@ SPACE_INFO_ATTR(bytes_stripe_stranded);
+ SPACE_INFO_ATTR(bytes_stripe_claimable);
+ SPACE_INFO_ATTR(bytes_stripe_open);
+ SPACE_INFO_ATTR(bytes_stripe_margin);
++SPACE_INFO_ATTR(bytes_stripe_reserve);
+ SPACE_INFO_ATTR(bytes_stripe_quarantine);
+ SPACE_INFO_ATTR(disk_used);
+ SPACE_INFO_ATTR(disk_total);
+@@ -1018,6 +1019,7 @@ static struct attribute *space_info_attrs[] = {
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_claimable),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_open),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_margin),
++ BTRFS_ATTR_PTR(space_info, bytes_stripe_reserve),
+ BTRFS_ATTR_PTR(space_info, bytes_stripe_quarantine),
+ BTRFS_ATTR_PTR(space_info, disk_used),
+ BTRFS_ATTR_PTR(space_info, disk_total),
+--
+2.47.3
+
--- /dev/null
+From 1c27225353cf83f9b418f297ce1f028332aec02d Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:18:19 -0400
+Subject: [RFC PATCH 73/85] btrfs: stripe_alloc: count whole stripes stranded
+ behind live runs as trapped (stripe_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: count whole stripes stranded behind
+live runs as trapped" (earlier in this series) that need code from
+"btrfs: stripe_meta: hold back whole stripes so tree blocks always land
+and trapped groups can be reclaimed", which comes after it in this
+series: they are applied here, once "btrfs: stripe_meta: hold back whole
+stripes so tree blocks always land and trapped groups can be reclaimed"
+is in, instead of with the rest of "btrfs: stripe_alloc: count whole
+stripes stranded behind live runs as trapped".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/space-info.c | 8 +++++---
+ 1 file changed, 5 insertions(+), 3 deletions(-)
+
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index 563a8832732bb..10c14fdc85bc4 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -1007,13 +1007,15 @@ 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 stripe_unusable=%llu stripe_open=%llu stripe_claimable=%llu stripe_margin=%llu stripe_reserve=%llu",
++"space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu stripe_unusable=%llu stripe_stranded=%llu stripe_open=%llu stripe_claimable=%llu stripe_margin=%llu stripe_reserve=%llu unmanaged_free=%lld",
+ 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_stripe_unusable, info->bytes_stripe_open,
++ info->bytes_stripe_unusable, info->bytes_stripe_stranded,
++ info->bytes_stripe_open,
+ info->bytes_stripe_claimable,
+- info->bytes_stripe_margin, info->bytes_stripe_reserve);
++ info->bytes_stripe_margin, info->bytes_stripe_reserve,
++ (s64)atomic64_read(&info->bytes_unmanaged_free));
+ }
+
+ void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
+--
+2.47.3
+
+++ /dev/null
-From f5fc101c0c49bbd2ca341ad13bdf8d495daa2899 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 1 Oct 2026 00:57:50 -0400
-Subject: [RFC PATCH 073/116] btrfs: stripe_alloc: keep relocation's stripe
- runs until relocation ends
-To: linux-btrfs@vger.kernel.org
-
-Relocation preallocates each destination extent and writes the data into
-it later, after the commit that ends relocate_block_group(). Under
-stripe_alloc the preallocation lands in a BTRFS_STRIPE_RUN_RELOC run,
-which drains at once (a preallocation has no IO to report) and is freed
-when that commit closes it. By the time the relocated data is written,
-no run covers its stripes: a write that does not cover a whole stripe
-can neither park to merge with its neighbour nor pad, and goes down as a
-read-modify-write. Relocated extents rarely line up with stripes, so
-that is roughly one RMW per relocated extent: an audited data balance on
-a 4-device raid5 made 2247 of them, every one NO_RUN, every one written
-by the data reloc inode into its own preallocation, and none over
-another owner's committed data (the stripes hold only relocation's own
-orphaned copies) -- harmless, but every one a stripe read.
-
-Keep RELOC runs after they close and drain, as metadata runs already are
-for the same reason, until relocation releases them from
-btrfs_release_data_reloc_bg(), which it calls on its way out (after the
-pointer update, before the next relocation can allocate). A retained
-run that has nothing in flight is not waited for by the commit's drain,
-and any forced quiesce of its block group (read-only, removal, unmount)
-releases it first. While retained, its range stays unclaimable and its
-stripes are relocation's alone, so the writes into them park and merge
-or pad like any other run's.
-
-reloc_run_retained / reloc_run_released in stripe_run_stats count the
-runs kept and released.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 72 +++++++++++++++++++++++++++++++++++++++---
- fs/btrfs/fs.h | 3 ++
- fs/btrfs/sysfs.c | 4 +++
- 3 files changed, 75 insertions(+), 4 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index e63ca269e6721..946102aea2df6 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -508,6 +508,12 @@ struct btrfs_open_stripe_run {
- 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
-+ * run_freed_on_drain().
-+ */
-+ bool retained;
- /*
- * One bit per sector of the run: set while that sector holds an
- * allocation someone still intends to write, clear otherwise.
-@@ -722,10 +728,21 @@ static bool open_stripe_run_dead(const struct btrfs_open_stripe_run *run)
- * stripe, and with no run there is nothing to pad against and nothing to
- * merge with. Metadata runs are therefore freed by
- * btrfs_retire_meta_stripes(), which runs once every tree block is on disk.
-+ *
-+ * Relocation's runs have the same problem across a whole relocation stage.
-+ * Relocation preallocates its destination extents (the run drains at once:
-+ * a preallocation has no IO to report) and writes them only after the
-+ * commit that ends relocate_block_group(), which would free the run. Every
-+ * relocated extent that shares a stripe with another then found no covering
-+ * run, could neither park nor pad, and went down as a read-modify-write.
-+ * They are retained until relocation releases them instead. Their stripes
-+ * hold nothing but relocation's own orphaned copies until the pointer update
-+ * that follows the writeback, and no allocation reaches them meanwhile: the
-+ * run is closed, and its range stays unclaimable while it exists.
- */
- static bool run_freed_on_drain(const struct btrfs_open_stripe_run *run)
- {
-- return run->class != BTRFS_STRIPE_RUN_META;
-+ return run->class != BTRFS_STRIPE_RUN_META && !run->retained;
- }
-
- static void free_open_stripe_run(struct btrfs_block_group *bg,
-@@ -787,7 +804,7 @@ static u64 close_open_stripe_run(struct btrfs_block_group *bg,
- tail_len = run->end - run->offset;
- run->end = run->offset;
- bg->stripe_open_remainder -= tail_len;
-- if (open_stripe_run_drained(run))
-+ if (open_stripe_run_drained(run) && !run->retained)
- free_open_stripe_run(bg, run);
- return tail_len;
- }
-@@ -1077,6 +1094,9 @@ 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);
- new_run->owner = 0;
- new_run->transid = transid;
- new_run->start = start;
-@@ -2609,6 +2629,10 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
- /* 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)
-+ continue;
- /* Metadata drains after tree writeback, not here. */
- if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
- continue;
-@@ -2621,6 +2645,42 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
- return ret;
- }
-
-+/*
-+ * Stop retaining @bg's relocation runs: free the ones already drained, and
-+ * let any still open or in flight be freed when they drain, like any other.
-+ */
-+static void release_retained_stripe_runs(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_open_stripe_run *run, *tmp;
-+ unsigned long flags;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry_safe(run, tmp, &bg->open_stripe_runs, list) {
-+ if (!run->retained)
-+ continue;
-+ run->retained = false;
-+ atomic64_inc(&bg->fs_info->stripe_run_stats.reloc_run_released);
-+ if (open_stripe_run_drained(run))
-+ free_open_stripe_run(bg, run);
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+}
-+
-+/*
-+ * Relocation is done with its destination stripes: release its retained
-+ * runs in every block group (the dedication of btrfs_release_data_reloc_bg()
-+ * can have moved between groups during the relocation).
-+ */
-+static void btrfs_release_stripe_reloc_runs(struct btrfs_fs_info *fs_info)
-+{
-+ struct btrfs_block_group *bg;
-+
-+ spin_lock(&fs_info->open_stripe_lock);
-+ list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
-+ release_retained_stripe_runs(bg);
-+ spin_unlock(&fs_info->open_stripe_lock);
-+}
-+
- /*
- * Close and drain all of a block group's stripe runs. The caller must
- * prevent new allocations first (e.g. the block group is read-only),
-@@ -2639,6 +2699,8 @@ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
- {
- struct btrfs_fs_info *fs_info = bg->fs_info;
-
-+ /* Nothing may outlive this, relocation's retained runs included. */
-+ release_retained_stripe_runs(bg);
- close_block_group_stripe_runs(bg, U64_MAX);
- /* Parked partial-stripe rbios hold the very bios the wait drains. */
- btrfs_flush_parked_rbios(fs_info, bg->start, bg->length, false);
-@@ -3206,10 +3268,10 @@ void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info)
- spin_unlock(&fs_info->relocation_bg_lock);
-
- if (!bytenr)
-- return;
-+ goto release;
- bg = btrfs_lookup_block_group(fs_info, bytenr);
- if (!bg)
-- return;
-+ goto release;
- if (bg->space_info) {
- spin_lock(&bg->space_info->lock);
- bg->space_info->bytes_stripe_claimable_reloc = 0;
-@@ -3217,6 +3279,8 @@ void btrfs_release_data_reloc_bg(struct btrfs_fs_info *fs_info)
- }
- btrfs_close_bg_open_stripes(bg);
- btrfs_put_block_group(bg);
-+release:
-+ btrfs_release_stripe_reloc_runs(fs_info);
- }
-
- struct btrfs_caching_control *btrfs_get_caching_control(
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 4ed55f974ea24..16fdd69b7f16f 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -960,6 +960,9 @@ struct btrfs_fs_info {
- 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;
- /* compaction passes that kept their group */
- atomic64_t compact_runs;
- /* compaction plans over the cap, relocated whole instead */
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 8895a53668415..5cbff0b128288 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1272,6 +1272,8 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- "strand_scan_bytes %lld\n"
- "strand_rescan_marks %lld\n"
- "nocow_run_dead_closed %lld\n"
-+ "reloc_run_retained %lld\n"
-+ "reloc_run_released %lld\n"
- "compact_runs %lld\n"
- "compact_fallbacks %lld\n"
- "compact_stripes %lld\n"
-@@ -1281,6 +1283,8 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- 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.nocow_run_dead_closed),
-+ atomic64_read(&fs_info->stripe_run_stats.reloc_run_retained),
-+ atomic64_read(&fs_info->stripe_run_stats.reloc_run_released),
- atomic64_read(&fs_info->stripe_run_stats.compact_runs),
- atomic64_read(&fs_info->stripe_run_stats.compact_fallbacks),
- atomic64_read(&fs_info->stripe_run_stats.compact_stripes),
---
-2.47.3
-
--- /dev/null
+From 11c8a7cfaaf14db5bbb2009c829b7848197f6073 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sun, 25 Oct 2026 06:27:49 -0400
+Subject: [RFC PATCH 74/85] btrfs: stripe_alloc: do not count a writeback
+ ENOSPC drop's give-back as supply (stripe_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: do not count a writeback ENOSPC
+drop's give-back as supply" (earlier in this series) that need code from
+"btrfs: stripe_meta: hold back whole stripes so tree blocks always land
+and trapped groups can be reclaimed", which comes after it in this
+series: they are applied here, once "btrfs: stripe_meta: hold back whole
+stripes so tree blocks always land and trapped groups can be reclaimed"
+is in, instead of with the rest of "btrfs: stripe_alloc: do not count a
+writeback ENOSPC drop's give-back as supply".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/space-info.c | 5 +++--
+ 1 file changed, 3 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
+index 10c14fdc85bc4..22839793ed94f 100644
+--- a/fs/btrfs/space-info.c
++++ b/fs/btrfs/space-info.c
+@@ -1007,7 +1007,7 @@ 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 stripe_unusable=%llu stripe_stranded=%llu stripe_open=%llu stripe_claimable=%llu stripe_margin=%llu stripe_reserve=%llu unmanaged_free=%lld",
++"space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu stripe_unusable=%llu stripe_stranded=%llu stripe_open=%llu stripe_claimable=%llu stripe_margin=%llu stripe_reserve=%llu unmanaged_free=%lld stripe_quarantine=%llu",
+ info->total_bytes, info->bytes_used, info->bytes_pinned,
+ info->bytes_reserved, info->bytes_may_use,
+ info->bytes_readonly, info->bytes_zone_unusable,
+@@ -1015,7 +1015,8 @@ static void __btrfs_dump_space_info(const struct btrfs_space_info *info)
+ info->bytes_stripe_open,
+ info->bytes_stripe_claimable,
+ info->bytes_stripe_margin, info->bytes_stripe_reserve,
+- (s64)atomic64_read(&info->bytes_unmanaged_free));
++ (s64)atomic64_read(&info->bytes_unmanaged_free),
++ info->bytes_stripe_quarantine);
+ }
+
+ void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
+--
+2.47.3
+
+++ /dev/null
-From 064683b6372aa03e0064c377b0c95b2057c94ad0 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 1 Oct 2026 04:20:09 -0400
-Subject: [RFC PATCH 074/116] btrfs: stripe_alloc: let relocation allocate a
- data chunk before it fails
-To: linux-btrfs@vger.kernel.org
-
-"btrfs: stripe_alloc: never let relocation wait on the whole-stripe gate"
-took BTRFS_RESERVE_FLUSH_DATA_RELOC out of can_ticket() on every
-filesystem. The point was not to wait at the stripe_alloc fill edge, but
-a reservation that cannot ticket also never reaches the flush states that
-allocate a data chunk. So relocation's prealloc reservation failed with
-ENOSPC whenever the existing data chunks happened to be full, however
-much unallocated space there was: balance-resume-test on a 10G
-single-device filesystem holding 4.5G reported "4 enospc errors during
-balance", each group refused within milliseconds of starting.
-
-When a relocation reservation fails, force one data chunk allocation and
-retry once. It still never waits: if no chunk can be allocated, or the
-new one does not help, it fails as before.
-
-Fixes: "btrfs: stripe_alloc: never let relocation wait on the whole-stripe gate"
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/space-info.c | 32 ++++++++++++++++++++++++++++++++
- 1 file changed, 32 insertions(+)
-
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index a672d1b304cfb..1dcd20f69fcb1 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -2257,6 +2257,28 @@ 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.
- */
-+/*
-+ * 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 once. 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;
-+}
-+
- int btrfs_reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
- enum btrfs_reserve_flush_enum flush)
- {
-@@ -2288,6 +2310,16 @@ int btrfs_reserve_data_bytes_held(struct btrfs_space_info *space_info, u64 bytes
- if (held)
- *held = 0;
- ret = __reserve_bytes(space_info, bytes, flush, held);
-+ /*
-+ * Not waiting is right at the stripe_alloc fill edge, where the space
-+ * relocation would wait for is what relocation itself frees. It is not
-+ * a reason to fail while there is unallocated space for a new chunk:
-+ * that made balance fail with ENOSPC on any filesystem whose data chunks
-+ * happened to be full.
-+ */
-+ if (ret == -ENOSPC && flush == BTRFS_RESERVE_FLUSH_DATA_RELOC &&
-+ reloc_alloc_data_chunk(space_info))
-+ ret = __reserve_bytes(space_info, bytes, flush, held);
- if (ret == -ENOSPC) {
- trace_btrfs_space_reservation(fs_info, "space_info:enospc",
- space_info->flags, bytes, 1);
---
-2.47.3
-
+++ /dev/null
-From 5487876f6a49d704e821e2911459e8e1541aa408 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 1 Oct 2026 12:14:49 -0400
-Subject: [RFC PATCH 075/116] btrfs: stripe_alloc: keep a stripe in the rbio
- cache until its run has written all of it
-To: linux-btrfs@vger.kernel.org
-
-A stripe run hands out its sectors in order, so a stripe it allocates is
-often written in pieces: a write that ends inside the stripe leaves the
-rest to later writes, and writeback allocates a whole range before any of
-its bios complete, so even a stripe the frontier has already passed can
-still have writes in flight. The later writes cannot pad (the earlier
-sectors are live), so unless the stripe is still in the rbio cache each
-is a read-modify-write that reads the earlier sectors back from the
-devices. Those sectors are not yet covered by the csum tree (their
-ordered extents have not finished), so what the devices return goes into
-the new parity unverified. A device that returns wrong data there
-destroys the earlier write, whose only intact copy at that point may be
-the parity: the strip-fault fixture (a device that returns random bytes
-for one strip per stripe) lost a file exactly this way, with every RMW of
-the run in this same-run class.
-
-The cache already prevents that read when the stripe is still cached: the
-later write steals the earlier write's pages (lock_stripe_add()) and reads
-nothing. But the cache is an LRU that any other stripe's write can push
-such a stripe out of. Pin it instead. Each run gets a written map beside
-its live map, set from each completed raid56 write's covered data sectors
-(rbio_orig_end_io(), before the cache decision in unlock_stripe()).
-cache_rbio() pins an rbio whose stripe is still waiting for writes
-(btrfs_stripe_run_incomplete()): an open run's allocation frontier lies
-inside it -- the rest is not even allocated yet, so every sector
-allocated so far may already be written -- or a run covering it, open,
-closed or kept for relocation, has live sectors there not yet written.
-The prune skips live pins and re-checks each against the runs, so a pin
-ends as soon as the stripe is complete or its run goes away. Nodatacow
-runs are excluded from the written check: they are rewritten in place
-for as long as the inode lives and are never complete. RBIO_PIN_MAX
-bounds the pinned entries; no memory is allocated for this, the stripe's
-pages are only released later. A completed write is marked in the run
-that owns it, by [run->start, run->end): the maps reach past run->end
-(they span at least BTRFS_STRIPE_RUN_LIVE_STRIPES stripes), so a write
-must never be recorded in an earlier run whose map merely overlaps it.
-written_not_live in stripe_park_stats counts completed-write sectors that
-are not live in their run, which should stay near zero.
-
-This removes the read rather than adding a recovery step for it: nothing
-here depends on checksums, sectors without them, or the reconstruction
-path. What remains is a stripe's first partial write, which reads only
-sectors nobody has written yet (traced on the fixture: every remaining
-data RMW read was of that kind). rbio_pinned in stripe_park_stats counts
-the pins.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 152 ++++++++++++++++++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 4 ++
- fs/btrfs/fs.h | 4 ++
- fs/btrfs/raid56.c | 138 ++++++++++++++++++++++++++++++++++---
- fs/btrfs/sysfs.c | 4 ++
- 5 files changed, 290 insertions(+), 12 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 946102aea2df6..beaa80d48291f 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -528,6 +528,13 @@ struct btrfs_open_stripe_run {
- * the run knows -- it handed the space out and took it back.
- */
- unsigned long *live;
-+ /*
-+ * Sectors of @live whose data has been written (raid56 write
-+ * completions, btrfs_stripe_run_mark_written()); same size as @live.
-+ * A stripe with live sectors not yet written is still waiting for
-+ * writes, and its cached rbio stays pinned (raid56.c, cache_rbio()).
-+ */
-+ unsigned long *written;
- u32 live_nbits; /* sectors @live covers; caps growth */
- };
-
-@@ -751,6 +758,7 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
- ASSERT(open_stripe_run_drained(run));
- list_del(&run->list);
- bitmap_free(run->live);
-+ bitmap_free(run->written);
- kfree(run);
- /*
- * Wholly free stripes inside this run's range were counted as trapped
-@@ -1002,6 +1010,8 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
-
- /* 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 ?
-+ bitmap_zalloc(new_run->live_nbits, GFP_NOFS) : NULL;
-
- /*
- * Install under fs_info->open_stripe_lock so that the block group
-@@ -1126,8 +1136,10 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- ret = 0;
- out:
- /* Unused on every path that did not install it, including errors. */
-- if (new_run)
-+ if (new_run) {
- bitmap_free(new_run->live);
-+ bitmap_free(new_run->written);
-+ }
- kfree(new_run);
- return ret;
- }
-@@ -1262,6 +1274,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- 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 ?
-+ bitmap_zalloc(new_run->live_nbits, GFP_NOFS) : NULL;
-
- /* See the installation comment in btrfs_alloc_from_open_stripe(). */
- spin_lock(&fs_info->open_stripe_lock);
-@@ -1313,8 +1327,10 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- ret = 0;
- out:
- /* Unused on every path that did not install it, including errors. */
-- if (new_run)
-+ if (new_run) {
- bitmap_free(new_run->live);
-+ bitmap_free(new_run->written);
-+ }
- kfree(new_run);
- return ret;
- }
-@@ -2373,6 +2389,137 @@ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
- * class: the raid56 parking gate treats NOCOW-class runs specially
- * (sync writes into them never park; see rbio_try_park()).
- */
-+/*
-+ * The part of [*start, *start + *len) that @run owns and tracks in its
-+ * written map: inside [run->start, run->end) -- the map itself reaches
-+ * further (it spans at least BTRFS_STRIPE_RUN_LIVE_STRIPES stripes from
-+ * run->start, past run->end into later runs' ranges), so it must never be
-+ * consulted outside the run's own range -- and inside the map. Nodatacow
-+ * runs keep no written map: they are rewritten in place for as long as the
-+ * inode lives and are never complete. Caller holds stripe_run_lock.
-+ */
-+static bool run_written_range(const struct btrfs_open_stripe_run *run,
-+ u64 *start, u64 *len)
-+{
-+ const u32 bits = run->bg->fs_info->sectorsize_bits;
-+ u64 lo, hi;
-+
-+ if (run->class == BTRFS_STRIPE_RUN_NOCOW)
-+ return false;
-+ if (!run->live || !run->written || !run->live_nbits)
-+ return false;
-+ lo = max(*start, run->start);
-+ hi = min3(*start + *len, run->end,
-+ run->start + ((u64)run->live_nbits << bits));
-+ if (lo >= hi)
-+ return false;
-+ *start = lo;
-+ *len = hi - lo;
-+ return true;
-+}
-+
-+/*
-+ * A raid56 write of [start, start + len) has completed: mark it written in
-+ * the run that owns it. Sectors that are not live in that run (freed while
-+ * the write was in flight, or a bookkeeping bug) are counted in
-+ * written_not_live: the pad oracle trusts this map to say which allocated
-+ * sectors hold data, so a write it misses could be zeroed.
-+ */
-+void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
-+ u64 len)
-+{
-+ const u32 bits = fs_info->sectorsize_bits;
-+ struct btrfs_block_group *bg;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ u32 not_live = 0;
-+
-+ if (list_empty_careful(&fs_info->open_stripe_bgs))
-+ return;
-+ bg = btrfs_lookup_block_group(fs_info, start);
-+ if (!bg)
-+ return;
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ u64 s = start, l = len;
-+ u32 first, nr, i;
-+
-+ if (!run_written_range(run, &s, &l))
-+ continue;
-+ first = (s - run->start) >> bits;
-+ nr = l >> bits;
-+ for (i = first; i < first + nr; i++)
-+ if (!test_bit(i, run->live))
-+ not_live++;
-+ bitmap_set(run->written, first, nr);
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ btrfs_put_block_group(bg);
-+ if (not_live)
-+ atomic64_add(not_live, &fs_info->stripe_park_stats.written_not_live);
-+}
-+
-+/* Has @run allocated sectors in [start, start + len) it has not yet written? */
-+static bool run_unwritten_in(struct btrfs_open_stripe_run *run, u64 start,
-+ u64 len)
-+{
-+ const u32 bits = run->bg->fs_info->sectorsize_bits;
-+ u32 first, last, i;
-+
-+ if (!run_written_range(run, &start, &len))
-+ return false;
-+ first = (start - run->start) >> bits;
-+ last = first + (len >> bits);
-+ for (i = first; i < last; i++)
-+ if (test_bit(i, run->live) && !test_bit(i, run->written))
-+ return true;
-+ return false;
-+}
-+
-+/*
-+ * Is [stripe_start, stripe_start + stripe_len) still waiting for writes from
-+ * a stripe run? Two ways:
-+ *
-+ * - an open run's allocation frontier lies strictly inside it: the run will
-+ * allocate and write the rest of the stripe later, although every sector
-+ * allocated so far may already be written;
-+ * - a run covering it has sectors allocated (live) but not yet written: the
-+ * frontier has moved past, and the writes are still in flight (writeback
-+ * allocates a whole range before any of its bios complete).
-+ *
-+ * Either way the stripe has been written in part, and the rest will arrive
-+ * as a sub-stripe write that needs the part already written.
-+ */
-+bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
-+ u64 stripe_start, u64 stripe_len)
-+{
-+ struct btrfs_block_group *bg;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ bool ret = false;
-+
-+ if (list_empty_careful(&fs_info->open_stripe_bgs))
-+ return false;
-+ bg = btrfs_lookup_block_group(fs_info, stripe_start);
-+ if (!bg)
-+ return false;
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (run->open && run->offset > stripe_start &&
-+ run->offset < stripe_start + stripe_len) {
-+ ret = true;
-+ break;
-+ }
-+ if (run_unwritten_in(run, stripe_start, stripe_len)) {
-+ ret = true;
-+ break;
-+ }
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ btrfs_put_block_group(bg);
-+ return ret;
-+}
-+
- bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class)
- {
-@@ -2775,6 +2922,7 @@ void btrfs_free_open_stripe_runs(struct btrfs_fs_info *fs_info)
- run->inflight_bytes);
- list_del(&run->list);
- bitmap_free(run->live);
-+ bitmap_free(run->written);
- kfree(run);
- }
- memset(bg->open_stripe, 0, sizeof(bg->open_stripe));
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index c8724effe36ca..fff321197b604 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -490,6 +490,10 @@ bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical);
- bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
- struct extent_buffer *eb,
- const struct writeback_control *wbc);
-+void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
-+ u64 len);
-+bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
-+ u64 stripe_start, u64 stripe_len);
- bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class);
- u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 16fdd69b7f16f..102892575f7cc 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -922,6 +922,10 @@ struct btrfs_fs_info {
- committed extent tree */
- atomic64_t meta_rmw_free;
- atomic64_t congestion_short;
-+ /* Frontier stripes pinned in the rbio cache (cache_rbio()). */
-+ atomic64_t rbio_pinned;
-+ /* Completed-write sectors not live in their run (should be ~0). */
-+ atomic64_t written_not_live;
- } stripe_park_stats;
-
- #ifdef CONFIG_BTRFS_DEBUG
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 865ecb86b9ead..c77a26ceab18e 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -78,6 +78,17 @@
- */
- #define RBIO_SYNC_PARK_BIT 8
-
-+/*
-+ * Set while a cached rbio holds a stripe that its run has not finished
-+ * writing: the cache prune skips it, so the run's next write into the stripe
-+ * takes the part already written from memory instead of reading it back
-+ * from the devices (see cache_rbio()).
-+ */
-+#define RBIO_PINNED_BIT 9
-+
-+/* At most this many pinned stripes; normally about one per stripe run. */
-+#define RBIO_PIN_MAX 256
-+
- #define RBIO_CACHE_SIZE 1024
-
- /*
-@@ -182,6 +193,8 @@ struct btrfs_stripe_hash_table {
- struct list_head stripe_cache;
- spinlock_t cache_lock;
- int cache_size;
-+ /* Cached rbios with RBIO_PINNED_BIT set, live or not. */
-+ int nr_pinned;
- /*
- * Parked partial write rbios (RBIO_PARKED_BIT), in park order.
- * parked_lock nests inside the hash and bio_list locks.
-@@ -563,6 +576,8 @@ static void __remove_rbio_from_cache(struct btrfs_raid_bio *rbio)
- if (test_and_clear_bit(RBIO_CACHE_BIT, &rbio->flags)) {
- list_del_init(&rbio->stripe_cache);
- table->cache_size -= 1;
-+ if (test_and_clear_bit(RBIO_PINNED_BIT, &rbio->flags))
-+ table->nr_pinned -= 1;
- freeit = true;
-
- /* if the bio list isn't empty, this rbio is
-@@ -641,6 +656,111 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info)
- info->stripe_hash_table = NULL;
- }
-
-+/*
-+ * The frontier stripe of an open stripe run is written more than once: the
-+ * run hands out its sectors in order, and each write that ends inside the
-+ * stripe leaves the rest to a later write. That later write cannot pad (the
-+ * earlier sectors are live) and would read them back: a read-modify-write
-+ * whose neighbour sectors are not yet covered by the csum tree (their ordered
-+ * extents have not finished), so whatever the devices return is folded into
-+ * parity unverified. Keep the stripe cached instead, so the later write
-+ * steals the pages it needs (lock_stripe_add()) and reads nothing.
-+ *
-+ * The stripe in question is any stripe its run has not finished writing
-+ * (btrfs_stripe_run_incomplete()): the stripe holding an open run's
-+ * allocation frontier, and also a stripe the frontier has already passed
-+ * whose remaining writes are still in flight (writeback allocates a whole
-+ * range before any of its bios complete -- most of the RMWs left by a
-+ * frontier-only pin were these). The pin lasts until the frontier has left
-+ * the stripe and every allocated sector of it has been written, or the run
-+ * goes away; each prune re-checks it against the run. The run's next
-+ * write into the stripe replaces the entry, so there are about as many
-+ * pinned stripes as stripes with writes in flight.
-+ */
-+static bool rbio_needs_pin(const struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return false;
-+ return btrfs_stripe_run_incomplete(fs_info,
-+ rbio->bioc->full_stripe_logical,
-+ (u64)rbio->nr_data * rbio->bioc->stripe_len);
-+}
-+
-+/* Re-checked at every prune: the pin ends when its run has written it all. */
-+static bool rbio_pin_live(const struct btrfs_raid_bio *rbio)
-+{
-+ return test_bit(RBIO_PINNED_BIT, &rbio->flags) && rbio_needs_pin(rbio);
-+}
-+
-+/*
-+ * A write completed: tell the stripe runs which sectors now hold their data,
-+ * as contiguous ranges of the data sectors this rbio's bios covered.
-+ */
-+static void rbio_mark_written(struct btrfs_raid_bio *rbio)
-+{
-+ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
-+ const u32 sectorsize = fs_info->sectorsize;
-+ const int nr = rbio->nr_data * rbio->stripe_nsectors;
-+ int i, first = -1;
-+
-+ if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return;
-+ for (i = 0; i <= nr; i++) {
-+ const bool covered = i < nr && rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR;
-+
-+ if (covered && first < 0)
-+ first = i;
-+ if (!covered && first >= 0) {
-+ btrfs_stripe_run_mark_written(fs_info,
-+ rbio->bioc->full_stripe_logical +
-+ (u64)first * sectorsize,
-+ (u64)(i - first) * sectorsize);
-+ first = -1;
-+ }
-+ }
-+}
-+
-+/*
-+ * Mark @rbio pinned or not; caller holds the cache lock and @rbio is in the
-+ * cache.
-+ */
-+static void rbio_set_pin(struct btrfs_stripe_hash_table *table,
-+ struct btrfs_raid_bio *rbio, bool pin)
-+{
-+ if (pin && table->nr_pinned >= RBIO_PIN_MAX &&
-+ !test_bit(RBIO_PINNED_BIT, &rbio->flags))
-+ pin = false;
-+ if (pin) {
-+ if (!test_and_set_bit(RBIO_PINNED_BIT, &rbio->flags))
-+ table->nr_pinned += 1;
-+ atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.rbio_pinned);
-+ } else if (test_and_clear_bit(RBIO_PINNED_BIT, &rbio->flags)) {
-+ table->nr_pinned -= 1;
-+ }
-+}
-+
-+/*
-+ * Evict from the cold end until the cache is within @limit, keeping @rbio
-+ * (just cached) and live pins. Caller holds the cache lock.
-+ */
-+static void rbio_cache_prune(struct btrfs_stripe_hash_table *table,
-+ struct btrfs_raid_bio *rbio, unsigned int limit)
-+{
-+ struct btrfs_raid_bio *found, *tmp;
-+
-+ list_for_each_entry_safe_reverse(found, tmp, &table->stripe_cache,
-+ stripe_cache) {
-+ if (table->cache_size <= limit)
-+ break;
-+ if (found == rbio || rbio_pin_live(found))
-+ continue;
-+ /* __remove_rbio_from_cache() drops a stale pin's count. */
-+ __remove_rbio_from_cache(found);
-+ }
-+}
-+
- /*
- * insert an rbio into the stripe cache. It
- * must have already been prepared by calling
-@@ -655,10 +775,12 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info)
- static void cache_rbio(struct btrfs_raid_bio *rbio)
- {
- struct btrfs_stripe_hash_table *table;
-+ bool pin;
-
- if (!test_bit(RBIO_CACHE_READY_BIT, &rbio->flags))
- return;
-
-+ pin = rbio_needs_pin(rbio);
- table = rbio->bioc->fs_info->stripe_hash_table;
-
- spin_lock(&table->cache_lock);
-@@ -674,19 +796,11 @@ static void cache_rbio(struct btrfs_raid_bio *rbio)
- list_add(&rbio->stripe_cache, &table->stripe_cache);
- table->cache_size += 1;
- }
-+ rbio_set_pin(table, rbio, pin);
-
- spin_unlock(&rbio->bio_list_lock);
-
-- if (table->cache_size > RBIO_CACHE_SIZE) {
-- struct btrfs_raid_bio *found;
--
-- found = list_last_entry(&table->stripe_cache,
-- struct btrfs_raid_bio,
-- stripe_cache);
--
-- if (found != rbio)
-- __remove_rbio_from_cache(found);
-- }
-+ rbio_cache_prune(table, rbio, RBIO_CACHE_SIZE);
-
- spin_unlock(&table->cache_lock);
- }
-@@ -1383,6 +1497,10 @@ static void rbio_orig_end_io(struct btrfs_raid_bio *rbio, blk_status_t status)
- rbio->csum_buf = NULL;
- rbio->csum_bitmap = NULL;
-
-+ /* Before the cache decision in unlock_stripe(): see cache_rbio(). */
-+ if (rbio->operation == BTRFS_RBIO_WRITE && status == BLK_STS_OK)
-+ rbio_mark_written(rbio);
-+
- /*
- * Clear the data bitmap, as the rbio may be cached for later usage.
- * do this before unlock_stripe() so there will be no new bio
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 5cbff0b128288..ede9047dd1112 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1222,6 +1222,8 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "meta_rmw_ghost %lld\n"
- "meta_rmw_free %lld\n"
- "congestion_short %lld\n"
-+ "rbio_pinned %lld\n"
-+ "written_not_live %lld\n"
- "parked_now %d\n",
- atomic64_read(&fs_info->stripe_park_stats.parked),
- atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
-@@ -1257,6 +1259,8 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_ghost),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free),
- atomic64_read(&fs_info->stripe_park_stats.congestion_short),
-+ atomic64_read(&fs_info->stripe_park_stats.rbio_pinned),
-+ atomic64_read(&fs_info->stripe_park_stats.written_not_live),
- atomic_read(&fs_info->stripe_parked_now));
- }
- BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
---
-2.47.3
-
--- /dev/null
+From dbd6acf9aefead735973a3e9b9f70ad05488289b Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sun, 20 Sep 2026 01:33:09 -0400
+Subject: [RFC PATCH 75/85] btrfs: stripe_meta: cover raid56 system chunks
+To: linux-btrfs@vger.kernel.org
+
+The chunk tree lives in system chunks, which carry no METADATA bit, so the
+whole-stripe rule that stripe_meta applies to raid56 tree blocks never
+applied to it: chunk tree blocks were placed by the clustered allocator,
+sharing stripes with chunk tree blocks committed earlier, and every chunk
+tree COW was a read-modify-write of such a stripe. The RMW audit measured
+it (meta_rmw_old over system chunks during chunk churn), and the mount
+warned about it. A torn parity rewrite there is the worst write hole the
+filesystem can take: with a member then lost, the committed chunk tree
+block that shared the stripe reconstructs wrong, the checksum rejects it,
+and nothing maps -- the degraded mount fails, and there is no second copy.
+
+Include system block groups in btrfs_is_stripe_meta_bg(). Everything
+downstream already keys on that predicate: the whole-stripe allocation in
+do_allocation_stripe(), the trapped-space accounting, the covered/uncovered
+decision in the RMW report and the audit. The four walks that select
+groups by space_info flags (the enable-time sweep, the unusable-space scan,
+the reclaim tick, the commit-time metadata run retirement) gain SYSTEM
+alongside DATA and METADATA, so system groups are armed, scanned, reclaimed
+when trapped, and have their runs closed after the commit's tree writes
+like metadata groups.
+
+reserve_chunk_space() sizes its request in tree blocks, but a chunk tree
+COW that needs a fresh run takes a whole stripe for its first block; the
+trapped bytes and the open run's remainder are already counted as used, so
+what is left is whole free stripes, and the check now demands one stripe
+of headroom beyond the request -- deciding when to allocate the next
+system chunk, without reserving the headroom -- or the chunk item for that
+very allocation could find no stripe to land in.
+
+The "does not cover raid56 system chunks" warning has nothing left to
+warn about and goes.
+
+Assisted-by: Claude:claude-fable-5-1
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 76 +++++++++++++++++++++++-------------------
+ fs/btrfs/extent-tree.c | 23 ++++++-------
+ fs/btrfs/raid56.c | 11 +++---
+ 3 files changed, 56 insertions(+), 54 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 73c7b5575c39d..8bf9914d98bce 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -2366,7 +2366,8 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
+ int raid;
+
+ if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
+- BTRFS_BLOCK_GROUP_METADATA)))
++ BTRFS_BLOCK_GROUP_METADATA |
++ BTRFS_BLOCK_GROUP_SYSTEM)))
+ continue;
+ /*
+ * Metadata: the scan that maintains the stripe_meta margin
+@@ -2411,33 +2412,6 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
+ }
+ }
+
+-/*
+- * stripe_alloc covers raid56 *data* block groups only. A filesystem whose
+- * metadata is also raid56 keeps the write hole there. The data guarantee is
+- * easy to read as a filesystem-wide one, so say once, when the policy turns
+- * on, what is not covered. That is btrfs_enable_stripe_alloc(): at mount the
+- * property applies after the block groups are read, so a report from
+- * btrfs_read_block_groups() would find the flag still clear. (Mixed block
+- * groups cannot get here: the property refuses them.)
+- */
+-static void warn_stripe_alloc_uncovered(struct btrfs_fs_info *info)
+-{
+- if (!btrfs_test_opt(info, STRIPE_ALLOC))
+- return;
+-
+- /*
+- * raid56 metadata is covered now that the policy follows the chunk
+- * profile. System chunks are not: btrfs_is_stripe_meta_bg() tests
+- * the METADATA flag, and a system chunk does not carry it, so a
+- * raid56 system chunk keeps the legacy read-modify-write and its
+- * write hole. They are small and rewritten rarely, but say so
+- * rather than let the earlier "covered" message imply otherwise.
+- */
+- if (info->avail_system_alloc_bits & BTRFS_BLOCK_GROUP_RAID56_MASK)
+- btrfs_warn(info,
+-"stripe_alloc does not cover raid56 system chunks: the write hole remains for them, consider converting to raid1c3/raid1c4");
+-}
+-
+ /*
+ * Drain the writes the legacy allocator placed before stripe_alloc was
+ * enabled on a live filesystem, then arm the write-hole invariant check.
+@@ -2491,7 +2465,6 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
+ if (live)
+ set_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags);
+ btrfs_set_opt(fs_info->mount_opt, STRIPE_ALLOC);
+- warn_stripe_alloc_uncovered(fs_info);
+ /*
+ * Arm stripe_unusable accounting for raid56 data groups whose caches
+ * loaded before the policy was enabled: block groups are read before
+@@ -3158,7 +3131,8 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
+ bg = list_first_entry(&retire_list, struct btrfs_block_group,
+ open_stripe_retire_list);
+ list_del_init(&bg->open_stripe_retire_list);
+- if (!(bg->flags & BTRFS_BLOCK_GROUP_METADATA))
++ if (!(bg->flags & (BTRFS_BLOCK_GROUP_METADATA |
++ BTRFS_BLOCK_GROUP_SYSTEM)))
+ continue;
+
+ while (again) {
+@@ -3375,7 +3349,8 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
+ * both carry trapped free space. Mixed groups are refused.
+ */
+ if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
+- BTRFS_BLOCK_GROUP_METADATA)))
++ BTRFS_BLOCK_GROUP_METADATA |
++ BTRFS_BLOCK_GROUP_SYSTEM)))
+ continue;
+ down_read(&sinfo->groups_sem);
+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
+@@ -5657,7 +5632,8 @@ static void btrfs_stripe_reclaim_tick(struct btrfs_fs_info *fs_info)
+ int raid;
+
+ if (!(sinfo->flags & (BTRFS_BLOCK_GROUP_DATA |
+- BTRFS_BLOCK_GROUP_METADATA)))
++ BTRFS_BLOCK_GROUP_METADATA |
++ BTRFS_BLOCK_GROUP_SYSTEM)))
+ continue;
+ if (READ_ONCE(sinfo->bg_reclaim_threshold) <= 0)
+ continue;
+@@ -7878,6 +7854,7 @@ static void reserve_chunk_space(struct btrfs_trans_handle *trans,
+ {
+ struct btrfs_fs_info *fs_info = trans->fs_info;
+ struct btrfs_space_info *info;
++ u64 headroom = 0;
+ u64 left;
+ bool want_system_chunk, need_system_chunk;
+ int ret = 0;
+@@ -7892,12 +7869,41 @@ static void reserve_chunk_space(struct btrfs_trans_handle *trans,
+ spin_lock(&info->lock);
+ left = info->total_bytes - btrfs_space_info_used(info, true);
+ want_system_chunk = info->total_bytes < system_space_target(info);
+- need_system_chunk = left < bytes;
+ spin_unlock(&info->lock);
+
++ /*
++ * Under stripe_alloc a raid56 system chunk places its tree blocks by
++ * whole stripes (btrfs_is_stripe_meta_bg()), and the bytes trapped in
++ * partial stripes and the open run's remainder are already counted
++ * as used above. What is left is whole free stripes, but the request
++ * is sized in tree blocks: a chunk tree COW that needs a fresh run
++ * takes a whole stripe for its first block, so demand one stripe of
++ * headroom beyond the request, or the chunk item for the very system
++ * chunk this would allocate finds no stripe to land in. The headroom
++ * decides when to allocate; it is not reserved.
++ */
++ if (btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
++ int raid;
++
++ down_read(&info->groups_sem);
++ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
++ struct btrfs_block_group *bg;
++
++ if (!(btrfs_raid_array[raid].bg_flag &
++ BTRFS_BLOCK_GROUP_RAID56_MASK))
++ continue;
++ list_for_each_entry(bg, &info->block_groups[raid], list)
++ headroom = max_t(u64, headroom,
++ bg->full_stripe_len);
++ }
++ up_read(&info->groups_sem);
++ }
++
++ need_system_chunk = left < bytes + headroom;
++
+ if (need_system_chunk && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
+- btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
+- left, bytes, type);
++ btrfs_info(fs_info, "left=%llu, need=%llu, headroom=%llu, flags=%llu",
++ left, bytes, headroom, type);
+ btrfs_dump_space_info(info, 0, false);
+ }
+
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 8fce8a5568222..51d06531a15ae 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4242,23 +4242,20 @@ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
+ /*
+ * Should this block group allocate tree blocks by whole stripes?
+ *
+- * The same rule data follows: only fully free stripes are claimed, and the
+- * partial stripe left at the end of a commit is padded out rather than
+- * revisited, so no tree block write ever lands in a stripe holding earlier
+- * committed data. Not separately gated: the chunk profile already decides
+- * it. raid56 metadata has the same write hole as raid56 data and gets the
+- * same protection at the same time; metadata on any other profile has no
+- * write hole to close, and the RAID56_MASK test below means the policy
+- * simply does not apply to it. The costs metadata brings -- a stranded
+- * stripe tail per commit, and an allocation failure that aborts the
+- * transaction rather than failing one write -- are the price of covering
+- * raid56 metadata at all, and a filesystem that does not want them wants
+- * raid1c3/raid1c4 metadata instead, which is the better answer anyway.
++ * The same rule as data: only fully free stripes are claimed, and the
++ * partial stripe left at the end of a commit is padded rather than
++ * revisited, so no tree block lands in a stripe holding committed blocks.
++ * It applies to every raid56 metadata and system group while stripe_alloc
++ * is on. The costs are a stranded stripe tail per commit, and an
++ * allocation failure aborts the transaction instead of failing one write.
++ * System chunks carry no METADATA bit but hold the chunk tree, so they are
++ * named explicitly.
+ */
+ bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg)
+ {
+ return btrfs_test_opt(bg->fs_info, STRIPE_ALLOC) &&
+- (bg->flags & BTRFS_BLOCK_GROUP_METADATA) &&
++ (bg->flags & (BTRFS_BLOCK_GROUP_METADATA |
++ BTRFS_BLOCK_GROUP_SYSTEM)) &&
+ !(bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
+ (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
+ !test_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &bg->runtime_flags);
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index c2ba1f3e7a25c..1afccd067b8a9 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -3593,12 +3593,11 @@ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
+
+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw);
+ /*
+- * A raid56 metadata group under stripe_meta is covered: its
+- * read-modify-writes are partial writes inside one transaction's
+- * run, counted by the audit as meta_rmw_cur, and the audit warns
+- * by itself should one ever touch a committed block. Only system
+- * chunks and mixed groups are the uncovered case this message is
+- * about.
++ * Every raid56 metadata and system group is a stripe_meta group while
++ * stripe_alloc is on, and stripe_alloc refuses to enable on mixed
++ * groups (btrfs_stripe_alloc_check_support()), so this warning is a
++ * defensive check: it fires only if a tree block group that should be
++ * covered is not.
+ */
+ bg = btrfs_lookup_block_group(fs_info, rbio->bioc->full_stripe_logical);
+ if (bg) {
+--
+2.47.3
+
+++ /dev/null
-From 3c72edd2884f45c05a461ed4ae62bc790b7f6833 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 2 Oct 2026 02:41:44 -0400
-Subject: [RFC PATCH 076/116] btrfs: stripe_alloc: pad a stripe's allocated
- sectors whose write is still to come
-To: linux-btrfs@vger.kernel.org
-
-A stripe run's first partial write into a stripe cannot pad today: the
-stripe's other sectors are allocated (live) to writes that are still in
-flight, so the pad oracle calls them live and the write goes down as a
-read-modify-write of the whole stripe. With the stripe pin keeping the
-stripe cached for every later write, this first write is the only data RMW
-left in a stripe run (traced on the strip-fault fixture: every remaining
-data RMW read was a first write), and the read it does is of sectors
-nobody has written: it can only fetch garbage into the parity, and on a
-device that returns wrong data it makes that parity disagree with what is
-on the disk.
-
-Use the run's written map: a live sector whose write has not completed
-holds nothing anyone has written, so it is as paddable as a dead one.
-Zeroing it is safe because its write is ordered after this one -- the
-padding write holds the stripe lock, every raid56 write to the stripe
-takes it, and rbio_orig_end_io() records a write's sectors in the written
-map before it unlocks the stripe -- and nothing reads the sector before
-its own write lands, since its extent is not committed until then. That
-write replaces the zeros; it is a sub-stripe write into a stripe written
-before, which the stripe pin serves from the cache.
-
-A live sector that HAS been written still refuses the pad, as before:
-that is now the precise meaning of the UNCOVERED decline. Nodatacow runs
-keep no written map (their extents are rewritten in place for as long as
-the inode lives) and are excluded. padded_unwritten in stripe_park_stats
-counts the pads that zeroed such sectors.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 34 ++++++++++++++++++++++++++++++----
- fs/btrfs/block-group.h | 1 +
- fs/btrfs/fs.h | 2 ++
- fs/btrfs/raid56.c | 28 +++++++++++++++++++++-------
- fs/btrfs/sysfs.c | 2 ++
- 5 files changed, 56 insertions(+), 11 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index beaa80d48291f..9b164bcac06e5 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1791,10 +1791,25 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
- * Which sectors of this stripe may be padded?
- *
- * Fills @dead with one bit per sector of the stripe, set where the sector
-- * holds nothing anyone intends to write: space the run has not handed out
-- * yet, and space it handed out but got back before the write was issued.
-+ * holds nothing anyone has written: space the run has not handed out yet,
-+ * space it handed out but got back before the write was issued, and space
-+ * it handed out whose write has not completed yet (the run's written map).
- * A caller may zero-fill exactly those and write the whole stripe.
- *
-+ * Zeroing an allocated sector whose write is still to come is safe because
-+ * that write is ordered after the caller's: the caller holds the stripe
-+ * lock, and every raid56 write to the stripe takes it; the sector's
-+ * completed writes are all in the written map by then (rbio_orig_end_io()
-+ * marks them before it unlocks the stripe), and nothing reads the sector
-+ * before its own write lands -- its extent is not committed until then.
-+ * It is what lets a stripe's FIRST partial write pad instead of reading
-+ * the rest of the stripe: the remaining sectors are allocated to writes
-+ * still in flight, and nobody has written them. Nodatacow runs are
-+ * excluded: they keep no written map (their extents are rewritten in
-+ * place for as long as the inode lives), so their live sectors hold data.
-+ * @unwritten, when non-NULL, gets the subset of @dead that is allocated
-+ * but unwritten.
-+ *
- * Returns false if no run covers the stripe, in which case nothing may be
- * padded: without a run there is no claim of exclusivity, and an uncovered
- * sector may hold committed data.
-@@ -1812,6 +1827,7 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
- */
- bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
- u64 stripe_len, unsigned long *dead,
-+ unsigned long *unwritten,
- struct btrfs_stripe_pad_info *info)
- {
- const u32 bits = fs_info->sectorsize_bits;
-@@ -1888,9 +1904,19 @@ bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
- break;
- }
- bitmap_zero(dead, nsectors);
-- for (u32 i = 0; i < nsectors; i++)
-- if (!test_bit(first + i, run->live))
-+ if (unwritten)
-+ bitmap_zero(unwritten, nsectors);
-+ for (u32 i = 0; i < nsectors; i++) {
-+ if (!test_bit(first + i, run->live)) {
-+ set_bit(i, dead);
-+ } else if (run->written &&
-+ run->class != BTRFS_STRIPE_RUN_NOCOW &&
-+ !test_bit(first + i, run->written)) {
- set_bit(i, dead);
-+ if (unwritten)
-+ set_bit(i, unwritten);
-+ }
-+ }
- if (info)
- info->reason = BTRFS_STRIPE_PAD_OK;
- ret = true;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index fff321197b604..ccb47edf2b895 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -547,6 +547,7 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
- u64 stripe_start, u64 stripe_len);
- bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
- u64 stripe_len, unsigned long *dead,
-+ 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);
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 102892575f7cc..6fc0aea024156 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -870,6 +870,8 @@ struct btrfs_fs_info {
- atomic64_t stuck;
- atomic64_t rmw_reads;
- atomic64_t padded;
-+ /* Pads that zeroed allocated sectors whose write was to come. */
-+ atomic64_t padded_unwritten;
- /*
- * Data read-modify-writes on a block group the allocator
- * covers. With allow_rmw empty this is the number the
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index c77a26ceab18e..7619793710679 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -3375,7 +3375,9 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- const u32 nsectors = rbio->nr_data * rbio->stripe_nsectors;
- struct btrfs_stripe_pad_info info;
- unsigned long *dead;
-+ unsigned long *unwritten;
- u32 covered = 0;
-+ u32 nr_unwritten = 0;
- bool ok = false;
- int i;
-
-@@ -3384,10 +3386,14 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- return false;
-
- dead = bitmap_zalloc(nsectors, GFP_NOFS);
-- if (!dead)
-+ unwritten = bitmap_zalloc(nsectors, GFP_NOFS);
-+ if (!dead || !unwritten) {
-+ bitmap_free(dead);
-+ bitmap_free(unwritten);
- return false;
-+ }
- if (!btrfs_stripe_run_pad_mask(fs_info, stripe_start, stripe_len, dead,
-- &info)) {
-+ unwritten, &info)) {
- rbio_record_pad(rbio, &info);
- trace_btrfs_stripe_pad_decline(fs_info, stripe_start,
- stripe_len, 0, 0, nsectors,
-@@ -3406,11 +3412,14 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- covered++;
-
- /*
-- * Every data sector this rbio does not cover must be dead. A live
-- * uncovered sector belongs to another writer's allocation and this
-- * write does not carry its data, so padding would destroy it: that
-- * is a distinct refusal from the oracle's, and it is the one that
-- * says another writer's allocation shares this stripe.
-+ * Every data sector this rbio does not cover must be dead: never
-+ * handed out, handed back, or handed out with its write still to
-+ * come (the oracle's written map; that write replaces the zeros). A
-+ * live uncovered sector that HAS been written holds data this write
-+ * does not carry, so padding would destroy it: that is a distinct
-+ * refusal from the oracle's, and it is the one that says the stripe
-+ * was written before -- the stripe pin (cache_rbio()) normally hands
-+ * this write those sectors from the cache, so it reads nothing.
- */
- for (i = 0; i < nsectors; i++) {
- if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
-@@ -3429,10 +3438,13 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- info.reason);
- goto out;
- }
-+ if (test_bit(i, unwritten))
-+ nr_unwritten++;
- }
- ok = true;
- out:
- bitmap_free(dead);
-+ bitmap_free(unwritten);
- if (!ok)
- return false;
-
-@@ -3463,6 +3475,8 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- /* The whole stripe goes out: every vertical position is written. */
- bitmap_set(&rbio->dbitmap, 0, rbio->stripe_nsectors);
- atomic64_inc(&fs_info->stripe_park_stats.padded);
-+ if (nr_unwritten)
-+ atomic64_inc(&fs_info->stripe_park_stats.padded_unwritten);
- return true;
- }
-
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index ede9047dd1112..aad4767baad63 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1196,6 +1196,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "expired %lld\n"
- "stuck %lld\n"
- "padded %lld\n"
-+ "padded_unwritten %lld\n"
- "rmw_reads %lld\n"
- "data_rmw %lld\n"
- "pad_decline_live %lld\n"
-@@ -1233,6 +1234,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.expired),
- atomic64_read(&fs_info->stripe_park_stats.stuck),
- atomic64_read(&fs_info->stripe_park_stats.padded),
-+ atomic64_read(&fs_info->stripe_park_stats.padded_unwritten),
- atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
- atomic64_read(&fs_info->stripe_park_stats.data_rmw),
- atomic64_read(&fs_info->stripe_park_stats.pad_decline_live),
---
-2.47.3
-
--- /dev/null
+From 370ac4e55a9ea07cc456c2c1c135419bbf020b7c Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 10 Oct 2026 00:19:18 -0400
+Subject: [RFC PATCH 76/85] btrfs: stripe_alloc: skip RAID5/6 groups that are
+ mapped as RAID1/RAID1C3 (stripe_meta part 2)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: skip RAID5/6 groups that are mapped
+as RAID1/RAID1C3" (earlier in this series) that need code from "btrfs:
+stripe_meta: cover raid56 system chunks", which comes after it in this
+series: they are applied here, once "btrfs: stripe_meta: cover raid56
+system chunks" is in, instead of with the rest of "btrfs: stripe_alloc:
+skip RAID5/6 groups that are mapped as RAID1/RAID1C3".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/extent-tree.c | 4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 51d06531a15ae..39fac849accd0 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4245,8 +4245,8 @@ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
+ * The same rule as data: only fully free stripes are claimed, and the
+ * partial stripe left at the end of a commit is padded rather than
+ * revisited, so no tree block lands in a stripe holding committed blocks.
+- * It applies to every raid56 metadata and system group while stripe_alloc
+- * is on. The costs are a stranded stripe tail per commit, and an
++ * It applies to every raid56 metadata and system group with more than one
++ * data stripe while stripe_alloc is on. The costs are a stranded stripe tail per commit, and an
+ * allocation failure aborts the transaction instead of failing one write.
+ * System chunks carry no METADATA bit but hold the chunk tree, so they are
+ * named explicitly.
+--
+2.47.3
+
+++ /dev/null
-From 0549fac4c074fc636f19a7c0f7e221f1ccd0c477 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 3 Oct 2026 18:57:15 -0400
-Subject: [RFC PATCH 077/116] btrfs: stripe_alloc: apply the property before
- tree-log replay
-To: linux-btrfs@vger.kernel.org
-
-The btrfs.stripe_alloc property comes into force when the top-level root
-directory's inode loads, which open_ctree() does after log replay, on the
-grounds that replay allocates no new data. It does allocate tree blocks,
-though, and commits them: btrfs_recover_log_trees() ends in a transaction
-commit. Without the policy those tree blocks go wherever there is free
-space, and after a crash that includes the free sectors left in partially
-written metadata stripes -- the crashed transaction's blocks and the tails
-of its stripe runs -- next to blocks the last commit still references.
-Writing them is a read-modify-write of those stripes: a write hole for as
-long as replay runs, and with a device that returns bad data, parity that
-no longer rebuilds the committed blocks.
-
-The strip-fault fixture found this: with raid5 metadata, a crash right
-after a burst of fsyncs, then a mount with one member returning random data
-for one strip per stripe, lost 54-214 files written and synced long before
-the crash, with about 20 tree blocks that could not be rebuilt. Every
-read-modify-write in the affected stripes came from
-open_ctree -> btrfs_recover_log_trees -> btrfs_commit_transaction.
-
-Read the xattr item before replay and enable the policy if it is set. It
-is read directly rather than through an inode: replay may rewrite the root
-directory's inode item, and an inode cached across it would go stale. The
-root directory's load after replay is unchanged and still applies the
-final state, including a change to the property that the log carried.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/disk-io.c | 12 +++++++----
- fs/btrfs/props.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++
- fs/btrfs/props.h | 1 +
- 3 files changed, 61 insertions(+), 4 deletions(-)
-
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index 3d3a51cd963d0..d61b2c42fd0a8 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -47,6 +47,7 @@
- #include "root-tree.h"
- #include "defrag.h"
- #include "uuid-tree.h"
-+#include "props.h"
- #include "relocation.h"
- #include "scrub.h"
- #include "super.h"
-@@ -3758,6 +3759,8 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
- if (btrfs_super_log_root(disk_super) != 0 &&
- !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
- btrfs_info(fs_info, "start tree-log replay");
-+ /* Replay allocates tree blocks: the policy must hold for them. */
-+ btrfs_load_stripe_alloc_prop_early(fs_info);
- ret = btrfs_replay_log(fs_info, fs_devices);
- if (ret)
- goto fail_qgroup;
-@@ -3776,10 +3779,11 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
- * policy) before anything that can allocate data -- the resumed
- * balance or dev replace kicked off below -- so filesystem-wide
- * policy is in force for every allocation this mount ever makes.
-- * Log replay above needed no policy: it allocates no new data, only
-- * re-references extents written before the crash. The iget applies
-- * the properties as a side effect; the later iget from fill_super
-- * finds them already applied.
-+ * Log replay above allocates no new data, only re-references extents
-+ * written before the crash, but it does allocate tree blocks and
-+ * commit them: btrfs_load_stripe_alloc_prop_early() put the policy in
-+ * force for that. The iget applies the properties as a side effect;
-+ * the later iget from fill_super finds them already applied.
- */
- {
- struct btrfs_inode *root_dir;
-diff --git a/fs/btrfs/props.c b/fs/btrfs/props.c
-index a09cc9481a696..9058360304270 100644
---- a/fs/btrfs/props.c
-+++ b/fs/btrfs/props.c
-@@ -18,6 +18,7 @@
- #include "block-group.h"
- #include "super.h"
- #include "dir-item.h"
-+#include "disk-io.h"
-
- #define BTRFS_PROP_HANDLERS_HT_BITS 8
- static DEFINE_HASHTABLE(prop_handlers_ht, BTRFS_PROP_HANDLERS_HT_BITS);
-@@ -284,6 +285,57 @@ static void inode_prop_iterator(void *ctx,
- set_bit(BTRFS_INODE_HAS_PROPS, &BTRFS_I(inode)->runtime_flags);
- }
-
-+/*
-+ * Apply the btrfs.stripe_alloc property before tree-log replay.
-+ *
-+ * The policy normally comes into force when the top-level root directory's
-+ * inode loads (prop_stripe_alloc_apply()), which open_ctree() does after log
-+ * replay. But replay allocates tree blocks and commits a transaction, and
-+ * without the policy those allocations land wherever there is free space --
-+ * including the free sectors a crash leaves in partially written stripes --
-+ * so its writes are read-modify-writes of stripes holding committed
-+ * metadata: a write hole for as long as replay runs, and with a device that
-+ * returns bad data, parity that no longer rebuilds the committed blocks.
-+ *
-+ * Read the xattr item directly rather than through an inode: replay may
-+ * rewrite the root directory's inode item, and an inode cached across it
-+ * would go stale. Only a set property is acted on here; the root
-+ * directory's load after replay applies the final state as usual, including
-+ * a change to the property that the log itself carried. Errors are left to
-+ * that load to report, as for any property.
-+ */
-+void btrfs_load_stripe_alloc_prop_early(struct btrfs_fs_info *fs_info)
-+{
-+ static const char name[] = XATTR_BTRFS_PREFIX "stripe_alloc";
-+ struct btrfs_dir_item *di;
-+ struct btrfs_root *root;
-+ struct btrfs_path *path;
-+ char value;
-+
-+ root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
-+ if (IS_ERR(root))
-+ return;
-+ path = btrfs_alloc_path();
-+ if (!path)
-+ goto out;
-+ di = btrfs_lookup_xattr(NULL, root, path, BTRFS_FIRST_FREE_OBJECTID,
-+ name, strlen(name), 0);
-+ if (IS_ERR_OR_NULL(di))
-+ goto out;
-+ if (btrfs_dir_data_len(path->nodes[0], di) != 1)
-+ goto out;
-+ read_extent_buffer(path->nodes[0], &value,
-+ (unsigned long)(di + 1) +
-+ btrfs_dir_name_len(path->nodes[0], di), 1);
-+ btrfs_release_path(path);
-+ if (value == '1' && !btrfs_enable_stripe_alloc(fs_info))
-+ btrfs_info(fs_info,
-+ "stripe_alloc property in force for tree-log replay");
-+out:
-+ btrfs_free_path(path);
-+ btrfs_put_root(root);
-+}
-+
- int btrfs_load_inode_props(struct btrfs_inode *inode, struct btrfs_path *path)
- {
- struct btrfs_root *root = inode->root;
-diff --git a/fs/btrfs/props.h b/fs/btrfs/props.h
-index 15d9a025c923d..f16ce20f68eee 100644
---- a/fs/btrfs/props.h
-+++ b/fs/btrfs/props.h
-@@ -23,6 +23,7 @@ int btrfs_validate_prop(const struct btrfs_inode *inode, const char *name,
- bool btrfs_ignore_prop(const struct btrfs_inode *inode, const char *name);
-
- int btrfs_load_inode_props(struct btrfs_inode *inode, struct btrfs_path *path);
-+void btrfs_load_stripe_alloc_prop_early(struct btrfs_fs_info *fs_info);
-
- int btrfs_inode_inherit_props(struct btrfs_trans_handle *trans,
- struct btrfs_inode *inode,
---
-2.47.3
-
--- /dev/null
+From 94620d2830c64ef9b046fec2180d7e5807226a7f Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sun, 4 Oct 2026 23:16:03 -0400
+Subject: [RFC PATCH 77/85] btrfs: stripe_alloc: give each log commit its own
+ metadata stripe run
+To: linux-btrfs@vger.kernel.org
+
+A metadata stripe run is keyed by transaction id alone, so every fsync log
+commit inside one transaction appends at the same frontier and into the same
+full stripe. A log commit's tree blocks are durable the instant fsync
+returns, so a later writer sharing that stripe -- the next log commit, or the
+transaction's ordinary metadata at commit -- has its sub-stripe write
+recompute parity over metadata the user was already promised. That is the
+raid56 write hole, on data a user was told was safe. Padding cannot cover it
+either: the earlier blocks are live in the run's liveness map, so
+rmw_try_pad_full() must decline.
+
+Give the log tree its own class. A BTRFS_STRIPE_RUN_META_LOG run is keyed by
+the owning subvolume's root id and that subvolume's log_transid, and is
+private like the per-inode runs: never in the shared band slots, found by
+walking for its key, so nothing else can join it. Each log commit therefore
+gets its own whole stripes and the sharing cannot arise, rather than being
+detected and worked around after the fact.
+
+The space cost is temporary by construction, which is the point of keying on
+log_transid rather than merely separating log blocks from other metadata. The
+log tree is freed at transaction commit, so a stripe holding only one log
+commit's blocks is wholly free once that happens and the commit-time rescan
+credits the whole stripe back. Measured on a 4-device raid5 filesystem with
+raid5 metadata and 16K nodes under six fsync writers, trapped space falls from
+a 20.2 MiB loaded peak to 1.25 MiB once the load stops and three commits pass,
+which is below the 23.7 MiB the plain allocator settles at. Metadata
+total_bytes settles at 2.15x the plain allocator's, and since allocated
+metadata chunks are not available to data, that multiple is the real cost on a
+small or full filesystem. Filling to ENOSPC leaves 384 KiB of df-avail, the
+same figure the plain allocator gives, so nothing is over-committed.
+
+Both directions of the sharing go to zero, and so does the disk-side witness:
+an audit counting uncovered tree blocks whose stripe holds log-tree headers
+reads 0 under load, against 223847 without the change. Padding declines fall
+from 36732 uncovered to 1.
+
+Retirement handles both metadata classes through
+btrfs_stripe_run_class_is_meta(), since a log run must not be closed and
+waited on in the commit-time drain that settles the data classes. Drain is by
+bytenr through end_bbio_meta_write() and clean_log_buffer(), so it is
+class-agnostic and covers the log tree's private free path. A sysfs knob,
+stripe_log_run, turns the class off so the change can be measured against
+itself on one boot.
+
+log_transid starts over with every transaction's log tree, so a run also
+carries its transaction id, and a run from an earlier transaction is
+closed rather than joined even when its log_transid matches: that
+transaction's commit retires the run and waits for its blocks, and
+would wait out its timeout for a block only the later transaction
+writes. Commit-heavy load (relocation of metadata groups during an fsync
+storm) hit that within minutes.
+
+Metadata runs drain only when their tree blocks are written, in a commit,
+so making a raid56 metadata group read-only (relocation, scrub) commits
+the current transaction first when the group has metadata runs, instead
+of waiting up to commit_interval for the next one while relocation holds
+reclaim_bgs_lock.
+
+The drain waits for metadata runs, at commit and when a group goes
+read-only, stay unbounded: a run that never drains has a tree block freed
+or allocated without a report, an accounting bug that should show as a
+hung commit where it happens rather than as later symptoms. After 60
+seconds they warn once and dump the group's runs (every run class) and
+keep waiting. Only a filesystem error ends them.
+
+Assisted-by: Claude:claude-opus-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/block-group.c | 240 ++++++++++++++++++++++++++++++++++++-----
+ fs/btrfs/block-group.h | 23 ++++
+ fs/btrfs/disk-io.c | 5 +
+ fs/btrfs/extent-tree.c | 24 ++++-
+ fs/btrfs/extent-tree.h | 7 ++
+ fs/btrfs/fs.h | 9 ++
+ fs/btrfs/sysfs.c | 39 ++++++-
+ 7 files changed, 317 insertions(+), 30 deletions(-)
+
+diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
+index 8bf9914d98bce..4333b3067a44f 100644
+--- a/fs/btrfs/block-group.c
++++ b/fs/btrfs/block-group.c
+@@ -533,22 +533,21 @@ struct btrfs_open_stripe_run {
+ */
+ unsigned long *written;
+ u32 live_nbits; /* sectors @live covers; caps growth */
++ /* META_LOG: the owning subvolume's log_transid this run belongs to. */
++ u64 log_transid;
+ };
+
+-static void btrfs_dump_open_meta_runs(struct btrfs_block_group *bg)
++static void btrfs_dump_open_stripe_runs(struct btrfs_block_group *bg)
+ {
+ struct btrfs_open_stripe_run *run;
+ unsigned long flags;
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+- list_for_each_entry(run, &bg->open_stripe_runs, list) {
+- if (run->class != BTRFS_STRIPE_RUN_META)
+- continue;
++ list_for_each_entry(run, &bg->open_stripe_runs, list)
+ btrfs_warn(bg->fs_info,
+-" run %llu..%llu frontier %llu open %d inflight %llu transid %llu",
+- run->start, run->end, run->offset, run->open,
+- run->inflight_bytes, run->transid);
+- }
++" run %llu..%llu class %d frontier %llu open %d inflight %llu transid %llu",
++ run->start, run->end, run->class, run->offset,
++ run->open, run->inflight_bytes, run->transid);
+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
+ }
+
+@@ -561,7 +560,7 @@ static bool bg_has_undrained_meta_runs(struct btrfs_block_group *bg,
+
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+- if (run->class != BTRFS_STRIPE_RUN_META)
++ if (!btrfs_stripe_run_class_is_meta(run->class))
+ continue;
+ /*
+ * An open run here belongs to the running transaction: the
+@@ -734,7 +733,7 @@ static bool open_stripe_run_dead(const struct btrfs_open_stripe_run *run)
+ */
+ static bool run_freed_on_drain(const struct btrfs_open_stripe_run *run)
+ {
+- return run->class != BTRFS_STRIPE_RUN_META && !run->retained;
++ return !btrfs_stripe_run_class_is_meta(run->class) && !run->retained;
+ }
+
+ static void free_open_stripe_run(struct btrfs_block_group *bg,
+@@ -1115,6 +1114,150 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
+ return ret;
+ }
+
++/*
++ * Allocate a log tree block from the private run of this log commit.
++ *
++ * The run is keyed by @owner (the subvolume's root id) and @log_transid, so
++ * each log commit gets whole stripes of its own: its blocks are durable once
++ * fsync returns, and no later writer may share a stripe with them (see
++ * BTRFS_STRIPE_RUN_META_LOG). An open run of the same owner from an earlier
++ * log commit is closed, as a stale-transid metadata run is in
++ * btrfs_alloc_from_open_stripe(). Like the other private runs, it is never
++ * placed in a band slot.
++ *
++ * 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_log_stripe_run(struct btrfs_block_group *bg, u64 num_bytes,
++ u64 owner, u64 log_transid,
++ u64 *ret_offset, u64 *available)
++{
++ struct btrfs_fs_info *fs_info = bg->fs_info;
++ const u64 fsl = bg->full_stripe_len;
++ const enum btrfs_stripe_run_class class = BTRFS_STRIPE_RUN_META_LOG;
++ struct btrfs_open_stripe_run *new_run;
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ u64 tail_start = 0;
++ u64 tail_len = 0;
++ u64 start;
++ u64 len;
++ int ret;
++
++ ASSERT(num_bytes);
++ *available = 0;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (run->class != class || run->owner != owner || !run->open)
++ continue;
++ /*
++ * A previous log commit of the same subvolume. Its blocks are
++ * durable, so this one must not continue into them; close it
++ * and claim fresh stripes below. log_transid starts over with
++ * every transaction's log tree, so a run from an earlier
++ * transaction can carry the same log_transid: the transid
++ * tells them apart. Joining it would hand that transaction's
++ * commit, which retires the run and waits for its blocks, a
++ * block only this transaction will write.
++ */
++ if (run->log_transid != log_transid ||
++ run->transid != btrfs_get_fs_generation(fs_info)) {
++ tail_len = close_open_stripe_run(bg, run, &tail_start);
++ break;
++ }
++ if (num_bytes <= run->end - run->offset) {
++ *ret_offset = run->offset;
++ run_live_set(run, run->offset, num_bytes, true);
++ run->offset += num_bytes;
++ run->inflight_bytes += num_bytes;
++ bg->stripe_open_remainder -= num_bytes;
++ if (run->offset == run->end)
++ run->open = false; /* full: closed, no tail */
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ stripe_open_remainder_sync(bg);
++ return 0;
++ }
++ /* Too small for this block: replace it. */
++ tail_len = close_open_stripe_run(bg, run, &tail_start);
++ break;
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ if (tail_len) {
++ btrfs_add_free_space(bg, tail_start, tail_len);
++ stripe_open_remainder_sync(bg);
++ }
++
++ /* Zeroed: the error paths below free ->live and must find NULL. */
++ new_run = kzalloc(sizeof(*new_run), GFP_NOFS);
++ if (!new_run)
++ return -ENOMEM;
++
++ ret = btrfs_claim_free_stripe_run(bg,
++ div64_u64(num_bytes + fsl - 1, fsl) * fsl,
++ &start, &len);
++ if (ret)
++ goto out;
++ if (len < num_bytes) {
++ btrfs_add_free_space(bg, start, len);
++ *available = max(*available, len);
++ ret = -ENOSPC;
++ goto out;
++ }
++
++ /* 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 ?
++ bitmap_zalloc(new_run->live_nbits, GFP_NOFS) : NULL;
++
++ spin_lock(&fs_info->open_stripe_lock);
++ if (list_empty(&bg->open_stripe_bg_list)) {
++ btrfs_get_block_group(bg);
++ list_add_tail(&bg->open_stripe_bg_list,
++ &fs_info->open_stripe_bgs);
++ }
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ if (bg->ro) {
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ spin_unlock(&fs_info->open_stripe_lock);
++ btrfs_add_free_space(bg, start, len);
++ *available = 0;
++ ret = -ENOSPC;
++ goto out;
++ }
++ new_run->bg = bg;
++ new_run->class = class;
++ new_run->persistent = false;
++ new_run->root = owner;
++ new_run->owner = owner;
++ new_run->log_transid = log_transid;
++ new_run->transid = btrfs_get_fs_generation(fs_info);
++ new_run->start = start;
++ new_run->end = start + len;
++ new_run->offset = start + num_bytes;
++ new_run->inflight_bytes = num_bytes;
++ new_run->open_seq = fs_info->stripe_retire_seq;
++ new_run->open = (new_run->offset != new_run->end);
++ run_live_set(new_run, start, num_bytes, true);
++ list_add_tail(&new_run->list, &bg->open_stripe_runs);
++ bg->stripe_open_remainder += new_run->end - new_run->offset;
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ spin_unlock(&fs_info->open_stripe_lock);
++
++ atomic64_inc(&fs_info->stripe_run_stats.log_run_opened);
++ stripe_open_remainder_sync(bg);
++ *ret_offset = start;
++ new_run = NULL;
++ ret = 0;
++out:
++ if (new_run) {
++ bitmap_free(new_run->live);
++ bitmap_free(new_run->written);
++ }
++ kfree(new_run);
++ return ret;
++}
++
+ /*
+ * The owner a private run is found by: the inode, or with
+ * stripe_log_data_shared a LOG-class run shared by every inode of the
+@@ -2905,7 +3048,7 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
+ * commit and their tree blocks are not written until later;
+ * btrfs_retire_meta_stripes() closes them once they are.
+ */
+- if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
++ if (btrfs_stripe_run_class_is_meta(run->class) && seq != U64_MAX)
+ continue;
+ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
+ for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++)
+@@ -2953,7 +3096,7 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
+ seq != U64_MAX)
+ continue;
+ /* Metadata drains after tree writeback, not here. */
+- if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
++ if (btrfs_stripe_run_class_is_meta(run->class) && seq != U64_MAX)
+ continue;
+ if (run->open_seq < seq) {
+ ret = false;
+@@ -3000,6 +3143,24 @@ static void btrfs_release_stripe_reloc_runs(struct btrfs_fs_info *fs_info)
+ spin_unlock(&fs_info->open_stripe_lock);
+ }
+
++/* Does @bg have metadata stripe runs? */
++static bool bg_has_meta_runs(struct btrfs_block_group *bg)
++{
++ struct btrfs_open_stripe_run *run;
++ unsigned long flags;
++ bool ret = false;
++
++ spin_lock_irqsave(&bg->stripe_run_lock, flags);
++ list_for_each_entry(run, &bg->open_stripe_runs, list) {
++ if (btrfs_stripe_run_class_is_meta(run->class)) {
++ ret = true;
++ break;
++ }
++ }
++ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
++ return ret;
++}
++
+ /*
+ * Close and drain all of a block group's stripe runs. The caller must
+ * prevent new allocations first (e.g. the block group is read-only),
+@@ -3013,15 +3174,37 @@ static void btrfs_release_stripe_reloc_runs(struct btrfs_fs_info *fs_info)
+ void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
+ {
+ struct btrfs_fs_info *fs_info = bg->fs_info;
++ bool warned = false;
+
+ /* Nothing may outlive this, relocation's retained runs included. */
+ release_retained_stripe_runs(bg);
+ close_block_group_stripe_runs(bg, U64_MAX);
+ /* Parked partial-stripe rbios hold the very bios the wait drains. */
+ btrfs_flush_parked_rbios(fs_info, bg->start, bg->length, false);
+- wait_var_event(&bg->open_stripe_runs,
+- bg_open_stripes_settled(bg, U64_MAX) ||
+- BTRFS_FS_ERROR(fs_info));
++ /*
++ * Metadata runs drain when their tree blocks are written and are
++ * freed by btrfs_retire_meta_stripes(), both in a commit. Commit now
++ * instead of waiting for the next one; no caller holds a transaction
++ * handle.
++ */
++ if (bg_has_meta_runs(bg))
++ btrfs_commit_current_transaction(fs_info->tree_root);
++ /*
++ * No timeout: a run that does not drain has an allocation that was
++ * never reported written or abandoned, an accounting bug to fix, not
++ * to wait out. Say which runs once, and keep waiting.
++ */
++ while (!wait_var_event_timeout(&bg->open_stripe_runs,
++ bg_open_stripes_settled(bg, U64_MAX) ||
++ BTRFS_FS_ERROR(fs_info), 60 * HZ)) {
++ if (warned)
++ continue;
++ btrfs_warn(fs_info,
++"block group %llu read-only transition waiting for stripe runs that do not drain",
++ bg->start);
++ btrfs_dump_open_stripe_runs(bg);
++ warned = true;
++ }
+ if (BTRFS_FS_ERROR(fs_info) && !bg_open_stripes_settled(bg, U64_MAX))
+ btrfs_warn(fs_info,
+ "block group %llu read-only with stripe runs still in flight after a filesystem error; not waiting for them",
+@@ -3127,6 +3310,7 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
+ while (!list_empty(&retire_list)) {
+ struct btrfs_open_stripe_run *run;
+ bool again = true;
++ bool warned = false;
+
+ bg = list_first_entry(&retire_list, struct btrfs_block_group,
+ open_stripe_retire_list);
+@@ -3142,7 +3326,7 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
+ again = false;
+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+- if (run->class != BTRFS_STRIPE_RUN_META ||
++ if (!btrfs_stripe_run_class_is_meta(run->class) ||
+ !run->open)
+ continue;
+ /*
+@@ -3176,18 +3360,22 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
+
+ /*
+ * Every tree block is on disk, so end_bbio_meta_write() has
+- * reported all of them and this normally does not wait. The
+- * timeout guards against a path that frees a tree block
+- * without reporting it to its run: warn and keep the run,
+- * which costs space, rather than hang the commit.
++ * reported all of them and this normally does not wait. A run
++ * that does not drain has a tree block that was freed without
++ * reporting to its run, an accounting bug: say which runs
++ * once, and keep waiting. Only a filesystem error ends the
++ * wait early.
+ */
+- if (!wait_var_event_timeout(&bg->open_stripe_runs,
+- !bg_has_undrained_meta_runs(bg, transid),
+- 60 * HZ)) {
++ while (!wait_var_event_timeout(&bg->open_stripe_runs,
++ !bg_has_undrained_meta_runs(bg, transid) ||
++ BTRFS_FS_ERROR(fs_info), 60 * HZ)) {
++ if (warned)
++ continue;
+ btrfs_warn(fs_info,
+-"metadata stripe runs in block group %llu did not drain; a tree block was freed without reporting to its run",
++"metadata stripe runs in block group %llu do not drain; a tree block was freed without reporting to its run",
+ bg->start);
+- btrfs_dump_open_meta_runs(bg);
++ btrfs_dump_open_stripe_runs(bg);
++ warned = true;
+ }
+
+ /* Drained and no longer needed for padding or merging. */
+@@ -3196,7 +3384,7 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
+ struct btrfs_open_stripe_run *next = NULL;
+
+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
+- if (run->class == BTRFS_STRIPE_RUN_META &&
++ if (btrfs_stripe_run_class_is_meta(run->class) &&
+ open_stripe_run_drained(run)) {
+ next = run;
+ break;
+diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
+index b1cbc08ce058d..605e040421e45 100644
+--- a/fs/btrfs/block-group.h
++++ b/fs/btrfs/block-group.h
+@@ -55,6 +55,15 @@ enum btrfs_stripe_run_class {
+ * (see btrfs_retire_meta_stripes()).
+ */
+ BTRFS_STRIPE_RUN_META,
++ /*
++ * Tree blocks of one log commit: a private run keyed by the subvolume's
++ * root id and log_transid, never placed in a band slot. A log commit's
++ * blocks are durable once fsync returns, so no later writer (the next
++ * log commit, or the transaction's own metadata) may share their
++ * stripes. It also keeps the space cost temporary: the log tree is
++ * freed at transaction commit, which frees its stripes whole.
++ */
++ BTRFS_STRIPE_RUN_META_LOG,
+ BTRFS_STRIPE_RUN_NR_CLASSES,
+ };
+
+@@ -496,6 +505,20 @@ 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_log_stripe_run(struct btrfs_block_group *bg, u64 num_bytes,
++ u64 owner, u64 log_transid,
++ u64 *ret_offset, u64 *available);
++/*
++ * Both metadata classes: tree blocks, retired after tree writeback rather
++ * than in the commit-time drain that settles the data classes. Every site
++ * that special-cases BTRFS_STRIPE_RUN_META for that reason must use this, or
++ * a log run would be closed and waited on in the wrong place.
++ */
++static inline bool btrfs_stripe_run_class_is_meta(enum btrfs_stripe_run_class c)
++{
++ return c == BTRFS_STRIPE_RUN_META || c == BTRFS_STRIPE_RUN_META_LOG;
++}
++
+ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
+ struct btrfs_inode *inode,
+ enum btrfs_stripe_run_class class,
+diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
+index d4b6de361fb3c..322daea247db4 100644
+--- a/fs/btrfs/disk-io.c
++++ b/fs/btrfs/disk-io.c
+@@ -2806,6 +2806,11 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
+ INIT_LIST_HEAD(&fs_info->caching_block_groups);
+ INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
+ INIT_WORK(&fs_info->stripe_alloc_enable_work, btrfs_stripe_alloc_enable_work);
++ /*
++ * Closing the log-tree fsync write hole is on by default; sysfs can
++ * turn it off so the change can be measured against itself on one boot.
++ */
++ fs_info->stripe_log_run = true;
+ fs_info->stripe_log_data_shared = true;
+ fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
+ fs_info->stripe_compact = 10;
+diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
+index 39fac849accd0..1ad3d605e4543 100644
+--- a/fs/btrfs/extent-tree.c
++++ b/fs/btrfs/extent-tree.c
+@@ -4320,7 +4320,20 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
+ * through the normal metadata allocator.
+ */
+ if (btrfs_is_stripe_meta_bg(block_group)) {
+- ret = btrfs_alloc_from_open_stripe(block_group,
++ /*
++ * Log tree blocks take a private run of their own, keyed by
++ * the log commit, so that no later writer can share a stripe
++ * with blocks an fsync has already made durable. Everything
++ * else shares the transaction's metadata runs.
++ */
++ if (ffe_ctl->for_treelog && fs_info->stripe_log_run)
++ ret = btrfs_alloc_from_log_stripe_run(block_group,
++ ffe_ctl->num_bytes,
++ ffe_ctl->log_owner,
++ ffe_ctl->log_transid,
++ &offset, &available);
++ else
++ ret = btrfs_alloc_from_open_stripe(block_group,
+ ffe_ctl->num_bytes,
+ BTRFS_STRIPE_RUN_META,
+ &offset, &available);
+@@ -5161,6 +5174,13 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ u64 flags;
+ int ret;
+ bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
++ /*
++ * A log root's key offset is the subvolume it logs, and log_transid
++ * names the commit; together they key the private stripe run that
++ * keeps one log commit's blocks off every later writer's stripes.
++ */
++ u64 log_owner = for_treelog ? root->root_key.offset : 0;
++ u64 log_transid = for_treelog ? root->log_transid : 0;
+ bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
+ struct btrfs_inode *steer_inode = NULL;
+ enum btrfs_stripe_run_class steer_class = BTRFS_STRIPE_RUN_COW;
+@@ -5212,6 +5232,8 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
+ ffe_ctl.delalloc = delalloc;
+ ffe_ctl.hint_byte = hint_byte;
+ ffe_ctl.for_treelog = for_treelog;
++ ffe_ctl.log_owner = log_owner;
++ ffe_ctl.log_transid = log_transid;
+ ffe_ctl.for_data_reloc = for_data_reloc;
+ ffe_ctl.steer_inode = steer_inode;
+ ffe_ctl.steer_class = steer_class;
+diff --git a/fs/btrfs/extent-tree.h b/fs/btrfs/extent-tree.h
+index f650cc79b094d..751babb11dedb 100644
+--- a/fs/btrfs/extent-tree.h
++++ b/fs/btrfs/extent-tree.h
+@@ -45,6 +45,13 @@ struct find_free_extent_ctl {
+
+ /* Allocation is called for tree-log */
+ bool for_treelog;
++ /*
++ * Log tree allocations only: the owning subvolume's root id and its
++ * log_transid, the key of the private stripe run this log commit's
++ * tree blocks belong to. See BTRFS_STRIPE_RUN_META_LOG.
++ */
++ u64 log_owner;
++ u64 log_transid;
+
+ /* Allocation is called for data relocation */
+ bool for_data_reloc;
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index a21750342d1e5..9e639f1788cb1 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -959,6 +959,13 @@ struct btrfs_fs_info {
+ atomic64_t audit_err;
+ } stripe_rmw_audit_stats;
+ #endif
++ /*
++ * Give each log commit its own private metadata stripe run
++ * (BTRFS_STRIPE_RUN_META_LOG), so that no later writer shares a stripe
++ * with tree blocks an fsync has already made durable. On by default
++ * (sysfs stripe_log_run).
++ */
++ bool stripe_log_run;
+ /*
+ * LOG-class data runs. Set (the default): runs are shared per
+ * (subvolume, log_transid); a log commit seals the stripe holding the
+@@ -992,6 +999,8 @@ struct btrfs_fs_info {
+ atomic64_t compact_stripes;
+ /* live bytes compaction moved */
+ atomic64_t compact_bytes;
++ /* private per-log-commit metadata runs opened */
++ atomic64_t log_run_opened;
+ /* log commits that waited to settle a logged extent, and how long */
+ atomic64_t log_settle_waits;
+ atomic64_t log_settle_wait_ns;
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 48b10f03e8092..6ea904c9805e3 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1190,7 +1190,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
+ /* Indexed by enum btrfs_stripe_run_class. */
+ static const char * const class_names[] = {
+- "cow", "reloc", "log", "nocow", "meta",
++ "cow", "reloc", "log", "nocow", "meta", "meta_log",
+ };
+ int live_by_class[BTRFS_STRIPE_RUN_NR_CLASSES];
+ int open_runs[BTRFS_STRIPE_RUN_NR_CLASSES];
+@@ -1267,7 +1267,8 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
+ "compact_runs %lld\n"
+ "compact_fallbacks %lld\n"
+ "compact_stripes %lld\n"
+- "compact_bytes %lld\n",
++ "compact_bytes %lld\n"
++ "log_run_opened %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),
+@@ -1278,7 +1279,8 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_run_stats.compact_runs),
+ atomic64_read(&fs_info->stripe_run_stats.compact_fallbacks),
+ atomic64_read(&fs_info->stripe_run_stats.compact_stripes),
+- atomic64_read(&fs_info->stripe_run_stats.compact_bytes));
++ atomic64_read(&fs_info->stripe_run_stats.compact_bytes),
++ atomic64_read(&fs_info->stripe_run_stats.log_run_opened));
+ }
+ BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
+
+@@ -1314,6 +1316,36 @@ BTRFS_ATTR_RW(, _name, btrfs_##_name##_show, btrfs_##_name##_store)
+
+ BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
+
++/*
++ * Whether each log commit gets its own private metadata stripe run. 0 puts
++ * log tree blocks back in the transaction's shared metadata runs, which
++ * reopens the log-tree fsync write hole.
++ */
++static ssize_t btrfs_stripe_log_run_show(struct kobject *kobj,
++ struct kobj_attribute *a, char *buf)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++
++ return sysfs_emit(buf, "%d\n", fs_info->stripe_log_run ? 1 : 0);
++}
++
++static ssize_t btrfs_stripe_log_run_store(struct kobject *kobj,
++ struct kobj_attribute *a,
++ const char *buf, size_t len)
++{
++ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
++ bool val;
++ int ret;
++
++ ret = kstrtobool(buf, &val);
++ if (ret)
++ return ret;
++ fs_info->stripe_log_run = val;
++ return len;
++}
++BTRFS_ATTR_RW(, stripe_log_run, btrfs_stripe_log_run_show,
++ btrfs_stripe_log_run_store);
++
+ static ssize_t btrfs_stripe_log_data_shared_show(struct kobject *kobj,
+ struct kobj_attribute *a, char *buf)
+ {
+@@ -1771,6 +1803,7 @@ static const struct attribute *btrfs_attrs[] = {
+ BTRFS_ATTR_PTR(, stripe_park_stats),
+ BTRFS_ATTR_PTR(, stripe_run_stats),
+ BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
++ BTRFS_ATTR_PTR(, stripe_log_run),
+ BTRFS_ATTR_PTR(, stripe_log_data_shared),
+ BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
+ BTRFS_ATTR_PTR(, stripe_park_congestion),
+--
+2.47.3
+
+++ /dev/null
-From 7f542d49c81857af6d107e52a8a7911ed0a0acf1 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 4 Oct 2026 12:26:45 -0400
-Subject: [RFC PATCH 078/116] btrfs: stripe_alloc: count refused rbio pins and
- track rbio cache high water
-To: linux-btrfs@vger.kernel.org
-
-The rbio cache keeps a stripe its run has not finished writing pinned, at
-most RBIO_PIN_MAX (256) of them; the next pin is refused and that stripe
-is cached evictable. If it is evicted before its run's next write into
-it, that write reads back the sectors already written, unverified: the
-case the pin exists to avoid. Nothing counted the refusals, so whether
-the limit is ever reached was unknown.
-
-stripe_park_stats gains:
- rbio_pin_refused pins refused at RBIO_PIN_MAX (every attempt)
- rbio_pinned_now pinned rbios now (nr_pinned: what the limit counts)
- rbio_pinned_live of those, pins still needed: re-checked against the
- runs at read time, as the prune does. A pin whose run
- has finished the stripe stays counted until its entry
- is evicted or cached again.
- rbio_pinned_hwm high water of pinned rbios since mount
- rbio_cache_now cached rbios now
- rbio_cache_hwm high water of cached rbios since mount (above
- RBIO_CACHE_SIZE only by live pins, which the prune
- keeps)
- meta_rmw_reads read-modify-writes of metadata/system stripes that had
- to read (data_rmw counts these with the data ones).
- The pin is what keeps a stripe of fsync log blocks
- cached for the next log commit; a refused pin can bring
- that read back.
-
-The high water marks are only raised under the cache lock. Reading the
-file walks the cache once under the cache lock (1024 entries at most).
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/fs.h | 15 +++++++++++++++
- fs/btrfs/raid56.c | 49 ++++++++++++++++++++++++++++++++++++++++++++---
- fs/btrfs/raid56.h | 2 ++
- fs/btrfs/sysfs.c | 17 ++++++++++++++++
- 4 files changed, 80 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 6fc0aea024156..e7845dfea530a 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -926,6 +926,21 @@ struct btrfs_fs_info {
- atomic64_t congestion_short;
- /* Frontier stripes pinned in the rbio cache (cache_rbio()). */
- atomic64_t rbio_pinned;
-+ /*
-+ * Pins refused because RBIO_PIN_MAX stripes were already
-+ * pinned: the stripe was cached evictable instead, and a later
-+ * write into it may read back the part already written.
-+ */
-+ atomic64_t rbio_pin_refused;
-+ /* High water since mount of pinned and of all cached rbios. */
-+ atomic64_t rbio_pinned_hwm;
-+ atomic64_t rbio_cache_hwm;
-+ /*
-+ * Read-modify-writes of metadata or system stripes that had to
-+ * read (data_rmw counts them with the data ones): the fsync log
-+ * stripes the pin keeps cached read back when it is refused.
-+ */
-+ atomic64_t meta_rmw_reads;
- /* Completed-write sectors not live in their run (should be ~0). */
- atomic64_t written_not_live;
- } stripe_park_stats;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 7619793710679..dc62d466e2a22 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -722,19 +722,31 @@ static void rbio_mark_written(struct btrfs_raid_bio *rbio)
- }
- }
-
-+static void rbio_stat_hwm(atomic64_t *hwm, int now)
-+{
-+ /* Only ever raised under the cache lock: no lost update. */
-+ if (now > atomic64_read(hwm))
-+ atomic64_set(hwm, now);
-+}
-+
- /*
- * Mark @rbio pinned or not; caller holds the cache lock and @rbio is in the
-- * cache.
-+ * cache. A pin refused at RBIO_PIN_MAX is counted at every attempt.
- */
- static void rbio_set_pin(struct btrfs_stripe_hash_table *table,
- struct btrfs_raid_bio *rbio, bool pin)
- {
- if (pin && table->nr_pinned >= RBIO_PIN_MAX &&
-- !test_bit(RBIO_PINNED_BIT, &rbio->flags))
-+ !test_bit(RBIO_PINNED_BIT, &rbio->flags)) {
-+ atomic64_inc(&table->fs_info->stripe_park_stats.rbio_pin_refused);
- pin = false;
-+ }
- if (pin) {
-- if (!test_and_set_bit(RBIO_PINNED_BIT, &rbio->flags))
-+ if (!test_and_set_bit(RBIO_PINNED_BIT, &rbio->flags)) {
- table->nr_pinned += 1;
-+ rbio_stat_hwm(&table->fs_info->stripe_park_stats.rbio_pinned_hwm,
-+ table->nr_pinned);
-+ }
- atomic64_inc(&rbio->bioc->fs_info->stripe_park_stats.rbio_pinned);
- } else if (test_and_clear_bit(RBIO_PINNED_BIT, &rbio->flags)) {
- table->nr_pinned -= 1;
-@@ -759,6 +771,35 @@ static void rbio_cache_prune(struct btrfs_stripe_hash_table *table,
- /* __remove_rbio_from_cache() drops a stale pin's count. */
- __remove_rbio_from_cache(found);
- }
-+ /* Above the limit only by live pins, which the prune keeps. */
-+ rbio_stat_hwm(&table->fs_info->stripe_park_stats.rbio_cache_hwm,
-+ table->cache_size);
-+}
-+
-+/*
-+ * Cached and pinned rbios now, for sysfs stripe_park_stats. @live re-checks
-+ * each pin against its run, as the prune does: a pin whose run has finished
-+ * writing the stripe is still counted in nr_pinned until the entry is
-+ * evicted or cached again.
-+ */
-+void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
-+ int *pinned, int *live)
-+{
-+ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
-+ struct btrfs_raid_bio *rbio;
-+
-+ *cached = 0;
-+ *pinned = 0;
-+ *live = 0;
-+ if (!table)
-+ return;
-+ spin_lock(&table->cache_lock);
-+ *cached = table->cache_size;
-+ *pinned = table->nr_pinned;
-+ list_for_each_entry(rbio, &table->stripe_cache, stripe_cache)
-+ if (rbio_pin_live(rbio))
-+ *live += 1;
-+ spin_unlock(&table->cache_lock);
- }
-
- /*
-@@ -3821,6 +3862,8 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- * count that should be zero.
- */
- atomic64_inc(&fs_info->stripe_park_stats.data_rmw);
-+ if (!(rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA))
-+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_reads);
- rbio_count_rmw_reason(rbio);
- /* A parked-then-flushed write that still had to read. */
- if (test_bit(RBIO_WAS_PARKED_BIT, &rbio->flags))
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index 8a618b86a5f18..1b24e19967cad 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -312,5 +312,7 @@ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
- u64 num_bytes, bool force);
-+void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
-+ int *pinned, int *live);
-
- #endif
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index aad4767baad63..0e14eca2c6367 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -25,6 +25,7 @@
- #include "misc.h"
- #include "fs.h"
- #include "accessors.h"
-+#include "raid56.h"
-
- /*
- * Structure name Path
-@@ -1186,7 +1187,9 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- struct kobj_attribute *a, char *buf)
- {
- struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+ int cached, pinned, live;
-
-+ btrfs_rbio_cache_usage(fs_info, &cached, &pinned, &live);
- return sysfs_emit(buf,
- "parked %lld\n"
- "merged_bytes %lld\n"
-@@ -1224,6 +1227,13 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "meta_rmw_free %lld\n"
- "congestion_short %lld\n"
- "rbio_pinned %lld\n"
-+ "rbio_pin_refused %lld\n"
-+ "rbio_pinned_now %d\n"
-+ "rbio_pinned_live %d\n"
-+ "rbio_pinned_hwm %lld\n"
-+ "rbio_cache_now %d\n"
-+ "rbio_cache_hwm %lld\n"
-+ "meta_rmw_reads %lld\n"
- "written_not_live %lld\n"
- "parked_now %d\n",
- atomic64_read(&fs_info->stripe_park_stats.parked),
-@@ -1262,6 +1272,13 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free),
- atomic64_read(&fs_info->stripe_park_stats.congestion_short),
- atomic64_read(&fs_info->stripe_park_stats.rbio_pinned),
-+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_refused),
-+ pinned,
-+ live,
-+ atomic64_read(&fs_info->stripe_park_stats.rbio_pinned_hwm),
-+ cached,
-+ atomic64_read(&fs_info->stripe_park_stats.rbio_cache_hwm),
-+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_reads),
- atomic64_read(&fs_info->stripe_park_stats.written_not_live),
- atomic_read(&fs_info->stripe_parked_now));
- }
---
-2.47.3
-
--- /dev/null
+From 0d3c2f28add6021e5c01082d66129e49e828b6bd Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Tue, 6 Oct 2026 00:11:38 -0400
+Subject: [RFC PATCH 78/85] btrfs: stripe_alloc: share LOG data runs per log
+ transaction (stripe_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: share LOG data runs per log
+transaction" (earlier in this series) that need code from "btrfs:
+stripe_alloc: give each log commit its own metadata stripe run", which
+comes after it in this series: they are applied here, once "btrfs:
+stripe_alloc: give each log commit its own metadata stripe run" is in,
+instead of with the rest of "btrfs: stripe_alloc: share LOG data runs
+per log transaction".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/disk-io.c | 5 +++--
+ fs/btrfs/sysfs.c | 16 ++++++++++++++--
+ 2 files changed, 17 insertions(+), 4 deletions(-)
+
+diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
+index 322daea247db4..27faf262898f7 100644
+--- a/fs/btrfs/disk-io.c
++++ b/fs/btrfs/disk-io.c
+@@ -2807,8 +2807,9 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
+ INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
+ INIT_WORK(&fs_info->stripe_alloc_enable_work, btrfs_stripe_alloc_enable_work);
+ /*
+- * Closing the log-tree fsync write hole is on by default; sysfs can
+- * turn it off so the change can be measured against itself on one boot.
++ * Defaults: each log commit gets its own metadata stripe run, and
++ * LOG-class data runs are shared per log transaction (clearing
++ * stripe_log_data_shared selects private runs with carry-forward).
+ */
+ fs_info->stripe_log_run = true;
+ fs_info->stripe_log_data_shared = true;
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 6ea904c9805e3..6f629e618a947 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1268,7 +1268,13 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
+ "compact_fallbacks %lld\n"
+ "compact_stripes %lld\n"
+ "compact_bytes %lld\n"
+- "log_run_opened %lld\n",
++ "log_run_opened %lld\n"
++ "log_settle_waits %lld\n"
++ "log_settle_wait_ns %lld\n"
++ "log_carry_ranges %lld\n"
++ "log_carry_bytes %lld\n"
++ "log_seals %lld\n"
++ "log_seal_bytes %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),
+@@ -1280,7 +1286,13 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_run_stats.compact_fallbacks),
+ atomic64_read(&fs_info->stripe_run_stats.compact_stripes),
+ atomic64_read(&fs_info->stripe_run_stats.compact_bytes),
+- atomic64_read(&fs_info->stripe_run_stats.log_run_opened));
++ atomic64_read(&fs_info->stripe_run_stats.log_run_opened),
++ atomic64_read(&fs_info->stripe_run_stats.log_settle_waits),
++ atomic64_read(&fs_info->stripe_run_stats.log_settle_wait_ns),
++ atomic64_read(&fs_info->stripe_run_stats.log_carry_ranges),
++ atomic64_read(&fs_info->stripe_run_stats.log_carry_bytes),
++ atomic64_read(&fs_info->stripe_run_stats.log_seals),
++ atomic64_read(&fs_info->stripe_run_stats.log_seal_bytes));
+ }
+ BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
+
+--
+2.47.3
+
--- /dev/null
+From 4a7162b0186b5c8ba3f17157c595750d9ea0d43b Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Fri, 9 Oct 2026 19:13:11 -0400
+Subject: [RFC PATCH 79/85] btrfs: stripe_alloc: count and log ordered extents
+ that end with sectors unwritten (debug_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: count and log ordered extents that
+end with sectors unwritten" (earlier in this series) that need code from
+"btrfs: stripe_alloc: share LOG data runs per log transaction
+(stripe_meta part)", which comes after it in this series: they are
+applied here, once "btrfs: stripe_alloc: share LOG data runs per log
+transaction (stripe_meta part)" is in, instead of with the rest of
+"btrfs: stripe_alloc: count and log ordered extents that end with
+sectors unwritten".
+
+They append the unwritten_on_end counters to the stripe_run_stats list
+after the log seal counters, which that patch adds to it.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/sysfs.c | 12 ++++++++++--
+ 1 file changed, 10 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 6f629e618a947..c23a55ca30866 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1274,7 +1274,11 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
+ "log_carry_ranges %lld\n"
+ "log_carry_bytes %lld\n"
+ "log_seals %lld\n"
+- "log_seal_bytes %lld\n",
++ "log_seal_bytes %lld\n"
++ "unwritten_on_end %lld\n"
++ "unwritten_on_end_bytes %lld\n"
++ "unwritten_on_end_truncated %lld\n"
++ "unwritten_on_end_truncated_bytes %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),
+@@ -1292,7 +1296,11 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_run_stats.log_carry_ranges),
+ atomic64_read(&fs_info->stripe_run_stats.log_carry_bytes),
+ atomic64_read(&fs_info->stripe_run_stats.log_seals),
+- atomic64_read(&fs_info->stripe_run_stats.log_seal_bytes));
++ atomic64_read(&fs_info->stripe_run_stats.log_seal_bytes),
++ atomic64_read(&fs_info->stripe_run_stats.unwritten_on_end),
++ atomic64_read(&fs_info->stripe_run_stats.unwritten_on_end_bytes),
++ atomic64_read(&fs_info->stripe_run_stats.unwritten_on_end_truncated),
++ atomic64_read(&fs_info->stripe_run_stats.unwritten_on_end_truncated_bytes));
+ }
+ BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
+
+--
+2.47.3
+
+++ /dev/null
-From 0545e8ac77819e8b6ef84abce5ea6785d4a86d4c Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 4 Oct 2026 12:35:08 -0400
-Subject: [RFC PATCH 079/116] btrfs: stripe_alloc: sweep stale rbio pins, and
- commit when live pins run low
-To: linux-btrfs@vger.kernel.org
-
-The rbio cache pins a stripe its run has not finished writing, so the
-run's next write into it takes the part already written from memory
-rather than reading it back unverified -- data at an open run's frontier,
-and the fsync-durable tree-log blocks a later log commit shares a stripe
-with. At most RBIO_PIN_MAX (256) are pinned; past that the pin is
-refused, and those read-backs come back.
-
-Every fsync-heavy workload reached the limit within seconds (13k-87k
-refusals a minute; 614 read-modify-write reads in a small-file
-create+fsync run, against none with the pins working), while buffered
-writeback peaked at 3-14 pins. nr_pinned counts a pin until its entry
-is evicted or cached again, also after its run has finished the stripe,
-so the limit fills with stale pins and refuses live ones.
-
-Two things now release pins:
-- A sweep (rbio_unpin_stale()) re-checks every pin against its run and
- clears the stale ones, under the cache lock, as the prune re-checks
- them. It runs when a pin is about to be taken with RBIO_PIN_LOW (3/4
- of the limit) or more counted -- at most once per RBIO_PIN_SWEEP_INTERVAL
- from that path -- and at every commit, right after
- btrfs_retire_open_stripes(), which closes every run and so makes every
- pin taken before it unnecessary.
-- If the pins left after a sweep (all live) are still RBIO_PIN_LOW or
- more, the transaction kthread is asked to commit now, once per
- transaction (as btrfs_commit_transaction_async() does). The commit
- ends every run; its sweep then frees the pins. Once the commit is
- done, a stripe's earlier writes are no longer at risk from a read-back:
- data checksums are committed, and the tree-log blocks are dead.
-
-stripe_park_stats gains rbio_pin_swept and rbio_pin_commit_requests.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/fs.h | 4 ++
- fs/btrfs/raid56.c | 86 +++++++++++++++++++++++++++++++++++++++++-
- fs/btrfs/raid56.h | 1 +
- fs/btrfs/sysfs.c | 4 ++
- fs/btrfs/transaction.c | 2 +
- 5 files changed, 96 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index e7845dfea530a..e9847d879a608 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -935,6 +935,10 @@ struct btrfs_fs_info {
- /* High water since mount of pinned and of all cached rbios. */
- atomic64_t rbio_pinned_hwm;
- atomic64_t rbio_cache_hwm;
-+ /* Stale pins cleared by a sweep (rbio_unpin_stale()). */
-+ atomic64_t rbio_pin_swept;
-+ /* Commits requested because live pins ran low. */
-+ atomic64_t rbio_pin_commit_requests;
- /*
- * Read-modify-writes of metadata or system stripes that had to
- * read (data_rmw counts them with the data ones): the fsync log
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index dc62d466e2a22..124236fc91c28 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -86,8 +86,19 @@
- */
- #define RBIO_PINNED_BIT 9
-
--/* At most this many pinned stripes; normally about one per stripe run. */
-+/*
-+ * At most this many pinned stripes: about as many as stripes with writes in
-+ * flight, but fsync-heavy work caches a partial stripe on nearly every write.
-+ * A pin goes stale when its run finishes the stripe and is only uncounted
-+ * when a sweep, an eviction or a re-cache finds it, so pinning past
-+ * RBIO_PIN_LOW sweeps first, and if the pins left are still live, asks for a
-+ * commit: the commit closes every run (btrfs_retire_open_stripes()), which
-+ * makes every pin unnecessary, and its sweep releases them.
-+ */
- #define RBIO_PIN_MAX 256
-+#define RBIO_PIN_LOW (RBIO_PIN_MAX * 3 / 4)
-+/* At most one sweep per this interval from the pin path (commits always sweep). */
-+#define RBIO_PIN_SWEEP_INTERVAL (HZ / 20)
-
- #define RBIO_CACHE_SIZE 1024
-
-@@ -195,6 +206,9 @@ struct btrfs_stripe_hash_table {
- int cache_size;
- /* Cached rbios with RBIO_PINNED_BIT set, live or not. */
- int nr_pinned;
-+ /* Last pin sweep, and the generation the last commit request was for. */
-+ unsigned long pin_sweep_jiffies;
-+ u64 pin_commit_gen;
- /*
- * Parked partial write rbios (RBIO_PARKED_BIT), in park order.
- * parked_lock nests inside the hash and bio_list locks.
-@@ -776,6 +790,73 @@ static void rbio_cache_prune(struct btrfs_stripe_hash_table *table,
- table->cache_size);
- }
-
-+/*
-+ * Clear the pins no longer needed (their run has written all of the stripe,
-+ * or is gone). Caller holds the cache lock, the same context the prune
-+ * re-checks pins in. Returns how many pins are left: all of them live.
-+ */
-+static int rbio_unpin_stale(struct btrfs_stripe_hash_table *table)
-+{
-+ struct btrfs_raid_bio *rbio;
-+ int swept = 0;
-+
-+ table->pin_sweep_jiffies = jiffies;
-+ list_for_each_entry(rbio, &table->stripe_cache, stripe_cache) {
-+ if (!test_bit(RBIO_PINNED_BIT, &rbio->flags) || rbio_needs_pin(rbio))
-+ continue;
-+ clear_bit(RBIO_PINNED_BIT, &rbio->flags);
-+ table->nr_pinned -= 1;
-+ swept++;
-+ }
-+ if (swept)
-+ atomic64_add(swept, &table->fs_info->stripe_park_stats.rbio_pin_swept);
-+ return table->nr_pinned;
-+}
-+
-+/*
-+ * About to pin with the pins running low: sweep the stale ones, and if the
-+ * live ones are still many, ask for a commit (once per transaction), which
-+ * ends every run and so every pin. Caller holds the cache lock.
-+ */
-+static void rbio_pins_low(struct btrfs_stripe_hash_table *table)
-+{
-+ struct btrfs_fs_info *fs_info = table->fs_info;
-+ u64 gen;
-+
-+ /*
-+ * Bounded: a sweep re-checks every pin against its run, and with the
-+ * pins all live the commit is what frees them, not another sweep.
-+ */
-+ if (!time_after(jiffies, table->pin_sweep_jiffies + RBIO_PIN_SWEEP_INTERVAL))
-+ return;
-+ if (rbio_unpin_stale(table) < RBIO_PIN_LOW)
-+ return;
-+ gen = btrfs_get_fs_generation(fs_info);
-+ if (table->pin_commit_gen == gen)
-+ return;
-+ table->pin_commit_gen = gen;
-+ atomic64_inc(&fs_info->stripe_park_stats.rbio_pin_commit_requests);
-+ /* As btrfs_commit_transaction_async(): the kthread commits now. */
-+ set_bit(BTRFS_FS_COMMIT_TRANS, &fs_info->flags);
-+ wake_up_process(fs_info->transaction_kthread);
-+}
-+
-+/*
-+ * A commit has retired every open stripe run: release the pins that leaves
-+ * stale. Pins of runs opened since then are re-checked, not dropped.
-+ */
-+void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info)
-+{
-+ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
-+
-+ if (!table || !btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ return;
-+ spin_lock(&table->cache_lock);
-+ if (table->nr_pinned)
-+ rbio_unpin_stale(table);
-+ spin_unlock(&table->cache_lock);
-+}
-+
- /*
- * Cached and pinned rbios now, for sysfs stripe_park_stats. @live re-checks
- * each pin against its run, as the prune does: a pin whose run has finished
-@@ -825,6 +906,9 @@ static void cache_rbio(struct btrfs_raid_bio *rbio)
- table = rbio->bioc->fs_info->stripe_hash_table;
-
- spin_lock(&table->cache_lock);
-+ if (pin && table->nr_pinned >= RBIO_PIN_LOW &&
-+ !test_bit(RBIO_PINNED_BIT, &rbio->flags))
-+ rbio_pins_low(table);
- spin_lock(&rbio->bio_list_lock);
-
- /* bump our ref if we were not in the list before */
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index 1b24e19967cad..957cc2d857b53 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -314,5 +314,6 @@ void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
- u64 num_bytes, bool force);
- void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
- int *pinned, int *live);
-+void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info);
-
- #endif
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 0e14eca2c6367..2fce0ffe5856a 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1233,6 +1233,8 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "rbio_pinned_hwm %lld\n"
- "rbio_cache_now %d\n"
- "rbio_cache_hwm %lld\n"
-+ "rbio_pin_swept %lld\n"
-+ "rbio_pin_commit_requests %lld\n"
- "meta_rmw_reads %lld\n"
- "written_not_live %lld\n"
- "parked_now %d\n",
-@@ -1278,6 +1280,8 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.rbio_pinned_hwm),
- cached,
- atomic64_read(&fs_info->stripe_park_stats.rbio_cache_hwm),
-+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_swept),
-+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_commit_requests),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_reads),
- atomic64_read(&fs_info->stripe_park_stats.written_not_live),
- atomic_read(&fs_info->stripe_parked_now));
-diff --git a/fs/btrfs/transaction.c b/fs/btrfs/transaction.c
-index 6007dce716bf5..aa251b32b1dcf 100644
---- a/fs/btrfs/transaction.c
-+++ b/fs/btrfs/transaction.c
-@@ -2481,6 +2481,8 @@ int btrfs_commit_transaction(struct btrfs_trans_handle *trans)
- * no-op when no stripe runs exist.
- */
- btrfs_retire_open_stripes(fs_info, cur_trans);
-+ /* Every run just closed: the rbio cache's pins on them are stale. */
-+ btrfs_rbio_unpin_stale(fs_info);
-
- btrfs_scrub_pause(fs_info);
- /*
---
-2.47.3
-
--- /dev/null
+From f7823fb8ab4d325a71cd00fb2d68f9b909d51aca Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:49 -0400
+Subject: [RFC PATCH 80/85] btrfs: raid56: say whether a metadata
+ read-modify-write is a write hole
+To: linux-btrfs@vger.kernel.org
+
+meta_rmw counts sub-stripe metadata writes, which is a proxy for exposure
+rather than a measurement of it. A stripe modified in place is only a write
+hole if it holds data some completed transaction is relying on; a stripe
+that two writes of the *same* transaction happen to split costs an extra
+read but risks nothing, because a tear loses that whole transaction anyway.
+The counter cannot tell those apart, so it cannot answer the only question
+that matters.
+
+The rbio can. A read-modify-write has already read every column the write
+does not cover, so at the point of the report it is holding the stripe's
+on-disk contents. Walk the uncovered tree block positions and read their
+headers: a block whose bytenr and fsid match belongs there, and its
+generation says which transaction put it there. Compare that against the
+generation of the blocks this write is carrying, taken from the same rbio,
+so a transaction committing concurrently cannot skew the verdict:
+
+ meta_rmw_cur the same transaction's own blocks -- a cost
+ meta_rmw_old an earlier transaction's -- a write hole
+ meta_rmw_free no tree block there at all
+
+System block groups are classified too, not just metadata ones. A system
+chunk carries no METADATA bit, so a flags test excludes it, but it holds
+the chunk tree: the same tree block header, the same generation field, and
+a worse consequence if a degraded crash tears it, since without the chunk
+tree no logical address can be mapped at all. meta_rmw already counted
+system chunks; only the classification skipped them, so their read-modify-
+writes were visible as a rate and never as a verdict. Whether a raid56
+system chunk ever rewrites parity over a committed tree block is therefore
+an open question that this answers by measurement rather than by reasoning
+about how the chunk tree is laid out.
+
+This trusts nothing the allocator says about itself. The stripe runs, the
+liveness map and the drain accounting are all bookkeeping that could be
+wrong in the same way twice; the header in the sector is what a degraded
+read would actually have to reconstruct.
+
+On a 3-device raid5 filesystem with raid5 metadata, 6000 small files with
+periodic syncs and then a third rewritten, plain stripe_alloc reports 249
+sub-stripe metadata writes of which 174 rewrite parity over committed tree
+blocks. Adding stripe_meta leaves 37 sub-stripe writes and none of them.
+
+An older header under the write is not yet a write hole: most belong to
+blocks that died with their stripe, which a torn parity write cannot hurt.
+So the committed extent tree, the witness a degraded read after a crash
+would consult, is asked whether the block is still referenced, with an
+extent item of the header's generation (a sector re-allocated in the
+current transaction carries a new item while the old header is still on
+disk). A live one is reported as before, with its bytenr and reference
+count; a dead one is counted as meta_rmw_ghost without a warning.
+
+The lookup runs in rmw_rbio() under the full-stripe lock, where reading a
+tree block of the same stripe would queue a rebuild behind that lock, so
+it does not block: commit_root_sem is taken with a trylock and the search
+uses path->nowait. A block not in memory is counted as meta_rmw_unknown.
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/fs.h | 14 +++
+ fs/btrfs/raid56.c | 214 ++++++++++++++++++++++++++++++++++++++++++++++
+ fs/btrfs/sysfs.c | 10 +++
+ 3 files changed, 238 insertions(+)
+
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 9e639f1788cb1..3fbe632d14a2d 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -913,6 +913,20 @@ struct btrfs_fs_info {
+ atomic64_t data_rmw_norun_ro;
+ atomic64_t data_rmw_reloc_writer;
+ atomic64_t meta_rmw;
++ /*
++ * Breakdown of what a metadata read-modify-write found in the
++ * columns it did not cover: a tree block of the generation
++ * being written (a cost, unless an fsynced log block), an
++ * older one (a write hole), or no tree block at all. See
++ * audit_uncovered_rmw().
++ */
++ atomic64_t meta_rmw_cur;
++ atomic64_t meta_rmw_old;
++ atomic64_t meta_rmw_ghost; /* older header, block dead in the
++ committed extent tree */
++ atomic64_t meta_rmw_unknown; /* older header, extent tree
++ not in memory to ask */
++ atomic64_t meta_rmw_free;
+ atomic64_t congestion_short;
+ /* Stripes pinned in the rbio cache (rbio_needs_pin()). */
+ atomic64_t rbio_pinned;
+diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
+index 1afccd067b8a9..b3fdffa6c1418 100644
+--- a/fs/btrfs/raid56.c
++++ b/fs/btrfs/raid56.c
+@@ -3573,6 +3573,219 @@ static bool need_read_stripe_sectors(struct btrfs_raid_bio *rbio)
+ return false;
+ }
+
++/*
++ * Read the header of the tree block at data-stripe sector @i, if there is
++ * one, from whichever copy of the sector this rbio is holding.
++ *
++ * @from_bio picks the source: the caller's pages (what this write is putting
++ * there) or the stripe pages (what an RMW read found on the disk). Returns
++ * false when the sector holds no tree block that belongs at this address --
++ * free space, or the remains of one from a previous life of the stripe.
++ */
++static bool rmw_peek_eb_generation(struct btrfs_raid_bio *rbio, u32 i,
++ bool from_bio, u64 *generation)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ const int stripe_nr = i / rbio->stripe_nsectors;
++ const int sectornr = i % rbio->stripe_nsectors;
++ const u64 logical = rbio->bioc->full_stripe_logical +
++ (u64)stripe_nr * rbio->bioc->stripe_len +
++ (u64)sectornr * fs_info->sectorsize;
++ const phys_addr_t *paddrs = from_bio ? rbio->bio_paddrs
++ : rbio->stripe_paddrs;
++ struct btrfs_header *hdr;
++ phys_addr_t paddr;
++ u64 found_bytenr;
++ bool bad_fsid;
++ void *kaddr;
++
++ paddr = paddrs[i * rbio->sector_nsteps];
++ if (paddr == INVALID_PADDR)
++ return false;
++ if (!from_bio && !test_bit(i, rbio->stripe_uptodate_bitmap))
++ return false;
++
++ kaddr = kmap_local_paddr(paddr);
++ hdr = kaddr;
++ found_bytenr = btrfs_stack_header_bytenr(hdr);
++ *generation = btrfs_stack_header_generation(hdr);
++ bad_fsid = memcmp(hdr->fsid, fs_info->fs_devices->metadata_uuid,
++ BTRFS_FSID_SIZE) != 0;
++ kunmap_local(kaddr);
++
++ return found_bytenr == logical && !bad_fsid;
++}
++
++/*
++ * Is @bytenr a tree block the committed extent tree still references? Read
++ * the commit root without locking, as the caching thread does, so this is
++ * safe from the raid56 worker with no transaction to join.
++ *
++ * Returns 1 if it is (or the lookup failed), 0 if not, and -EAGAIN if the
++ * answer needs a tree block that is not in memory. The caller holds the
++ * full stripe lock, so it must not read from disk: a read of a block in
++ * this stripe that needs reconstruction would wait for that lock.
++ */
++static int rmw_block_referenced(struct btrfs_fs_info *fs_info, u64 bytenr,
++ u64 header_gen, u64 *refs, u64 *extent_gen)
++{
++ struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
++ struct btrfs_path *path;
++ struct btrfs_key key;
++ int live = 1;
++ int ret;
++
++ *refs = 0;
++ *extent_gen = 0;
++ path = btrfs_alloc_path();
++ if (!path)
++ return 1;
++ path->search_commit_root = 1;
++ path->skip_locking = 1;
++ path->nowait = 1;
++ key.objectid = bytenr;
++ key.type = BTRFS_METADATA_ITEM_KEY;
++ key.offset = (u64)-1;
++ if (!down_read_trylock(&fs_info->commit_root_sem)) {
++ btrfs_free_path(path);
++ return -EAGAIN;
++ }
++ ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
++ if (ret > 0)
++ ret = btrfs_previous_extent_item(extent_root, path, bytenr);
++ if (ret == 0) {
++ btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
++ if (key.objectid == bytenr &&
++ (key.type == BTRFS_METADATA_ITEM_KEY ||
++ key.type == BTRFS_EXTENT_ITEM_KEY)) {
++ struct btrfs_extent_item *ei;
++
++ ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
++ struct btrfs_extent_item);
++ *refs = btrfs_extent_refs(path->nodes[0], ei);
++ *extent_gen = btrfs_extent_generation(path->nodes[0], ei);
++ /*
++ * An extent item at this bytenr from a LATER
++ * transaction than the header on disk belongs to a
++ * new block allocated here whose write has not landed
++ * yet; the header is the dead previous occupant.
++ * Only an item of the header's own generation makes
++ * the block on disk live.
++ */
++ live = (*refs != 0 && *extent_gen == header_gen);
++ } else {
++ live = 0;
++ }
++ } else if (ret > 0) {
++ live = 0;
++ } else if (ret == -EAGAIN) {
++ live = -EAGAIN;
++ }
++ up_read(&fs_info->commit_root_sem);
++ btrfs_free_path(path);
++ return live;
++}
++
++/*
++ * Decide whether an uncovered metadata read-modify-write is a write hole or
++ * only a cost, from the tree blocks it read: their parity is about to be
++ * rewritten while their own sectors stay put.
++ *
++ * - Same generation as the blocks this write carries (meta_rmw_cur): the
++ * block belongs to the running transaction, which a crash discards --
++ * except a log tree block, which is durable once its fsync returns.
++ * The audit does not tell log blocks apart, so it cannot see a write
++ * hole over fsynced log blocks; keeping them out of shared stripes is
++ * stripe_log_run's job.
++ * - Older, and still referenced by the committed extent tree: a write hole
++ * over committed metadata (meta_rmw_old).
++ *
++ * Comparing against this rbio's own blocks, not fs_info's committed
++ * generation, keeps a concurrent commit from skewing the verdict.
++ */
++static void audit_uncovered_rmw(struct btrfs_raid_bio *rbio)
++{
++ struct btrfs_fs_info *fs_info = rbio->bioc->fs_info;
++ const u32 sectors_per_tree = fs_info->nodesize >> fs_info->sectorsize_bits;
++ const u32 nsectors = rbio->nr_data * rbio->stripe_nsectors;
++ u64 write_gen = 0;
++
++ /*
++ * Tree blocks only: metadata and system groups. A mixed group's
++ * sectors need not hold tree blocks.
++ */
++ if (rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA)
++ return;
++ if (!(rbio->bioc->map_type & (BTRFS_BLOCK_GROUP_METADATA |
++ BTRFS_BLOCK_GROUP_SYSTEM)))
++ return;
++
++ /*
++ * Both loops read bio_paddrs to tell what this write covers, and the
++ * paths that reach here do not all populate it (a cached rbio that
++ * failed to pad never indexes). Idempotent, so just do it.
++ */
++ index_rbio_pages(rbio);
++
++ /* The generation this write is putting into the stripe. */
++ for (u32 i = 0; i < nsectors; i += sectors_per_tree) {
++ u64 gen;
++
++ if (rmw_peek_eb_generation(rbio, i, true, &gen))
++ write_gen = max(write_gen, gen);
++ }
++ if (!write_gen)
++ return;
++
++ for (u32 i = 0; i < nsectors; i += sectors_per_tree) {
++ u64 gen;
++
++ /* Covered by this write: it is what we are putting there. */
++ if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
++ continue;
++ if (!rmw_peek_eb_generation(rbio, i, false, &gen)) {
++ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_free);
++ continue;
++ }
++ if (gen >= write_gen) {
++ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_cur);
++ continue;
++ }
++ /*
++ * An older header is a write hole only if the committed extent
++ * tree still references the block: a reclaimed stripe keeps the
++ * headers of dead blocks, and tearing those harms nothing a
++ * reader can reach. The commit root is what a crash would see.
++ */
++ {
++ const int stripe_nr = i / rbio->stripe_nsectors;
++ const int sectornr = i % rbio->stripe_nsectors;
++ const u64 logical = rbio->bioc->full_stripe_logical +
++ (u64)stripe_nr * rbio->bioc->stripe_len +
++ (u64)sectornr * fs_info->sectorsize;
++ u64 refs;
++ u64 egen;
++ int ret;
++
++ ret = rmw_block_referenced(fs_info, logical, gen, &refs,
++ &egen);
++ if (ret == -EAGAIN) {
++ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_unknown);
++ continue;
++ }
++ if (!ret) {
++ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_ghost);
++ continue;
++ }
++ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_old);
++ btrfs_warn_rl(fs_info,
++"read-modify-write of stripe %llu rewrites parity over committed tree block %llu at generation %llu (refs %llu, extent generation %llu) while writing generation %llu: write hole",
++ rbio->bioc->full_stripe_logical, logical,
++ gen, refs, egen, write_gen);
++ }
++ }
++}
++
+ /*
+ * Count and audit a metadata or system read-modify-write
+ * (audit_uncovered_rmw()), and warn if it lands in a raid56 group that
+@@ -3592,6 +3805,7 @@ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
+ return;
+
+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw);
++ audit_uncovered_rmw(rbio);
+ /*
+ * Every raid56 metadata and system group is a stripe_meta group while
+ * stripe_alloc is on, and stripe_alloc refuses to enable on mixed
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index c23a55ca30866..e731a049e7da1 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1212,6 +1212,11 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "padded_unwritten %lld\n"
+ "rmw_reads %lld\n"
+ "meta_rmw %lld\n"
++ "meta_rmw_cur %lld\n"
++ "meta_rmw_old %lld\n"
++ "meta_rmw_ghost %lld\n"
++ "meta_rmw_unknown %lld\n"
++ "meta_rmw_free %lld\n"
+ "rbio_pin_refused %lld\n"
+ "rbio_pinned_now %d\n"
+ "rbio_pinned_live %d\n"
+@@ -1232,6 +1237,11 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.padded_unwritten),
+ atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
++ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
++ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
++ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_ghost),
++ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_unknown),
++ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free),
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_refused),
+ pinned,
+ live,
+--
+2.47.3
+
+++ /dev/null
-From 5c17642cd1a8a7bf3110119ac4d6ae2d675aa1ad Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 4 Oct 2026 17:46:19 -0400
-Subject: [RFC PATCH 080/116] btrfs: stripe_alloc: break rbio pins and open
- stripe runs down by run class
-To: linux-btrfs@vger.kernel.org
-
-Under fsync load the rbio cache holds up to ~190 pins its runs still need,
-against 35-55 with the same load on raid1 metadata, so most of them look
-like metadata stripes: tree-log blocks share the transaction's META run
-with the tree blocks COWed in it, a log commit writes its part of a stripe
-and the rest waits for the transaction commit. Data runs are private per
-fsyncing inode and closed at every log commit, so they should be many and
-short. Say which, instead of inferring it.
-
-stripe_park_stats gains rbio_pinned_live_<class> (live pins by the class of
-the run that still needs the stripe) and open_runs_<class> (open runs by
-class), for class cow, reloc, log, nocow and meta.
-btrfs_stripe_run_incomplete() becomes a wrapper around
-btrfs_stripe_run_incomplete_class(), which also says which run's class.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 51 ++++++++++++++++++++++++++++++++----------
- fs/btrfs/block-group.h | 3 +++
- fs/btrfs/raid56.c | 20 +++++++++++++----
- fs/btrfs/raid56.h | 2 +-
- fs/btrfs/sysfs.c | 24 ++++++++++++++++----
- 5 files changed, 79 insertions(+), 21 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 9b164bcac06e5..5076e7cdb4ee8 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2516,28 +2516,29 @@ static bool run_unwritten_in(struct btrfs_open_stripe_run *run, u64 start,
- * Either way the stripe has been written in part, and the rest will arrive
- * as a sub-stripe write that needs the part already written.
- */
--bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
-- u64 stripe_start, u64 stripe_len)
-+/*
-+ * As btrfs_stripe_run_incomplete(), returning the class of the run that
-+ * leaves the stripe incomplete, or -1 if none does.
-+ */
-+int btrfs_stripe_run_incomplete_class(struct btrfs_fs_info *fs_info,
-+ u64 stripe_start, u64 stripe_len)
- {
- struct btrfs_block_group *bg;
- struct btrfs_open_stripe_run *run;
- unsigned long flags;
-- bool ret = false;
-+ int ret = -1;
-
- if (list_empty_careful(&fs_info->open_stripe_bgs))
-- return false;
-+ return -1;
- bg = btrfs_lookup_block_group(fs_info, stripe_start);
- if (!bg)
-- return false;
-+ return -1;
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (run->open && run->offset > stripe_start &&
-- run->offset < stripe_start + stripe_len) {
-- ret = true;
-- break;
-- }
-- if (run_unwritten_in(run, stripe_start, stripe_len)) {
-- ret = true;
-+ if ((run->open && run->offset > stripe_start &&
-+ run->offset < stripe_start + stripe_len) ||
-+ run_unwritten_in(run, stripe_start, stripe_len)) {
-+ ret = run->class;
- break;
- }
- }
-@@ -2546,6 +2547,32 @@ bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
- return ret;
- }
-
-+bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
-+ u64 stripe_start, u64 stripe_len)
-+{
-+ return btrfs_stripe_run_incomplete_class(fs_info, stripe_start,
-+ stripe_len) >= 0;
-+}
-+
-+/* Open stripe runs by class, for sysfs: @counts has NR_CLASSES entries. */
-+void btrfs_count_open_stripe_runs(struct btrfs_fs_info *fs_info, int *counts)
-+{
-+ struct btrfs_block_group *bg;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+
-+ memset(counts, 0, sizeof(*counts) * BTRFS_STRIPE_RUN_NR_CLASSES);
-+ spin_lock(&fs_info->open_stripe_lock);
-+ list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list) {
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list)
-+ if (run->open && run->class < BTRFS_STRIPE_RUN_NR_CLASSES)
-+ counts[run->class]++;
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ }
-+ spin_unlock(&fs_info->open_stripe_lock);
-+}
-+
- bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class)
- {
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index ccb47edf2b895..6bef68593d947 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -494,6 +494,9 @@ void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
- u64 len);
- bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
- u64 stripe_start, u64 stripe_len);
-+int btrfs_stripe_run_incomplete_class(struct btrfs_fs_info *fs_info,
-+ u64 stripe_start, u64 stripe_len);
-+void btrfs_count_open_stripe_runs(struct btrfs_fs_info *fs_info, int *counts);
- bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class);
- u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 124236fc91c28..caa30f222def7 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -864,22 +864,34 @@ void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info)
- * evicted or cached again.
- */
- void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
-- int *pinned, int *live)
-+ int *pinned, int *live, int *live_by_class)
- {
- struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
- struct btrfs_raid_bio *rbio;
-+ int class;
-
- *cached = 0;
- *pinned = 0;
- *live = 0;
-+ memset(live_by_class, 0, sizeof(*live_by_class) * BTRFS_STRIPE_RUN_NR_CLASSES);
- if (!table)
- return;
- spin_lock(&table->cache_lock);
- *cached = table->cache_size;
- *pinned = table->nr_pinned;
-- list_for_each_entry(rbio, &table->stripe_cache, stripe_cache)
-- if (rbio_pin_live(rbio))
-- *live += 1;
-+ list_for_each_entry(rbio, &table->stripe_cache, stripe_cache) {
-+ if (!test_bit(RBIO_PINNED_BIT, &rbio->flags) ||
-+ !btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ continue;
-+ class = btrfs_stripe_run_incomplete_class(fs_info,
-+ rbio->bioc->full_stripe_logical,
-+ (u64)rbio->nr_data * rbio->bioc->stripe_len);
-+ if (class < 0)
-+ continue;
-+ *live += 1;
-+ if (class < BTRFS_STRIPE_RUN_NR_CLASSES)
-+ live_by_class[class] += 1;
-+ }
- spin_unlock(&table->cache_lock);
- }
-
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index 957cc2d857b53..bd3b73f040f9a 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -313,7 +313,7 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
- u64 num_bytes, bool force);
- void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
-- int *pinned, int *live);
-+ int *pinned, int *live, int *live_by_class);
- void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info);
-
- #endif
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 2fce0ffe5856a..21892535a3c8c 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1187,10 +1187,19 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- struct kobj_attribute *a, char *buf)
- {
- struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-- int cached, pinned, live;
--
-- btrfs_rbio_cache_usage(fs_info, &cached, &pinned, &live);
-- return sysfs_emit(buf,
-+ /* Indexed by enum btrfs_stripe_run_class. */
-+ static const char * const class_names[] = {
-+ "cow", "reloc", "log", "nocow", "meta",
-+ };
-+ int live_by_class[BTRFS_STRIPE_RUN_NR_CLASSES];
-+ int open_runs[BTRFS_STRIPE_RUN_NR_CLASSES];
-+ int cached, pinned, live, class;
-+ ssize_t len;
-+
-+ BUILD_BUG_ON(ARRAY_SIZE(class_names) != BTRFS_STRIPE_RUN_NR_CLASSES);
-+ btrfs_rbio_cache_usage(fs_info, &cached, &pinned, &live, live_by_class);
-+ btrfs_count_open_stripe_runs(fs_info, open_runs);
-+ len = sysfs_emit(buf,
- "parked %lld\n"
- "merged_bytes %lld\n"
- "filled %lld\n"
-@@ -1285,6 +1294,13 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_reads),
- atomic64_read(&fs_info->stripe_park_stats.written_not_live),
- atomic_read(&fs_info->stripe_parked_now));
-+ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
-+ len += sysfs_emit_at(buf, len, "rbio_pinned_live_%s %d\n",
-+ class_names[class], live_by_class[class]);
-+ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
-+ len += sysfs_emit_at(buf, len, "open_runs_%s %d\n",
-+ class_names[class], open_runs[class]);
-+ return len;
- }
- BTRFS_ATTR(, stripe_park_stats, btrfs_stripe_park_stats_show);
-
---
-2.47.3
-
+++ /dev/null
-From a44ba1c6dac1fb65b1451712c482c708522070a9 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 4 Oct 2026 23:16:03 -0400
-Subject: [RFC PATCH 081/116] btrfs: stripe_alloc: give each log commit its own
- metadata stripe run
-To: linux-btrfs@vger.kernel.org
-
-A metadata stripe run is keyed by transaction id alone, so every fsync log
-commit inside one transaction appends at the same frontier and into the same
-full stripe. A log commit's tree blocks are durable the instant fsync
-returns, so a later writer sharing that stripe -- the next log commit, or the
-transaction's ordinary metadata at commit -- has its sub-stripe write
-recompute parity over metadata the user was already promised. That is the
-raid56 write hole, on data a user was told was safe. Padding cannot cover it
-either: the earlier blocks are live in the run's liveness map, so
-rmw_try_pad_full() must decline.
-
-Give the log tree its own class. A BTRFS_STRIPE_RUN_META_LOG run is keyed by
-the owning subvolume's root id and that subvolume's log_transid, and is
-private like the per-inode runs: never in the shared band slots, found by
-walking for its key, so nothing else can join it. Each log commit therefore
-gets its own whole stripes and the sharing cannot arise, rather than being
-detected and worked around after the fact.
-
-The space cost is temporary by construction, which is the point of keying on
-log_transid rather than merely separating log blocks from other metadata. The
-log tree is freed at transaction commit, so a stripe holding only one log
-commit's blocks is wholly free once that happens and the commit-time rescan
-credits the whole stripe back. Measured on a 4-device raid5 filesystem with
-raid5 metadata and 16K nodes under six fsync writers, trapped space falls from
-a 20.2 MiB loaded peak to 1.25 MiB once the load stops and three commits pass,
-which is below the 23.7 MiB the plain allocator settles at. Metadata
-total_bytes settles at 2.15x the plain allocator's, and since allocated
-metadata chunks are not available to data, that multiple is the real cost on a
-small or full filesystem. Filling to ENOSPC leaves 384 KiB of df-avail, the
-same figure the plain allocator gives, so nothing is over-committed.
-
-Both directions of the sharing go to zero, and so does the disk-side witness:
-an audit counting uncovered tree blocks whose stripe holds log-tree headers
-reads 0 under load, against 223847 without the change. Padding declines fall
-from 36732 uncovered to 1.
-
-Retirement handles both metadata classes through
-btrfs_stripe_run_class_is_meta(), since a log run must not be closed and
-waited on in the commit-time drain that settles the data classes. Drain is by
-bytenr through end_bbio_meta_write() and clean_log_buffer(), so it is
-class-agnostic and covers the log tree's private free path. A sysfs knob,
-stripe_log_run, turns the class off so the change can be measured against
-itself on one boot.
-
-log_transid starts over with every transaction's log tree, so a run also
-carries its transaction id, and a run from an earlier transaction is
-closed rather than joined even when its log_transid matches: that
-transaction's commit retires the run and waits for its blocks, and
-would wait out its timeout for a block only the later transaction
-writes. Commit-heavy load (relocation of metadata groups during an fsync
-storm) hit that within minutes.
-
-Assisted-by: Claude:claude-opus-5
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 165 +++++++++++++++++++++++++++++++++++++++--
- fs/btrfs/block-group.h | 34 +++++++++
- fs/btrfs/disk-io.c | 5 ++
- fs/btrfs/extent-tree.c | 24 +++++-
- fs/btrfs/extent-tree.h | 7 ++
- fs/btrfs/fs.h | 10 +++
- fs/btrfs/sysfs.c | 40 +++++++++-
- 7 files changed, 274 insertions(+), 11 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 5076e7cdb4ee8..7c7ea3a8a02eb 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -536,6 +536,8 @@ struct btrfs_open_stripe_run {
- */
- unsigned long *written;
- u32 live_nbits; /* sectors @live covers; caps growth */
-+ /* META_LOG: the owning subvolume's log_transid this run belongs to. */
-+ u64 log_transid;
- };
-
- static void btrfs_dump_open_meta_runs(struct btrfs_block_group *bg)
-@@ -545,7 +547,7 @@ static void btrfs_dump_open_meta_runs(struct btrfs_block_group *bg)
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (run->class != BTRFS_STRIPE_RUN_META)
-+ if (!btrfs_stripe_run_class_is_meta(run->class))
- continue;
- btrfs_warn(bg->fs_info,
- " run %llu..%llu frontier %llu open %d inflight %llu transid %llu",
-@@ -564,7 +566,7 @@ static bool bg_has_undrained_meta_runs(struct btrfs_block_group *bg,
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (run->class != BTRFS_STRIPE_RUN_META)
-+ if (!btrfs_stripe_run_class_is_meta(run->class))
- continue;
- /*
- * An open run here belongs to the running transaction: the
-@@ -749,7 +751,7 @@ static bool open_stripe_run_dead(const struct btrfs_open_stripe_run *run)
- */
- static bool run_freed_on_drain(const struct btrfs_open_stripe_run *run)
- {
-- return run->class != BTRFS_STRIPE_RUN_META && !run->retained;
-+ return !btrfs_stripe_run_class_is_meta(run->class) && !run->retained;
- }
-
- static void free_open_stripe_run(struct btrfs_block_group *bg,
-@@ -1144,6 +1146,155 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- return ret;
- }
-
-+/*
-+ * Allocate a log tree block from the private run of this log commit.
-+ *
-+ * The run is keyed by @owner, the root id of the subvolume whose log this is,
-+ * and @log_transid, that subvolume's log transaction. Every log commit
-+ * therefore gets its own whole stripes, which is the whole point: a log
-+ * commit's blocks are durable the instant fsync returns, so no later writer
-+ * may share a stripe with them, and keying the run this way makes that true
-+ * by construction rather than by a check. A stale-epoch run found here is
-+ * closed, exactly as a stale-transid metadata run is in
-+ * btrfs_alloc_from_open_stripe_epoch(); its tail goes back to the free space
-+ * cache and the stripes it filled are credited back once the log tree is
-+ * freed at transaction commit.
-+ *
-+ * Private, like the per-inode runs: never placed in the shared band slots,
-+ * found by walking for the key, so nothing else can join.
-+ *
-+ * 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_log_stripe_run(struct btrfs_block_group *bg, u64 num_bytes,
-+ u64 owner, u64 log_transid,
-+ u64 *ret_offset, u64 *available)
-+{
-+ struct btrfs_fs_info *fs_info = bg->fs_info;
-+ const u64 fsl = bg->full_stripe_len;
-+ const enum btrfs_stripe_run_class class = BTRFS_STRIPE_RUN_META_LOG;
-+ struct btrfs_open_stripe_run *new_run;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ u64 tail_start = 0;
-+ u64 tail_len = 0;
-+ u64 start;
-+ u64 len;
-+ int ret;
-+
-+ ASSERT(num_bytes);
-+ *available = 0;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (run->class != class || run->owner != owner || !run->open)
-+ continue;
-+ /*
-+ * A previous log commit of the same subvolume. Its blocks are
-+ * durable, so this one must not continue into them; close it
-+ * and claim fresh stripes below. log_transid starts over with
-+ * every transaction's log tree, so a run from an earlier
-+ * transaction can carry the same log_transid: the transid
-+ * tells them apart. Joining it would hand that transaction's
-+ * commit, which retires the run and waits for its blocks, a
-+ * block only this transaction will write.
-+ */
-+ if (run->log_transid != log_transid ||
-+ run->transid != btrfs_get_fs_generation(fs_info)) {
-+ tail_len = close_open_stripe_run(bg, run, &tail_start);
-+ break;
-+ }
-+ if (num_bytes <= run->end - run->offset) {
-+ *ret_offset = run->offset;
-+ run_live_set(run, run->offset, num_bytes, true);
-+ run->offset += num_bytes;
-+ run->inflight_bytes += num_bytes;
-+ bg->stripe_open_remainder -= num_bytes;
-+ if (run->offset == run->end)
-+ run->open = false; /* full; drains, is freed */
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ stripe_open_remainder_sync(bg);
-+ return 0;
-+ }
-+ /* Too small for this block: replace it. */
-+ tail_len = close_open_stripe_run(bg, run, &tail_start);
-+ break;
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ if (tail_len) {
-+ btrfs_add_free_space(bg, tail_start, tail_len);
-+ stripe_open_remainder_sync(bg);
-+ }
-+
-+ /* Zeroed: the error paths below free ->live and must find NULL. */
-+ new_run = kzalloc(sizeof(*new_run), GFP_NOFS);
-+ if (!new_run)
-+ return -ENOMEM;
-+
-+ ret = btrfs_claim_free_stripe_run(bg,
-+ div64_u64(num_bytes + fsl - 1, fsl) * fsl,
-+ &start, &len);
-+ if (ret)
-+ goto out;
-+ if (len < num_bytes) {
-+ btrfs_add_free_space(bg, start, len);
-+ *available = max(*available, len);
-+ ret = -ENOSPC;
-+ goto out;
-+ }
-+
-+ /* 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 ?
-+ bitmap_zalloc(new_run->live_nbits, GFP_NOFS) : NULL;
-+
-+ spin_lock(&fs_info->open_stripe_lock);
-+ if (list_empty(&bg->open_stripe_bg_list)) {
-+ btrfs_get_block_group(bg);
-+ list_add_tail(&bg->open_stripe_bg_list,
-+ &fs_info->open_stripe_bgs);
-+ }
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ if (bg->ro) {
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ spin_unlock(&fs_info->open_stripe_lock);
-+ btrfs_add_free_space(bg, start, len);
-+ *available = 0;
-+ ret = -ENOSPC;
-+ goto out;
-+ }
-+ new_run->bg = bg;
-+ new_run->class = class;
-+ new_run->persistent = false;
-+ new_run->owner = owner;
-+ new_run->log_transid = log_transid;
-+ new_run->transid = btrfs_get_fs_generation(fs_info);
-+ new_run->start = start;
-+ new_run->end = start + len;
-+ new_run->offset = start + num_bytes;
-+ new_run->inflight_bytes = num_bytes;
-+ new_run->open_seq = fs_info->stripe_retire_seq;
-+ new_run->open = (new_run->offset != new_run->end);
-+ run_live_set(new_run, start, num_bytes, true);
-+ list_add_tail(&new_run->list, &bg->open_stripe_runs);
-+ bg->stripe_open_remainder += new_run->end - new_run->offset;
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ spin_unlock(&fs_info->open_stripe_lock);
-+
-+ atomic64_inc(&fs_info->stripe_run_stats.log_run_opened);
-+ stripe_open_remainder_sync(bg);
-+ *ret_offset = start;
-+ new_run = NULL;
-+ ret = 0;
-+out:
-+ if (new_run) {
-+ bitmap_free(new_run->live);
-+ bitmap_free(new_run->written);
-+ }
-+ kfree(new_run);
-+ return ret;
-+}
-+
- /*
- * Allocate num_bytes for a log-active inode from its private LOG-class run
- * in this block group, claiming a fresh run when the inode has none here or
-@@ -2786,7 +2937,7 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
- * commit and their tree blocks are not written until later;
- * btrfs_retire_meta_stripes() closes them once they are.
- */
-- if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
-+ if (btrfs_stripe_run_class_is_meta(run->class) && seq != U64_MAX)
- continue;
- for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
- for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++)
-@@ -2834,7 +2985,7 @@ static bool bg_open_stripes_settled(struct btrfs_block_group *bg, u64 seq)
- seq != U64_MAX)
- continue;
- /* Metadata drains after tree writeback, not here. */
-- if (run->class == BTRFS_STRIPE_RUN_META && seq != U64_MAX)
-+ if (btrfs_stripe_run_class_is_meta(run->class) && seq != U64_MAX)
- continue;
- if (run->open_seq < seq) {
- ret = false;
-@@ -3038,7 +3189,7 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
- again = false;
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (run->class != BTRFS_STRIPE_RUN_META ||
-+ if (!btrfs_stripe_run_class_is_meta(run->class) ||
- !run->open)
- continue;
- /*
-@@ -3098,7 +3249,7 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
- struct btrfs_open_stripe_run *next = NULL;
-
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (run->class == BTRFS_STRIPE_RUN_META &&
-+ if (btrfs_stripe_run_class_is_meta(run->class) &&
- open_stripe_run_drained(run)) {
- next = run;
- break;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 6bef68593d947..6feea39c82427 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -54,6 +54,26 @@ enum btrfs_stripe_run_class {
- * (see btrfs_retire_meta_stripes()).
- */
- BTRFS_STRIPE_RUN_META,
-+ /*
-+ * Tree blocks of one log commit: a private run keyed by the owning
-+ * subvolume's root id and that subvolume's log_transid, never placed
-+ * in the shared band slots.
-+ *
-+ * The point is exclusivity in both directions. A log commit's blocks
-+ * become durable the moment fsync returns, so no LATER writer may share
-+ * a stripe with them -- not the next log commit, and not the
-+ * transaction's ordinary metadata at commit -- or that writer's
-+ * sub-stripe write recomputes parity over metadata the user was
-+ * promised. Keying the run by log_transid gives each log commit its
-+ * own whole stripes, which settles it by construction.
-+ *
-+ * It is also what makes the space cost temporary. The log tree is
-+ * freed at transaction commit, so a stripe holding only one log
-+ * commit's blocks is wholly free once that happens, and the
-+ * commit-time rescan credits the whole stripe back. A remainder left
-+ * beside long-lived ordinary metadata would instead wait for balance.
-+ */
-+ BTRFS_STRIPE_RUN_META_LOG,
- BTRFS_STRIPE_RUN_NR_CLASSES,
- };
-
-@@ -463,6 +483,20 @@ 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_log_stripe_run(struct btrfs_block_group *bg, u64 num_bytes,
-+ u64 owner, u64 log_transid,
-+ u64 *ret_offset, u64 *available);
-+/*
-+ * Both metadata classes: tree blocks, retired after tree writeback rather
-+ * than in the commit-time drain that settles the data classes. Every site
-+ * that special-cases BTRFS_STRIPE_RUN_META for that reason must use this, or
-+ * a log run would be closed and waited on in the wrong place.
-+ */
-+static inline bool btrfs_stripe_run_class_is_meta(enum btrfs_stripe_run_class c)
-+{
-+ return c == BTRFS_STRIPE_RUN_META || c == BTRFS_STRIPE_RUN_META_LOG;
-+}
-+
- int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- struct btrfs_inode *inode,
- enum btrfs_stripe_run_class class,
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index d61b2c42fd0a8..24dcb483b96eb 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -2806,6 +2806,11 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
- INIT_LIST_HEAD(&fs_info->caching_block_groups);
- INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
- INIT_WORK(&fs_info->stripe_alloc_enable_work, btrfs_stripe_alloc_enable_work);
-+ /*
-+ * Closing the log-tree fsync write hole is on by default; sysfs can
-+ * turn it off so the change can be measured against itself on one boot.
-+ */
-+ fs_info->stripe_log_run = true;
- fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
- fs_info->stripe_compact = 10;
- fs_info->stripe_park_sync_timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index e9d83591baf30..f09a54d4ee199 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4279,7 +4279,20 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- * through the normal metadata allocator.
- */
- if (btrfs_is_stripe_meta_bg(block_group)) {
-- ret = btrfs_alloc_from_open_stripe(block_group,
-+ /*
-+ * Log tree blocks take a private run of their own, keyed by
-+ * the log commit, so that no later writer can share a stripe
-+ * with blocks an fsync has already made durable. Everything
-+ * else shares the transaction's metadata runs.
-+ */
-+ if (ffe_ctl->for_treelog && fs_info->stripe_log_run)
-+ ret = btrfs_alloc_from_log_stripe_run(block_group,
-+ ffe_ctl->num_bytes,
-+ ffe_ctl->log_owner,
-+ ffe_ctl->log_transid,
-+ &offset, &available);
-+ else
-+ ret = btrfs_alloc_from_open_stripe(block_group,
- ffe_ctl->num_bytes,
- BTRFS_STRIPE_RUN_META,
- &offset, &available);
-@@ -5110,6 +5123,13 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- u64 flags;
- int ret;
- bool for_treelog = (btrfs_root_id(root) == BTRFS_TREE_LOG_OBJECTID);
-+ /*
-+ * A log root's key offset is the subvolume it logs, and log_transid
-+ * names the commit; together they key the private stripe run that
-+ * keeps one log commit's blocks off every later writer's stripes.
-+ */
-+ u64 log_owner = for_treelog ? root->root_key.offset : 0;
-+ u64 log_transid = for_treelog ? root->log_transid : 0;
- bool for_data_reloc = (btrfs_is_data_reloc_root(root) && is_data);
- struct btrfs_inode *steer_inode = NULL;
- enum btrfs_stripe_run_class steer_class = BTRFS_STRIPE_RUN_COW;
-@@ -5165,6 +5185,8 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- ffe_ctl.delalloc = delalloc;
- ffe_ctl.hint_byte = hint_byte;
- ffe_ctl.for_treelog = for_treelog;
-+ ffe_ctl.log_owner = log_owner;
-+ ffe_ctl.log_transid = log_transid;
- ffe_ctl.for_data_reloc = for_data_reloc;
- ffe_ctl.steer_inode = steer_inode;
- ffe_ctl.steer_class = steer_class;
-diff --git a/fs/btrfs/extent-tree.h b/fs/btrfs/extent-tree.h
-index 13096c06fe61d..428a5d31cd459 100644
---- a/fs/btrfs/extent-tree.h
-+++ b/fs/btrfs/extent-tree.h
-@@ -45,6 +45,13 @@ struct find_free_extent_ctl {
-
- /* Allocation is called for tree-log */
- bool for_treelog;
-+ /*
-+ * Log tree allocations only: the owning subvolume's root id and its
-+ * log_transid, the key of the private stripe run this log commit's
-+ * tree blocks belong to. See BTRFS_STRIPE_RUN_META_LOG.
-+ */
-+ u64 log_owner;
-+ u64 log_transid;
-
- /* Allocation is called for data relocation */
- bool for_data_reloc;
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index e9847d879a608..2b9ff81b778bb 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -969,6 +969,14 @@ struct btrfs_fs_info {
- atomic64_t audit_err;
- } stripe_rmw_audit_stats;
- #endif
-+ /*
-+ * Give each log commit its own private metadata stripe run
-+ * (BTRFS_STRIPE_RUN_META_LOG), so that no later writer shares a stripe
-+ * with tree blocks an fsync has already made durable. On by default;
-+ * sysfs-writable so the change can be measured against itself on one
-+ * boot.
-+ */
-+ bool stripe_log_run;
- /*
- * Stripe run lifecycle observability: lifetime counters exposed
- * through sysfs stripe_run_stats, so a test can show it exercised
-@@ -996,6 +1004,8 @@ struct btrfs_fs_info {
- atomic64_t compact_stripes;
- /* live bytes compaction moved */
- atomic64_t compact_bytes;
-+ /* private per-log-commit metadata runs opened */
-+ atomic64_t log_run_opened;
- } stripe_run_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 21892535a3c8c..d3cdc0daa9e98 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1189,7 +1189,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- struct btrfs_fs_info *fs_info = to_fs_info(kobj);
- /* Indexed by enum btrfs_stripe_run_class. */
- static const char * const class_names[] = {
-- "cow", "reloc", "log", "nocow", "meta",
-+ "cow", "reloc", "log", "nocow", "meta", "meta_log",
- };
- int live_by_class[BTRFS_STRIPE_RUN_NR_CLASSES];
- int open_runs[BTRFS_STRIPE_RUN_NR_CLASSES];
-@@ -1320,7 +1320,8 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- "compact_runs %lld\n"
- "compact_fallbacks %lld\n"
- "compact_stripes %lld\n"
-- "compact_bytes %lld\n",
-+ "compact_bytes %lld\n"
-+ "log_run_opened %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),
-@@ -1331,7 +1332,8 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_run_stats.compact_runs),
- atomic64_read(&fs_info->stripe_run_stats.compact_fallbacks),
- atomic64_read(&fs_info->stripe_run_stats.compact_stripes),
-- atomic64_read(&fs_info->stripe_run_stats.compact_bytes));
-+ atomic64_read(&fs_info->stripe_run_stats.compact_bytes),
-+ atomic64_read(&fs_info->stripe_run_stats.log_run_opened));
- }
- BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
-
-@@ -1367,6 +1369,37 @@ static ssize_t btrfs_##_name##_store(struct kobject *kobj, \
- BTRFS_ATTR_RW(, _name, btrfs_##_name##_show, btrfs_##_name##_store)
-
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
-+
-+/*
-+ * Whether each log commit gets its own private metadata stripe run. Off puts
-+ * log tree blocks back in the transaction's shared metadata runs, reopening
-+ * the log-tree fsync write hole, so the change can be measured against itself
-+ * on one boot.
-+ */
-+static ssize_t btrfs_stripe_log_run_show(struct kobject *kobj,
-+ struct kobj_attribute *a, char *buf)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+
-+ return sysfs_emit(buf, "%d\n", fs_info->stripe_log_run ? 1 : 0);
-+}
-+
-+static ssize_t btrfs_stripe_log_run_store(struct kobject *kobj,
-+ struct kobj_attribute *a,
-+ const char *buf, size_t len)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+ bool val;
-+ int ret;
-+
-+ ret = kstrtobool(buf, &val);
-+ if (ret)
-+ return ret;
-+ fs_info->stripe_log_run = val;
-+ return len;
-+}
-+BTRFS_ATTR_RW(, stripe_log_run, btrfs_stripe_log_run_show,
-+ btrfs_stripe_log_run_store);
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_sync_timeout_ms, stripe_park_sync_timeout_ms);
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_congestion, stripe_park_congestion);
-
-@@ -1772,6 +1805,7 @@ static const struct attribute *btrfs_attrs[] = {
- BTRFS_ATTR_PTR(, stripe_park_stats),
- BTRFS_ATTR_PTR(, stripe_run_stats),
- BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
-+ BTRFS_ATTR_PTR(, stripe_log_run),
- BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
- BTRFS_ATTR_PTR(, stripe_park_congestion),
- BTRFS_ATTR_PTR(, stripe_compact),
---
-2.47.3
-
--- /dev/null
+From 00221b3dedbc3abae5c2ebc91a652c8a06aac067 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:50 -0400
+Subject: [RFC PATCH 81/85] btrfs: stripe_alloc: tunable park deadlines, and
+ say why padding declined (debug_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: tunable park deadlines, and say why
+padding declined" (earlier in this series) that need code from "btrfs:
+raid56: say whether a metadata read-modify-write is a write hole", which
+comes after it in this series: they are applied here, once "btrfs:
+raid56: say whether a metadata read-modify-write is a write hole" is in,
+instead of with the rest of "btrfs: stripe_alloc: tunable park
+deadlines, and say why padding declined".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/sysfs.c | 8 ++++++++
+ 1 file changed, 8 insertions(+)
+
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index e731a049e7da1..df45b64ae49e3 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1211,6 +1211,10 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "padded %lld\n"
+ "padded_unwritten %lld\n"
+ "rmw_reads %lld\n"
++ "data_rmw %lld\n"
++ "pad_decline_live %lld\n"
++ "pad_decline_no_run %lld\n"
++ "pad_decline_unallocated %lld\n"
+ "meta_rmw %lld\n"
+ "meta_rmw_cur %lld\n"
+ "meta_rmw_old %lld\n"
+@@ -1236,6 +1240,10 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.padded),
+ atomic64_read(&fs_info->stripe_park_stats.padded_unwritten),
+ atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw),
++ atomic64_read(&fs_info->stripe_park_stats.pad_decline_live),
++ atomic64_read(&fs_info->stripe_park_stats.pad_decline_no_run),
++ atomic64_read(&fs_info->stripe_park_stats.pad_decline_unallocated),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
+--
+2.47.3
+
+++ /dev/null
-From 77cf7621c923fb0ba6d7b2d0361f1d9fa0f78fe0 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Mon, 5 Oct 2026 21:13:17 -0400
-Subject: [RFC PATCH 082/116] btrfs: stripe_alloc: don't make a parked rbio
- wait for sectors that will never be written
-To: linux-btrfs@vger.kernel.org
-
-A parked partial-stripe rbio is ready when its bios cover everything its
-stripe run has allocated in the stripe, measured up to the run's frontier
-(btrfs_stripe_run_alloc_ceiling()). The frontier is not always the end of
-what will be written: an allocation that is abandoned, or a tree block that
-is freed before it is written, leaves its sectors below the frontier with no
-live bit. They never get a bio, so an rbio parked in such a stripe never
-becomes ready and leaves only when it is kicked or its park deadline
-expires (100 ms for async writeback).
-
-Lower the ceiling to the end of the last live sector at or above the
-stripe's start. The sectors above it are not live, and the pad path
-already fills them on the same live-map test, so the rbio goes out as a
-padded full-stripe write as soon as the allocated sectors are all present.
-Live bits are set under stripe_run_lock together with the frontier
-advance, so an allocation in progress always keeps the ceiling up.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 26 ++++++++++++++++++++++++++
- 1 file changed, 26 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 7c7ea3a8a02eb..6d31001c188a2 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1901,6 +1901,31 @@ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
- return ret;
- }
-
-+/*
-+ * Lower an allocation ceiling to the end of the last live sector at or above
-+ * @floor. Sectors between it and the frontier were allocated and abandoned:
-+ * they never get a bio, so a parked rbio counting on them would leave only
-+ * when kicked or at its park deadline. Caller holds bg->stripe_run_lock.
-+ */
-+static u64 run_live_ceiling(const struct btrfs_open_stripe_run *run, u64 floor,
-+ u64 ceiling)
-+{
-+ const u32 bits = run->bg->fs_info->sectorsize_bits;
-+ u32 first;
-+ u32 i;
-+
-+ if (!run->live || !run->live_nbits || floor < run->start ||
-+ ceiling <= floor)
-+ return ceiling;
-+ first = (floor - run->start) >> bits;
-+ i = (ceiling - run->start) >> bits;
-+ if (i > run->live_nbits)
-+ return ceiling;
-+ while (i > first && !test_bit(i - 1, run->live))
-+ i--;
-+ return run->start + ((u64)i << bits);
-+}
-+
- /*
- * How far has the covering run allocated into this stripe? Returns the
- * exclusive end of the allocated prefix, clamped to the stripe, or U64_MAX
-@@ -1931,6 +1956,7 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
- continue;
- ceiling = clamp(run->offset, stripe_start,
- stripe_start + stripe_len);
-+ ceiling = run_live_ceiling(run, stripe_start, ceiling);
- break;
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
---
-2.47.3
-
--- /dev/null
+From b1c2f116b1f03bf020ea758261f07a89fc4712ab Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:51 -0400
+Subject: [RFC PATCH 82/85] btrfs: stripe_alloc: trace why padding declined, at
+ the moment it declined (debug_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: trace why padding declined, at the
+moment it declined" (earlier in this series) that need code from "btrfs:
+raid56: say whether a metadata read-modify-write is a write hole", which
+comes after it in this series: they are applied here, once "btrfs:
+raid56: say whether a metadata read-modify-write is a write hole" is in,
+instead of with the rest of "btrfs: stripe_alloc: trace why padding
+declined, at the moment it declined".
+
+Assisted-by: Claude:claude-fable-5
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/sysfs.c | 2 ++
+ 1 file changed, 2 insertions(+)
+
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index df45b64ae49e3..8f6e55452bbfb 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1215,6 +1215,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "pad_decline_live %lld\n"
+ "pad_decline_no_run %lld\n"
+ "pad_decline_unallocated %lld\n"
++ "pad_decline_uncovered %lld\n"
+ "meta_rmw %lld\n"
+ "meta_rmw_cur %lld\n"
+ "meta_rmw_old %lld\n"
+@@ -1244,6 +1245,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.pad_decline_live),
+ atomic64_read(&fs_info->stripe_park_stats.pad_decline_no_run),
+ atomic64_read(&fs_info->stripe_park_stats.pad_decline_unallocated),
++ atomic64_read(&fs_info->stripe_park_stats.pad_decline_uncovered),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
+--
+2.47.3
+
--- /dev/null
+From 8c1af409d04fb26378e23b6a5045ed85b488a890 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Wed, 30 Sep 2026 18:07:52 -0400
+Subject: [RFC PATCH 83/85] btrfs: stripe_alloc: attribute each data
+ read-modify-write to why padding declined (debug_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: attribute each data read-modify-write
+to why padding declined" (earlier in this series) that need code from
+"btrfs: raid56: say whether a metadata read-modify-write is a write
+hole", which comes after it in this series: they are applied here, once
+"btrfs: raid56: say whether a metadata read-modify-write is a write
+hole" is in, instead of with the rest of "btrfs: stripe_alloc: attribute
+each data read-modify-write to why padding declined".
+
+It also drops the pad_decline_live and pad_decline_unallocated counters:
+these hunks remove their last readers.
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/fs.h | 9 +--------
+ fs/btrfs/sysfs.c | 28 ++++++++++++++++++++++++----
+ 2 files changed, 25 insertions(+), 12 deletions(-)
+
+diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
+index 3fbe632d14a2d..edb2202d17c4b 100644
+--- a/fs/btrfs/fs.h
++++ b/fs/btrfs/fs.h
+@@ -882,15 +882,8 @@ struct btrfs_fs_info {
+ * parked ones.
+ */
+ atomic64_t data_rmw;
+- /*
+- * Why padding declined: live (the rest of the stripe is
+- * allocated and not yet written), no_run (no open run covers
+- * the stripe), unallocated (the run's frontier has not reached
+- * the stripe).
+- */
+- atomic64_t pad_decline_live;
++ /* Why padding declined: no open run covers the stripe. */
+ atomic64_t pad_decline_no_run;
+- atomic64_t pad_decline_unallocated;
+ /*
+ * Oracle allowed padding, but a sector below the frontier is
+ * not covered by this write: another allocation shares the
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 8f6e55452bbfb..a15b8d79e6b80 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1212,10 +1212,20 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "padded_unwritten %lld\n"
+ "rmw_reads %lld\n"
+ "data_rmw %lld\n"
+- "pad_decline_live %lld\n"
+ "pad_decline_no_run %lld\n"
+- "pad_decline_unallocated %lld\n"
+ "pad_decline_uncovered %lld\n"
++ "data_rmw_pad_ok_nomem %lld\n"
++ "data_rmw_no_run %lld\n"
++ "data_rmw_uncovered %lld\n"
++ "data_rmw_not_tried %lld\n"
++ "data_rmw_norun_no_bgs %lld\n"
++ "data_rmw_norun_no_bg %lld\n"
++ "data_rmw_norun_no_cover %lld\n"
++ "data_rmw_norun_no_live %lld\n"
++ "data_rmw_norun_overhang %lld\n"
++ "data_rmw_norun_past_map %lld\n"
++ "data_rmw_norun_bg_ro %lld\n"
++ "data_rmw_reloc_writer %lld\n"
+ "meta_rmw %lld\n"
+ "meta_rmw_cur %lld\n"
+ "meta_rmw_old %lld\n"
+@@ -1242,10 +1252,20 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.padded_unwritten),
+ atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
+ atomic64_read(&fs_info->stripe_park_stats.data_rmw),
+- atomic64_read(&fs_info->stripe_park_stats.pad_decline_live),
+ atomic64_read(&fs_info->stripe_park_stats.pad_decline_no_run),
+- atomic64_read(&fs_info->stripe_park_stats.pad_decline_unallocated),
+ atomic64_read(&fs_info->stripe_park_stats.pad_decline_uncovered),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[BTRFS_STRIPE_PAD_OK]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[BTRFS_STRIPE_PAD_NO_RUN]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[BTRFS_STRIPE_PAD_UNCOVERED]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[BTRFS_STRIPE_PAD_NR_REASONS]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[0]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[1]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[2]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[3]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[4]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[5]),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun_ro),
++ atomic64_read(&fs_info->stripe_park_stats.data_rmw_reloc_writer),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
+--
+2.47.3
+
+++ /dev/null
-From 0d8508b1518fcd6952849a84af7bf8dc39a62212 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 6 Oct 2026 00:11:38 -0400
-Subject: [RFC PATCH 083/116] btrfs: stripe_alloc: share LOG data runs per log
- transaction
-To: linux-btrfs@vger.kernel.org
-
-An fsyncing inode's data goes into a private LOG-class stripe run, which
-each log commit settles: the run is closed, the commit waits for all of the
-run's data IO, and the extents left in its final partial stripe are
-recorded for carry-forward, so the next fsync re-dirties them and moves
-them into the inode's new run. Every fsync therefore leaves one partial
-stripe per inode, and a back-to-back fsync loop rewrites the previous
-fsync's tail each time.
-
-Share the runs instead:
-
-- LOG-class runs are keyed by (subvolume, log_transid at allocation)
- instead of the inode, so the inodes logging in one log transaction fill
- the same stripes. An allocation of a full stripe or more keeps the
- inode's private run, so small fsync extents never share the partial last
- stripe of a large one and wait for its IO.
-- A log commit does not close a shared run. It seals the stripe holding
- the end of the logged extent: the run's frontier moves to that stripe's
- end, the skipped sectors go back to the free space cache like a closed
- run's tail (the stripe's final write pads them), and the run goes on in
- the next stripe. Nothing allocates beside the extent after its log
- commit.
-- The settle kicks only the logged extent's stripes and waits until every
- allocated sector in them is written (the run's written map), rather than
- for the whole run to drain. Writers sharing those stripes park and merge
- into the same full-stripe write, so the wait couples an fsync to them and
- to nothing else. It has no timeout: returning while a neighbour's sector
- is unwritten would let its later partial write RMW the extent after the
- log made it durable. Completed writes wake the waiters.
-- Nothing is carried forward: a final partial stripe stays until the
- extents in it are freed or compaction moves them.
-
-Measured on 5 x 8 GiB raid5 data with raid1 and raid5 metadata, against
-private runs with carry-forward, same rep: at 16 and 64 writers and with
-one fsync per inode, 1.2-2.9x the fsyncs/s (one 64-writer rep of eight:
-0.8x), 3-8x fewer device bytes per fsync and less slab; one writer is at
-parity on latency with 17-29% fewer device bytes. The one workload that
-can lose is two large streaming writers beside small fsync writers: a small
-fsync waits for neighbours that joined its stripe and sit behind the large
-IO (0.5-1.9x the fsyncs/s; the p99.9 there is dominated by a multi-second
-log-commit tail that both modes, and stock raid5, show).
-
-/sys/fs/btrfs/<uuid>/stripe_log_data_shared (default 1) switches a
-filesystem back to private runs with carry-forward. stripe_run_stats gains
-log_settle_waits and log_settle_wait_ns (both), log_carry_ranges and
-log_carry_bytes (private runs), and log_seals and log_seal_bytes (shared
-runs).
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 171 +++++++++++++++++++++++++++++++++++++----
- fs/btrfs/defrag.c | 6 ++
- fs/btrfs/disk-io.c | 4 +
- fs/btrfs/fs.h | 19 +++++
- fs/btrfs/sysfs.c | 42 +++++++++-
- 5 files changed, 227 insertions(+), 15 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 6d31001c188a2..d9afc2f6d8e4a 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1296,11 +1296,35 @@ int btrfs_alloc_from_log_stripe_run(struct btrfs_block_group *bg, u64 num_bytes,
- }
-
- /*
-- * Allocate num_bytes for a log-active inode from its private LOG-class run
-- * in this block group, claiming a fresh run when the inode has none here or
-- * the current one does not fit. Private runs are never placed in the shared
-- * band slots and are found by owner lookup, so no other allocation can join
-- * an inode's run and one inode's log commit settles only its own stripes.
-+ * The owner a private run is found by: the inode, or with
-+ * stripe_log_data_shared a LOG-class run shared by every inode of the
-+ * subvolume logging in the same log transaction. An allocation of a full
-+ * stripe or more keeps the inode's private run, so small fsync extents never
-+ * share the partial last stripe of a large one and wait for its IO. Bit 63
-+ * keeps the shared keys apart from inode numbers.
-+ */
-+static u64 stripe_run_owner(struct btrfs_inode *inode,
-+ enum btrfs_stripe_run_class class, u64 num_bytes,
-+ u64 fsl)
-+{
-+ struct btrfs_root *root = inode->root;
-+
-+ if (class == BTRFS_STRIPE_RUN_LOG && num_bytes < fsl &&
-+ READ_ONCE(root->fs_info->stripe_log_data_shared))
-+ return BIT_ULL(63) |
-+ ((btrfs_root_id(root) & 0x7fffffffULL) << 32) |
-+ (u32)READ_ONCE(root->log_transid);
-+ return btrfs_ino(inode);
-+}
-+
-+/*
-+ * Allocate num_bytes for a log-active inode from its private run in this
-+ * block group -- for LOG-class data with stripe_log_data_shared, the run its
-+ * subvolume shares for the current log transaction (stripe_run_owner()) --
-+ * claiming a fresh run when there is none here or the current one does not
-+ * fit. Private runs are never placed in the shared band slots and are found
-+ * by owner lookup, so only allocations with the same owner join a run, and a
-+ * log commit settles only the stripes holding its own extents.
- *
- * A replaced run (too small for this allocation) is closed immediately: the
- * inode moves on to the fresh run, so keeping the remainder open would only
-@@ -1320,7 +1344,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- {
- struct btrfs_fs_info *fs_info = bg->fs_info;
- const u64 fsl = bg->full_stripe_len;
-- const u64 ino = btrfs_ino(inode);
-+ const u64 ino = stripe_run_owner(inode, class, num_bytes, fsl);
- struct btrfs_open_stripe_run *new_run;
- struct btrfs_open_stripe_run *run;
- unsigned long flags;
-@@ -2180,6 +2204,7 @@ static void log_carry_record(struct btrfs_inode *inode, u64 file_start,
- carry->range[carry->nr_ranges].len = file_len;
- carry->range[carry->nr_ranges].disk_bytenr = bytenr;
- carry->nr_ranges++;
-+ atomic64_inc(&inode->root->fs_info->stripe_run_stats.log_carry_ranges);
- }
-
- /*
-@@ -2287,6 +2312,82 @@ void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
- spin_unlock(&fs_info->open_stripe_lock);
- }
-
-+/*
-+ * A log commit on a shared LOG run: instead of closing the run, move its
-+ * frontier past the stripe holding the end of the logged extent, so nothing
-+ * allocates beside the extent after the log commit while the run goes on in
-+ * the next stripe. The skipped sectors are not live (the pad oracle fills
-+ * them) and go back to the free space cache like a closed run's tail: inside
-+ * a partly live stripe they count as trapped until the stripe frees, and a
-+ * later close returns only [offset, end), which no longer includes them.
-+ * Caller holds bg->stripe_run_lock. Returns the skipped length.
-+ */
-+static u64 seal_log_stripe(struct btrfs_block_group *bg,
-+ struct btrfs_open_stripe_run *run, u64 ext_end,
-+ u64 *skip_start)
-+{
-+ const u64 fsl = bg->full_stripe_len;
-+ u64 boundary;
-+ u64 skip;
-+
-+ if (!run->open)
-+ return 0;
-+ boundary = bg->start + stripe_round_down(ext_end - 1 - bg->start, fsl) + fsl;
-+ if (run->offset >= boundary)
-+ return 0;
-+ boundary = min(boundary, run->end);
-+ skip = boundary - run->offset;
-+ *skip_start = run->offset;
-+ run->offset = boundary;
-+ bg->stripe_open_remainder -= skip;
-+ if (run->offset == run->end) {
-+ int class;
-+ int band;
-+
-+ 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)
-+ bg->open_stripe[class][band] = NULL;
-+ run->open = false;
-+ if (open_stripe_run_drained(run) && !run->retained)
-+ free_open_stripe_run(bg, run);
-+ }
-+ return skip;
-+}
-+
-+static bool run_unwritten_in(struct btrfs_open_stripe_run *run, u64 start,
-+ u64 len);
-+
-+/*
-+ * Per-stripe settle (stripe_log_data_shared): every allocated sector of the
-+ * stripes holding [bytenr, bytenr + num_bytes) has been written, or no run
-+ * covers them any more. Writers sharing those stripes park and merge into
-+ * the same full-stripe write, so this waits for them and for nothing else in
-+ * the run.
-+ */
-+static bool stripe_log_extent_written(struct btrfs_block_group *bg,
-+ u64 bytenr, u64 num_bytes)
-+{
-+ const u64 fsl = bg->full_stripe_len;
-+ const u64 s = bg->start + stripe_round_down(bytenr - bg->start, fsl);
-+ const u64 e = bg->start +
-+ stripe_round_down(bytenr + num_bytes - bg->start + fsl - 1, fsl);
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ bool written = true;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (bytenr < run->start || bytenr >= run->offset)
-+ continue;
-+ if (run_unwritten_in(run, s, e - s))
-+ written = false;
-+ break;
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ return written;
-+}
-+
- /*
- * A log commit is about to make the extent at [bytenr, bytenr + num_bytes)
- * durable. Once the log super lands, no later write may extend or RMW the
-@@ -2302,9 +2403,19 @@ void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
- * below short-circuits. It is a pure data-IO wait (no transaction joins),
- * safe under the inode log mutex and a running transaction handle.
- *
-+ * With stripe_log_data_shared, a shared run is not closed: the log commit
-+ * seals the stripe holding the end of the extent (seal_log_stripe()) and the
-+ * run goes on, only the extent's own stripes are kicked, and for any run the
-+ * wait is for every allocated sector of those stripes to be written
-+ * (stripe_log_extent_written()) rather than for the run to drain. There is
-+ * no timeout: returning while a neighbour's sector in those stripes is still
-+ * unwritten would let its later partial write RMW the extent after it is
-+ * durable.
-+ *
- * [file_start, file_start + file_len) is the extent's file range, recorded
-- * for carry-forward when the extent sits in the run's final partial stripe;
-- * file_len == 0 opts the extent out of carrying (settling still happens).
-+ * for carry-forward when the extent sits in the run's final partial stripe
-+ * (stripe_log_data_shared clear only); file_len == 0 opts the extent out of
-+ * carrying (settling still happens).
- */
- void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- u64 file_len, u64 bytenr, u64 num_bytes)
-@@ -2319,6 +2430,8 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- u64 flush_len = 0;
- u64 ps_start = 0;
- u64 ps_len = 0;
-+ u64 seal_start = 0;
-+ u64 seal_len = 0;
-
- /*
- * The fsync overwrite policy waives the log-window guarantee:
-@@ -2347,6 +2460,17 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- */
- if (run->class == BTRFS_STRIPE_RUN_NOCOW)
- break;
-+ if (READ_ONCE(fs_info->stripe_log_data_shared) &&
-+ (run->owner & BIT_ULL(63))) {
-+ const u64 fsl = bg->full_stripe_len;
-+
-+ /* only the logged extent's stripes, not the shared run */
-+ flush_start = bg->start + stripe_round_down(bytenr - bg->start, fsl);
-+ flush_len = bg->start + stripe_round_down(bytenr + num_bytes - 1 - bg->start, fsl) +
-+ fsl - flush_start;
-+ seal_len = seal_log_stripe(bg, run, bytenr + num_bytes, &seal_start);
-+ break;
-+ }
- flush_start = run->start;
- flush_len = run->end - run->start;
- /*
-@@ -2375,18 +2499,36 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-
-- log_carry_record(inode, file_start, file_len, bytenr, num_bytes,
-- ps_start, ps_len);
-+ if (!READ_ONCE(fs_info->stripe_log_data_shared))
-+ log_carry_record(inode, file_start, file_len, bytenr, num_bytes,
-+ ps_start, ps_len);
-
-+ if (seal_len) {
-+ btrfs_add_free_space(bg, seal_start, seal_len);
-+ stripe_open_remainder_sync(bg);
-+ atomic64_inc(&fs_info->stripe_run_stats.log_seals);
-+ atomic64_add(seal_len, &fs_info->stripe_run_stats.log_seal_bytes);
-+ }
- if (tail_len) {
- btrfs_add_free_space(bg, tail_start, tail_len);
- stripe_open_remainder_sync(bg);
- }
- if (flush_len) {
-+ ktime_t t0;
-+
- btrfs_flush_parked_rbios(fs_info, flush_start, flush_len, false);
-- wait_var_event(&bg->open_stripe_runs,
-- stripe_log_range_settled(bg, bytenr) ||
-- BTRFS_FS_ERROR(fs_info));
-+ t0 = ktime_get();
-+ if (READ_ONCE(fs_info->stripe_log_data_shared))
-+ wait_var_event(&bg->open_stripe_runs,
-+ stripe_log_extent_written(bg, bytenr, num_bytes) ||
-+ BTRFS_FS_ERROR(fs_info));
-+ else
-+ wait_var_event(&bg->open_stripe_runs,
-+ stripe_log_range_settled(bg, bytenr) ||
-+ BTRFS_FS_ERROR(fs_info));
-+ atomic64_inc(&fs_info->stripe_run_stats.log_settle_waits);
-+ atomic64_add(ktime_to_ns(ktime_sub(ktime_get(), t0)),
-+ &fs_info->stripe_run_stats.log_settle_wait_ns);
- }
- btrfs_put_block_group(bg);
- }
-@@ -2657,6 +2799,9 @@ void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
- bitmap_set(run->written, first, nr);
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ /* Per-stripe log settles wait on the written map, not on a drain. */
-+ if (READ_ONCE(fs_info->stripe_log_data_shared))
-+ wake_up_var(&bg->open_stripe_runs);
- btrfs_put_block_group(bg);
- if (not_live)
- atomic64_add(not_live, &fs_info->stripe_park_stats.written_not_live);
-diff --git a/fs/btrfs/defrag.c b/fs/btrfs/defrag.c
-index 5d319df6524d8..fd69a7d34f60c 100644
---- a/fs/btrfs/defrag.c
-+++ b/fs/btrfs/defrag.c
-@@ -1399,6 +1399,9 @@ void btrfs_carry_log_tail(struct btrfs_inode *inode)
- return;
- if (!READ_ONCE(inode->log_carry))
- return;
-+ /* Shared per-log-transaction runs do not carry (and record nothing). */
-+ if (READ_ONCE(inode->root->fs_info->stripe_log_data_shared))
-+ return;
- copy = kmalloc(sizeof(*copy), GFP_NOFS);
- if (!copy)
- return;
-@@ -1412,6 +1415,9 @@ void btrfs_carry_log_tail(struct btrfs_inode *inode)
- inode->log_carry->nr_ranges = 0;
- mutex_unlock(&inode->log_mutex);
-
-+ for (int i = 0; i < copy->nr_ranges; i++)
-+ atomic64_add(copy->range[i].len,
-+ &inode->root->fs_info->stripe_run_stats.log_carry_bytes);
- for (int i = 0; i < copy->nr_ranges; i++)
- carry_one_range(inode, copy->range[i].start,
- copy->range[i].len,
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index 24dcb483b96eb..826341066b242 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -2809,8 +2809,12 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
- /*
- * Closing the log-tree fsync write hole is on by default; sysfs can
- * turn it off so the change can be measured against itself on one boot.
-+ * LOG-class data runs shared per log transaction are the default too;
-+ * clearing stripe_log_data_shared goes back to private runs with
-+ * carry-forward.
- */
- fs_info->stripe_log_run = true;
-+ fs_info->stripe_log_data_shared = true;
- fs_info->stripe_park_timeout_ms = BTRFS_RBIO_PARK_TIMEOUT_MS;
- fs_info->stripe_compact = 10;
- fs_info->stripe_park_sync_timeout_ms = BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS;
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 2b9ff81b778bb..2734a8404a9b2 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -977,6 +977,16 @@ struct btrfs_fs_info {
- * boot.
- */
- bool stripe_log_run;
-+ /*
-+ * LOG-class data runs. Set (the default): runs are shared per
-+ * (subvolume, log_transid); a log commit seals the stripe holding the
-+ * end of the logged extent and the run goes on, allocations of a full
-+ * stripe or more stay in the inode's private run, and the commit waits
-+ * only for the logged extent's own stripes. Clear: one private run
-+ * per fsyncing inode, closed at each log commit, with carry-forward of
-+ * its final partial stripe. See btrfs_log_settle_stripes().
-+ */
-+ bool stripe_log_data_shared;
- /*
- * Stripe run lifecycle observability: lifetime counters exposed
- * through sysfs stripe_run_stats, so a test can show it exercised
-@@ -1006,6 +1016,15 @@ struct btrfs_fs_info {
- atomic64_t compact_bytes;
- /* private per-log-commit metadata runs opened */
- atomic64_t log_run_opened;
-+ /* log commits that waited to settle a logged extent, and how long */
-+ atomic64_t log_settle_waits;
-+ atomic64_t log_settle_wait_ns;
-+ /* carry-forward: ranges recorded, bytes re-dirtied at fsync entry */
-+ atomic64_t log_carry_ranges;
-+ atomic64_t log_carry_bytes;
-+ /* shared runs: frontier stripes sealed at log commit, bytes skipped */
-+ atomic64_t log_seals;
-+ atomic64_t log_seal_bytes;
- } stripe_run_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_opt;
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index d3cdc0daa9e98..baa3c4e780120 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1321,7 +1321,13 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- "compact_fallbacks %lld\n"
- "compact_stripes %lld\n"
- "compact_bytes %lld\n"
-- "log_run_opened %lld\n",
-+ "log_run_opened %lld\n"
-+ "log_settle_waits %lld\n"
-+ "log_settle_wait_ns %lld\n"
-+ "log_carry_ranges %lld\n"
-+ "log_carry_bytes %lld\n"
-+ "log_seals %lld\n"
-+ "log_seal_bytes %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),
-@@ -1333,7 +1339,13 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_run_stats.compact_fallbacks),
- atomic64_read(&fs_info->stripe_run_stats.compact_stripes),
- atomic64_read(&fs_info->stripe_run_stats.compact_bytes),
-- atomic64_read(&fs_info->stripe_run_stats.log_run_opened));
-+ atomic64_read(&fs_info->stripe_run_stats.log_run_opened),
-+ atomic64_read(&fs_info->stripe_run_stats.log_settle_waits),
-+ atomic64_read(&fs_info->stripe_run_stats.log_settle_wait_ns),
-+ atomic64_read(&fs_info->stripe_run_stats.log_carry_ranges),
-+ atomic64_read(&fs_info->stripe_run_stats.log_carry_bytes),
-+ atomic64_read(&fs_info->stripe_run_stats.log_seals),
-+ atomic64_read(&fs_info->stripe_run_stats.log_seal_bytes));
- }
- BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
-
-@@ -1400,6 +1412,31 @@ static ssize_t btrfs_stripe_log_run_store(struct kobject *kobj,
- }
- BTRFS_ATTR_RW(, stripe_log_run, btrfs_stripe_log_run_show,
- btrfs_stripe_log_run_store);
-+
-+static ssize_t btrfs_stripe_log_data_shared_show(struct kobject *kobj,
-+ struct kobj_attribute *a, char *buf)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+
-+ return sysfs_emit(buf, "%d\n", READ_ONCE(fs_info->stripe_log_data_shared) ? 1 : 0);
-+}
-+
-+static ssize_t btrfs_stripe_log_data_shared_store(struct kobject *kobj,
-+ struct kobj_attribute *a,
-+ const char *buf, size_t len)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+ bool val;
-+ int ret;
-+
-+ ret = kstrtobool(buf, &val);
-+ if (ret)
-+ return ret;
-+ WRITE_ONCE(fs_info->stripe_log_data_shared, val);
-+ return len;
-+}
-+BTRFS_ATTR_RW(, stripe_log_data_shared, btrfs_stripe_log_data_shared_show,
-+ btrfs_stripe_log_data_shared_store);
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_sync_timeout_ms, stripe_park_sync_timeout_ms);
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_congestion, stripe_park_congestion);
-
-@@ -1806,6 +1843,7 @@ static const struct attribute *btrfs_attrs[] = {
- BTRFS_ATTR_PTR(, stripe_run_stats),
- BTRFS_ATTR_PTR(, stripe_park_timeout_ms),
- BTRFS_ATTR_PTR(, stripe_log_run),
-+ BTRFS_ATTR_PTR(, stripe_log_data_shared),
- BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
- BTRFS_ATTR_PTR(, stripe_park_congestion),
- BTRFS_ATTR_PTR(, stripe_compact),
---
-2.47.3
-
--- /dev/null
+From e63b3c7abf59fc929a99c3ca00ff3ea8be776366 Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Sat, 19 Sep 2026 13:17:55 -0400
+Subject: [RFC PATCH 84/85] btrfs: raid56: adaptive park deadline from the
+ parked-rbio backlog (debug_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: raid56: adaptive park deadline from the parked-rbio
+backlog" (earlier in this series) that need code from "btrfs: raid56:
+say whether a metadata read-modify-write is a write hole", which comes
+after it in this series: they are applied here, once "btrfs: raid56: say
+whether a metadata read-modify-write is a write hole" is in, instead of
+with the rest of "btrfs: raid56: adaptive park deadline from the
+parked-rbio backlog".
+
+Assisted-by: Claude:claude-opus-4-8
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/sysfs.c | 8 ++++++--
+ 1 file changed, 6 insertions(+), 2 deletions(-)
+
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index a15b8d79e6b80..671ea394b636c 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1232,6 +1232,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "meta_rmw_ghost %lld\n"
+ "meta_rmw_unknown %lld\n"
+ "meta_rmw_free %lld\n"
++ "congestion_short %lld\n"
+ "rbio_pin_refused %lld\n"
+ "rbio_pinned_now %d\n"
+ "rbio_pinned_live %d\n"
+@@ -1240,7 +1241,8 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "rbio_cache_hwm %lld\n"
+ "rbio_pin_swept %lld\n"
+ "rbio_pin_commit_requests %lld\n"
+- "meta_rmw_reads %lld\n",
++ "meta_rmw_reads %lld\n"
++ "parked_now %d\n",
+ atomic64_read(&fs_info->stripe_park_stats.parked),
+ atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
+ atomic64_read(&fs_info->stripe_park_stats.filled),
+@@ -1272,6 +1274,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_ghost),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_unknown),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free),
++ atomic64_read(&fs_info->stripe_park_stats.congestion_short),
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_refused),
+ pinned,
+ live,
+@@ -1280,7 +1283,8 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.rbio_cache_hwm),
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_swept),
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_commit_requests),
+- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_reads));
++ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_reads),
++ atomic_read(&fs_info->stripe_parked_now));
+ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
+ len += sysfs_emit_at(buf, len, "rbio_pinned_live_%s %d\n",
+ class_names[class], live_by_class[class]);
+--
+2.47.3
+
+++ /dev/null
-From 3ed13bd4b34d1faa4cad991e4c40a9522432a9e8 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 6 Oct 2026 12:40:29 -0400
-Subject: [RFC PATCH 084/116] btrfs: stripe_alloc: let relocation allocate as
- many data chunks as its reservation needs
-To: linux-btrfs@vger.kernel.org
-
-When a DATA_RELOC reservation fails, btrfs_reserve_data_bytes_held() forces
-one data chunk and retries. One chunk is not always enough: relocation
-reserves a whole cluster at once (prealloc_file_extent_cluster(), up to a full
-1 GiB block group of extents), and a new chunk can be smaller than that.
-During a device remove the chunk size cap is 10% of total_rw_bytes, which
-btrfs_shrink_device() has already reduced by the device being removed: on a
-4 x 3 GiB raid1 filesystem the forced chunk is 928 MiB, the retry still
-fails, and the first relocation pass of the 1 GiB data block group returns
--ENOSPC.
-
-btrfs_shrink_device() retries the block group once, and the second pass
-normally succeeds only because the first pass's empty 928 MiB chunk is still
-there, so one more forced chunk covers the cluster. If the cleaner deletes
-that unused chunk between the passes, the second pass fails the same way and
-the device remove fails with ENOSPC on a filesystem that is mostly empty
-(alloc-hints-replace-test's remove arm, 2 of 13 runs on misc-next, where the
-type writer's frequent commits run the cleaner often).
-
-Keep allocating while the allocation succeeds. Each success consumes
-unallocated device space, so the loop ends when there is none left.
-
-Fixes: 9f5878214e787 ("btrfs: stripe_alloc: let relocation allocate a data chunk before it fails")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/space-info.c | 10 ++++++++--
- 1 file changed, 8 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 1dcd20f69fcb1..781abadf24362 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -2316,9 +2316,15 @@ int btrfs_reserve_data_bytes_held(struct btrfs_space_info *space_info, u64 bytes
- * a reason to fail while there is unallocated space for a new chunk:
- * that made balance fail with ENOSPC on any filesystem whose data chunks
- * happened to be full.
-+ *
-+ * One chunk is not always enough: relocation reserves a whole cluster
-+ * (up to a full 1 GiB block group of extents) at once, and a new chunk
-+ * can be smaller than that -- during a device remove the chunk size cap
-+ * follows the shrunk filesystem. Keep allocating while it succeeds;
-+ * each success consumes unallocated space, so this ends.
- */
-- if (ret == -ENOSPC && flush == BTRFS_RESERVE_FLUSH_DATA_RELOC &&
-- reloc_alloc_data_chunk(space_info))
-+ while (ret == -ENOSPC && flush == BTRFS_RESERVE_FLUSH_DATA_RELOC &&
-+ reloc_alloc_data_chunk(space_info))
- ret = __reserve_bytes(space_info, bytes, flush, held);
- if (ret == -ENOSPC) {
- trace_btrfs_space_reservation(fs_info, "space_info:enospc",
---
-2.47.3
-
--- /dev/null
+From 1944ff74ed890d045c8d8f7346c44c519f6a2dee Mon Sep 17 00:00:00 2001
+From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
+Date: Thu, 1 Oct 2026 12:14:49 -0400
+Subject: [RFC PATCH 85/85] btrfs: stripe_alloc: keep a stripe in the rbio
+ cache until its run has written all of it (debug_meta part)
+To: linux-btrfs@vger.kernel.org
+
+The hunks of "btrfs: stripe_alloc: keep a stripe in the rbio cache until
+its run has written all of it" (earlier in this series) that need code
+from "btrfs: raid56: say whether a metadata read-modify-write is a write
+hole", which comes after it in this series: they are applied here, once
+"btrfs: raid56: say whether a metadata read-modify-write is a write
+hole" is in, instead of with the rest of "btrfs: stripe_alloc: keep a
+stripe in the rbio cache until its run has written all of it".
+
+Assisted-by: Claude:claude-opus-5-5
+---
+ fs/btrfs/sysfs.c | 4 ++++
+ 1 file changed, 4 insertions(+)
+
+diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
+index 671ea394b636c..213001078a2ab 100644
+--- a/fs/btrfs/sysfs.c
++++ b/fs/btrfs/sysfs.c
+@@ -1233,6 +1233,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "meta_rmw_unknown %lld\n"
+ "meta_rmw_free %lld\n"
+ "congestion_short %lld\n"
++ "rbio_pinned %lld\n"
+ "rbio_pin_refused %lld\n"
+ "rbio_pinned_now %d\n"
+ "rbio_pinned_live %d\n"
+@@ -1242,6 +1243,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ "rbio_pin_swept %lld\n"
+ "rbio_pin_commit_requests %lld\n"
+ "meta_rmw_reads %lld\n"
++ "written_not_live %lld\n"
+ "parked_now %d\n",
+ atomic64_read(&fs_info->stripe_park_stats.parked),
+ atomic64_read(&fs_info->stripe_park_stats.merged_bytes),
+@@ -1275,6 +1277,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_unknown),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free),
+ atomic64_read(&fs_info->stripe_park_stats.congestion_short),
++ atomic64_read(&fs_info->stripe_park_stats.rbio_pinned),
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_refused),
+ pinned,
+ live,
+@@ -1284,6 +1287,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_swept),
+ atomic64_read(&fs_info->stripe_park_stats.rbio_pin_commit_requests),
+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_reads),
++ atomic64_read(&fs_info->stripe_park_stats.written_not_live),
+ atomic_read(&fs_info->stripe_parked_now));
+ for (class = 0; class < BTRFS_STRIPE_RUN_NR_CLASSES; class++)
+ len += sysfs_emit_at(buf, len, "rbio_pinned_live_%s %d\n",
+--
+2.47.3
+
+++ /dev/null
-From 9ceaa90468ee8bd38a0f8eba7e07877fd2ed7935 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 00:17:47 -0400
-Subject: [RFC PATCH 085/116] btrfs: stripe_alloc: key private stripe runs by
- subvolume and inode
-To: linux-btrfs@vger.kernel.org
-
-Private LOG and NOCOW stripe runs are found by their owner, which is the
-inode number. Inode numbers are only unique within a subvolume: the first
-file created in every subvolume is inode 257. So inodes with the same
-number in different subvolumes are treated as one owner:
-
-- They join each other's private runs. For NOCOW runs this breaks the
- isolation the run exists for: btrfs_stripe_nocow_writable() lets an inode
- write in place into any stripe of a NOCOW run with its inode number, so
- an in-place write can read-modify-write a stripe holding another
- subvolume's file's data, and a torn write can damage that file. For LOG
- runs, one inode's log commit settles stripes holding the other inode's
- extents.
-- Evicting an inode closes the open runs of every same-numbered inode in
- other subvolumes, and the META_LOG run of the subvolume whose root id
- equals the inode number (META_LOG runs use the root id as owner, and
- subvolume ids share the range of inode numbers). An early close traps
- the run's free tail until the space is reclaimed.
-
-Record the subvolume's root id in each private run and match on (root,
-owner). Eviction closes only the inode's own LOG and NOCOW runs. The
-shared LOG key no longer needs the low 31 bits of the root id, which also
-let subvolumes with ids 2^31 apart share a run.
-
-Fixes: b0883536e21be ("btrfs: stripe_alloc: isolate nodatacow and preallocated extents by stripe")
-Fixes: d84a06902203c ("btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow extents")
-Fixes: 1e024fc04bccd ("btrfs: stripe_alloc: persist nocow runs across commits and remounts")
-Fixes: 927940f4222f8 ("btrfs: stripe_alloc: share LOG data runs per log transaction")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 36 +++++++++++++++++++++++++-----------
- 1 file changed, 25 insertions(+), 11 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index d9afc2f6d8e4a..141ac2b45397b 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -504,7 +504,14 @@ struct btrfs_open_stripe_run {
- u64 inflight_bytes; /* reserved bytes with data IO pending */
- u64 open_seq; /* fs_info->stripe_retire_seq at open */
- u64 transid; /* fs_info->generation at open */
-- u64 owner; /* LOG class: btrfs_ino of the owner */
-+ /*
-+ * Private runs are found by (root, owner): root is the subvolume's
-+ * root id, owner the inode number (LOG, NOCOW), a shared LOG key
-+ * (bit 63 set, see stripe_run_owner()), or for META_LOG the root id
-+ * again. Inode numbers are only unique within a subvolume.
-+ */
-+ u64 root;
-+ u64 owner;
- enum btrfs_stripe_run_class class;
- bool open; /* accepting allocations */
- bool persistent; /* survives commits; see close_block_group_stripe_runs() */
-@@ -1266,6 +1273,7 @@ int btrfs_alloc_from_log_stripe_run(struct btrfs_block_group *bg, u64 num_bytes,
- new_run->bg = bg;
- new_run->class = class;
- new_run->persistent = false;
-+ new_run->root = owner;
- new_run->owner = owner;
- new_run->log_transid = log_transid;
- new_run->transid = btrfs_get_fs_generation(fs_info);
-@@ -1301,7 +1309,8 @@ int btrfs_alloc_from_log_stripe_run(struct btrfs_block_group *bg, u64 num_bytes,
- * subvolume logging in the same log transaction. An allocation of a full
- * stripe or more keeps the inode's private run, so small fsync extents never
- * share the partial last stripe of a large one and wait for its IO. Bit 63
-- * keeps the shared keys apart from inode numbers.
-+ * keeps the shared keys apart from inode numbers; the subvolume is matched
-+ * separately, by run->root.
- */
- static u64 stripe_run_owner(struct btrfs_inode *inode,
- enum btrfs_stripe_run_class class, u64 num_bytes,
-@@ -1311,9 +1320,7 @@ static u64 stripe_run_owner(struct btrfs_inode *inode,
-
- if (class == BTRFS_STRIPE_RUN_LOG && num_bytes < fsl &&
- READ_ONCE(root->fs_info->stripe_log_data_shared))
-- return BIT_ULL(63) |
-- ((btrfs_root_id(root) & 0x7fffffffULL) << 32) |
-- (u32)READ_ONCE(root->log_transid);
-+ return BIT_ULL(63) | (u32)READ_ONCE(root->log_transid);
- return btrfs_ino(inode);
- }
-
-@@ -1344,6 +1351,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- {
- struct btrfs_fs_info *fs_info = bg->fs_info;
- const u64 fsl = bg->full_stripe_len;
-+ const u64 root_id = btrfs_root_id(inode->root);
- const u64 ino = stripe_run_owner(inode, class, num_bytes, fsl);
- struct btrfs_open_stripe_run *new_run;
- struct btrfs_open_stripe_run *run;
-@@ -1359,7 +1367,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (run->class != class || run->owner != ino || !run->open)
-+ if (run->class != class || run->root != root_id ||
-+ run->owner != ino || !run->open)
- continue;
- if (num_bytes <= run->end - run->offset) {
- *ret_offset = run->offset;
-@@ -1414,8 +1423,8 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- * 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) &&
-+ if (stripe_extents_owned_by(fs_info, root_id, ino, stripe, fsl,
-+ &frontier, true) &&
- frontier > stripe && frontier < stripe + fsl &&
- num_bytes <= stripe + fsl - frontier) {
- tlen = stripe + fsl - frontier;
-@@ -1483,6 +1492,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- BTRFS_STRIPE_RMW_PREALLOC));
- if (class == BTRFS_STRIPE_RUN_NOCOW)
- atomic64_inc(&fs_info->stripe_run_stats.nocow_run_opened);
-+ new_run->root = root_id;
- new_run->owner = ino;
- new_run->start = start;
- new_run->end = start + len;
-@@ -1897,7 +1907,7 @@ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
- if (cur < run->start || cur >= run->end)
- continue;
- if (run->class == BTRFS_STRIPE_RUN_NOCOW &&
-- run->owner == ino)
-+ run->root == root_id && run->owner == ino)
- verdict = 1;
- else
- verdict = -1;
-@@ -2269,7 +2279,7 @@ static bool stripe_range_run_free(struct btrfs_block_group *bg, u64 start,
- }
-
- /*
-- * Close every private stripe run owned by @inode, of any class: called at
-+ * Close every private LOG and NOCOW run owned by @inode: 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
-@@ -2278,6 +2288,7 @@ static bool stripe_range_run_free(struct btrfs_block_group *bg, u64 start,
- void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
- {
- struct btrfs_fs_info *fs_info = inode->root->fs_info;
-+ const u64 root_id = btrfs_root_id(inode->root);
- const u64 ino = btrfs_ino(inode);
- struct btrfs_block_group *bg;
-
-@@ -2294,7 +2305,10 @@ void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (!run->open || run->owner != ino)
-+ if (!run->open || run->root != root_id ||
-+ run->owner != ino ||
-+ (run->class != BTRFS_STRIPE_RUN_LOG &&
-+ run->class != BTRFS_STRIPE_RUN_NOCOW))
- continue;
- tail_len = close_open_stripe_run(bg, run, &tail_start);
- break;
---
-2.47.3
-
+++ /dev/null
-From 7db5408eb960737f39550d1d12576ed34f0f97c5 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 00:49:17 -0400
-Subject: [RFC PATCH 086/116] btrfs: stripe_alloc: do not treat an allocation
- error as a found extent
-To: linux-btrfs@vger.kernel.org
-
-do_allocation_stripe() returns -ENOMEM when it cannot allocate a stripe
-run. find_free_extent() only treats a positive return as "try the next
-block group" and takes anything else as success, so it went on to reserve
-ffe_ctl->found_offset, which was not set by this group: 0 on the first
-group of a search, or an offset an earlier group handed back after an
-undone allocation and that is still free there. The first reserves a
-range at logical 0 (an ordered extent that cannot be mapped, or a tree
-block whose delayed ref aborts the transaction); the second gives the
-same space to two owners.
-
-Skip the group on an error, as on any other failure, and return the error
-instead of -ENOSPC if no other group has space.
-
-Fixes: e88c1e86fc86a ("btrfs: add the stripe_alloc allocation policy for raid56 data")
-Fixes: 773ba20ff66e8 ("btrfs: stripe_alloc: private per-inode stripe runs for log-active inodes")
-Fixes: 51fcf2348a33f ("btrfs: stripe_meta: allocate tree blocks by whole stripes")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/extent-tree.c | 16 ++++++++++++++--
- 1 file changed, 14 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index f09a54d4ee199..ed8317209f847 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4800,6 +4800,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
- struct btrfs_fs_info *fs_info = root->fs_info;
- int ret = 0;
- int cache_block_group_error = 0;
-+ int alloc_error = 0;
- struct btrfs_block_group *block_group = NULL;
- struct btrfs_space_info *space_info;
- bool full_search = false;
-@@ -4984,6 +4985,17 @@ static noinline int find_free_extent(struct btrfs_root *root,
- ret = do_allocation(block_group, ffe_ctl, &bg_ret);
- if (ret > 0)
- goto loop;
-+ if (ret < 0) {
-+ /*
-+ * The stripe allocator could not allocate its run
-+ * tracking (-ENOMEM). ffe_ctl->found_offset is not
-+ * valid; try the other groups and report the error
-+ * if none of them has space.
-+ */
-+ if (!alloc_error)
-+ alloc_error = ret;
-+ goto loop;
-+ }
-
- if (bg_ret && bg_ret != block_group) {
- btrfs_release_block_group(block_group, ffe_ctl->delalloc);
-@@ -5049,7 +5061,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
- if (ret > 0)
- goto search;
-
-- if (ret == -ENOSPC && !cache_block_group_error) {
-+ if (ret == -ENOSPC && !cache_block_group_error && !alloc_error) {
- /*
- * Use ffe_ctl->total_free_space as fallback if we can't find
- * any contiguous hole.
-@@ -5061,7 +5073,7 @@ static noinline int find_free_extent(struct btrfs_root *root,
- spin_unlock(&space_info->lock);
- ins->offset = ffe_ctl->max_extent_size;
- } else if (ret == -ENOSPC) {
-- ret = cache_block_group_error;
-+ ret = cache_block_group_error ?: alloc_error;
- }
- return ret;
- }
---
-2.47.3
-
+++ /dev/null
-From d6d94cf983c906599778dc6bacb036f7c403d8ee Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 00:50:45 -0400
-Subject: [RFC PATCH 087/116] btrfs: stripe_alloc: mark an ended ordered
- extent's sectors written
-To: linux-btrfs@vger.kernel.org
-
-A sector enters a run's written map only when a raid56 write of it
-completes successfully. An ordered extent can end without writing all of
-its sectors: a write error, truncation of folios that were never
-submitted, a short direct write, or teardown of an extent whose IO never
-started. Its sectors then stay allocated and unwritten for as long as the
-run exists, and everything that waits on the written map waits for them:
-
-- With shared LOG runs, btrfs_log_settle_stripes() waits, with no timeout,
- for every allocated sector of the logged extent's stripes to be
- written. The fsync holds a transaction handle, and only the commit
- closes the run, so the fsync and every later transaction start hang
- until the filesystem is forced read-only.
-- The rbio cache keeps the stripe pinned until the run has written all of
- it.
-
-When an ordered extent reports to its run, mark its whole range written.
-After a successful write this changes nothing. Otherwise no write of
-those sectors is still coming, which is what the waiters need to know.
-Marking them written rather than dead also keeps them from being padded:
-a later partial write to the stripe reads them, so nothing a truncated
-extent kept is zeroed. Wake the waiters while the run lock is still held,
-since the run and its group can be freed once it is dropped.
-
-Fixes: 927940f4222f8 ("btrfs: stripe_alloc: share LOG data runs per log transaction")
-Fixes: d0b94c811a9a1 ("btrfs: stripe_alloc: keep a stripe in the rbio cache until its run has written all of it")
-Fixes: 9ec29923fbd7f ("btrfs: stripe_alloc: pad a stripe's allocated sectors whose write is still to come")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 17 ++++++++++++++++-
- fs/btrfs/block-group.h | 2 +-
- fs/btrfs/ordered-data.c | 3 ++-
- 3 files changed, 19 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 141ac2b45397b..89c8af4dfc7a5 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -3057,15 +3057,30 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
- * bio end_io context. The run pointer stays valid until the reporter's own
- * bytes are reported: a run with inflight bytes is never freed.
- */
-+/*
-+ * An ordered extent's data IO is over, whether or not all of it reached the
-+ * disk: stop counting it as in flight, and mark its sectors written. A
-+ * sector whose write failed or was never issued (truncation, a short direct
-+ * write, error teardown) will not be written now. Marking it keeps a log
-+ * settle from waiting for it forever, and a written sector is never padded,
-+ * so a later partial write to the stripe reads it instead of zeroing it.
-+ */
- void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
-- u64 num_bytes)
-+ u64 start, u64 num_bytes)
- {
- struct btrfs_block_group *bg = run->bg;
-+ const u32 bits = bg->fs_info->sectorsize_bits;
- unsigned long flags;
-+ u64 s = start;
-+ u64 l = num_bytes;
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- ASSERT(run->inflight_bytes >= num_bytes);
- run->inflight_bytes -= num_bytes;
-+ if (run_written_range(run, &s, &l))
-+ bitmap_set(run->written, (s - run->start) >> bits, l >> bits);
-+ /* Under the lock: the run and the group may be gone after it. */
-+ wake_up_var(&bg->open_stripe_runs);
- open_stripe_run_drain_reported(bg, run);
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- }
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 6feea39c82427..88c24dfbe136a 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -509,7 +509,7 @@ void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
- void btrfs_open_stripe_write_abandoned(struct btrfs_block_group *bg, u64 start,
- u64 num_bytes);
- void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
-- u64 num_bytes);
-+ u64 start, u64 num_bytes);
- void btrfs_open_stripe_write_done_bytenr(struct btrfs_fs_info *fs_info,
- u64 start, u64 num_bytes);
- struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
-diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
-index 8e06a4266b3a3..931be63ce1727 100644
---- a/fs/btrfs/ordered-data.c
-+++ b/fs/btrfs/ordered-data.c
-@@ -413,7 +413,8 @@ static void btrfs_ordered_stripe_write_done(struct btrfs_ordered_extent *ordered
- if (!run)
- return;
- ordered->stripe_run = NULL;
-- btrfs_open_stripe_write_done_run(run, ordered->disk_num_bytes);
-+ btrfs_open_stripe_write_done_run(run, ordered->disk_bytenr,
-+ ordered->disk_num_bytes);
- }
-
- static bool can_finish_ordered_extent(struct btrfs_ordered_extent *ordered,
---
-2.47.3
-
+++ /dev/null
-From 8a2735833465c220be2deb2f68995414b6caa48b Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 00:51:15 -0400
-Subject: [RFC PATCH 088/116] btrfs: stripe_alloc: read the shared LOG run mode
- once per log settle
-To: linux-btrfs@vger.kernel.org
-
-btrfs_log_settle_stripes() read stripe_log_data_shared once to decide
-whether to seal or close the run and again to decide what to wait for. A
-sysfs change between the two reads could seal a shared run and then wait
-for no run to cover the extent, which only the commit provides, while
-the fsync holds the transaction handle that commit waits for.
-btrfs_stripe_run_mark_written() also stopped waking settle waiters once
-the knob was cleared, stranding any that were already waiting in shared
-mode.
-
-Read the knob once per settle, and wake the waiters on every completed
-write.
-
-Fixes: 927940f4222f8 ("btrfs: stripe_alloc: share LOG data runs per log transaction")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 12 ++++++------
- 1 file changed, 6 insertions(+), 6 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 89c8af4dfc7a5..7888f55c34430 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2435,6 +2435,8 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- u64 file_len, u64 bytenr, u64 num_bytes)
- {
- struct btrfs_fs_info *fs_info = inode->root->fs_info;
-+ /* Once: the seal and the wait below must agree on the mode. */
-+ const bool shared = READ_ONCE(fs_info->stripe_log_data_shared);
- struct btrfs_block_group *bg;
- struct btrfs_open_stripe_run *run;
- unsigned long flags;
-@@ -2474,8 +2476,7 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- */
- if (run->class == BTRFS_STRIPE_RUN_NOCOW)
- break;
-- if (READ_ONCE(fs_info->stripe_log_data_shared) &&
-- (run->owner & BIT_ULL(63))) {
-+ if (shared && (run->owner & BIT_ULL(63))) {
- const u64 fsl = bg->full_stripe_len;
-
- /* only the logged extent's stripes, not the shared run */
-@@ -2513,7 +2514,7 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-
-- if (!READ_ONCE(fs_info->stripe_log_data_shared))
-+ if (!shared)
- log_carry_record(inode, file_start, file_len, bytenr, num_bytes,
- ps_start, ps_len);
-
-@@ -2532,7 +2533,7 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
-
- btrfs_flush_parked_rbios(fs_info, flush_start, flush_len, false);
- t0 = ktime_get();
-- if (READ_ONCE(fs_info->stripe_log_data_shared))
-+ if (shared)
- wait_var_event(&bg->open_stripe_runs,
- stripe_log_extent_written(bg, bytenr, num_bytes) ||
- BTRFS_FS_ERROR(fs_info));
-@@ -2814,8 +2815,7 @@ void btrfs_stripe_run_mark_written(struct btrfs_fs_info *fs_info, u64 start,
- }
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- /* Per-stripe log settles wait on the written map, not on a drain. */
-- if (READ_ONCE(fs_info->stripe_log_data_shared))
-- wake_up_var(&bg->open_stripe_runs);
-+ wake_up_var(&bg->open_stripe_runs);
- btrfs_put_block_group(bg);
- if (not_live)
- atomic64_add(not_live, &fs_info->stripe_park_stats.written_not_live);
---
-2.47.3
-
+++ /dev/null
-From 11b27450d340cebc88073ef5fbbc188d49cef882 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 00:54:41 -0400
-Subject: [RFC PATCH 089/116] btrfs: stripe_alloc: remove only the set bits of
- a bitmap when claiming a split run
-To: linux-btrfs@vger.kernel.org
-
-A fully-free stripe run can span free space entries, and
-claim_stripe_run_pieces() removes it piece by piece. For a bitmap entry
-it took the piece to the end of the bitmap's window. When the run goes on
-in an extent entry that starts inside the same window (set bits up to the
-entry, then the entry), that piece covers the entry too:
-bitmap_clear_bits() subtracts the whole piece from the bitmap and from
-ctl->free_space, although part of it was never set, and the loop then
-steps past the extent entry without removing it. The bitmap's byte count
-goes wrong, and the extent entry's bytes stay free in the cache while the
-claiming run owns them, so they can be handed out again once the run is
-gone.
-
-Take a bitmap piece only to the end of the set bits that start at the
-piece, so the next piece finds the extent entry. Add a self-test with
-this layout.
-
-Fixes: 3230ad28b8b14 ("btrfs: stripe_alloc: claim fully-free stripes that span free space entries")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/free-space-cache.c | 15 ++++++++++++---
- fs/btrfs/tests/free-space-tests.c | 27 +++++++++++++++++++++++++++
- 2 files changed, 39 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index f0c3187554deb..c7c55d108486c 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2778,10 +2778,19 @@ static bool claim_stripe_run_pieces(struct btrfs_block_group *block_group,
- break;
-
- if (info->bitmap) {
-- const u64 b_end = info->offset +
-- (u64)BITS_PER_BITMAP * unit;
-+ const unsigned long bit =
-+ offset_to_bit(info->offset, unit, off);
-+ const unsigned long zero =
-+ find_next_zero_bit(info->bitmap,
-+ BITS_PER_BITMAP, bit);
-
-- piece = min(remaining, b_end - off);
-+ /*
-+ * Only the set bits from @off: the run may go on in
-+ * an extent entry inside this bitmap's window.
-+ */
-+ piece = min(remaining, (u64)(zero - bit) * unit);
-+ if (WARN_ON(!piece))
-+ break;
- if (!btrfs_free_space_trimmed(info))
- atomic64_add(piece,
- &discard_ctl->discard_bytes_saved);
-diff --git a/fs/btrfs/tests/free-space-tests.c b/fs/btrfs/tests/free-space-tests.c
-index 1ee9632d7e0b6..4022cadcd9e4c 100644
---- a/fs/btrfs/tests/free-space-tests.c
-+++ b/fs/btrfs/tests/free-space-tests.c
-@@ -1166,6 +1166,33 @@ static int test_stripe_claim(struct btrfs_block_group *cache, u32 sectorsize)
- goto out;
- }
-
-+ /*
-+ * A free stripe split inside one bitmap window: set bits, then an
-+ * extent entry. The claim must remove both pieces, and nothing else.
-+ */
-+ ret = test_add_free_space_entry(cache, 0, fsl / 2, 1);
-+ if (ret) {
-+ test_err("error adding bitmap entry %d", ret);
-+ goto out;
-+ }
-+ ret = test_add_free_space_entry(cache, fsl / 2, fsl / 2, 0);
-+ if (ret) {
-+ test_err("error adding extent entry %d", ret);
-+ goto out;
-+ }
-+ ret = btrfs_claim_free_stripe_run(cache, fsl, &start, &len);
-+ if (ret || start != 0 || len != fsl) {
-+ test_err("bitmap+extent claim wrong: ret %d start %llu len %llu",
-+ ret, start, len);
-+ ret = -EINVAL;
-+ goto out;
-+ }
-+ ret = check_cache_empty(cache);
-+ if (ret) {
-+ test_err("bitmap+extent 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);
---
-2.47.3
-
+++ /dev/null
-From 7d19226b292f654c6f741534c9dbd4e8b8ca2621 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 00:54:48 -0400
-Subject: [RFC PATCH 090/116] btrfs: stripe_alloc: claim a stripe tail in one
- free space lock section
-To: linux-btrfs@vger.kernel.org
-
-btrfs_claim_stripe_tail() re-adopts the free tail of a partial stripe
-owned by one nodatacow inode. It counted the tail's free bytes under
-ctl->tree_lock, dropped the lock, and then called
-btrfs_remove_free_space(), which returns 0 when the range is not in the
-cache at all. Two allocations for the same inode can re-adopt the same
-tail at once (two direct writers, or writeback racing fallocate): both
-count it free, one removes it, the other's remove finds nothing and still
-succeeds, and both install a run over the same bytes and hand out the same
-extent start. Discard opens the same window: trimming takes an entry out
-of the cache and puts it back after the IO, and a remove in between also
-"succeeds".
-
-Count and remove in the same tree_lock section, with
-claim_stripe_run_pieces() doing the removal as for any claimed run, and
-fail with -ENOSPC unless the whole tail is in the cache. Add a self-test
-that claims the same tail twice.
-
-Fixes: 1e024fc04bccd ("btrfs: stripe_alloc: persist nocow runs across commits and remounts")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/free-space-cache.c | 41 ++++++++++++++++++++++---------
- fs/btrfs/tests/free-space-tests.c | 29 ++++++++++++++++++++++
- 2 files changed, 59 insertions(+), 11 deletions(-)
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index c7c55d108486c..0489213c4435e 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2529,24 +2529,32 @@ static bool find_stripe_run_in_bitmap(struct btrfs_free_space_ctl *ctl,
- * Returns 0 on success, -ENOSPC if no aligned fully-free stripe is present
- * in this block group, -ENOMEM if the slow path could not allocate.
- */
-+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:
-- * nothing else can consume free space inside a partially used stripe of a
-- * stripe_alloc block group (allocations come only from claimed runs, and
-- * runs claim only fully-free stripes), so the verify-then-remove sequence
-- * cannot race with another consumer -- except a concurrent re-adoption by
-- * the same inode, which this function's recount safely turns into one
-- * winner and one -ENOSPC.
-+ * 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)) {
-@@ -2584,11 +2592,22 @@ int btrfs_claim_stripe_tail(struct btrfs_block_group *block_group,
- 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 (found != len)
-- return -ENOSPC;
-- return btrfs_remove_free_space(block_group, start, len);
-+ if (spare)
-+ kmem_cache_free(btrfs_free_space_cachep, spare);
-+ return ret;
- }
-
- /*
-diff --git a/fs/btrfs/tests/free-space-tests.c b/fs/btrfs/tests/free-space-tests.c
-index 4022cadcd9e4c..5da244e148321 100644
---- a/fs/btrfs/tests/free-space-tests.c
-+++ b/fs/btrfs/tests/free-space-tests.c
-@@ -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);
---
-2.47.3
-
+++ /dev/null
-From f122420a94a8e61bba581893ecf4cdea0432bbc9 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 00:57:34 -0400
-Subject: [RFC PATCH 091/116] btrfs: stripe_alloc: keep the stripe totals
- consistent with the groups during the commit scan
-To: linux-btrfs@vger.kernel.org
-
-btrfs_scan_stripe_unusable() makes the space_info's stripe_unusable and
-stripe_claimable totals authoritative at commit by summing the armed
-groups' values. It read the group values without a lock, dropped
-groups_sem, and then assigned the totals under sinfo->lock. Everything
-else changes a group value under the free space tree lock and the total
-by delta under sinfo->lock, in a separate step, so an update between the
-scan's read and its assignment was lost or counted twice:
-
-- a claim lowers the group's claimable and then the total; read before
- the claim and assigned after it, the total keeps the claimed bytes;
-- a group made read-only is disarmed and its claimable leaves the total;
- read before and assigned after, the read-only group's whole claimable
- supply is back in the total until the next commit, and data
- reservations are admitted against it that writeback cannot place;
-- an arm adds the group to the total after setting it up, so a scan in
- between counts it twice.
-
-Over-counting claimable supply is the direction that admits writes which
-later fail. It also matches the occasional unexplained mid-balance ENOSPC
-while every invariant held.
-
-Update a group's values and the total together under sinfo->lock
-everywhere (claim, arm, disarm, rescan), and have the scan sum the groups
-under sinfo->lock, still holding groups_sem for the list walk. The total
-then always equals the sum of the armed groups. Do not restore the
-stripe_meta margin and reserve if stripe_alloc was disabled after the
-scan started, since the disable path has cleared them and no later scan
-would clear them again.
-
-Fixes: 0d65b0f893beb ("btrfs: account stripe_alloc trapped free space for honest statfs")
-Fixes: cf30dc92901fa ("btrfs: stripe_alloc: count claimable whole-stripe supply directly")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 47 +++++++++++++++++--------
- fs/btrfs/free-space-cache.c | 69 ++++++++++++++++++++-----------------
- 2 files changed, 71 insertions(+), 45 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 7888f55c34430..50d8e6f9ad42e 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -3624,21 +3624,35 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- */
- if (force || dirty)
- btrfs_block_group_rescan_stripe_unusable(bg);
-- /*
-- * Sum the authoritative per-group values into the
-- * space_info total so it cannot drift from repeated
-- * arm/disarm/rescan deltas. Disarmed (read-only)
-- * groups are excluded; their free space is already
-- * accounted as read-only.
-- */
-- if (READ_ONCE(bg->stripe_unusable_ready)) {
-- total += READ_ONCE(bg->stripe_unusable);
-+ }
-+ }
-+
-+ /*
-+ * Sum the authoritative per-group values into the space_info
-+ * total so it cannot drift from repeated arm/disarm/rescan
-+ * deltas. Disarmed (read-only) groups are excluded; their
-+ * free space is already accounted as read-only. Every update
-+ * of a group's values also updates the total under
-+ * sinfo->lock, so summing under it gives totals that match
-+ * the groups: claims, arms and disarms that race with the
-+ * scan are neither lost nor counted twice.
-+ */
-+ spin_lock(&sinfo->lock);
-+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-+ struct btrfs_block_group *bg;
-+
-+ if (!(btrfs_raid_array[raid].bg_flag &
-+ BTRFS_BLOCK_GROUP_RAID56_MASK))
-+ continue;
-+ list_for_each_entry(bg, &sinfo->block_groups[raid],
-+ list) {
-+ if (bg->stripe_unusable_ready) {
-+ total += bg->stripe_unusable;
- total_stranded += READ_ONCE(bg->stripe_stranded);
-- total_claimable +=
-- READ_ONCE(bg->stripe_claimable);
-+ total_claimable += bg->stripe_claimable;
- if (bg->start == READ_ONCE(fs_info->data_reloc_bg))
- total_claimable_reloc +=
-- READ_ONCE(bg->stripe_claimable);
-+ bg->stripe_claimable;
- nr_rw++;
- largest = max(largest, bg->length);
- }
-@@ -3647,12 +3661,17 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- }
- up_read(&sinfo->groups_sem);
-
-- spin_lock(&sinfo->lock);
- sinfo->bytes_stripe_unusable = total;
- sinfo->bytes_stripe_claimable = total_claimable;
- sinfo->bytes_stripe_claimable_reloc = total_claimable_reloc;
- sinfo->bytes_stripe_stranded = total_stranded;
-- if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA)) {
-+ /*
-+ * Not if the option went off since the check above: the
-+ * disable path has cleared the margin and reserve, and no
-+ * later scan would clear them again.
-+ */
-+ if (!(sinfo->flags & BTRFS_BLOCK_GROUP_DATA) &&
-+ btrfs_test_opt(fs_info, STRIPE_ALLOC)) {
- u64 reserve = 0;
-
- /*
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 0489213c4435e..0d006a25295a9 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1524,6 +1524,10 @@ static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
- * ENOSPC, corrected upward by the commit rescan), never HIGH: a
- * reservation admitted against phantom supply fails at writeback and
- * drops buffered data. Caller holds ctl->tree_lock.
-+ *
-+ * The group's value and the space_info total change in one sinfo->lock
-+ * section, as everywhere else, so that btrfs_scan_stripe_unusable(), which
-+ * sums the groups under that lock, never sees one without the other.
- */
- static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta)
- {
-@@ -1531,14 +1535,16 @@ static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta)
-
- if (!READ_ONCE(bg->stripe_unusable_ready) || !delta)
- return;
-+ if (!sinfo) {
-+ if (delta < 0 && bg->stripe_claimable < (u64)-delta)
-+ delta = -(s64)bg->stripe_claimable;
-+ bg->stripe_claimable += delta;
-+ return;
-+ }
-+ spin_lock(&sinfo->lock);
- if (delta < 0 && bg->stripe_claimable < (u64)-delta)
- delta = -(s64)bg->stripe_claimable;
-- if (!delta)
-- return;
- bg->stripe_claimable += delta;
-- if (!sinfo)
-- return;
-- spin_lock(&sinfo->lock);
- if (delta < 0 && sinfo->bytes_stripe_claimable < (u64)-delta)
- sinfo->bytes_stripe_claimable = 0;
- else
-@@ -2217,22 +2223,19 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *bg)
- return;
- }
- trapped = stripe_unusable_scan(bg, freep, nstripes);
-- bg->stripe_unusable = trapped;
- /* Every free byte is claimable or trapped; the scan split them. */
-- bg->stripe_claimable = ctl->free_space - trapped;
-- claimable = bg->stripe_claimable;
-+ claimable = ctl->free_space - trapped;
-+ /* Group and total together; see stripe_claimable_mod(). */
-+ spin_lock(&bg->space_info->lock);
-+ bg->stripe_unusable = trapped;
-+ bg->stripe_claimable = claimable;
- bg->stripe_unusable_ready = true;
-+ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info, trapped);
-+ btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
-+ claimable);
-+ spin_unlock(&bg->space_info->lock);
- spin_unlock(&ctl->tree_lock);
- kvfree(freep);
--
-- if (trapped || claimable) {
-- spin_lock(&bg->space_info->lock);
-- btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
-- trapped);
-- btrfs_space_info_update_bytes_stripe_claimable(bg->space_info,
-- claimable);
-- spin_unlock(&bg->space_info->lock);
-- }
- }
-
- /*
-@@ -2257,22 +2260,20 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
- spin_unlock(&ctl->tree_lock);
- return;
- }
-+ /* Group and total together; see stripe_claimable_mod(). */
-+ spin_lock(&bg->space_info->lock);
- trapped = bg->stripe_unusable;
- claimable = bg->stripe_claimable;
- bg->stripe_claimable = 0;
- bg->stripe_unusable_ready = false;
-+ btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
-+ -(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);
- spin_unlock(&ctl->tree_lock);
--
-- if (trapped || claimable) {
-- spin_lock(&bg->space_info->lock);
-- btrfs_space_info_update_bytes_stripe_unusable(bg->space_info,
-- -(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);
-- }
- }
-
-
-@@ -2388,10 +2389,9 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
- stripe_return_clusters(bg);
- spin_lock(&ctl->tree_lock);
- if (bg->stripe_unusable_ready) { /* skip if disarmed (read-only) */
-- u64 scanned;
-+ const u64 trapped = stripe_unusable_scan(bg, freep, nstripes);
-+ const u64 scanned = ctl->free_space - trapped;
-
-- bg->stripe_unusable = stripe_unusable_scan(bg, freep, nstripes);
-- scanned = ctl->free_space - bg->stripe_unusable;
- /*
- * The incremental rules may only under-count claimable
- * supply; counting more than the scan finds means a missed
-@@ -2406,7 +2406,14 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
- WARN_RATELIMIT(bg->stripe_claimable > scanned,
- "bg %llu incremental stripe_claimable %llu above scanned %llu",
- bg->start, bg->stripe_claimable, scanned);
-+ /*
-+ * Under sinfo->lock so btrfs_scan_stripe_unusable() sums
-+ * both new values or both old ones.
-+ */
-+ spin_lock(&bg->space_info->lock);
-+ bg->stripe_unusable = trapped;
- bg->stripe_claimable = scanned;
-+ spin_unlock(&bg->space_info->lock);
- /*
- * Hand a group full of trapped free space to the reclaim
- * worker (btrfs_stripe_bg_wants_reclaim()), but not again
---
-2.47.3
-
+++ /dev/null
-From f6c9504e560c3f3123ccbec6931639845e141109 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 00:58:45 -0400
-Subject: [RFC PATCH 092/116] btrfs: stripe_alloc: do not delete an unused
- block group that still has stripe runs
-To: linux-btrfs@vger.kernel.org
-
-btrfs_delete_unused_bgs() removes a group whose used, reserved and pinned
-counts are all zero. A stripe run's unallocated remainder is out of the
-free space cache but counted in none of those, and the cleaner makes the
-group read-only with inc_block_group_ro(), which does not retire runs. A
-group can therefore be removed while a run still covers it:
-
-- a persistent nocow run whose file's extents in the group were all freed
- (the run closes as dead at the next commit), or
-- the running transaction's metadata run in a group whose tree blocks
- were all freed again before their delayed refs ran.
-
-btrfs_remove_block_group() then warns about the open runs, and when the
-run closes later its tail is added to the removed group's free space
-cache. Those entries leak with the group, and with async discard the
-removed group is queued for discard again.
-
-After making the group read-only, which keeps new runs out, leave it for a
-later pass if any run still covers it. The runs it can have close by the
-next commit.
-
-Fixes: e88c1e86fc86a ("btrfs: add the stripe_alloc allocation policy for raid56 data")
-Fixes: 1e024fc04bccd ("btrfs: stripe_alloc: persist nocow runs across commits and remounts")
-Fixes: 51fcf2348a33f ("btrfs: stripe_meta: allocate tree blocks by whole stripes")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 26 ++++++++++++++++++++++++++
- fs/btrfs/block-group.h | 1 +
- 2 files changed, 27 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 50d8e6f9ad42e..f34181d7ce17a 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2278,6 +2278,18 @@ static bool stripe_range_run_free(struct btrfs_block_group *bg, u64 start,
- 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 LOG and NOCOW run owned by @inode: called at
- * inode eviction so a persistent nocow run's claimed tail does not stay
-@@ -5223,6 +5235,20 @@ 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. Read-only, the group
-+ * gets no new runs, and these close by the next commit; try
-+ * again after it.
-+ */
-+ 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);
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 88c24dfbe136a..c4e043ecacca5 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -502,6 +502,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- enum btrfs_stripe_run_class class,
- 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,
---
-2.47.3
-
+++ /dev/null
-From d800d45ed7969f1fbbd360e9db54a354ac4bc6e9 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:00:24 -0400
-Subject: [RFC PATCH 093/116] btrfs: stripe_meta: commit before waiting for
- metadata runs when making a group read-only
-To: linux-btrfs@vger.kernel.org
-
-btrfs_retire_block_group_stripes() closes a group's stripe runs and waits
-until none is left. Metadata runs drain only when their tree blocks are
-written and are freed only by btrfs_retire_meta_stripes(), both in a
-transaction commit, so making a raid56 metadata group read-only, for
-relocation or scrub, waited up to commit_interval for the next periodic
-commit while relocation held reclaim_bgs_lock.
-
-Commit the current transaction first when the group has metadata runs;
-the callers hold no transaction handle. The wait itself stays unbounded:
-a run that never drains has an allocation that was never reported written
-or abandoned, which is an accounting bug. After 60 seconds, say which
-runs are stuck, once, and keep waiting. The dump now covers every run
-class, not only metadata.
-
-Fixes: 51fcf2348a33f ("btrfs: stripe_meta: allocate tree blocks by whole stripes")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 61 +++++++++++++++++++++++++++++++++---------
- 1 file changed, 49 insertions(+), 12 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index f34181d7ce17a..d5fa24cbf43d8 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -547,20 +547,17 @@ struct btrfs_open_stripe_run {
- u64 log_transid;
- };
-
--static void btrfs_dump_open_meta_runs(struct btrfs_block_group *bg)
-+static void btrfs_dump_open_stripe_runs(struct btrfs_block_group *bg)
- {
- struct btrfs_open_stripe_run *run;
- unsigned long flags;
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
-- list_for_each_entry(run, &bg->open_stripe_runs, list) {
-- if (!btrfs_stripe_run_class_is_meta(run->class))
-- continue;
-+ list_for_each_entry(run, &bg->open_stripe_runs, list)
- btrfs_warn(bg->fs_info,
--" run %llu..%llu frontier %llu open %d inflight %llu transid %llu",
-- run->start, run->end, run->offset, run->open,
-- run->inflight_bytes, run->transid);
-- }
-+" run %llu..%llu class %d frontier %llu open %d inflight %llu transid %llu",
-+ run->start, run->end, run->class, run->offset,
-+ run->open, run->inflight_bytes, run->transid);
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- }
-
-@@ -3244,6 +3241,24 @@ static void btrfs_release_stripe_reloc_runs(struct btrfs_fs_info *fs_info)
- spin_unlock(&fs_info->open_stripe_lock);
- }
-
-+/* Does @bg have metadata stripe runs? */
-+static bool bg_has_meta_runs(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ bool ret = false;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (btrfs_stripe_run_class_is_meta(run->class)) {
-+ ret = true;
-+ break;
-+ }
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ return ret;
-+}
-+
- /*
- * Close and drain all of a block group's stripe runs. The caller must
- * prevent new allocations first (e.g. the block group is read-only),
-@@ -3261,15 +3276,37 @@ static void btrfs_release_stripe_reloc_runs(struct btrfs_fs_info *fs_info)
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
- {
- struct btrfs_fs_info *fs_info = bg->fs_info;
-+ bool warned = false;
-
- /* Nothing may outlive this, relocation's retained runs included. */
- release_retained_stripe_runs(bg);
- close_block_group_stripe_runs(bg, U64_MAX);
- /* Parked partial-stripe rbios hold the very bios the wait drains. */
- btrfs_flush_parked_rbios(fs_info, bg->start, bg->length, false);
-- wait_var_event(&bg->open_stripe_runs,
-- bg_open_stripes_settled(bg, U64_MAX) ||
-- BTRFS_FS_ERROR(fs_info));
-+ /*
-+ * Metadata runs drain when their tree blocks are written and are
-+ * freed by btrfs_retire_meta_stripes(), both in a commit. Commit now
-+ * instead of waiting for the next one; no caller holds a transaction
-+ * handle.
-+ */
-+ if (bg_has_meta_runs(bg))
-+ btrfs_commit_current_transaction(fs_info->tree_root);
-+ /*
-+ * No timeout: a run that does not drain has an allocation that was
-+ * never reported written or abandoned, an accounting bug to fix, not
-+ * to wait out. Say which runs once, and keep waiting.
-+ */
-+ while (!wait_var_event_timeout(&bg->open_stripe_runs,
-+ bg_open_stripes_settled(bg, U64_MAX) ||
-+ BTRFS_FS_ERROR(fs_info), 60 * HZ)) {
-+ if (warned)
-+ continue;
-+ btrfs_warn(fs_info,
-+"block group %llu read-only transition waiting for stripe runs that do not drain",
-+ bg->start);
-+ btrfs_dump_open_stripe_runs(bg);
-+ warned = true;
-+ }
- if (BTRFS_FS_ERROR(fs_info) && !bg_open_stripes_settled(bg, U64_MAX))
- btrfs_warn(fs_info,
- "block group %llu read-only with stripe runs still in flight after a filesystem error; not waiting for them",
-@@ -3452,7 +3489,7 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
- btrfs_warn(fs_info,
- "metadata stripe runs in block group %llu did not drain; a tree block was freed without reporting to its run",
- bg->start);
-- btrfs_dump_open_meta_runs(bg);
-+ btrfs_dump_open_stripe_runs(bg);
- }
-
- /* Drained and no longer needed for padding or merging. */
---
-2.47.3
-
+++ /dev/null
-From 71c8da87174ad11a798adfaf05f2eb099169662d Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:01:51 -0400
-Subject: [RFC PATCH 094/116] btrfs: raid56: do not read tree blocks under the
- stripe lock in the metadata RMW audit
-To: linux-btrfs@vger.kernel.org
-
-When a metadata write goes out as a read-modify-write, audit_uncovered_rmw()
-looks at the tree blocks in the columns the write does not cover, and asks
-the committed extent tree whether each older one is still referenced.
-That lookup runs in rmw_rbio() while the rbio holds the full-stripe lock,
-and btrfs_search_slot() can read tree blocks from disk. If one of them
-lies in this same stripe and has to be reconstructed (a degraded array or
-a bad sector), the read becomes a rebuild rbio that queues behind the
-stripe lock the auditing rbio holds while it waits for that read. The
-search could also wait for commit_root_sem behind a commit with the stripe
-locked.
-
-Search without blocking: take commit_root_sem with a trylock and set
-path->nowait, so a tree block that is not in memory ends the lookup with
--EAGAIN instead of a read. Count those as meta_rmw_unknown instead of
-calling them write holes.
-
-Fixes: 23750c9620f4f ("btrfs: raid56: say whether a metadata read-modify-write is a write hole")
-Fixes: 1e604474ed570 ("btrfs: stripe_alloc: tell a dead tree block from a live one in the metadata RMW audit")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/fs.h | 2 ++
- fs/btrfs/raid56.c | 38 +++++++++++++++++++++++++++-----------
- fs/btrfs/sysfs.c | 2 ++
- 3 files changed, 31 insertions(+), 11 deletions(-)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 2734a8404a9b2..aa46009225fa1 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -922,6 +922,8 @@ struct btrfs_fs_info {
- atomic64_t meta_rmw_old;
- atomic64_t meta_rmw_ghost; /* older header, block dead in the
- committed extent tree */
-+ atomic64_t meta_rmw_unknown; /* older header, extent tree
-+ not in memory to ask */
- atomic64_t meta_rmw_free;
- atomic64_t congestion_short;
- /* Frontier stripes pinned in the rbio cache (cache_rbio()). */
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index caa30f222def7..802b0eb7ecc39 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -3686,29 +3686,37 @@ static bool rmw_peek_eb_generation(struct btrfs_raid_bio *rbio, u32 i,
- /*
- * Is @bytenr a tree block the committed extent tree still references? Read
- * the commit root without locking, as the caching thread does, so this is
-- * safe from the raid56 worker with no transaction to join; a lookup that
-- * cannot answer counts the block as live.
-+ * safe from the raid56 worker with no transaction to join.
-+ *
-+ * Returns 1 if it is (or the lookup failed), 0 if not, and -EAGAIN if the
-+ * answer needs a tree block that is not in memory. The caller holds the
-+ * full stripe lock, so it must not read from disk: a read of a block in
-+ * this stripe that needs reconstruction would wait for that lock.
- */
--static bool rmw_block_referenced(struct btrfs_fs_info *fs_info, u64 bytenr,
-- u64 header_gen, u64 *refs, u64 *extent_gen)
-+static int rmw_block_referenced(struct btrfs_fs_info *fs_info, u64 bytenr,
-+ u64 header_gen, u64 *refs, u64 *extent_gen)
- {
- struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
- struct btrfs_path *path;
- struct btrfs_key key;
-- bool live = true;
-+ int live = 1;
- int ret;
-
- *refs = 0;
- *extent_gen = 0;
- path = btrfs_alloc_path();
- if (!path)
-- return true;
-+ return 1;
- path->search_commit_root = 1;
- path->skip_locking = 1;
-+ path->nowait = 1;
- key.objectid = bytenr;
- key.type = BTRFS_METADATA_ITEM_KEY;
- key.offset = (u64)-1;
-- down_read(&fs_info->commit_root_sem);
-+ if (!down_read_trylock(&fs_info->commit_root_sem)) {
-+ btrfs_free_path(path);
-+ return -EAGAIN;
-+ }
- ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
- if (ret > 0)
- ret = btrfs_previous_extent_item(extent_root, path, bytenr);
-@@ -3733,10 +3741,12 @@ static bool rmw_block_referenced(struct btrfs_fs_info *fs_info, u64 bytenr,
- */
- live = (*refs != 0 && *extent_gen == header_gen);
- } else {
-- live = false;
-+ live = 0;
- }
- } else if (ret > 0) {
-- live = false;
-+ live = 0;
-+ } else if (ret == -EAGAIN) {
-+ live = -EAGAIN;
- }
- up_read(&fs_info->commit_root_sem);
- btrfs_free_path(path);
-@@ -3837,9 +3847,15 @@ static void audit_uncovered_rmw(struct btrfs_raid_bio *rbio)
- (u64)sectornr * fs_info->sectorsize;
- u64 refs;
- u64 egen;
-+ int ret;
-
-- if (!rmw_block_referenced(fs_info, logical, gen, &refs,
-- &egen)) {
-+ ret = rmw_block_referenced(fs_info, logical, gen, &refs,
-+ &egen);
-+ if (ret == -EAGAIN) {
-+ atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_unknown);
-+ continue;
-+ }
-+ if (!ret) {
- atomic64_inc(&fs_info->stripe_park_stats.meta_rmw_ghost);
- continue;
- }
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index baa3c4e780120..486af39185555 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1233,6 +1233,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "meta_rmw_cur %lld\n"
- "meta_rmw_old %lld\n"
- "meta_rmw_ghost %lld\n"
-+ "meta_rmw_unknown %lld\n"
- "meta_rmw_free %lld\n"
- "congestion_short %lld\n"
- "rbio_pinned %lld\n"
-@@ -1280,6 +1281,7 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_cur),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_old),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_ghost),
-+ atomic64_read(&fs_info->stripe_park_stats.meta_rmw_unknown),
- atomic64_read(&fs_info->stripe_park_stats.meta_rmw_free),
- atomic64_read(&fs_info->stripe_park_stats.congestion_short),
- atomic64_read(&fs_info->stripe_park_stats.rbio_pinned),
---
-2.47.3
-
+++ /dev/null
-From 8b790906dd5d1c4486ad7852adb9545571cb05e4 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:02:29 -0400
-Subject: [RFC PATCH 095/116] btrfs: raid56: stop the park timer before
- destroying the raid56 workqueue
-To: linux-btrfs@vger.kernel.org
-
-Partial-stripe rbios can be parked to wait for the rest of their stripe.
-A per-filesystem delayed work expires them, queueing each on
-fs_info->rmw_workers, and re-arms itself while anything is parked. It was
-cancelled only in btrfs_free_stripe_hash_table(), from btrfs_free_fs_info(),
-after btrfs_stop_all_workers() had destroyed rmw_workers. An rbio still
-parked at unmount, or on the open_ctree() failure path, would then be
-queued on a freed workqueue, and the rbio and its bios leaked.
-
-Before stopping the workers, send down whatever is still parked, let the
-workqueue finish it, and cancel the timer while the workqueue still
-exists. Normally nothing is parked by then.
-
-Fixes: 41622124ff9fb ("btrfs: raid56: batch stripe_alloc partial writes into full-stripe writes")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/disk-io.c | 2 ++
- fs/btrfs/raid56.c | 21 +++++++++++++++++++++
- fs/btrfs/raid56.h | 1 +
- 3 files changed, 24 insertions(+)
-
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index 826341066b242..f54d82a6c7c6d 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -3869,6 +3869,7 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
- invalidate_and_check_btree_folios(fs_info);
-
- fail_sb_buffer:
-+ btrfs_stop_parked_rbios(fs_info);
- btrfs_stop_all_workers(fs_info);
- btrfs_free_open_stripe_runs(fs_info);
- btrfs_free_block_groups(fs_info);
-@@ -4633,6 +4634,7 @@ void __cold close_ctree(struct btrfs_fs_info *fs_info)
- * submit after we stop all workers.
- */
- invalidate_and_check_btree_folios(fs_info);
-+ btrfs_stop_parked_rbios(fs_info);
- btrfs_stop_all_workers(fs_info);
-
- /*
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 802b0eb7ecc39..d90843bf98816 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -655,6 +655,27 @@ static void btrfs_clear_rbio_cache(struct btrfs_fs_info *info)
- spin_unlock(&table->cache_lock);
- }
-
-+/*
-+ * Send every parked rbio down and stop the park timer, before the raid56
-+ * workqueue is destroyed: the timer queues its expired rbios there. By
-+ * now nothing should be parked; a few passes cover an rbio that parks
-+ * again on its way down.
-+ */
-+void btrfs_stop_parked_rbios(struct btrfs_fs_info *fs_info)
-+{
-+ struct btrfs_stripe_hash_table *table = fs_info->stripe_hash_table;
-+
-+ if (!table || !fs_info->rmw_workers)
-+ return;
-+ for (int i = 0; i < 3 && !list_empty_careful(&table->parked); i++) {
-+ btrfs_flush_parked_rbios(fs_info, 0, U64_MAX, true);
-+ flush_workqueue(fs_info->rmw_workers);
-+ }
-+ cancel_delayed_work_sync(&table->parked_work);
-+ flush_workqueue(fs_info->rmw_workers);
-+ WARN_ON(!list_empty_careful(&table->parked));
-+}
-+
- /*
- * remove all cached entries and free the hash table
- * used by unmount
-diff --git a/fs/btrfs/raid56.h b/fs/btrfs/raid56.h
-index bd3b73f040f9a..22687b6194f93 100644
---- a/fs/btrfs/raid56.h
-+++ b/fs/btrfs/raid56.h
-@@ -312,6 +312,7 @@ int btrfs_alloc_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info);
- void btrfs_flush_parked_rbios(struct btrfs_fs_info *fs_info, u64 start,
- u64 num_bytes, bool force);
-+void btrfs_stop_parked_rbios(struct btrfs_fs_info *fs_info);
- void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
- int *pinned, int *live, int *live_by_class);
- void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info);
---
-2.47.3
-
+++ /dev/null
-From 7fbce6419dfccaf276d7e2fe080e7e29fa6f24d0 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:02:46 -0400
-Subject: [RFC PATCH 096/116] btrfs: stripe_alloc: order the filesystem error
- before waking stripe drain waiters
-To: linux-btrfs@vger.kernel.org
-
-The drain and settle waits for stripe runs also end when the filesystem
-goes into error, and __btrfs_handle_fs_error() wakes them after storing
-fs_error. The store is not under a lock, and wake_up_var() looks for
-waiters without taking one, so on a weakly ordered CPU the check can pass
-before the store is visible: a waiter that has just found no error and
-is about to sleep is not woken, and sleeps through the error it was meant
-to give up on.
-
-Add the full barrier wake_up_var() requires when the condition is not
-set under a lock.
-
-Fixes: 820a7bd489de7 ("btrfs: stripe_alloc: do not wait for stripe runs to drain on an errored filesystem")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 7 +++++++
- 1 file changed, 7 insertions(+)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index d5fa24cbf43d8..a924d6ff5cc47 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -3323,6 +3323,13 @@ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info)
- {
- struct btrfs_block_group *bg;
-
-+ /*
-+ * The caller set fs_error without a lock, and wake_up_var() checks
-+ * for waiters without one: order the store before that check, or a
-+ * waiter that has just tested BTRFS_FS_ERROR is missed. Pairs with
-+ * the barrier in prepare_to_wait_event().
-+ */
-+ smp_mb();
- spin_lock(&fs_info->open_stripe_lock);
- list_for_each_entry(bg, &fs_info->open_stripe_bgs, open_stripe_bg_list)
- wake_up_var(&bg->open_stripe_runs);
---
-2.47.3
-
+++ /dev/null
-From e7542b1e8cc8eb37a3ca07e3faf4cd3376cdd783 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:03:09 -0400
-Subject: [RFC PATCH 097/116] btrfs: raid56: set a padded rbio's data bitmap
- under bio_list_lock
-To: linux-btrfs@vger.kernel.org
-
-rmw_try_pad_full() decides to write the whole stripe and sets every bit
-of rbio->dbitmap. It runs before RBIO_RMW_LOCKED_BIT is set, so another
-writer can still merge into the rbio, and merge_rbio() ORs that rbio's
-bits into dbitmap under bio_list_lock. The pad's bitmap_set() took no
-lock. Both are read-modify-writes of the same word, so one could undo
-the other: a lost pad bit leaves those rows out of the write while
-cache_rbio_pages() records their zero-filled pages as up to date, and
-the cached stripe no longer matches the disk.
-
-Take bio_list_lock for the pad's bitmap update.
-
-Fixes: 2b016cafebc40 ("btrfs: raid56: pad sub-stripe writes to full stripes in open runs")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/raid56.c | 8 +++++++-
- 1 file changed, 7 insertions(+), 1 deletion(-)
-
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index d90843bf98816..9f3647a98f4e2 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -3630,8 +3630,14 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- }
-
- set_bit(RBIO_PADDED_BIT, &rbio->flags);
-- /* The whole stripe goes out: every vertical position is written. */
-+ /*
-+ * The whole stripe goes out: every vertical position is written.
-+ * Under bio_list_lock: until RBIO_RMW_LOCKED_BIT is set, merge_rbio()
-+ * can still OR another rbio's bits into this bitmap.
-+ */
-+ spin_lock(&rbio->bio_list_lock);
- bitmap_set(&rbio->dbitmap, 0, rbio->stripe_nsectors);
-+ spin_unlock(&rbio->bio_list_lock);
- atomic64_inc(&fs_info->stripe_park_stats.padded);
- if (nr_unwritten)
- atomic64_inc(&fs_info->stripe_park_stats.padded_unwritten);
---
-2.47.3
-
+++ /dev/null
-From b12511e299112bd2a3d0b1d758611ecfa3720ca4 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:05:05 -0400
-Subject: [RFC PATCH 098/116] btrfs: stripe_alloc: forget the failed-claim
- verdict when a cluster returns its space
-To: linux-btrfs@vger.kernel.org
-
-A failed claim scan sets max_claimable_run to 0, so later claims in the
-group fail at once until free space is added. Every path that adds free
-space resets it, except returning an allocation cluster's entries to the
-group. After a runtime enable, stripe_return_clusters() hands a legacy
-cluster's space back: a claim that had failed before that kept failing
-until some unrelated free reset the verdict, while the scan counted the
-returned space as claimable.
-
-Reset the verdict when a cluster's entries are returned.
-
-Fixes: 0b8c35f2c7aef ("btrfs: stripe_alloc: cache a failed stripe run scan per block group")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/free-space-cache.c | 2 ++
- 1 file changed, 2 insertions(+)
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 0d006a25295a9..aa6103d3a79b6 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1869,6 +1869,8 @@ static void __btrfs_return_cluster_to_free_space(
- cluster->block_group = NULL;
- cluster->window_start = 0;
- list_del_init(&cluster->block_group_list);
-+ /* As for any free space added back; see __btrfs_add_free_space(). */
-+ block_group->max_claimable_run = (u64)-1;
-
- node = rb_first(&cluster->root);
- while (node) {
---
-2.47.3
-
+++ /dev/null
-From 05511b2cb911cfb6aec742b3e271986f6c461985 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:05:32 -0400
-Subject: [RFC PATCH 099/116] btrfs: stripe_alloc: do not let a remount revert
- the stripe_alloc property
-To: linux-btrfs@vger.kernel.org
-
-The stripe_alloc property turns the policy on and off at runtime by
-setting STRIPE_ALLOC in fs_info->mount_opt. A remount copies the whole
-mount_opt word from its fs_context, which took its snapshot when the
-context was created; with fsconfig() that can be any time earlier. A
-property change in between was silently undone by the remount, without
-the enable or disable work that goes with it (arming or disarming the
-stripe accounting, draining legacy writes).
-
-Carry the current STRIPE_ALLOC value into the context before applying it.
-
-Fixes: 586a55e708aa4 ("btrfs: stripe_alloc: control the policy with a filesystem property")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/super.c | 10 ++++++++++
- 1 file changed, 10 insertions(+)
-
-diff --git a/fs/btrfs/super.c b/fs/btrfs/super.c
-index 903bce51fb1fd..cc88140377e74 100644
---- a/fs/btrfs/super.c
-+++ b/fs/btrfs/super.c
-@@ -1530,6 +1530,16 @@ static int btrfs_reconfigure(struct fs_context *fc)
- if (ret < 0)
- goto restore;
-
-+ /*
-+ * STRIPE_ALLOC is set by the stripe_alloc property, not by a mount
-+ * option, and can change after @ctx copied fs_info->mount_opt (an
-+ * fsconfig context lives as long as its caller wants). Keep the
-+ * current value.
-+ */
-+ if (btrfs_test_opt(fs_info, STRIPE_ALLOC))
-+ btrfs_set_opt(ctx->mount_opt, STRIPE_ALLOC);
-+ else
-+ btrfs_clear_opt(ctx->mount_opt, STRIPE_ALLOC);
- btrfs_ctx_to_info(fs_info, ctx);
- btrfs_remount_begin(fs_info, old_ctx.mount_opt, fc->sb_flags);
- btrfs_resize_thread_pool(fs_info, fs_info->thread_pool_size,
---
-2.47.3
-
+++ /dev/null
-From 04e92cdc7e5252ff18b6109cea7e2a49023a3c75 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:06:05 -0400
-Subject: [RFC PATCH 100/116] btrfs: stripe_alloc: do not block a NOWAIT write
- in the nocow stripe check
-To: linux-btrfs@vger.kernel.org
-
-can_nocow_file_extent() asks btrfs_stripe_nocow_writable() whether an
-extent's stripes belong to the inode alone, and when no open run answers
-that, it searches the extent tree with blocking reads and locks, even for
-an IOCB_NOWAIT write. The write then blocks where its caller asked it not
-to.
-
-Pass the caller's nowait down to the search, which already has a
-nonblocking mode. 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.
-
-Fixes: d84a06902203c ("btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow extents")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 8 +++++---
- fs/btrfs/block-group.h | 2 +-
- fs/btrfs/inode.c | 3 ++-
- 3 files changed, 8 insertions(+), 5 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index a924d6ff5cc47..e1a1a65e6d62d 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1869,7 +1869,7 @@ static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
- * data 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;
-@@ -1916,11 +1916,13 @@ bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
- * 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.
-+ * 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,
-- NULL, false))
-+ NULL, nowait))
- verdict = -1;
- if (verdict < 0) {
- ret = false;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index c4e043ecacca5..f5c5ed1b04345 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -588,7 +588,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);
- void btrfs_show_stripe_rmw(struct seq_file *seq, u32 mask);
- void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index d5732d8938f14..52ae8dd17457d 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -1888,7 +1888,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;
-
- /*
---
-2.47.3
-
+++ /dev/null
-From 713b3a800b3e6860fc833e693eab59e5ca13a38f Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:06:45 -0400
-Subject: [RFC PATCH 101/116] btrfs: stripe_alloc: keep the head of a claimed
- free space entry under the lock
-To: linux-btrfs@vger.kernel.org
-
-When btrfs_claim_free_stripe_run() claims a run from inside one extent
-entry, the entry keeps the tail and the head is added back with
-__btrfs_add_free_space() after ctl->tree_lock is dropped. That allocates
-a new entry, and the return value was ignored: if the allocation failed,
-the head was gone from the cache until the next mount.
-
-Allocate a spare entry before taking the lock, as the slow path already
-does, and link the head with it inside the lock. Without one, fall back
-to adding it afterwards as before.
-
-Fixes: efd06353d32e1 ("btrfs: add btrfs_claim_free_stripe_run() for stripe-exclusive allocation")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/free-space-cache.c | 29 ++++++++++++++++++++++++-----
- 1 file changed, 24 insertions(+), 5 deletions(-)
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index aa6103d3a79b6..7026742de2adf 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2888,6 +2888,13 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- /* Claims are always whole stripes; tolerate an unaligned want_bytes. */
- want_bytes = div64_u64(want_bytes, fsl) * fsl;
-
-+ /*
-+ * For the head of a claimed extent entry, or for a run strictly
-+ * inside one, so neither has to be added back after the lock is
-+ * dropped, where an allocation failure would lose it.
-+ */
-+ spare = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
-+
- spin_lock(&ctl->tree_lock);
-
- /*
-@@ -2918,11 +2925,14 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- * for the belt-and-braces case of a run strictly inside
- * one extent entry, whose removal splits it in two.
- */
-- spin_unlock(&ctl->tree_lock);
-- spare = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
-- if (!spare)
-- return -ENOMEM;
-- spin_lock(&ctl->tree_lock);
-+ if (!spare) {
-+ spin_unlock(&ctl->tree_lock);
-+ spare = kmem_cache_zalloc(btrfs_free_space_cachep,
-+ GFP_NOFS);
-+ if (!spare)
-+ return -ENOMEM;
-+ spin_lock(&ctl->tree_lock);
-+ }
- if (!find_free_stripe_run_slow(block_group, want_bytes,
- &run_start, &run_len)) {
- /*
-@@ -2967,6 +2977,15 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- } else {
- kmem_cache_free(btrfs_free_space_cachep, entry);
- }
-+ if (head_len && spare) {
-+ spare->offset = head_start;
-+ spare->bytes = head_len;
-+ spare->trim_state = head_trim_state;
-+ ret2 = link_free_space(ctl, spare);
-+ ASSERT(!ret2); /* -EEXIST; Logic error */
-+ spare_used = true;
-+ head_len = 0;
-+ }
- }
- stripe_claimable_mod(block_group, -(s64)run_len);
- *start = run_start;
---
-2.47.3
-
+++ /dev/null
-From 18da8ca4c637ee9ad9385a5b3fecb78120d6727a Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:06:59 -0400
-Subject: [RFC PATCH 102/116] btrfs: stripe_meta: check the block group lookup
- when freeing an unwritten tree block
-To: linux-btrfs@vger.kernel.org
-
-btrfs_free_tree_block() passes the result of btrfs_lookup_block_group()
-straight to btrfs_is_stripe_meta_bg() and btrfs_put_block_group(). A tree
-block always has a group, so this does not fail in practice, but the
-twin in clean_log_buffer() checks, and a NULL here would oops. Check it
-here too.
-
-Fixes: 51fcf2348a33f ("btrfs: stripe_meta: allocate tree blocks by whole stripes")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/extent-tree.c | 10 ++++++----
- 1 file changed, 6 insertions(+), 4 deletions(-)
-
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index ed8317209f847..4c56e3ecf5846 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -3666,10 +3666,12 @@ int btrfs_free_tree_block(struct btrfs_trans_handle *trans,
- */
- if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
- bg = btrfs_lookup_block_group(fs_info, buf->start);
-- if (btrfs_is_stripe_meta_bg(bg))
-- btrfs_open_stripe_write_abandoned(bg, buf->start,
-- buf->len);
-- btrfs_put_block_group(bg);
-+ if (bg) {
-+ if (btrfs_is_stripe_meta_bg(bg))
-+ btrfs_open_stripe_write_abandoned(bg, buf->start,
-+ buf->len);
-+ btrfs_put_block_group(bg);
-+ }
- }
-
- if (root_id != BTRFS_TREE_LOG_OBJECTID) {
---
-2.47.3
-
+++ /dev/null
-From 7664407e70b855c087b2534e927da17385523de2 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:07:22 -0400
-Subject: [RFC PATCH 103/116] btrfs: stripe_alloc: remove the unused
- stripe_rmw_opt field
-To: linux-btrfs@vger.kernel.org
-
-btrfs_stripe_allow_rmw() combines fs_info->stripe_rmw_opt with the
-stripe_alloc_allow_rmw property, but nothing has set stripe_rmw_opt since
-the mount option it came from was removed; it is always 0. Drop it.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/fs.h | 4 +---
- 1 file changed, 1 insertion(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index aa46009225fa1..096434fa4ff14 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -1029,7 +1029,6 @@ struct btrfs_fs_info {
- atomic64_t log_seal_bytes;
- } stripe_run_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
-- u32 stripe_rmw_opt;
- u32 stripe_rmw_prop;
- /*
- * Reclaim compacts a mostly live stripe_alloc / stripe_meta group once
-@@ -1475,8 +1474,7 @@ static inline u32 btrfs_stripe_allow_rmw(const struct btrfs_fs_info *fs_info)
- {
- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
- return 0;
-- return READ_ONCE(fs_info->stripe_rmw_opt) |
-- READ_ONCE(fs_info->stripe_rmw_prop);
-+ return READ_ONCE(fs_info->stripe_rmw_prop);
- }
-
- static inline void btrfs_wake_unfinished_drop(struct btrfs_fs_info *fs_info)
---
-2.47.3
-
+++ /dev/null
-From 1f653944834fd224ccbb4c309f1290acd4b4bc49 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:16:09 -0400
-Subject: [RFC PATCH 104/116] btrfs: stripe_alloc: correct and trim the block
- group comments
-To: linux-btrfs@vger.kernel.org
-
-Comment-only cleanup of block-group.[ch] after review:
-
-- move comments that had drifted onto the wrong function back to their
- own (btrfs_enable_stripe_alloc(), btrfs_stripe_open_run_class(),
- btrfs_stripe_run_incomplete(), btrfs_open_stripe_write_done(),
- btrfs_retire_open_stripes());
-- correct comments the code had outgrown: shared LOG runs, keying by
- subvolume and owner, the run close rules, the stripe_alloc_allow_rmw
- property name, stripe_unusable and stripe_claimable accounting, and
- references to functions that no longer exist;
-- say that stripe_run_lock is taken with interrupts disabled although all
- IO completion now runs in task context, and document why teardown may
- free runs that ordered extents point to;
-- drop history (one-off reports, quoted warnings, lockdep output) and
- shorten comments to what a maintainer needs.
-
-No code changes.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 782 ++++++++++++++++-------------------------
- fs/btrfs/block-group.h | 75 ++--
- 2 files changed, 336 insertions(+), 521 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index e1a1a65e6d62d..96f5daaafd4ec 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -449,44 +449,41 @@ void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
- * The raid56 stripe allocation policy only allocates from "open stripe
- * runs": contiguous, stripe-aligned regions claimed whole from the free
- * space cache (btrfs_claim_free_stripe_run()) and filled strictly
-- * sequentially. A run stops accepting allocations when it is exhausted,
-- * when an allocation does not fit in its remainder, or when it is retired
-- * at transaction commit; a closed run is never reopened, and its
-- * unallocated tail returns to the free space cache where, being part of a
-- * partially filled stripe, it cannot be claimed again until the whole
-- * stripe frees. This guarantees a full stripe only receives writes
-- * between two commits of the same transaction window, which is what
-- * closes the raid56 write hole for these block groups.
-+ * sequentially. A run is closed when it is exhausted, when it loses a
-+ * band collision (stripe_run_place()), when a private run is too small and
-+ * is replaced, when a metadata run belongs to an earlier transaction, or
-+ * when it is retired at transaction commit. A closed run is never
-+ * reopened, and its unallocated tail returns to the free space cache
-+ * where, being part of a partially filled stripe, it cannot be claimed
-+ * until the whole stripe frees. So every stripe is written within one
-+ * run's lifetime, which closes the raid56 write hole for these block
-+ * groups.
- *
-- * Each run counts the bytes reserved from it whose data IO has not yet
-- * completed (inflight_bytes). At commit time, while the transaction
-- * still accepts joins (before TRANS_STATE_COMMIT_DOING),
-- * btrfs_retire_open_stripes() closes every run opened before the commit
-- * and waits for their inflight bytes to drain. The placement matters
-- * twice over. It must be a pure data-IO wait, never an ordered extent
-- * completion wait (whose processing needs a transaction join). And it
-- * must run where joins still succeed: a task holding unreported run
-- * bytes -- a reserved extent whose bio has not completed -- may block on
-- * a transaction join, e.g. for a chunk allocation while walking a
-- * delalloc range, and the drain waits for those very bytes.
-+ * Each run counts the bytes reserved from it whose IO has not completed
-+ * (inflight_bytes). At commit, while the transaction still accepts joins
-+ * (before TRANS_STATE_COMMIT_DOING), btrfs_retire_open_stripes() closes
-+ * the data runs opened before the commit and waits for them to drain. The
-+ * wait must be a pure data-IO wait, never an ordered extent completion
-+ * wait, and must happen where joins still succeed: a task holding
-+ * unreported run bytes may block on a join (e.g. a chunk allocation during
-+ * delalloc). Metadata runs are retired after tree writeback
-+ * (btrfs_retire_meta_stripes()); persistent NOCOW runs survive commits.
- *
-- * Allocations racing with the commit open new runs stamped with a newer
-- * open_seq and are not retired or waited for: they belong to the next
-- * window. Because the commit still accepts joins after the drain, an
-- * ordered extent from such a run could complete fast and try to add its
-- * file extent to the committing transaction; the finish path compares
-- * the extent's run sequence with the transaction's retired sequence and
-- * defers to the next transaction instead. The membership add, the
-- * sequence read and the run installation happen atomically under
-- * fs_info->open_stripe_lock against the walk's bump-and-snapshot, so
-- * every run is either seen by the walk that retires its window or
-- * stamped with a sequence that forces the deferral.
-+ * Runs opened while the commit is in progress carry a newer open_seq and
-+ * belong to the next window. An ordered extent from such a run that
-+ * completes before the commit ends sees that its run's open_seq is not
-+ * retired by this transaction and defers its file extent to the next one.
-+ * The membership add, the sequence read and the run installation happen
-+ * atomically under fs_info->open_stripe_lock, so every run is either seen
-+ * by the walk that retires its window or stamped with a sequence that
-+ * forces the deferral.
- *
- * Lock order: fs_info->open_stripe_lock outside bg->stripe_run_lock. The
-- * stripe_run_lock is irq-safe because completed data IO is reported from
-- * bio end_io context. Membership in fs_info->open_stripe_bgs holds a
-- * block group reference and is removed only by the retire walk once the
-- * group has no runs left.
-+ * stripe_run_lock is taken with interrupts disabled, which no current
-+ * caller needs: completed IO is reported from bio completion work, which
-+ * runs in task context. Membership in fs_info->open_stripe_bgs holds a
-+ * block group reference, dropped by the retire walk once the group has no
-+ * runs left, or by btrfs_free_open_stripe_runs() at teardown.
- */
-
- static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
-@@ -522,17 +519,10 @@ struct btrfs_open_stripe_run {
- */
- bool retained;
- /*
-- * One bit per sector of the run: set while that sector holds an
-- * allocation someone still intends to write, clear otherwise.
-- *
-- * This is what lets a partial write be padded out to a full stripe.
-- * The frontier alone cannot answer the question: space above it is
-- * obviously free, but an allocation below it may have been abandoned
-- * before it was ever written (a tree block COWed twice in one
-- * transaction, a reservation released, an allocation the finder
-- * discarded), leaving a hole that is just as safe to zero-fill.
-- * Padding needs to know which uncovered sectors are dead, and only
-- * the run knows -- it handed the space out and took it back.
-+ * One bit per sector of the run, set while the sector holds an
-+ * allocation someone still intends to write. Padding uses it to find
-+ * dead sectors below the frontier (allocations abandoned before they
-+ * were written), which are as safe to zero-fill as space above it.
- */
- unsigned long *live;
- /*
-@@ -606,13 +596,9 @@ static bool open_stripe_run_drained(const struct btrfs_open_stripe_run *run)
- /*
- * 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 (raid5 over 4 devices, or
-- * raid6 over 5) gives 192K, and 5, 6 and 7 data stripes are no better. The
-- * kernel's round_down() and IS_ALIGNED() are mask operations defined only for
-- * power-of-two moduli: applied to 192K they silently return a value that is
-- * not a stripe boundary at all (round_down(1179648, 196608) yields 1048576,
-- * a third of a stripe low). Use division.
-+ * 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() and IS_ALIGNED() must not be used. Divide instead.
- */
- static u64 stripe_round_down(u64 val, u64 fsl)
- {
-@@ -686,12 +672,10 @@ static void run_live_set(struct btrfs_open_stripe_run *run, u64 start, u64 len,
- first = (start - run->start) >> bits;
- nr = len >> bits;
- /*
-- * Past the end of the map. Growth is capped at what the map covers,
-- * so this should be unreachable; if it ever happens the map no longer
-- * describes the run, and padding must not trust it -- zero-filling a
-- * sector that is really live would destroy data. Retiring the map
-- * makes btrfs_stripe_run_pad_mask() decline the run, so the write
-- * degrades to a read-modify-write rather than to corruption.
-+ * Growth is capped at the map size, so this should be unreachable. If
-+ * it happens, retire the map: btrfs_stripe_run_pad_mask() then declines
-+ * the run, and the write falls back to read-modify-write instead of
-+ * zero-filling a sector that may be live.
- */
- if (unlikely(first + nr > run->live_nbits)) {
- WARN_ON_ONCE(1);
-@@ -705,20 +689,14 @@ static void run_live_set(struct btrfs_open_stripe_run *run, u64 start, u64 len,
- }
-
- /*
-- * A run is dead when every byte it ever handed out has been freed again.
-- *
-- * The live map already answers this: a bit is set while its sector holds an
-- * allocation someone still intends to write, and btrfs_stripe_run_note_free()
-- * clears it when the extent is freed. A dead run owns no data at all, so the
-- * write-hole invariants it exists to uphold have nothing left to protect --
-- * it is pure hoarding, and the whole stripes freed inside its range stay
-- * unclaimable (btrfs_stripe_run_range_usable()) until it is gone.
-+ * 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: bytes allocated but not yet reported have no
-- * live bit of their own after an abandon, and an in-flight write must keep
-- * its stripes. A retired live map (live_nbits == 0) means liveness is
-- * unknown, which is never a licence to close. Caller holds
-- * bg->stripe_run_lock.
-+ * 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)
- {
-@@ -732,26 +710,20 @@ static bool open_stripe_run_dead(const struct btrfs_open_stripe_run *run)
- }
-
- /*
-- * A drained run may still be needed.
-+ * Whether a run is freed as soon as it drains. Two kinds must outlive the
-+ * drain, because later writes to their stripes still need a covering run to
-+ * park against or pad from:
- *
-- * Metadata writeback issues one rbio per contiguous run of tree blocks, so
-- * a stripe's columns can be submitted separately. If the run were freed as
-- * soon as its counter hit zero -- which happens when the first column's
-- * completions arrive -- the second column would find no run covering its
-- * stripe, and with no run there is nothing to pad against and nothing to
-- * merge with. Metadata runs are therefore freed by
-- * btrfs_retire_meta_stripes(), which runs once every tree block is on disk.
-+ * - Metadata runs: writeback may submit a stripe's tree blocks as separate
-+ * rbios, so the run drains after the first one. They are freed by
-+ * btrfs_retire_meta_stripes() once every tree block is on disk.
- *
-- * Relocation's runs have the same problem across a whole relocation stage.
-- * Relocation preallocates its destination extents (the run drains at once:
-- * a preallocation has no IO to report) and writes them only after the
-- * commit that ends relocate_block_group(), which would free the run. Every
-- * relocated extent that shares a stripe with another then found no covering
-- * run, could neither park nor pad, and went down as a read-modify-write.
-- * They are retained until relocation releases them instead. Their stripes
-- * hold nothing but relocation's own orphaned copies until the pointer update
-- * that follows the writeback, and no allocation reaches them meanwhile: the
-- * run is closed, and its range stays unclaimable while it exists.
-+ * - Relocation runs: relocation preallocates its destination extents (no
-+ * IO, so the run drains at once) and writes them only after the commit
-+ * that ends relocate_block_group(). They are retained until relocation
-+ * releases them (btrfs_release_stripe_reloc_runs()). Meanwhile their
-+ * stripes hold only relocation's own copies, and the closed run keeps its
-+ * range unclaimable.
- */
- static bool run_freed_on_drain(const struct btrfs_open_stripe_run *run)
- {
-@@ -780,14 +752,10 @@ static void free_open_stripe_run(struct btrfs_block_group *bg,
- }
-
- /*
-- * Report a run's transition to drained. Freeing wakes the retire waiters as
-- * a side effect of free_open_stripe_run(); a metadata run instead stays
-- * behind for padding and merging until btrfs_retire_meta_stripes() collects
-- * it, but that same retirer may already be asleep waiting for exactly this
-- * drain -- completion reports normally all precede its wait, but a report
-- * can arrive outside the writeback window (a tree block freed before it was
-- * written, e.g. an unwritten log tree block). Wake it, or it sleeps out
-- * its whole timeout.
-+ * A run has drained. Free it if nothing needs it any more; otherwise
-+ * (metadata or retained relocation runs) wake the waiters directly, since a
-+ * report can arrive after btrfs_retire_meta_stripes() started waiting, e.g.
-+ * when an unwritten tree block is freed.
- */
- static void open_stripe_run_drain_reported(struct btrfs_block_group *bg,
- struct btrfs_open_stripe_run *run)
-@@ -871,7 +839,7 @@ static u64 stripe_run_place(struct btrfs_block_group *bg,
- int band = stripe_run_band(bg, run->end - run->offset);
- struct btrfs_open_stripe_run *occ = bg->open_stripe[class][band];
-
-- /* Per-inode LOG runs are private and never occupy a band slot. */
-+ /* Private runs (LOG, NOCOW, META_LOG) never occupy a band slot. */
- ASSERT(class != BTRFS_STRIPE_RUN_LOG);
-
- if (occ) {
-@@ -892,13 +860,13 @@ static u64 stripe_run_place(struct btrfs_block_group *bg,
- }
-
- /*
-- * Allocate num_bytes from the block group's open stripe run, opening a new
-- * run via btrfs_claim_free_stripe_run() when there is none or the current
-- * one does not fit. If the freshly claimed stripes directly follow an open
-- * run of the same class, that run grows to absorb them instead (see the
-- * comment at the claim site). The allocation counts toward the run's
-- * inflight bytes until btrfs_open_stripe_write_done() reports its data IO
-- * complete.
-+ * Allocate num_bytes from the block group's shared open runs of @class,
-+ * best fit across the remaining-space bands, claiming a new run via
-+ * btrfs_claim_free_stripe_run() when none fits. If the freshly claimed
-+ * stripes directly follow an open run of the same class, that run grows to
-+ * absorb them instead (see the comment at the claim site). The allocation
-+ * counts toward the run's inflight bytes until its IO is reported done or
-+ * abandoned.
- *
- * Returns 0 and sets *ret_offset, -ENOSPC if no fully-free stripe run in
- * this block group can satisfy the allocation, or -ENOMEM.
-@@ -972,7 +940,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- run->inflight_bytes += num_bytes;
- bg->stripe_open_remainder -= num_bytes;
- if (run->offset == run->end)
-- run->open = false; /* full; drains then is freed */
-+ run->open = false; /* full: closed, no tail */
- else
- tail_len = stripe_run_place(bg, run, &tail_start);
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-@@ -989,10 +957,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- if (nr_evict)
- stripe_open_remainder_sync(bg);
-
-- /*
-- * Zeroed: the error paths below reach out: before the liveness map is
-- * allocated and must find a NULL there rather than uninitialised heap.
-- */
-+ /* Zeroed, so the error paths can free ->live and ->written. */
- new_run = kzalloc(sizeof(*new_run), GFP_NOFS);
- if (!new_run)
- return -ENOMEM;
-@@ -1049,20 +1014,13 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- goto out;
- }
- /*
-- * Growable frontier: if the claimed region [start, start+len) directly
-- * follows the end of an open run of the same class, grow that run to
-- * absorb it and place this allocation at the run's old tail, spilling
-- * contiguously into the claimed stripes. Without this, an allocation
-- * larger than every open run's remainder would open a separate run and
-- * the old tail -- perfectly usable space the misfit merely jumped over
-- * -- would sit unfillable until a small allocation happened to find it,
-- * or be stranded outright when a band collision or commit closed the
-- * run. Growing preserves stripe exclusivity: the grown stripes were
-- * claimed fully free, and the run still closes at the next commit and
-- * is never reopened, so every stripe of the run is filled within one
-- * open-run lifetime. The run keeps its open_seq: it can only still be
-- * in a band slot if the retire walk for its window has not run, which
-- * this lock nesting excludes from racing us.
-+ * Growable frontier: if the claimed region directly follows an open run
-+ * of the same class, grow that run over it and place this allocation at
-+ * the run's old tail, so the tail is used rather than stranded when the
-+ * run closes. Stripe exclusivity holds: the grown stripes were claimed
-+ * fully free, and the run is still retired at commit. The run keeps
-+ * its open_seq: it can only still be in a band slot if the retire walk
-+ * for its window has not run, which this lock nesting excludes.
- */
- for (band = 0; band < BTRFS_STRIPE_RUN_NR_BANDS; band++) {
- struct btrfs_open_stripe_run *r = bg->open_stripe[class][band];
-@@ -1096,7 +1054,7 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- bg->stripe_open_remainder += len;
- bg->stripe_open_remainder -= num_bytes;
- if (r->offset == r->end)
-- r->open = false; /* full; drains then is freed */
-+ r->open = false; /* full: closed, no tail */
- else
- tail_len = stripe_run_place(bg, r, &tail_start);
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-@@ -1153,19 +1111,13 @@ int btrfs_alloc_from_open_stripe(struct btrfs_block_group *bg, u64 num_bytes,
- /*
- * Allocate a log tree block from the private run of this log commit.
- *
-- * The run is keyed by @owner, the root id of the subvolume whose log this is,
-- * and @log_transid, that subvolume's log transaction. Every log commit
-- * therefore gets its own whole stripes, which is the whole point: a log
-- * commit's blocks are durable the instant fsync returns, so no later writer
-- * may share a stripe with them, and keying the run this way makes that true
-- * by construction rather than by a check. A stale-epoch run found here is
-- * closed, exactly as a stale-transid metadata run is in
-- * btrfs_alloc_from_open_stripe_epoch(); its tail goes back to the free space
-- * cache and the stripes it filled are credited back once the log tree is
-- * freed at transaction commit.
-- *
-- * Private, like the per-inode runs: never placed in the shared band slots,
-- * found by walking for the key, so nothing else can join.
-+ * The run is keyed by @owner (the subvolume's root id) and @log_transid, so
-+ * each log commit gets whole stripes of its own: its blocks are durable once
-+ * fsync returns, and no later writer may share a stripe with them (see
-+ * BTRFS_STRIPE_RUN_META_LOG). An open run of the same owner from an earlier
-+ * log commit is closed, as a stale-transid metadata run is in
-+ * btrfs_alloc_from_open_stripe(). Like the other private runs, it is never
-+ * placed in a band slot.
- *
- * Returns 0 and sets *ret_offset, -ENOSPC if no fully-free stripe run in this
- * block group can satisfy the allocation, or -ENOMEM.
-@@ -1215,7 +1167,7 @@ int btrfs_alloc_from_log_stripe_run(struct btrfs_block_group *bg, u64 num_bytes,
- run->inflight_bytes += num_bytes;
- bg->stripe_open_remainder -= num_bytes;
- if (run->offset == run->end)
-- run->open = false; /* full; drains, is freed */
-+ run->open = false; /* full: closed, no tail */
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- stripe_open_remainder_sync(bg);
- return 0;
-@@ -1322,20 +1274,19 @@ static u64 stripe_run_owner(struct btrfs_inode *inode,
- }
-
- /*
-- * Allocate num_bytes for a log-active inode from its private run in this
-- * block group -- for LOG-class data with stripe_log_data_shared, the run its
-- * subvolume shares for the current log transaction (stripe_run_owner()) --
-- * claiming a fresh run when there is none here or the current one does not
-- * fit. Private runs are never placed in the shared band slots and are found
-- * by owner lookup, so only allocations with the same owner join a run, and a
-- * log commit settles only the stripes holding its own extents.
-+ * Allocate num_bytes for @inode from its private run of @class (LOG or
-+ * NOCOW) in this block group, claiming a fresh run when there is none or it
-+ * does not fit. With stripe_log_data_shared, small LOG allocations use the
-+ * run the subvolume shares for the current log transaction
-+ * (stripe_run_owner()). Private runs are never placed in a band slot and
-+ * are found by subvolume and owner, so a log commit settles only stripes
-+ * holding its own extents. A NOCOW allocation may instead re-adopt the
-+ * free tail of the inode's last partial stripe (@readopt_hint).
- *
-- * A replaced run (too small for this allocation) is closed immediately: the
-- * inode moves on to the fresh run, so keeping the remainder open would only
-- * strand it until the commit-time retirement. Two racing allocations for
-- * the same inode can each claim a fresh run; the owner walk then serves one
-- * of them and the other drains and retires at the next commit -- an
-- * occasional trapped tail, not a correctness problem.
-+ * A run too small for this allocation is closed at once rather than left
-+ * to strand its tail until commit. Two racing allocations for one owner
-+ * may each claim a run; the spare drains at the next commit, costing a
-+ * trapped tail, not correctness.
- *
- * Returns 0 and sets *ret_offset, -ENOSPC if no fully-free stripe run in
- * this block group can satisfy the allocation, or -ENOMEM.
-@@ -1374,7 +1325,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- run->inflight_bytes += num_bytes;
- bg->stripe_open_remainder -= num_bytes;
- if (run->offset == run->end)
-- run->open = false; /* full; drains, is freed */
-+ run->open = false; /* full: closed, no tail */
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- stripe_open_remainder_sync(bg);
- return 0;
-@@ -1388,10 +1339,7 @@ int btrfs_alloc_from_inode_stripe_run(struct btrfs_block_group *bg,
- stripe_open_remainder_sync(bg);
- }
-
-- /*
-- * Zeroed: the error paths below reach out: before the liveness map is
-- * allocated and must find a NULL there rather than uninitialised heap.
-- */
-+ /* Zeroed, so the error paths can free ->live and ->written. */
- new_run = kzalloc(sizeof(*new_run), GFP_NOFS);
- if (!new_run)
- return -ENOMEM;
-@@ -1562,14 +1510,14 @@ void btrfs_stripe_run_note_free(struct btrfs_block_group *bg, u64 bytenr,
- }
-
- /*
-- * A live stripe run's address range must not be re-claimed while the run
-- * object still exists: an ENOSPC discard storm can return every byte of a
-- * stripe to the free cache while its run is still draining other stripes'
-- * IO, and a second run claimed over the same range would make the
-+ * 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
-+ * (abandoned allocations): a second run over the same range would make the
- * range-to-run lookups (ordered extent attach, IO reporting) ambiguous and
- * corrupt the inflight accounting. Trim the candidate to end before the
-- * first overlapping run; reject it outright if its head overlaps. Caller
-- * holds ctl->tree_lock; stripe_run_lock nests inside it.
-+ * first overlapping run, and reject it if its head overlaps or less than a
-+ * full stripe remains. Caller holds ctl->tree_lock; stripe_run_lock nests
-+ * inside it.
- */
- bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- u64 run_start, u64 *run_len)
-@@ -1598,17 +1546,13 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- }
-
- /*
-- * For the stripe_unusable scan: wholly free stripes that overlap a live
-- * stripe run's range cannot be claimed while the run object exists (see
-- * btrfs_stripe_run_range_usable()) -- the run was claimed over them, the
-- * extents allocated there were freed again, and the run has not been freed
-- * yet; a nodatacow inode's private run lives until the inode is evicted.
-- * Counted as claimable, they let the admission gate admit writes the claim
-- * path then refuses, and writeback drops the data. Take them out of @freep
-- * (so the caller counts them neither as claimable nor as partial) and return
-- * their total; free_open_stripe_run() marks the group for rescan so they
-- * are credited back when the run dies. Caller holds ctl->tree_lock;
-- * stripe_run_lock nests inside it.
-+ * For the stripe_unusable scan: whole free stripes inside a live run's
-+ * range cannot be claimed while the run exists
-+ * (btrfs_stripe_run_range_usable()), so they must not count as claimable
-+ * or the admission gate would admit writes that cannot be placed. Clear
-+ * them from @freep and return their total; free_open_stripe_run() marks the
-+ * group for rescan so they are credited back when the run goes. Caller
-+ * holds ctl->tree_lock; stripe_run_lock nests inside it.
- */
- u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
- u64 nstripes)
-@@ -1696,27 +1640,16 @@ void btrfs_show_stripe_rmw(struct seq_file *seq, 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.
- *
-- * @nowait must be set by callers that hold space_info->groups_sem, i.e.
-- * anything reached from find_free_extent(). Blocking on an extent tree
-- * lock there is a deadlock: 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 the
-- * cycle. Both sides only read groups_sem, but it is an rw_semaphore and
-- * block group add/remove take it for write, so a queued writer between the
-- * two readers is enough. Reported by lockdep on a plain fallocate:
-- *
-- * rlock(&space_info->groups_sem) lock(btrfs-extent-01)
-- * lock(&space_info->groups_sem)
-- * rlock(btrfs-extent-01)
-- *
-- * With @nowait the search try-locks and returns -EAGAIN instead, which
-- * lands in the error paths below as "not provably ours" -- the safe
-- * answer, since every caller treats false as a reason to decline an
-- * optimisation rather than as a fact about the extents.
-+ * 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,
-@@ -1734,12 +1667,8 @@ static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
- if (!path)
- return false;
- /*
-- * Read-only search, so nowait is legal here (btrfs_search_slot()
-- * asserts nowait is never combined with cow). It is honoured by the
-- * whole walk below: search_slot try-locks the root node,
-- * btrfs_previous_extent_item() reaches search_slot via
-- * btrfs_prev_leaf(), and btrfs_next_leaf() passes time_seq 0 so its
-- * ASSERT(!path->nowait) does not apply.
-+ * 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;
-
-@@ -1817,14 +1746,9 @@ static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
- goto out;
- }
- /*
-- * The extent's single backref is keyed, not inline, when the
-- * leaf had no room to grow the item (insert_inline_extent_backref()
-- * returns -EAGAIN and insert_extent_backref() adds a separate
-- * EXTENT_DATA_REF item). Such an extent item ends right after
-- * the header, and reading an inline ref there reads the next
-- * item's bytes: btrfs_get_extent_inline_ref_type() warns about
-- * "invalid extent inline ref type 1". Treat it as not owned;
-- * the answer is the conservative one either way.
-+ * With a keyed (non-inline) backref the item ends after the
-+ * header, and reading an inline ref would read the next item.
-+ * Treat it as not owned, the conservative answer.
- */
- if (btrfs_item_size(leaf, slot) < sizeof(*ei) +
- btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY)) {
-@@ -1855,18 +1779,15 @@ static bool stripe_extents_owned_by(struct btrfs_fs_info *fs_info,
- }
-
- /*
-- * May [start, start + num_bytes) be written in place under
-- * stripe-exclusive allocation? Only when the stripe_alloc_nocow policy
-- * is enabled and every full stripe the range touches is isolated to
-- * @inode: an in-place write RMWs the stripe's parity, so a degraded
-- * crash can tear every extent sharing the stripe -- isolation confines
-- * that blast radius to the writing file, which opted out of COW
-- * protection. Fast path: the stripe belongs to one of the inode's own
-- * NOCOW-class runs (such stripes have only ever held its extents).
-- * Slow path: the committed extent tree proves sole ownership. Extents
-- * that fail simply stay force-COWed -- and their rewrite is steered
-- * into the inode's private NOCOW run, so the next overwrite of the same
-- * data passes.
-+ * May [start, start + num_bytes) be written in place under stripe-exclusive
-+ * allocation? Only when stripe_alloc_allow_rmw includes @which and every
-+ * full stripe the range touches is isolated to @inode: an in-place write
-+ * RMWs parity, so a crash can tear every extent sharing the stripe, and
-+ * isolation confines that to the file that opted out of COW. Fast path:
-+ * the stripe is in one of the inode's own NOCOW runs. Slow path: the
-+ * committed extent tree proves sole ownership. Extents that fail stay
-+ * COWed, and their rewrite lands in the inode's NOCOW run, so the next
-+ * overwrite passes.
- */
- bool btrfs_stripe_nocow_writable(struct btrfs_inode *inode, u64 start,
- u64 num_bytes, u32 which, bool nowait)
-@@ -2000,40 +1921,24 @@ u64 btrfs_stripe_run_alloc_ceiling(struct btrfs_fs_info *fs_info,
- /*
- * Which sectors of this stripe may be padded?
- *
-- * Fills @dead with one bit per sector of the stripe, set where the sector
-- * holds nothing anyone has written: space the run has not handed out yet,
-- * space it handed out but got back before the write was issued, and space
-- * it handed out whose write has not completed yet (the run's written map).
-- * A caller may zero-fill exactly those and write the whole stripe.
-- *
-- * Zeroing an allocated sector whose write is still to come is safe because
-- * that write is ordered after the caller's: the caller holds the stripe
-- * lock, and every raid56 write to the stripe takes it; the sector's
-- * completed writes are all in the written map by then (rbio_orig_end_io()
-- * marks them before it unlocks the stripe), and nothing reads the sector
-- * before its own write lands -- its extent is not committed until then.
-- * It is what lets a stripe's FIRST partial write pad instead of reading
-- * the rest of the stripe: the remaining sectors are allocated to writes
-- * still in flight, and nobody has written them. Nodatacow runs are
-- * excluded: they keep no written map (their extents are rewritten in
-- * place for as long as the inode lives), so their live sectors hold data.
-- * @unwritten, when non-NULL, gets the subset of @dead that is allocated
-- * but unwritten.
-+ * Fills @dead with one bit per sector, set where the sector holds nothing
-+ * anyone has written: never handed out, handed out and abandoned, or
-+ * handed out with the write not yet completed (per the run's written map).
-+ * The caller may zero-fill exactly those and write the whole stripe.
-+ * @unwritten, when non-NULL, gets the subset that is allocated but
-+ * unwritten.
- *
-- * Returns false if no run covers the stripe, in which case nothing may be
-- * padded: without a run there is no claim of exclusivity, and an uncovered
-- * sector may hold committed data.
-+ * Zeroing an allocated sector whose write is still to come is safe: the
-+ * caller holds the stripe lock, which every raid56 write to the stripe
-+ * takes, so that write lands after the caller's; completed writes are in
-+ * the written map before the stripe is unlocked (rbio_orig_end_io()); and
-+ * nothing reads the sector before its own write lands, since its extent is
-+ * not committed until then. A NOCOW run's written map is not consulted:
-+ * its live sectors are rewritten in place, so they may already hold data.
- *
-- * This replaces asking where the run's frontier is. The frontier answers
-- * "what has never been allocated", which misses allocations that were
-- * abandoned below it -- a tree block COWed twice in one transaction, a
-- * reservation released, an allocation the finder discarded. Those leave
-- * holes that are equally safe to pad, and skipping them is the difference
-- * between padding most partial stripes and padding all of them.
-- *
-- * @info, when non-NULL, reports the covering run's state at the moment of
-- * the decision, for the pad-decline trace: a later extent-tree dump cannot
-- * reconstruct where the frontier was when the write arrived.
-+ * Returns false if no run covers the stripe; nothing may be padded then,
-+ * since an uncovered sector may hold committed data. @info, when non-NULL,
-+ * records the covering run's state for the pad-decline trace.
- */
- bool btrfs_stripe_run_pad_mask(struct btrfs_fs_info *fs_info, u64 stripe_start,
- u64 stripe_len, unsigned long *dead,
-@@ -2290,11 +2195,9 @@ bool btrfs_block_group_has_stripe_runs(struct btrfs_block_group *bg)
- }
-
- /*
-- * Close every private LOG and NOCOW run owned by @inode: 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.
-+ * Close @inode's open LOG and NOCOW runs at eviction, so a persistent NOCOW
-+ * run's claimed tail does not stay unusable for the rest of the mount. The
-+ * tails return to the free space cache.
- */
- void btrfs_close_inode_stripe_runs(struct btrfs_inode *inode)
- {
-@@ -2415,32 +2318,23 @@ static bool stripe_log_extent_written(struct btrfs_block_group *bg,
-
- /*
- * A log commit is about to make the extent at [bytenr, bytenr + num_bytes)
-- * durable. Once the log super lands, no later write may extend or RMW the
-- * extent's stripes -- the log-window analogue of invariant I2, which the
-- * commit-time retirement provides for full commits. Close the open run
-- * covering the extent so nothing further allocates into its stripes, kick
-- * any parked partial writes for it, and wait for all data IO into it to
-- * finish. Extents in full or already-settled stripes cost one list walk.
-- *
-- * The drain is bounded: run inflight is counted from allocation, which
-- * happens during writeback with submission following in the same pass, so
-- * the wait is bio flight time plus the parked-write deadline that the flush
-- * below short-circuits. It is a pure data-IO wait (no transaction joins),
-- * safe under the inode log mutex and a running transaction handle.
-+ * durable, after which no later write may extend or RMW its stripes. Close
-+ * the run covering the extent so nothing more allocates into its stripes,
-+ * kick any parked partial writes there, and wait for all IO into the run to
-+ * finish. This is a pure data-IO wait (no transaction joins), bounded by
-+ * bio flight time because parked writes are flushed first, and is safe
-+ * under the inode log mutex and a running transaction handle.
- *
-- * With stripe_log_data_shared, a shared run is not closed: the log commit
-- * seals the stripe holding the end of the extent (seal_log_stripe()) and the
-- * run goes on, only the extent's own stripes are kicked, and for any run the
-- * wait is for every allocated sector of those stripes to be written
-- * (stripe_log_extent_written()) rather than for the run to drain. There is
-- * no timeout: returning while a neighbour's sector in those stripes is still
-- * unwritten would let its later partial write RMW the extent after it is
-- * durable.
-+ * With stripe_log_data_shared a shared LOG run is not closed: the stripe
-+ * holding the end of the extent is sealed (seal_log_stripe()). In that
-+ * mode the wait, for any run, is for every allocated sector of the
-+ * extent's stripes to be written (stripe_log_extent_written()) rather than
-+ * for the run to drain. Neither wait has a timeout: returning early would
-+ * let a neighbour's partial write RMW the extent after it is durable.
- *
- * [file_start, file_start + file_len) is the extent's file range, recorded
-- * for carry-forward when the extent sits in the run's final partial stripe
-- * (stripe_log_data_shared clear only); file_len == 0 opts the extent out of
-- * carrying (settling still happens).
-+ * for carry-forward when the extent is in the run's final partial stripe
-+ * (stripe_log_data_shared clear only); file_len == 0 opts out of carrying.
- */
- void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- u64 file_len, u64 bytenr, u64 num_bytes)
-@@ -2460,11 +2354,7 @@ void btrfs_log_settle_stripes(struct btrfs_inode *inode, u64 file_start,
- u64 seal_start = 0;
- u64 seal_len = 0;
-
-- /*
-- * The fsync overwrite policy waives the log-window guarantee:
-- * logged stripes may be extended and RMWed like before the
-- * close-at-log-commit machinery existed.
-- */
-+ /* stripe_alloc_allow_rmw=fsync waives the log-commit guarantee. */
- if (btrfs_stripe_allow_rmw(fs_info) & BTRFS_STRIPE_RMW_FSYNC)
- return;
- if (list_empty_careful(&fs_info->open_stripe_bgs))
-@@ -2646,12 +2536,6 @@ static void stripe_alloc_sweep_groups(struct btrfs_fs_info *fs_info, bool arm)
- }
- }
-
--/*
-- * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
-- * property on the top-level subvolume's root directory. Runs during mount
-- * when the root directory inode loads its properties -- before any user IO
-- * -- or at runtime from btrfs_set_prop().
-- */
- /*
- * Drain the writes the legacy allocator placed before stripe_alloc was
- * enabled on a live filesystem, then arm the write-hole invariant check.
-@@ -2666,12 +2550,10 @@ void btrfs_stripe_alloc_enable_work(struct work_struct *work)
- btrfs_start_delalloc_roots(fs_info, LONG_MAX, false);
- btrfs_wait_ordered_roots(fs_info, U64_MAX, NULL);
- /*
-- * Tree blocks the legacy allocator placed in the transaction that
-- * was running at the flip are written by that transaction's commit,
-- * into the partly used stripes they were allocated in: under raid56
-- * metadata that commit is the last legacy read-modify-write, and the
-- * metadata RMW reporter says so. Wait for it before arming the
-- * check, which would otherwise report those writes as violations.
-+ * Tree blocks the legacy allocator placed in the transaction running at
-+ * the flip are written into partly used stripes by that transaction's
-+ * commit. Wait for it before arming the check, which would otherwise
-+ * report those writes as violations.
- */
- btrfs_commit_current_transaction(fs_info->tree_root);
- clear_bit(BTRFS_FS_STRIPE_ALLOC_ENABLING, &fs_info->flags);
-@@ -2679,6 +2561,12 @@ void btrfs_stripe_alloc_enable_work(struct work_struct *work)
- "stripe_alloc: writes placed before the policy was enabled have landed");
- }
-
-+/*
-+ * Turn on stripe-exclusive allocation, from the "stripe_alloc" filesystem
-+ * property on the top-level subvolume's root directory. Runs during mount
-+ * when the root directory inode loads its properties -- before any user IO
-+ * -- or at runtime from btrfs_set_prop().
-+ */
- int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
- {
- bool live = test_bit(BTRFS_FS_OPEN, &fs_info->flags);
-@@ -2709,11 +2597,7 @@ int btrfs_enable_stripe_alloc(struct btrfs_fs_info *fs_info)
- * when their caching thread finishes, now that the policy is on.
- */
- stripe_alloc_sweep_groups(fs_info, true);
-- /*
-- * At mount btrfs_fill_super() states the outcome once, for the option
-- * and the property alike, so repeating it here would only double the
-- * line. A property set on a live filesystem has no such reporter.
-- */
-+ /* At mount, btrfs_fill_super() reports the outcome. */
- if (live) {
- btrfs_info(fs_info,
- "using stripe-exclusive allocation for raid56 data (filesystem property)");
-@@ -2739,27 +2623,18 @@ void btrfs_disable_stripe_alloc(struct btrfs_fs_info *fs_info)
- }
-
- /*
-- * Does @logical lie within a stripe run (open or draining)? Used by the
-- * raid56 layer to decide whether a partial write to this stripe may be
-- * parked to collect into a full-stripe write: an open run guarantees the
-- * rest of the stripe is either filled before the run closes or never, and
-- * a draining run's frozen frontier makes "never" decidable -- everything
-- * allocated below it is inflight IO the commit drain already waits for,
-- * and everything above it is dead space the pad fills. Excluding draining
-- * runs made every run's tail writes unparkable -- a run closes on
-- * exhaustion in the gap between allocation and write arrival -- and those
-- * writes are the bulk of stripe_alloc's read-modify-writes.
-+ * Does @logical lie within a stripe run, open or draining? The raid56 layer
-+ * uses this to decide whether a partial write may be parked to merge into a
-+ * full-stripe write. An open run fills the rest of the stripe later or
-+ * never; a draining run's frontier is frozen, so everything below it is IO
-+ * the commit drain already waits for and everything above it is dead space
-+ * padding may fill.
- */
- bool btrfs_stripe_in_open_run(struct btrfs_fs_info *fs_info, u64 logical)
- {
- return btrfs_stripe_open_run_class(fs_info, logical, NULL);
- }
-
--/*
-- * Like btrfs_stripe_in_open_run(), also reporting the covering run's
-- * class: the raid56 parking gate treats NOCOW-class runs specially
-- * (sync writes into them never park; see rbio_try_park()).
-- */
- /*
- * The part of [*start, *start + *len) that @run owns and tracks in its
- * written map: inside [run->start, run->end) -- the map itself reaches
-@@ -2849,20 +2724,6 @@ static bool run_unwritten_in(struct btrfs_open_stripe_run *run, u64 start,
- return false;
- }
-
--/*
-- * Is [stripe_start, stripe_start + stripe_len) still waiting for writes from
-- * a stripe run? Two ways:
-- *
-- * - an open run's allocation frontier lies strictly inside it: the run will
-- * allocate and write the rest of the stripe later, although every sector
-- * allocated so far may already be written;
-- * - a run covering it has sectors allocated (live) but not yet written: the
-- * frontier has moved past, and the writes are still in flight (writeback
-- * allocates a whole range before any of its bios complete).
-- *
-- * Either way the stripe has been written in part, and the rest will arrive
-- * as a sub-stripe write that needs the part already written.
-- */
- /*
- * As btrfs_stripe_run_incomplete(), returning the class of the run that
- * leaves the stripe incomplete, or -1 if none does.
-@@ -2894,6 +2755,20 @@ int btrfs_stripe_run_incomplete_class(struct btrfs_fs_info *fs_info,
- return ret;
- }
-
-+/*
-+ * Is [stripe_start, stripe_start + stripe_len) still waiting for writes from
-+ * a stripe run? Two ways:
-+ *
-+ * - an open run's allocation frontier lies strictly inside it: the run will
-+ * allocate and write the rest of the stripe later, although every sector
-+ * allocated so far may already be written;
-+ * - a run covering it has sectors allocated (live) but not yet written: the
-+ * frontier has moved past, and the writes are still in flight (writeback
-+ * allocates a whole range before any of its bios complete).
-+ *
-+ * Either way the stripe has been written in part, and the rest will arrive
-+ * as a sub-stripe write that needs the part already written.
-+ */
- bool btrfs_stripe_run_incomplete(struct btrfs_fs_info *fs_info,
- u64 stripe_start, u64 stripe_len)
- {
-@@ -2920,6 +2795,11 @@ void btrfs_count_open_stripe_runs(struct btrfs_fs_info *fs_info, int *counts)
- spin_unlock(&fs_info->open_stripe_lock);
- }
-
-+/*
-+ * Like btrfs_stripe_in_open_run(), also reporting the covering run's
-+ * class: the raid56 parking gate treats NOCOW-class runs specially
-+ * (sync writes into them never park; see rbio_try_park()).
-+ */
- bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class)
- {
-@@ -2936,18 +2816,10 @@ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- if (logical < run->start || logical >= run->end)
- continue;
- /*
-- * A run stops being "open" as soon as it is full, but its
-- * stripes stay exclusively ours until it drains, and a
-- * closed run's end has been shrunk to its frontier, so a
-- * write into it (necessarily below the frontier) still
-- * matches. Metadata needs the draining window: allocation
-- * and writeback are separated by the whole transaction.
-- * Data needs it too: a run closes on exhaustion in the gap
-- * between allocation and write arrival, and refusing here
-- * made every run's tail writes unparkable -- the bulk of
-- * stripe_alloc's read-modify-writes. The commit drain
-- * waits for exactly these arrivals; parking them is what
-- * lets the stripe go out whole.
-+ * Draining runs match too (see btrfs_stripe_in_open_run()):
-+ * a closed run's end is shrunk to its frontier, so a write
-+ * into it is below the frontier and its stripes are still
-+ * exclusive.
- */
- if (class)
- *class = run->class;
-@@ -2959,11 +2831,6 @@ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- return ret;
- }
-
--/*
-- * Report completed (or abandoned) data IO for an allocation made with
-- * btrfs_alloc_from_open_stripe(). Every allocated byte must be reported
-- * exactly once, in any number of pieces (e.g. after ordered extent splits).
-- */
- /*
- * Report bytes that will never be written: an allocation released before
- * its write was issued. Same accounting as a completion, plus the sectors
-@@ -2990,6 +2857,12 @@ void btrfs_open_stripe_write_abandoned(struct btrfs_block_group *bg, u64 start,
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
- }
-
-+/*
-+ * Report completed IO for an allocation from any stripe run. Every
-+ * allocated byte must be reported exactly once, here or through
-+ * btrfs_open_stripe_write_abandoned(), in any number of pieces (e.g. after
-+ * ordered extent splits).
-+ */
- void btrfs_open_stripe_write_done(struct btrfs_block_group *bg, u64 start,
- u64 num_bytes)
- {
-@@ -3064,11 +2937,10 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
-
- /*
- * Pointer-based variant of btrfs_open_stripe_write_done() for callers that
-- * recorded the run at allocation or ordered extent creation time; safe from
-- * bio end_io context. The run pointer stays valid until the reporter's own
-- * bytes are reported: a run with inflight bytes is never freed.
-- */
--/*
-+ * recorded the run at allocation or ordered extent creation time. The run
-+ * pointer stays valid until the reporter's own bytes are reported: a run
-+ * with inflight bytes is never freed.
-+ *
- * An ordered extent's data IO is over, whether or not all of it reached the
- * disk: stop counting it as in flight, and mark its sectors written. A
- * sector whose write failed or was never issued (truncation, a short direct
-@@ -3098,9 +2970,10 @@ void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
-
- /*
- * Close the block group's open runs that predate @seq and return their
-- * unallocated tails to the free space cache. Does not wait for inflight IO.
-- * Only the bg->open_stripe[][] slots can ever be open, so one pass over the
-- * classes and their remaining-space bands suffices.
-+ * unallocated tails to the free space cache. Does not wait for inflight
-+ * IO. Metadata runs are left to btrfs_retire_meta_stripes() and persistent
-+ * NOCOW runs stay open unless dead, except when @seq is U64_MAX (read-only,
-+ * removal, unmount), which closes everything.
- */
- static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
- u64 seq)
-@@ -3119,26 +2992,15 @@ static void close_block_group_stripe_runs(struct btrfs_block_group *bg,
- if (!run->open || run->open_seq >= seq)
- continue;
- /*
-- * A nodatacow inode's private run survives transaction
-- * commits while the stripe_alloc_allow_rmw policy lets its
-- * data be written in place: its stripes then hold only that
-- * inode's expendable (write-hole-waived) data, so invariant
-- * I2 has nothing to protect there, and closing would burn a
-- * stripe per commit for a slowly appended nocow file. With
-- * nothing waived the run holds ordinary COWed extents (or
-- * unwritten preallocation) and closes like a COW run: kept
-- * open, it only strands the whole stripes freed inside its
-- * range until the inode is evicted. Forced quiescing
-- * (read-only, removal, unmount: seq == U64_MAX) still closes
-- * persistent runs, as does the owning inode's eviction.
-+ * 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) {
-- /*
-- * ... unless nothing is left alive in it. A dead run
-- * holds no data to protect and its stripes cannot be
-- * reclaimed while it exists, so close it now rather
-- * than waiting for the owner's eviction.
-- */
-+ /* 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);
-@@ -3267,13 +3129,9 @@ static bool bg_has_meta_runs(struct btrfs_block_group *bg)
- * otherwise this can wait forever. Membership in fs_info->open_stripe_bgs
- * is left for the next retire walk to collect.
- *
-- * A filesystem that has gone into error ends the wait as well: after a
-- * transaction abort the ordered extents holding a run's bytes in flight
-- * may never complete (they are torn down at unmount), so a run can stay
-- * undrained for the rest of the mount. Waiting for it there would block
-- * the caller -- relocation, holding reclaim_bgs_lock and sb_writers --
-- * forever. The runs are then left as they are; btrfs_free_open_stripe_runs()
-- * releases them at teardown and reports the bytes still counted.
-+ * The wait also ends when the filesystem is in error: after a transaction
-+ * abort the ordered extents holding a run's bytes may never complete. The
-+ * runs are then left for btrfs_free_open_stripe_runs() at teardown.
- */
- void btrfs_retire_block_group_stripes(struct btrfs_block_group *bg)
- {
-@@ -3339,27 +3197,16 @@ void btrfs_wake_open_stripe_waiters(struct btrfs_fs_info *fs_info)
- }
-
- /*
-- * Commit-time retirement: close every stripe run opened before this call
-- * and wait for all data IO into the stripes of those runs to complete.
-- * Must run while the committing transaction still accepts joins (before
-- * TRANS_STATE_COMMIT_DOING): tasks holding unreported run bytes can block
-- * on a join (e.g. a chunk allocation mid-delalloc), and this drain waits
-- * for their IO. Records the bumped sequence in @trans; ordered extents
-- * from runs with open_seq >= it defer their file extents to the next
-- * transaction, closing the fast-completion window this placement opens.
-- * Calls are serialized by the transaction commit; @trans may be NULL for
-- * the final cleanup call.
-- */
--/*
-- * Teardown: release every open stripe run and the block group reference
-- * each group with runs holds. The commit normally retires runs, and the
-- * release of a group's last run drops its membership here; a mount that
-- * fails after log replay has already allocated tree blocks, and an unmount
-- * after a transaction abort, never commit again, and
-- * btrfs_free_block_groups() then asserts on the leftover references. By
-- * the time this runs the workers are stopped and the roots dropped, so no
-- * IO is left to report; a run still counting bytes in flight is noted and
-- * released all the same.
-+ * Teardown: free every remaining stripe run and drop each group's
-+ * membership reference. Needed when no final commit retired them: a mount
-+ * that fails after log replay allocated tree blocks, or an unmount after a
-+ * transaction abort. IO is quiesced by now, so a run still counting
-+ * inflight bytes is reported and freed anyway.
-+ *
-+ * Ordered extents point at their runs (ordered->stripe_run), so this relies
-+ * on none being left: at unmount every inode, and with it every ordered
-+ * extent, is gone before close_ctree() runs, delayed iputs are drained, and
-+ * on both paths the workers that complete ordered extents are stopped first.
- */
- void btrfs_free_open_stripe_runs(struct btrfs_fs_info *fs_info)
- {
-@@ -3396,20 +3243,13 @@ void btrfs_free_open_stripe_runs(struct btrfs_fs_info *fs_info)
- }
-
- /*
-- * Close and drain the metadata stripe runs, once every tree block this
-+ * Close and drain the metadata stripe runs once every tree block this
- * transaction allocated has reached the disk.
- *
-- * This is the second half of a two-phase closure. The first half happens
-- * implicitly: btrfs_retire_open_stripes() runs earlier in the commit and
-- * skips these runs, so they stay open for allocation right through the
-- * commit-time tree building that follows it. Here the allocation side is
-- * finished and the writes are complete, so the runs can be closed and their
-- * unused tails returned.
-- *
-- * Ordering matters in both directions. Closing earlier would strand tree
-- * blocks the commit has not allocated yet; draining earlier would wait for
-- * writes the commit has not issued yet, which is precisely the deadlock
-- * mixed block groups used to hit.
-+ * btrfs_retire_open_stripes() runs earlier in the commit and skips these
-+ * runs, so they stay open for the commit's own tree block allocations.
-+ * Closing earlier would strand blocks the commit has yet to allocate;
-+ * draining earlier would wait for writes the commit has yet to issue.
- */
- void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
- {
-@@ -3481,16 +3321,10 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
-
- /*
- * Every tree block is on disk, so end_bbio_meta_write() has
-- * reported all of them and this settles without waiting.
-- *
-- * Bounded rather than indefinite on purpose. A run drains
-- * only when every byte allocated from it has been reported,
-- * by writeback or by whatever freed the block before it was
-- * written; a path that frees a tree block without reporting
-- * would otherwise wedge the commit with no clue as to which
-- * one. Time out, say so, and carry on: the stripe is then
-- * left open, which costs space, where hanging costs the
-- * filesystem.
-+ * reported all of them and this normally does not wait. The
-+ * timeout guards against a path that frees a tree block
-+ * without reporting it to its run: warn and keep the run,
-+ * which costs space, rather than hang the commit.
- */
- if (!wait_var_event_timeout(&bg->open_stripe_runs,
- !bg_has_undrained_meta_runs(bg, transid),
-@@ -3524,23 +3358,13 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
- /*
- * Should this tree block be left dirty for the transaction commit to write?
- *
-- * A stripe filled by one transaction is written in one piece only if all of
-- * its tree blocks go out in the same writeback pass. The opportunistic
-- * passes -- memory reclaim, the periodic writeback timer -- do not know
-- * about stripes and will happily write three tree blocks now and the other
-- * five later, which turns a full-stripe write into two read-modify-writes.
-- *
-- * Zoned mode has the same problem for a different reason (a tree block that
-- * is not at its zone's write pointer cannot be written yet) and solves it
-- * the same way: btrfs_check_meta_write_pointer() declines the block and the
-- * writeback loop leaves it dirty. This declines on stripe grounds instead.
-- *
-- * WB_SYNC_ALL is never deferred. That is what keeps this from deadlocking:
-- * a reclaimer that must have these pages written waits on WB_SYNC_ALL, which
-- * always proceeds, so dirty metadata pinned in an incomplete stripe can
-- * always be flushed by the caller who needs the memory. Only the
-- * best-effort passes are turned away, and turning one away asks for a commit
-- * rather than leaving the pages for the periodic writeback to find again.
-+ * A stripe of tree blocks goes out as one full-stripe write only if all of
-+ * its blocks are written in the same pass. Opportunistic writeback (memory
-+ * reclaim, the periodic timer) does not know about stripes and would split
-+ * it into read-modify-writes, so it is declined here, as zoned mode does in
-+ * btrfs_check_meta_write_pointer(), and a commit is requested instead.
-+ * WB_SYNC_ALL is never deferred, so a caller that needs the pages written
-+ * can always get them written.
- */
- bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
- struct extent_buffer *eb,
-@@ -3567,6 +3391,17 @@ bool btrfs_defer_stripe_meta_write(struct btrfs_fs_info *fs_info,
- return defer;
- }
-
-+/*
-+ * Commit-time retirement: close every data stripe run opened before this
-+ * call and wait for its IO to complete. Metadata runs are retired later by
-+ * btrfs_retire_meta_stripes(), and persistent NOCOW runs survive. Must run
-+ * while the committing transaction still accepts joins (before
-+ * TRANS_STATE_COMMIT_DOING): tasks holding unreported run bytes can block on
-+ * a join, and this drain waits for their IO. Records the bumped sequence in
-+ * @trans; ordered extents from runs with open_seq >= it defer their file
-+ * extents to the next transaction. Calls are serialized by the transaction
-+ * commit; @trans is NULL for the final cleanup call.
-+ */
- void btrfs_retire_open_stripes(struct btrfs_fs_info *fs_info,
- struct btrfs_transaction *trans)
- {
-@@ -3744,18 +3579,14 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- */
- sinfo->bytes_stripe_margin = 2ULL * nr_rw * unit;
- /*
-- * COW frees trap stripes rather than free them (a
-- * stripe is claimable again only once every block in
-- * it is dead), so the space_info settles around half
-- * used, half trapped. Only relocation packs live tree
-- * blocks back into whole stripes, and it needs the
-- * moved group's live bytes claimable elsewhere first.
-- * Hold back enough for any one group, capped at a
-- * quarter of the space_info, from everyone but the
-- * relocation task. With a single group there is no
-- * elsewhere to hold it for. This is an accounting
-- * hold-back only: a committing transaction still
-- * allocates from these stripes if it must.
-+ * COW frees trap stripes (a stripe is claimable only
-+ * once every block in it is dead), and only relocation
-+ * packs live blocks back into whole stripes, which
-+ * needs room elsewhere for the moved group. With more
-+ * than one group, hold back one group's worth, capped
-+ * at a quarter of the space_info, from all but
-+ * relocation. Accounting only: a committing
-+ * transaction may still allocate here.
- */
- if (nr_rw > 1 && unit)
- reserve = round_up(min(largest,
-@@ -3774,10 +3605,11 @@ void btrfs_scan_stripe_unusable(struct btrfs_fs_info *fs_info, bool force)
- }
-
- /*
-- * With stripe-exclusive allocation, no in-place (nocow/prealloc) write may
-- * land in a raid56 data block group: it could tear a stripe containing
-- * committed extents of other files, which is exactly the write hole. The
-- * write paths use this to force COW for such extents.
-+ * Does stripe-exclusive allocation force COW for an in-place (nocow or
-+ * prealloc) write at @bytenr? True for any raid56 data group under
-+ * stripe_alloc, since an in-place write could tear a stripe holding other
-+ * files' committed extents. The caller may still allow the write when
-+ * btrfs_stripe_nocow_writable() proves the stripes belong to the inode.
- */
- bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr)
- {
-@@ -3796,18 +3628,14 @@ bool btrfs_stripe_alloc_forces_cow(struct btrfs_fs_info *fs_info, u64 bytenr)
-
- #ifdef CONFIG_BTRFS_DEBUG
- /*
-- * Write-hole invariant checker, called for every raid56 write operation
-- * (full-stripe and sub-stripe/RMW alike). With stripe-exclusive
-- * allocation, a raid56 data stripe may only be written while an open or
-- * draining stripe run covers it: once its run retires and drains, nothing
-- * may ever write it again, and a write outside any run means an
-- * allocation bypassed the policy. Either way it is the write hole about
-- * to happen, caught deterministically at the point of the write instead
-- * of probabilistically after a crash plus a device failure.
-+ * Write-hole invariant checker, called for every raid56 write (full-stripe
-+ * and sub-stripe alike). Under stripe_alloc and stripe_meta a stripe may
-+ * only be written while an open or draining run covers it; a write outside
-+ * every run means a retired stripe is being rewritten or an allocation
-+ * bypassed the policy.
- *
-- * Block groups that hosted relocation-class runs are skipped:
-- * relocation legitimately overwrites its preallocated extents in place
-- * after their runs drain.
-+ * Groups that hosted RELOC or NOCOW runs are skipped: those extents are
-+ * legitimately overwritten in place after their runs drain.
- */
- void btrfs_stripe_check_write(struct btrfs_fs_info *fs_info,
- u64 full_stripe_start, bool sub_stripe)
-@@ -5528,13 +5356,11 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
-
- /*
- * A stripe_alloc / stripe_meta group's live extents can only move into
-- * whole free stripes, and relocation never waits for them. Once the
-- * worker has emptied and removed enough groups, the ones left are the
-- * trapped ones it was queued to move next with next to nothing
-- * claimable, while gigabytes may sit unallocated: give it a chunk to
-- * relocate into, once per attempt. Here rather than in the reservation
-- * path so that a device shrink, which relocates without room by design,
-- * keeps failing cleanly instead of growing into space it cannot use.
-+ * whole free stripes. When the rest of the space_info has too few
-+ * claimable bytes for them, allocate a chunk to relocate into, once per
-+ * attempt. Done here rather than in the reservation path so that a
-+ * device shrink, which relocates without spare room by design, still
-+ * fails cleanly.
- */
- if (btrfs_is_stripe_alloc_bg(bg) || btrfs_is_stripe_meta_bg(bg)) {
- u64 elsewhere = READ_ONCE(space_info->bytes_stripe_claimable);
-@@ -5728,8 +5554,10 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- LIST_HEAD(retry_list);
- int reclaimed = 0;
-
-- /* Relocation cannot proceed, and the stripe drain it starts with
-- * would wait for IO that will not complete. */
-+ /*
-+ * Relocation cannot proceed, and the stripe drain it starts with
-+ * would wait for IO that will not complete.
-+ */
- if (BTRFS_FS_ERROR(fs_info))
- return;
-
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index f5c5ed1b04345..7fc544e4fe208 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -31,10 +31,11 @@ enum btrfs_stripe_run_class {
- BTRFS_STRIPE_RUN_COW,
- BTRFS_STRIPE_RUN_RELOC,
- /*
-- * Private per-inode runs for log-active (fsync-heavy) inodes. Never
-- * placed in the shared band slots: each run is owned by one inode and
-- * found by owner lookup, so one inode's log commit settles only its
-- * own stripes.
-+ * Data of log-active (fsync-heavy) inodes. Never placed in the band
-+ * slots: runs are found by subvolume and owner, either the inode or,
-+ * with stripe_log_data_shared, the subvolume's current log transaction
-+ * (stripe_run_owner()), so a log commit settles only stripes holding
-+ * its own extents.
- */
- BTRFS_STRIPE_RUN_LOG,
- /*
-@@ -55,23 +56,12 @@ enum btrfs_stripe_run_class {
- */
- BTRFS_STRIPE_RUN_META,
- /*
-- * Tree blocks of one log commit: a private run keyed by the owning
-- * subvolume's root id and that subvolume's log_transid, never placed
-- * in the shared band slots.
-- *
-- * The point is exclusivity in both directions. A log commit's blocks
-- * become durable the moment fsync returns, so no LATER writer may share
-- * a stripe with them -- not the next log commit, and not the
-- * transaction's ordinary metadata at commit -- or that writer's
-- * sub-stripe write recomputes parity over metadata the user was
-- * promised. Keying the run by log_transid gives each log commit its
-- * own whole stripes, which settles it by construction.
-- *
-- * It is also what makes the space cost temporary. The log tree is
-- * freed at transaction commit, so a stripe holding only one log
-- * commit's blocks is wholly free once that happens, and the
-- * commit-time rescan credits the whole stripe back. A remainder left
-- * beside long-lived ordinary metadata would instead wait for balance.
-+ * Tree blocks of one log commit: a private run keyed by the subvolume's
-+ * root id and log_transid, never placed in a band slot. A log commit's
-+ * blocks are durable once fsync returns, so no later writer (the next
-+ * log commit, or the transaction's own metadata) may share their
-+ * stripes. It also keeps the space cost temporary: the log tree is
-+ * freed at transaction commit, which frees its stripes whole.
- */
- BTRFS_STRIPE_RUN_META_LOG,
- BTRFS_STRIPE_RUN_NR_CLASSES,
-@@ -167,11 +157,10 @@ enum btrfs_block_group_flags {
- */
- BLOCK_GROUP_FLAG_STRIPE_UNUSABLE_DIRTY,
- /*
-- * The group has hosted NOCOW-class stripe runs. With the
-- * stripe_alloc_nocow policy, isolated nodatacow/prealloc extents
-- * are legitimately overwritten in place after their runs drain, so
-- * the write-hole debug check skips such groups (sticky, debug
-- * only), like relocation above.
-+ * The group has hosted NOCOW-class stripe runs. When
-+ * stripe_alloc_allow_rmw permits it, isolated nodatacow/prealloc
-+ * extents are overwritten in place after their runs drain, so the
-+ * write-hole debug check skips such groups (sticky, debug only).
- */
- BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED,
- };
-@@ -285,9 +274,8 @@ struct btrfs_block_group {
- /*
- * Open stripe runs for stripe-exclusive (raid56 write hole safe)
- * allocation. The runs list, the open_stripe pointer and all run
-- * fields are protected by stripe_run_lock, which is irq-safe
-- * because completed data IO is reported from bio end_io context;
-- * see the "Open stripe runs" comment in block-group.c.
-+ * fields are protected by stripe_run_lock; see the "Open stripe runs"
-+ * comment in block-group.c.
- */
- spinlock_t stripe_run_lock;
- struct list_head open_stripe_runs;
-@@ -310,14 +298,14 @@ struct btrfs_block_group {
- struct list_head open_stripe_retire_list;
-
- /*
-- * Free bytes trapped in partially filled stripes of a stripe_alloc
-- * block group: they are genuine free space (present in the free space
-- * cache and the free space tree, so no on-disk accounting changes) but
-- * the stripe-exclusive allocator cannot hand them out until the whole
-- * stripe frees. Computed once at cache-in and maintained incrementally
-- * as free space is added; both this counter and the ready flag are
-- * protected by free_space_ctl->tree_lock. Only statfs subtracts it
-- * (honest f_bavail); the reservation layer is deliberately unchanged.
-+ * Free bytes trapped in partially filled stripes of a stripe_alloc or
-+ * stripe_meta block group: present in the free space cache, but not
-+ * allocatable until the whole stripe frees. Computed at cache-in and
-+ * by the commit rescan; space trapped in between is added only to
-+ * space_info->bytes_stripe_unusable (which counts as used), until the
-+ * commit scan resets that total to the sum of the groups. This
-+ * counter and the ready flag change under both
-+ * free_space_ctl->tree_lock and space_info->lock.
- */
- u64 stripe_unusable;
- /*
-@@ -336,8 +324,9 @@ struct btrfs_block_group {
- * Directly measured claimable supply: bytes of fully free, aligned
- * whole stripes in the free space cache -- exactly what
- * btrfs_claim_free_stripe_run() can take. Maintained incrementally
-- * under ctl->tree_lock by rules that only ever err LOW (early
-- * write()-time ENOSPC), corrected upward by the commit rescan.
-+ * under ctl->tree_lock by rules meant to err only low (early
-+ * write()-time ENOSPC); the commit rescan corrects it, and warns if
-+ * it was ever high.
- */
- u64 stripe_claimable;
- /*
-@@ -346,8 +335,8 @@ struct btrfs_block_group {
- * exhaustive scan proved there is no claimable run. Claims fail in
- * O(1) while the bound is below one full stripe; adding free space
- * resets it to unknown. Unlike stripe_claimable (an accounting
-- * estimate), this caches what the scan itself proved, so it stays
-- * correct even when the accounting errs high. Protected by
-+ * estimate), this caches what the scan itself proved, so it does not
-+ * depend on stripe_claimable being exact. Protected by
- * free_space_ctl->tree_lock; only meaningful once the block group is
- * fully cached.
- */
-@@ -542,9 +531,7 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- u64 run_start, u64 *run_len);
- /*
- * Why padding could or could not proceed, and the run state it was decided
-- * against. Filled at the moment of the decision so a trace can answer
-- * "where was the frontier when this write arrived", which reconstructing
-- * the extent tree afterwards cannot.
-+ * against, for the pad-decline trace.
- */
- enum btrfs_stripe_pad_reason {
- BTRFS_STRIPE_PAD_OK = 0,
---
-2.47.3
-
+++ /dev/null
-From b2f629981ca637a71e9204ba74bc004d6a8a4629 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 01:17:49 -0400
-Subject: [RFC PATCH 105/116] btrfs: stripe_alloc: correct and trim the
- comments outside the block group code
-To: linux-btrfs@vger.kernel.org
-
-Comment-only cleanup of the rest of the series after review:
-
-- move kernel-doc that had drifted onto the wrong function or field back
- (btrfs_claim_free_stripe_run(), btrfs_reserve_data_bytes(), the sysfs
- debug attributes, the btrfs_inode and fs_info members);
-- correct comments the code had outgrown: shared LOG runs and
- carry-forward, the removed mount option and old policy name, the
- claimable debits, padding of allocated sectors whose write is still to
- come, and what the metadata RMW audit can see (it cannot tell fsynced
- log tree blocks from the running transaction's own);
-- drop history (named workloads, one-off measurements, "Phase 1") and
- shorten comments to what a maintainer needs.
-
-No code changes.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/btrfs_inode.h | 52 ++++----
- fs/btrfs/defrag.c | 27 ++---
- fs/btrfs/delalloc-space.c | 23 ++--
- fs/btrfs/disk-io.c | 19 +--
- fs/btrfs/extent-tree.c | 114 +++++++-----------
- fs/btrfs/extent-tree.h | 7 +-
- fs/btrfs/file.c | 15 +--
- fs/btrfs/free-space-cache.c | 175 +++++++++++----------------
- fs/btrfs/fs.h | 60 ++++------
- fs/btrfs/inode.c | 9 +-
- fs/btrfs/ordered-data.c | 5 +-
- fs/btrfs/props.c | 23 ++--
- fs/btrfs/raid56.c | 228 +++++++++++++-----------------------
- fs/btrfs/space-info.c | 195 +++++++++++-------------------
- fs/btrfs/space-info.h | 53 +++------
- fs/btrfs/super.c | 9 +-
- fs/btrfs/sysfs.c | 29 ++---
- 17 files changed, 397 insertions(+), 646 deletions(-)
-
-diff --git a/fs/btrfs/btrfs_inode.h b/fs/btrfs/btrfs_inode.h
-index fc0421de26bf4..8cb09b291597a 100644
---- a/fs/btrfs/btrfs_inode.h
-+++ b/fs/btrfs/btrfs_inode.h
-@@ -89,13 +89,12 @@ enum {
- BTRFS_INODE_FREE_SPACE_INODE,
- /*
- * Set the first time this inode is fsynced under stripe-exclusive
-- * allocation and never cleared while the inode stays cached. A
-- * log-active inode's datacow allocations are steered into the inode's
-- * own private LOG-class stripe run, so that its log commits settle
-- * only its own stripes instead of closing (and trapping the tails of)
-- * runs shared with other writers. Purely an allocation placement
-- * hint: correctness comes from the log-commit settling itself, which
-- * works on runs of any class.
-+ * allocation, and kept while the inode stays cached. A log-active
-+ * inode's datacow allocations go to LOG-class stripe runs (per inode,
-+ * or shared per log transaction with stripe_log_data_shared), so log
-+ * commits settle only stripes holding logged extents instead of
-+ * closing runs shared with other writers. Placement only: correctness
-+ * comes from log-commit settling, which works on runs of any class.
- */
- BTRFS_INODE_LOG_ALLOC,
- /* Set when there are no capabilities in XATTs for the inode. */
-@@ -141,16 +140,16 @@ enum {
- BTRFS_INODE_ROOT_STUB,
- };
-
--/* in memory btrfs inode */
- /*
-- * Carry-forward bookkeeping for a log-active inode under stripe-exclusive
-- * allocation. ps_start/ps_len remember the final partial stripes of the
-- * inode's recently closed private runs (a small ring; older entries are
-- * overwritten). range[] records the file ranges of logged extents living
-- * in those partial stripes, for the next fsync to re-dirty; disk_bytenr
-- * lets the consumer verify the range still maps there before carrying.
-- * Bounded loss: when the ring or the range table overflows, the extra
-- * extents simply stay put and their stripes free the slow way.
-+ * Carry-forward bookkeeping for a log-active inode whose LOG runs are
-+ * private (stripe_log_data_shared clear). ps_start/ps_len remember the
-+ * final partial stripes of the inode's recently closed private runs (a
-+ * small ring; older entries are overwritten). range[] records the file
-+ * ranges of logged extents living in those partial stripes, for the next
-+ * fsync to re-dirty; disk_bytenr lets the consumer verify the range still
-+ * maps there before carrying. Bounded loss: when the ring or the range
-+ * table overflows, the extra extents simply stay put and their stripes free
-+ * the slow way.
- */
- #define BTRFS_LOG_CARRY_NR_PS 4
- #define BTRFS_LOG_CARRY_NR_RANGES 48
-@@ -166,6 +165,7 @@ struct btrfs_log_carry {
- } range[BTRFS_LOG_CARRY_NR_RANGES];
- };
-
-+/* in memory btrfs inode */
- struct btrfs_inode {
- /* which subvolume this inode belongs to */
- struct btrfs_root *root;
-@@ -355,23 +355,17 @@ struct btrfs_inode {
- };
-
- /*
-- * Carry-forward state for a log-active inode (see
-- * BTRFS_INODE_LOG_ALLOC): the file ranges of this inode's extents
-- * that were left in the final partial stripe of a private stripe run
-- * closed at a log commit. The next fsync re-dirties them so they
-- * COW forward into the current run, letting the old partial stripe
-- * free whole. Lazily allocated; both recording (during logging) and
-- * consuming (at fsync entry) run under log_mutex.
-+ * Carry-forward state (struct btrfs_log_carry), lazily allocated;
-+ * recorded and consumed under log_mutex.
- */
- struct btrfs_log_carry *log_carry;
-
- /*
-- * Start of the last extent allocated from this inode's private
-- * LOG-class stripe run (see BTRFS_INODE_LOG_ALLOC). Advisory only:
-- * it seeds the allocator's search hint so consecutive allocations
-- * find the block group holding the inode's run. The run itself is
-- * found by owner lookup under the block group's stripe_run_lock, so a
-- * stale hint costs a miss, never a wrong run.
-+ * Start of the last extent allocated from one of this inode's private
-+ * stripe runs (LOG or NOCOW class). Only a search hint, so
-+ * consecutive allocations find the block group holding the run; the
-+ * run is found by owner lookup, so a stale hint costs a miss, never a
-+ * wrong run.
- */
- u64 log_run_hint;
-
-diff --git a/fs/btrfs/defrag.c b/fs/btrfs/defrag.c
-index fd69a7d34f60c..79defb1cc0a1f 100644
---- a/fs/btrfs/defrag.c
-+++ b/fs/btrfs/defrag.c
-@@ -1264,15 +1264,14 @@ static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
- }
-
- /*
-- * Carry-forward for log-active inodes under stripe-exclusive allocation
-- * (see struct btrfs_log_carry). Re-dirty a file range recorded at the
-- * last log commit so the coming writeback COWs it into the inode's
-- * current private stripe run and the old partial stripe can free whole.
-- * The range is carried only while it still fully maps to the recorded
-- * disk bytenr; a range that was rewritten, truncated, hole-punched or
-- * already carried fails that check and is skipped -- skipping only costs
-- * the space optimization, never correctness. Modeled on
-- * defrag_one_range().
-+ * Carry-forward for log-active inodes with private LOG runs (see struct
-+ * btrfs_log_carry). Re-dirty a file range recorded at the last log commit
-+ * so the coming writeback COWs it into the inode's current private stripe
-+ * run and the old partial stripe can free whole. The range is carried only
-+ * while it still fully maps to the recorded disk bytenr; a range that was
-+ * rewritten, truncated, hole-punched or already carried fails that check
-+ * and is skipped -- skipping only costs the space optimization, never
-+ * correctness. Modeled on defrag_one_range().
- */
- static int carry_one_range(struct btrfs_inode *inode, u64 start, u64 len,
- u64 disk_bytenr)
-@@ -1382,11 +1381,11 @@ static int carry_one_range(struct btrfs_inode *inode, u64 start, u64 len,
- /*
- * Consume the inode's carry table (see struct btrfs_log_carry): re-dirty
- * every recorded range so the caller's upcoming writeback carries them
-- * into the inode's current private stripe run. Called at fsync entry
-- * with the inode locked; takes log_mutex only to detach the table, so
-- * the logging side never records into a half-consumed list. All
-- * failures are soft: an uncarried range just leaves its old stripe to
-- * free the slow way.
-+ * into the inode's current private stripe run. Does nothing with shared
-+ * LOG runs (stripe_log_data_shared). Called at fsync entry with the inode
-+ * locked; takes log_mutex only to detach the table, so the logging side
-+ * never records into a half-consumed list. All failures are soft: an
-+ * uncarried range just leaves its old stripe to free the slow way.
- */
- void btrfs_carry_log_tail(struct btrfs_inode *inode)
- {
-diff --git a/fs/btrfs/delalloc-space.c b/fs/btrfs/delalloc-space.c
-index 4748c90897f5e..f0b1937b4e29f 100644
---- a/fs/btrfs/delalloc-space.c
-+++ b/fs/btrfs/delalloc-space.c
-@@ -172,20 +172,15 @@ int btrfs_check_data_free_space(struct btrfs_inode *inode,
- flush = BTRFS_RESERVE_NO_FLUSH;
-
- /*
-- * stripe_alloc: probe for the pessimistic reservation margin on top
-- * of the bytes themselves, so the ticketed flush below has to
-- * produce enough claimable whole stripes to cover this write's
-- * worst case, and a writer that cannot be covered gets an honest
-- * ENOSPC here rather than a dropped writeback later. The margin is
-- * then re-charged into bytes_stripe_margin by the metadata reservation
-- * (btrfs_mod_outstanding_extents()), which carries it until writeback.
-- * A caller that passes @stripe_held keeps the probe's margin in
-- * bytes_may_use until then and releases it with
-- * btrfs_release_data_margin_probe() after its metadata reservation:
-- * released here, the gap between the two let concurrent writers be
-- * admitted into each other's margin at the fill edge, and their
-- * writebacks then found no stripe. Without @stripe_held (callers
-- * that take no metadata reservation) it is released at once.
-+ * 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)) {
-diff --git a/fs/btrfs/disk-io.c b/fs/btrfs/disk-io.c
-index f54d82a6c7c6d..27faf262898f7 100644
---- a/fs/btrfs/disk-io.c
-+++ b/fs/btrfs/disk-io.c
-@@ -2807,11 +2807,9 @@ void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
- INIT_LIST_HEAD(&fs_info->open_stripe_bgs);
- INIT_WORK(&fs_info->stripe_alloc_enable_work, btrfs_stripe_alloc_enable_work);
- /*
-- * Closing the log-tree fsync write hole is on by default; sysfs can
-- * turn it off so the change can be measured against itself on one boot.
-- * LOG-class data runs shared per log transaction are the default too;
-- * clearing stripe_log_data_shared goes back to private runs with
-- * carry-forward.
-+ * Defaults: each log commit gets its own metadata stripe run, and
-+ * LOG-class data runs are shared per log transaction (clearing
-+ * stripe_log_data_shared selects private runs with carry-forward).
- */
- fs_info->stripe_log_run = true;
- fs_info->stripe_log_data_shared = true;
-@@ -3785,14 +3783,9 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
-
- /*
- * Load the top-level root directory's properties (the stripe_alloc
-- * policy) before anything that can allocate data -- the resumed
-- * balance or dev replace kicked off below -- so filesystem-wide
-- * policy is in force for every allocation this mount ever makes.
-- * Log replay above allocates no new data, only re-references extents
-- * written before the crash, but it does allocate tree blocks and
-- * commit them: btrfs_load_stripe_alloc_prop_early() put the policy in
-- * force for that. The iget applies the properties as a side effect;
-- * the later iget from fill_super finds them already applied.
-+ * policy) before anything that can allocate data, such as the resumed
-+ * balance or dev replace below. The iget applies them as a side
-+ * effect; the later iget from fill_super finds them applied.
- */
- {
- struct btrfs_inode *root_dir;
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 4c56e3ecf5846..4178d2541b8ae 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -3655,14 +3655,11 @@ int btrfs_free_tree_block(struct btrfs_trans_handle *trans,
- return 0;
-
- /*
-- * Last ref to a tree block this transaction allocated and never
-- * wrote: no writeback completion will ever report it to its stripe
-- * run. Report it here, before the free paths diverge. When the
-- * delayed ref head was already processed (truncate and friends run
-- * delayed refs mid-transaction for throttling) check_ref_cleanup()
-- * below returns 0 and the free goes through __btrfs_free_extent()
-- * and the pin/unpin machinery, none of which know about the run --
-- * the run's inflight count would never drain.
-+ * A tree block this transaction allocated and never wrote gets no
-+ * writeback completion to report it to its stripe run, so report it
-+ * here, before the free paths diverge: if its delayed ref head already
-+ * ran, the free goes through __btrfs_free_extent() and the pin
-+ * machinery, which know nothing of stripe runs.
- */
- if (!btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
- bg = btrfs_lookup_block_group(fs_info, buf->start);
-@@ -4212,15 +4209,12 @@ static int do_allocation_zoned(struct btrfs_block_group *block_group,
- }
-
- /*
-- * Should this block group use stripe-exclusive allocation? Never issuing
-- * sub-stripe writes into stripes containing committed data is what closes
-- * the raid56 write hole for datacow writes; see the "Open stripe runs"
-- * comment in block-group.c.
-- *
-- * Data only, and not the data in a mixed block group: metadata is not ready
-- * for this allocator (see the mixed block group rejection in
-- * btrfs_check_mountopts(), which is the real gate -- the METADATA test here
-- * is belt and braces for a block group that somehow reaches this path).
-+ * Should this data block group use stripe-exclusive allocation? Never
-+ * issuing sub-stripe writes into stripes containing committed data is what
-+ * closes the raid56 write hole; see "Open stripe runs" in block-group.c.
-+ * Metadata is covered by btrfs_is_stripe_meta_bg(). Mixed groups are
-+ * excluded: stripe_alloc refuses to enable on them
-+ * (btrfs_stripe_alloc_check_support()).
- */
- bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
- {
-@@ -4233,24 +4227,14 @@ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
- /*
- * Should this block group allocate tree blocks by whole stripes?
- *
-- * The same rule data follows: only fully free stripes are claimed, and the
-- * partial stripe left at the end of a commit is padded out rather than
-- * revisited, so no tree block write ever lands in a stripe holding earlier
-- * committed data. Not separately gated: the chunk profile already decides
-- * it. raid56 metadata has the same write hole as raid56 data and gets the
-- * same protection at the same time; metadata on any other profile has no
-- * write hole to close, and the RAID56_MASK test below means the policy
-- * simply does not apply to it. The costs metadata brings -- a stranded
-- * stripe tail per commit, and an allocation failure that aborts the
-- * transaction rather than failing one write -- are the price of covering
-- * raid56 metadata at all, and a filesystem that does not want them wants
-- * raid1c3/raid1c4 metadata instead, which is the better answer anyway.
-- *
-- * System chunks are tree blocks too -- the chunk tree, without which nothing
-- * maps -- and carry no METADATA bit, so they are named here explicitly. A
-- * chunk tree block landing in a stripe with committed chunk tree blocks is
-- * the worst possible write hole: a torn parity rewrite there costs the whole
-- * filesystem on the next degraded mount, not one file.
-+ * The same rule as data: only fully free stripes are claimed, and the
-+ * partial stripe left at the end of a commit is padded rather than
-+ * revisited, so no tree block lands in a stripe holding committed blocks.
-+ * It applies to every raid56 metadata and system group while stripe_alloc
-+ * is on. The costs are a stranded stripe tail per commit, and an
-+ * allocation failure aborts the transaction instead of failing one write.
-+ * System chunks carry no METADATA bit but hold the chunk tree, so they are
-+ * named explicitly.
- */
- bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg)
- {
-@@ -4329,16 +4313,11 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- (ffe_ctl->for_data_reloc !=
- (block_group->start == fs_info->data_reloc_bg))) {
- /*
-- * Relocation stays in its group. Everyone else stays out of
-- * it only while the other groups can serve them: the
-- * dedication can land after a write was admitted against
-- * this group's stripes (the read-only guard covers that
-- * transition, not this one), and refusing the write here
-- * drops its data at writeback. The class tag on the runs
-- * keeps the two sides from ever sharing a stripe, so a
-- * last-resort allocation in the relocation group is safe,
-- * merely unhelpful to relocation. Zoned's hard exclusion
-- * follows from append-only zones, which do not apply here.
-+ * Relocation stays in its group. Others avoid it only while
-+ * other groups can serve them: the dedication can land after a
-+ * write was admitted against this group's stripes, and refusing
-+ * that write here would drop its data. Runs are tagged by
-+ * class, so the two never share a stripe either way.
- */
- if (ffe_ctl->for_data_reloc ||
- ffe_ctl->loop < LOOP_ALLOC_CHUNK)
-@@ -4356,14 +4335,13 @@ static int do_allocation_stripe(struct btrfs_block_group *block_group,
- return 1;
-
- /*
-- * Steered allocations come from the inode's own private run of the
-- * requested class: a log-active inode's log commits then settle only
-- * its own stripes, and nocow/prealloc extents never share a stripe
-- * with another file's data. If this block group has no fully-free
-- * stripes left for a private run, fall through to the shared runs --
-- * safe in both cases: log-commit settling covers any placement, and
-- * a nocow/prealloc extent that lands in a shared stripe simply stays
-- * force-COWed.
-+ * Steered allocations come from a private run of the requested class:
-+ * the inode's own, or for LOG-class allocations under a full stripe
-+ * with stripe_log_data_shared, the run its subvolume shares for the
-+ * current log transaction (stripe_run_owner()). If this block group
-+ * has no fully free stripe for such a run, fall through to the shared
-+ * runs: log-commit settling covers any placement, and a nocow/prealloc
-+ * extent in a shared stripe is simply COWed.
- */
- if (ffe_ctl->steer_inode) {
- struct btrfs_inode *steer_inode = ffe_ctl->steer_inode;
-@@ -5149,18 +5127,14 @@ 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) -- but only while the stripe_alloc_allow_rmw
-- * policy lets that kind of extent be written in place: otherwise
-- * every write to it is COWed like anyone else's, and a private run
-- * (which outlives commits) would only strand the whole stripes freed
-- * inside its range until the inode is evicted; 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)) {
-@@ -5255,12 +5229,10 @@ int btrfs_reserve_extent(struct btrfs_root *root, struct btrfs_inode *inode,
- "stripe_alloc: data writeback allocation of %llu bytes returned ENOSPC despite reservation margin; buffered data in this range will be dropped",
- num_bytes);
- /*
-- * Metadata twin. A tree block reservation was admitted
-- * against the whole-stripe supply (trapped and open-run bytes
-- * count as used in the space_info), so a raid56 stripe_meta
-- * tree block should always find a whole stripe or an open
-- * run. If it does not, the transaction aborts: report the
-- * counters so the accounting hole can be identified.
-+ * Tree block reservations are admitted against the
-+ * whole-stripe supply, so a stripe_meta tree block should
-+ * always find a whole stripe or an open run. If not, the
-+ * transaction aborts: log the counters.
- */
- if (!is_data && btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
- (flags & BTRFS_BLOCK_GROUP_RAID56_MASK)) {
-diff --git a/fs/btrfs/extent-tree.h b/fs/btrfs/extent-tree.h
-index 428a5d31cd459..a1f4d9f37866a 100644
---- a/fs/btrfs/extent-tree.h
-+++ b/fs/btrfs/extent-tree.h
-@@ -57,10 +57,9 @@ struct find_free_extent_ctl {
- bool for_data_reloc;
-
- /*
-- * Data allocation to steer into a private per-inode stripe run under
-- * stripe-exclusive allocation (LOG class for log-active inodes,
-- * NOCOW class for nodatacow files' and preallocated extents), with
-- * the class to use.
-+ * Data allocation to steer into a private stripe run (see
-+ * stripe_run_owner()), and the run class: NOCOW for nodatacow and
-+ * preallocated extents, LOG for log-active inodes.
- */
- struct btrfs_inode *steer_inode;
- enum btrfs_stripe_run_class steer_class;
-diff --git a/fs/btrfs/file.c b/fs/btrfs/file.c
-index 0a6e59c11b1f1..1af09fbaf2bf9 100644
---- a/fs/btrfs/file.c
-+++ b/fs/btrfs/file.c
-@@ -1553,8 +1553,8 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
- /*
- * Under stripe-exclusive allocation, mark the inode log-active before
- * this fsync flushes its delalloc, so that even the first fsync's
-- * allocations are steered into the inode's own LOG-class stripe run
-- * (see BTRFS_INODE_LOG_ALLOC). Sticky while the inode stays cached:
-+ * allocations are steered into LOG-class stripe runs (see
-+ * BTRFS_INODE_LOG_ALLOC). Sticky while the inode stays cached:
- * one fsync is taken as a signal that more will follow.
- */
- if (btrfs_test_opt(fs_info, STRIPE_ALLOC) &&
-@@ -1593,11 +1593,12 @@ int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
- btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
-
- /*
-- * Re-dirty the tail ranges recorded at the last log commit so the
-- * writeback below carries them into the inode's current private
-- * stripe run, letting the old partial stripe free whole (see
-- * struct btrfs_log_carry). Purely a space optimization: a range
-- * that cannot be carried is simply skipped.
-+ * With private LOG runs (stripe_log_data_shared clear), re-dirty the
-+ * tail ranges recorded at the last log commit so the writeback below
-+ * carries them into the inode's current private stripe run, letting
-+ * the old partial stripe free whole (see struct btrfs_log_carry).
-+ * Purely a space optimization: a range that cannot be carried is
-+ * simply skipped.
- */
- btrfs_carry_log_tail(inode);
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 7026742de2adf..b7caca10cb10d 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1425,17 +1425,12 @@ static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
- kmem_cache_free(btrfs_free_space_cachep, info);
- out:
- /*
-- * Do NOT incrementally credit newly-freed whole stripes here. Add paths
-- * re-add space that a low-level remove never de-credited -- the async
-- * discard trim (unlink_free_space / bitmap_clear_bits + do_trimming's
-- * re-add) and btrfs_remove_free_space's middle-split tail -- so crediting
-- * on add double-counts and stripe_claimable drifts ABOVE the authoritative
-- * scan. That is the dangerous direction: once admission gates on the
-- * counter, an over-count admits reservations against phantom supply that
-- * writeback then drops. The incremental rules now only ever DEBIT
-- * (removes/claims, which err low); the per-commit rescan is the sole
-- * upward correction, so the counter can only under-count (early, clean
-- * write()-time ENOSPC) -- never over-count.
-+ * Adding free space never credits stripe_claimable: some add paths
-+ * re-add space that was never debited (async discard's re-add, the tail
-+ * of btrfs_remove_free_space()'s middle split), and crediting would
-+ * count it twice. The counter may only err low (an early ENOSPC); an
-+ * over-count admits reservations writeback cannot place. The commit
-+ * rescan is the only upward correction.
- */
- btrfs_discard_update_discardable(block_group);
- spin_unlock(&ctl->tree_lock);
-@@ -1517,13 +1512,9 @@ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
- static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
-
- /*
-- * stripe_alloc: keep the directly measured claimable whole-stripe supply
-- * in step with free space mutations. Positive deltas come from returned
-- * ranges' interior whole stripes, negative from claims and removals. The
-- * blind rules only ever err by counting claimable LOW (early write()-time
-- * ENOSPC, corrected upward by the commit rescan), never HIGH: a
-- * reservation admitted against phantom supply fails at writeback and
-- * drops buffered data. Caller holds ctl->tree_lock.
-+ * Debit the claimable whole-stripe supply for claims and removals. Returned
-+ * free space is never credited here (see __btrfs_add_free_space()); the
-+ * commit rescan restores it. Caller holds ctl->tree_lock.
- *
- * The group's value and the space_info total change in one sinfo->lock
- * section, as everywhere else, so that btrfs_scan_stripe_unusable(), which
-@@ -1571,20 +1562,12 @@ static u64 stripe_touched_bytes(const struct btrfs_block_group *bg,
- }
-
- /*
-- * stripe_alloc: count the sub-stripe fragments of a returning free range
-- * as trapped immediately, without waiting for the commit-time rescan.
-- *
-- * The rescan remains the authority, but reservations (which now carry the
-- * pessimistic per-extent margin) read bytes_stripe_unusable in the middle
-- * of a transaction, and any mid-transaction return of free space -- an
-- * unpinned deletion, a same-transaction free, a drained run tail, a freed
-- * reservation -- otherwise leaves its fragments backing admissions the
-- * claim rule can never honor. Whole stripes lying fully inside the
-- * returned range are trivially fully free (hence claimable) and are not
-- * counted; the partial head and tail fragments are counted trapped even
-- * though neighbouring free space may complete their stripes. That is a
-- * bounded overcount in the safe direction (early ENOSPC at admission,
-- * reconciled by the next rescan), never an undercount.
-+ * 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)
-@@ -2100,14 +2083,12 @@ static u64 stripe_free_walk(struct btrfs_block_group *bg, u32 *freep)
- }
-
- /*
-- * Total trapped free bytes (free space in partially filled stripes) over the
-- * whole block group -- the authoritative definition of stripe_unusable,
-- * recomputed at cache-in and after each commit that changed the group's free
-- * space. Every free byte is accumulated into a per-stripe array (so a stripe
-- * whose total free is neither zero nor a whole stripe is partially filled, and
-- * its free bytes are trapped). @freep is a zeroed array of stripe_unusable_
-- * nstripes() u32 entries the caller allocates before taking the tree lock (it
-- * can be large); this runs with ctl->tree_lock held.
-+ * The authoritative stripe_unusable of the block group: free bytes in
-+ * partially filled stripes, plus whole free stripes stranded behind live
-+ * runs. Recomputed at cache-in and after each commit that changed the
-+ * group's free space. @freep is a zeroed array of
-+ * stripe_unusable_nstripes() entries, allocated by the caller before taking
-+ * ctl->tree_lock, which is held here.
- */
- static u64 stripe_unusable_scan(struct btrfs_block_group *bg, u32 *freep,
- u64 nstripes)
-@@ -2280,21 +2261,14 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
-
-
- /*
-- * Does this stripe_alloc / stripe_meta group want the reclaim worker? Like
-- * zoned's zone_unusable reclaim: once enough of the group's FREE space is
-- * trapped in partially used stripes (zoned compares with the capacity, but a
-- * stripe group also holds claimable whole stripes), relocation packs the live
-- * extents into whole stripes elsewhere. A group whose live data is below the
-- * same threshold is cheap enough to move whole and free; a fuller one is
-- * compacted instead (btrfs_compact_chunk()): only the extents in its partial
-- * stripes move, at most half its live bytes, and the group stays. Either way
-- * only when that data fits in the claimable supply of the OTHER groups:
-- * relocation needs whole stripes too, and a group queued while there is
-- * nowhere to move it starves writers with read-only transitions and fails
-- * each time at the fill edge. The worker re-checks. Reads the counters
-- * without locks; the commit-time rescan calls it with fresh values, the
-- * cleaner's periodic re-evaluation with slightly stale ones, and either
-- * error is caught by the worker.
-+ * Does this stripe_alloc / stripe_meta group want the reclaim worker? As
-+ * with zoned's zone_unusable, reclaim once enough of the group's free space
-+ * is trapped. A group whose live data is below the threshold is relocated
-+ * whole; a fuller one is compacted (btrfs_compact_chunk()), moving only the
-+ * extents in its partial stripes. Either way, only when the data fits in
-+ * the other groups' claimable supply: relocation needs whole stripes too,
-+ * and queueing a group with nowhere to move it only costs writers read-only
-+ * transitions. Counters are read unlocked; the worker re-checks.
- */
- enum stripe_reclaim_kind {
- STRIPE_RECLAIM_NONE,
-@@ -2324,12 +2298,10 @@ static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group
- return STRIPE_RECLAIM_NONE;
- if (used >= mult_perc(bg->length, thresh)) {
- /*
-- * Too full to move whole: compact it once its trapped space is
-- * stripe_compact percent of the whole group. Measured against
-- * the free space, as for a whole relocation below, a mostly
-- * live group never qualified: its little free space is mostly
-- * whole stripes, so the trapped share of it stays small while
-- * the trapped bytes grow.
-+ * Too full to move whole: compact once trapped space reaches
-+ * stripe_compact percent of the group's length. (A share of
-+ * free space, as below, would stay small here: a mostly live
-+ * group's little free space is mostly whole stripes.)
- */
- const u32 pct = READ_ONCE(bg->fs_info->stripe_compact);
-
-@@ -2396,14 +2368,10 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
-
- /*
- * The incremental rules may only under-count claimable
-- * supply; counting more than the scan finds means a missed
-- * consumption site, the direction that admits reservations
-- * writeback cannot honor. Rate-limited rather than _ONCE: a
-- * persistent gap -- e.g. a filesystem carrying extents from the
-- * legacy allocator, a layout the incremental rules were not
-- * shaped for -- recurs every commit, and hiding all but the
-- * first hit loses that signal in the field. The clamp below
-- * keeps each rescan authoritative regardless.
-+ * supply; more than the scan finds means a missed debit,
-+ * which admits reservations writeback cannot honor. Rate
-+ * limited, not _ONCE, because such a gap recurs every commit.
-+ * The assignment below keeps the rescan authoritative.
- */
- WARN_RATELIMIT(bg->stripe_claimable > scanned,
- "bg %llu incremental stripe_claimable %llu above scanned %llu",
-@@ -2433,11 +2401,9 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
- kvfree(freep);
- if (reclaim) {
- /*
-- * Stamp the hysteresis only when the mark lands. A group
-- * that is already on another list (a chunk created this
-- * transaction is still on trans->new_bgs) cannot be linked,
-- * and stamping it anyway lost the mark for five minutes and,
-- * on an idle filesystem with no commit to rescan it, for good.
-+ * Stamp the hysteresis only if the mark lands: a group still on
-+ * another list (a new chunk on trans->new_bgs) cannot be
-+ * queued, and must stay eligible at the next rescan.
- */
- spin_lock(&bg->lock);
- if (btrfs_mark_bg_to_reclaim(bg))
-@@ -2515,29 +2481,6 @@ static bool find_stripe_run_in_bitmap(struct btrfs_free_space_ctl *ctl,
- return false;
- }
-
--/*
-- * Claim a contiguous run of fully-free full stripes.
-- *
-- * On success the run is removed from the free space cache and the caller owns
-- * [*start, *start + *len) exclusively until it either allocates from it or
-- * returns the unused remainder with btrfs_add_free_space().
-- *
-- * want_bytes must be a full_stripe_len multiple and is a maximum; the
-- * smallest successful claim is a single full stripe. A fully-free stripe
-- * split across free space entries (an extent entry adjoining a bitmap, or
-- * two bitmaps: adjacent extent entries merge on insert, but extent/bitmap
-- * neighbours and neighbouring bitmap windows do not) is found by the
-- * entry-blind slow path. It has to be: stripe_unusable accounting is
-- * entry-blind too, so it admits data reservations against exactly these
-- * stripes, and a stripe the accounting admits but the claim cannot reach
-- * becomes a buffered write that fails -ENOSPC at writeback, dropping the
-- * pages -- full_stripe_len is not a power of two, so stripe boundaries
-- * drift through the fixed bitmap windows and such stripes are a
-- * certainty, not a corner case.
-- *
-- * Returns 0 on success, -ENOSPC if no aligned fully-free stripe is present
-- * in this block group, -ENOMEM if the slow path could not allocate.
-- */
- static bool claim_stripe_run_pieces(struct btrfs_block_group *block_group,
- u64 start, u64 len,
- struct btrfs_free_space *spare);
-@@ -2846,8 +2789,10 @@ static bool claim_stripe_run_pieces(struct btrfs_block_group *block_group,
- ret2 = link_free_space(ctl, info);
- ASSERT(!ret2); /* -EEXIST; Logic error */
- } else {
-- /* Strictly inside: split head off, spare
-- * becomes the tail. */
-+ /*
-+ * Strictly inside: split head off, spare
-+ * becomes the tail.
-+ */
- ASSERT(!spare_used);
- spare->offset = off + piece;
- spare->bytes = e_end - spare->offset;
-@@ -2866,6 +2811,23 @@ static bool claim_stripe_run_pieces(struct btrfs_block_group *block_group,
- return spare_used;
- }
-
-+/*
-+ * Claim a contiguous run of fully free full stripes.
-+ *
-+ * On success the run is removed from the free space cache and the caller
-+ * owns [*start, *start + *len) until it allocates from it or returns the
-+ * remainder with btrfs_add_free_space(). @want_bytes is a maximum; the
-+ * smallest claim is one full stripe.
-+ *
-+ * A fully free stripe may span free space entries: extent and bitmap
-+ * entries do not merge, and when full_stripe_len is not a power of two,
-+ * stripe boundaries drift through the fixed bitmap windows. The slow path
-+ * finds such stripes; stripe_claimable counts them, so missing them would
-+ * fail writes that admission accepted.
-+ *
-+ * Returns 0 on success, -ENOSPC if no fully free stripe is present, or
-+ * -ENOMEM if the slow path could not allocate.
-+ */
- int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- u64 want_bytes, u64 *start, u64 *len)
- {
-@@ -2898,16 +2860,11 @@ int btrfs_claim_free_stripe_run(struct btrfs_block_group *block_group,
- spin_lock(&ctl->tree_lock);
-
- /*
-- * Fail fast without scanning when a previous exhaustive scan proved
-- * this block group has no claimable run (max_claimable_run == 0, set
-- * below): only adding free space can create one, and
-- * __btrfs_add_free_space() resets the bound when it does. Also skip
-- * when the total free space cannot possibly hold one full stripe.
-- * Without this, a fragmented block group costs a full O(size) scan
-- * under ctl->tree_lock for EVERY failed claim - one per small
-- * allocation - which starves the delalloc workers at 100% CPU on
-- * large aged filesystems. Only trust the bound once the block group
-- * is fully cached: cache loading links entries directly, bypassing
-+ * Fail fast when an earlier exhaustive scan found no claimable run
-+ * (max_claimable_run == 0; __btrfs_add_free_space() resets it) or less
-+ * than one full stripe is free; otherwise every failed claim rescans a
-+ * fragmented group under ctl->tree_lock. Trust the bound only once the
-+ * group is cached: cache loading links entries without
- * __btrfs_add_free_space(), so the reset would be missed.
- */
- if (btrfs_block_group_done(block_group) &&
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index 096434fa4ff14..aec2ff64f0704 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -520,9 +520,10 @@ struct btrfs_free_space_ctl;
- struct btrfs_free_space;
-
- /*
-- * Park deadline defaults, ms. Both are tunable at runtime through
-- * /sys/fs/btrfs/<uuid>/stripe_park_{,sync_}timeout_ms; the constants here
-- * are only the initial values.
-+ * Default park deadlines, ms (sysfs stripe_park_{,sync_}timeout_ms). Sync
-+ * writes (REQ_SYNC) have a waiter blocked on them, so their deadline is
-+ * just long enough for the rest of one writeback pass over the stripe to
-+ * merge in.
- */
- #define BTRFS_RBIO_PARK_TIMEOUT_MS 100
- #define BTRFS_RBIO_PARK_SYNC_TIMEOUT_MS 3
-@@ -873,28 +874,25 @@ struct btrfs_fs_info {
- /* Pads that zeroed allocated sectors whose write was to come. */
- atomic64_t padded_unwritten;
- /*
-- * Data read-modify-writes on a block group the allocator
-- * covers. With allow_rmw empty this is the number the
-- * stripe-exclusive claim is about, and it should be zero;
-- * rmw_reads counts only the parked ones, so it cannot say
-- * whether a workload RMWs at all.
-+ * Data read-modify-writes in a covered block group, parked or
-+ * not; zero with allow_rmw empty. rmw_reads counts only the
-+ * parked ones.
- */
- atomic64_t data_rmw;
- /*
-- * Why padding refused, so "some RMW remains" names a defect
-- * instead of a symptom. live: the rest of the stripe is
-- * allocated and its data has not arrived (wait longer, or
-- * kick when the frontier advances). no_run: no open run
-- * covers the stripe, so the run closed before its own write
-- * went down (a lifetime problem). unallocated: the run's
-- * frontier has not reached the stripe being written at all.
-+ * Why padding declined: live (the rest of the stripe is
-+ * allocated and not yet written), no_run (no open run covers
-+ * the stripe), unallocated (the run's frontier has not reached
-+ * the stripe).
- */
- atomic64_t pad_decline_live;
- atomic64_t pad_decline_no_run;
- atomic64_t pad_decline_unallocated;
-- /* Oracle allowed padding, but a sector below the
-- * frontier is not covered by this write: another
-- * allocation shares the stripe. */
-+ /*
-+ * Oracle allowed padding, but a sector below the frontier is
-+ * not covered by this write: another allocation shares the
-+ * stripe.
-+ */
- atomic64_t pad_decline_uncovered;
- /*
- * data_rmw split by why padding declined for the rbio that
-@@ -915,8 +913,9 @@ struct btrfs_fs_info {
- /*
- * Breakdown of what a metadata read-modify-write found in the
- * columns it did not cover: a tree block of the generation
-- * being written (a cost), an older one (a write hole), or no
-- * tree block at all. See audit_uncovered_rmw().
-+ * being written (a cost, unless an fsynced log block), an
-+ * older one (a write hole), or no tree block at all. See
-+ * audit_uncovered_rmw().
- */
- atomic64_t meta_rmw_cur;
- atomic64_t meta_rmw_old;
-@@ -926,7 +925,7 @@ struct btrfs_fs_info {
- not in memory to ask */
- atomic64_t meta_rmw_free;
- atomic64_t congestion_short;
-- /* Frontier stripes pinned in the rbio cache (cache_rbio()). */
-+ /* Stripes pinned in the rbio cache (rbio_needs_pin()). */
- atomic64_t rbio_pinned;
- /*
- * Pins refused because RBIO_PIN_MAX stripes were already
-@@ -974,9 +973,8 @@ struct btrfs_fs_info {
- /*
- * Give each log commit its own private metadata stripe run
- * (BTRFS_STRIPE_RUN_META_LOG), so that no later writer shares a stripe
-- * with tree blocks an fsync has already made durable. On by default;
-- * sysfs-writable so the change can be measured against itself on one
-- * boot.
-+ * with tree blocks an fsync has already made durable. On by default
-+ * (sysfs stripe_log_run).
- */
- bool stripe_log_run;
- /*
-@@ -989,11 +987,7 @@ struct btrfs_fs_info {
- * its final partial stripe. See btrfs_log_settle_stripes().
- */
- bool stripe_log_data_shared;
-- /*
-- * Stripe run lifecycle observability: lifetime counters exposed
-- * through sysfs stripe_run_stats, so a test can show it exercised
-- * the nocow private-run and stranded-stripe paths at all.
-- */
-+ /* Stripe run lifecycle counters (sysfs stripe_run_stats). */
- struct {
- /* private NOCOW runs opened (they outlive commits) */
- atomic64_t nocow_run_opened;
-@@ -1037,9 +1031,7 @@ struct btrfs_fs_info {
- */
- u32 stripe_compact;
- /*
-- * Parking deadlines in ms, tunable through sysfs so the constants
-- * can be swept against a workload instead of rebuilt for each
-- * data point. 0 disables parking for that class. See
-+ * Park deadlines, ms (sysfs); 0 disables parking for that class. See
- * rbio_try_park().
- */
- u32 stripe_park_timeout_ms;
-@@ -1119,9 +1111,9 @@ struct btrfs_fs_info {
-
- struct semaphore uuid_tree_rescan_sem;
-
-- /* Used to reclaim the metadata space in the background. */
-- /* drains the legacy allocator's writes after a runtime stripe_alloc enable */
-+ /* Drains legacy writes after stripe_alloc is enabled at runtime. */
- struct work_struct stripe_alloc_enable_work;
-+ /* Used to reclaim the metadata space in the background. */
- struct work_struct async_reclaim_work;
- struct work_struct async_data_reclaim_work;
- struct work_struct preempt_reclaim_work;
-diff --git a/fs/btrfs/inode.c b/fs/btrfs/inode.c
-index 52ae8dd17457d..bff140549c744 100644
---- a/fs/btrfs/inode.c
-+++ b/fs/btrfs/inode.c
-@@ -1877,10 +1877,11 @@ static int can_nocow_file_extent(struct btrfs_path *path,
- * data relocation inode is exempt: its preallocated extents live in
- * relocation-class stripe runs that never share stripes with other
- * data, and relocation depends on its writes landing in place.
-- * With the stripe_alloc_nocow policy, an extent whose stripes are
-- * isolated to this inode may be written in place after all: the
-- * write hole it reintroduces can tear only the writing file's own
-- * data, which is the nodatacow/prealloc contract.
-+ * When the btrfs.stripe_alloc_allow_rmw property allows it for
-+ * nodatacow or prealloc extents, an extent whose stripes are isolated
-+ * to this inode may be written in place after all: the write hole it
-+ * reintroduces can tear only the writing file's own data, which is
-+ * the nodatacow/prealloc contract.
- */
- if (!btrfs_is_data_reloc_root(root) &&
- btrfs_stripe_alloc_forces_cow(root->fs_info, io_start) &&
-diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
-index 931be63ce1727..5bd8ff43f9d52 100644
---- a/fs/btrfs/ordered-data.c
-+++ b/fs/btrfs/ordered-data.c
-@@ -222,8 +222,9 @@ static struct btrfs_ordered_extent *alloc_ordered_extent(
- * block group membership is established before the allocation
- * returns, so an ordered extent for a stripe-run allocation cannot
- * observe an empty list. NOCOW and PREALLOC ordered extents write
-- * to previously allocated extents, which can never sit inside a
-- * stripe run (runs are claimed from fully-free stripes).
-+ * into extents whose allocation was already reported (a
-+ * preallocation is reported when it is reserved), so they have
-+ * nothing to report.
- */
- if (!is_nocow &&
- !list_empty_careful(&inode->root->fs_info->open_stripe_bgs)) {
-diff --git a/fs/btrfs/props.c b/fs/btrfs/props.c
-index 9058360304270..741ccacb42f84 100644
---- a/fs/btrfs/props.c
-+++ b/fs/btrfs/props.c
-@@ -288,21 +288,16 @@ static void inode_prop_iterator(void *ctx,
- /*
- * Apply the btrfs.stripe_alloc property before tree-log replay.
- *
-- * The policy normally comes into force when the top-level root directory's
-- * inode loads (prop_stripe_alloc_apply()), which open_ctree() does after log
-- * replay. But replay allocates tree blocks and commits a transaction, and
-- * without the policy those allocations land wherever there is free space --
-- * including the free sectors a crash leaves in partially written stripes --
-- * so its writes are read-modify-writes of stripes holding committed
-- * metadata: a write hole for as long as replay runs, and with a device that
-- * returns bad data, parity that no longer rebuilds the committed blocks.
-+ * The property normally takes effect when the top-level root directory's
-+ * inode loads (prop_stripe_alloc_apply()), which open_ctree() does after
-+ * log replay. Replay allocates tree blocks and commits, and without the
-+ * policy those writes may read-modify-write stripes holding committed
-+ * metadata.
- *
-- * Read the xattr item directly rather than through an inode: replay may
-- * rewrite the root directory's inode item, and an inode cached across it
-- * would go stale. Only a set property is acted on here; the root
-- * directory's load after replay applies the final state as usual, including
-- * a change to the property that the log itself carried. Errors are left to
-- * that load to report, as for any property.
-+ * Read the xattr item directly: replay may rewrite the root directory's
-+ * inode item, and an inode cached across replay would go stale. Only a set
-+ * property is acted on here; the load after replay applies the final state
-+ * (including any change the log carried) and reports errors.
- */
- void btrfs_load_stripe_alloc_prop_early(struct btrfs_fs_info *fs_info)
- {
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 9f3647a98f4e2..60e636821c40a 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -49,11 +49,10 @@
-
- /*
- * Set when a partial write rbio's uncovered data sectors were zero-filled
-- * instead of read (they lie at or past the covering stripe run's
-- * allocation frontier and have never been written). The write path then
-- * writes them out with the stripe -- parity must match the disk, or
-- * scrub would flag the never-written sectors -- turning the partial
-- * write into a full-stripe write with no read phase.
-+ * instead of read, because the covering stripe run says they hold nothing
-+ * (see rmw_try_pad_full()). The zeroes are written with the stripe so
-+ * parity matches the disk: the partial write becomes a full-stripe write
-+ * with no read phase.
- */
- #define RBIO_PADDED_BIT 5
-
-@@ -82,7 +81,7 @@
- * Set while a cached rbio holds a stripe that its run has not finished
- * writing: the cache prune skips it, so the run's next write into the stripe
- * takes the part already written from memory instead of reading it back
-- * from the devices (see cache_rbio()).
-+ * from the devices (see rbio_needs_pin()).
- */
- #define RBIO_PINNED_BIT 9
-
-@@ -92,8 +91,9 @@
- * A pin goes stale when its run finishes the stripe and is only uncounted
- * when a sweep, an eviction or a re-cache finds it, so pinning past
- * RBIO_PIN_LOW sweeps first, and if the pins left are still live, asks for a
-- * commit: the commit closes every run (btrfs_retire_open_stripes()), which
-- * makes every pin unnecessary, and its sweep releases them.
-+ * commit: the commit retires the runs (btrfs_retire_open_stripes(), and
-+ * btrfs_retire_meta_stripes() for metadata), which makes their pins
-+ * unnecessary, and its sweep releases them.
- */
- #define RBIO_PIN_MAX 256
- #define RBIO_PIN_LOW (RBIO_PIN_MAX * 3 / 4)
-@@ -102,13 +102,6 @@
-
- #define RBIO_CACHE_SIZE 1024
-
--/*
-- * How long a parked partial write rbio may wait for merges before flushing.
-- * Sync writes (fsync- or sync-driven writeback, REQ_SYNC) have a waiter
-- * blocked on their completion, so they get a much shorter deadline: long
-- * enough for the rest of one writeback pass over the same stripe to merge
-- * in, short enough to stay invisible in fsync latency.
-- */
- /* Scan period of the park timer while anything is parked. */
- #define BTRFS_RBIO_PARK_SCAN_MS 3
-
-@@ -692,25 +685,18 @@ void btrfs_free_stripe_hash_table(struct btrfs_fs_info *info)
- }
-
- /*
-- * The frontier stripe of an open stripe run is written more than once: the
-- * run hands out its sectors in order, and each write that ends inside the
-- * stripe leaves the rest to a later write. That later write cannot pad (the
-- * earlier sectors are live) and would read them back: a read-modify-write
-- * whose neighbour sectors are not yet covered by the csum tree (their ordered
-- * extents have not finished), so whatever the devices return is folded into
-- * parity unverified. Keep the stripe cached instead, so the later write
-- * steals the pages it needs (lock_stripe_add()) and reads nothing.
-+ * A stripe its open run has not finished writing is written more than once:
-+ * each write that ends inside the stripe leaves the rest to a later write.
-+ * That later write cannot pad (the earlier sectors are live) and would read
-+ * them back, folding into parity whatever the devices return before the
-+ * csum tree covers those sectors. Keep such a stripe cached instead, so the
-+ * later write steals the pages it needs (lock_stripe_add()) and reads
-+ * nothing.
- *
-- * The stripe in question is any stripe its run has not finished writing
-- * (btrfs_stripe_run_incomplete()): the stripe holding an open run's
-- * allocation frontier, and also a stripe the frontier has already passed
-- * whose remaining writes are still in flight (writeback allocates a whole
-- * range before any of its bios complete -- most of the RMWs left by a
-- * frontier-only pin were these). The pin lasts until the frontier has left
-- * the stripe and every allocated sector of it has been written, or the run
-- * goes away; each prune re-checks it against the run. The run's next
-- * write into the stripe replaces the entry, so there are about as many
-- * pinned stripes as stripes with writes in flight.
-+ * That is the stripe holding the run's allocation frontier, and any stripe
-+ * behind it whose allocated sectors are still being written
-+ * (btrfs_stripe_run_incomplete()). Each prune re-checks the pin against
-+ * the run, and the run's next write into the stripe replaces the entry.
- */
- static bool rbio_needs_pin(const struct btrfs_raid_bio *rbio)
- {
-@@ -845,8 +831,8 @@ static void rbio_pins_low(struct btrfs_stripe_hash_table *table)
- u64 gen;
-
- /*
-- * Bounded: a sweep re-checks every pin against its run, and with the
-- * pins all live the commit is what frees them, not another sweep.
-+ * Rate limited: a sweep walks every pin, and only a commit frees live
-+ * ones.
- */
- if (!time_after(jiffies, table->pin_sweep_jiffies + RBIO_PIN_SWEEP_INTERVAL))
- return;
-@@ -881,8 +867,8 @@ void btrfs_rbio_unpin_stale(struct btrfs_fs_info *fs_info)
- /*
- * Cached and pinned rbios now, for sysfs stripe_park_stats. @live re-checks
- * each pin against its run, as the prune does: a pin whose run has finished
-- * writing the stripe is still counted in nr_pinned until the entry is
-- * evicted or cached again.
-+ * writing the stripe is still counted in nr_pinned until a sweep, an
-+ * eviction or a re-cache finds it.
- */
- void btrfs_rbio_cache_usage(struct btrfs_fs_info *fs_info, int *cached,
- int *pinned, int *live, int *live_by_class)
-@@ -1123,11 +1109,9 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- return false;
-
- /*
-- * A sync write into a nodatacow inode's private run has a waiter
-- * behind it and nothing worth waiting to merge with: in-place
-- * overwrites arrive one fsync at a time, and the plain (unparked)
-- * write path is what stock nodatacow latency looks like. Park only
-- * async writeback there.
-+ * A sync write into a nodatacow inode's private run has a waiter and
-+ * nothing to merge with (in-place overwrites arrive one fsync at a
-+ * time): park only async writeback there.
- */
- if (class == BTRFS_STRIPE_RUN_NOCOW &&
- timeout_ms == sync_timeout_ms)
-@@ -1146,15 +1130,11 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- return false;
-
- /*
-- * Park-congestion feedback. stripe_parked_now is the live count of
-- * parked rbios. When it runs ahead of the stripe_park_congestion knob
-- * (0 = off) the park machinery is not clearing its backlog -- merges
-- * are not arriving fast enough, the regime a small-file / partial-write
-- * fill produces -- so collapse this write's deadline to the short sync
-- * value (the sync-park path below flushes at it, skipping the stuck
-- * cap). Negative feedback: the shorter deadline drains the backlog, so
-- * once it falls back under the knob new writes regain the full deadline
-- * and full-stripe batching. No space-state assumption.
-+ * Park-congestion feedback: when more rbios are parked than
-+ * stripe_park_congestion allows (0 = off), merges are not arriving fast
-+ * enough to clear the backlog, so give this write the short sync
-+ * deadline (which also skips the stuck cap). Once the backlog drains
-+ * below the knob, new writes get the full deadline again.
- */
- {
- unsigned int congestion =
-@@ -1177,18 +1157,11 @@ static bool rbio_try_park(struct btrfs_raid_bio *rbio)
- rbio->park_stuck_deadline = jiffies +
- msecs_to_jiffies(timeout_ms * 10);
- /*
-- * Take a reference of our own before publishing. The moment
-- * parked_lock is dropped this rbio is visible to every flusher, and a
-- * flusher that claims it starts the RMW, which runs to completion and
-- * frees the rbio -- while we are still in this function, about to read
-- * it again in the fullness recheck below. Its other two references,
-- * the initial one and the stripe hash list's, are both consumed by
-- * that completion, so neither protects us.
-- *
-- * It has to be OUR reference, not one owned by the parked list: an
-- * unparker would inherit a list reference and drop it, and the
-- * unparker is exactly the thread racing us here. Nobody can consume
-- * this one but us.
-+ * Take a reference of our own before publishing: once parked_lock is
-+ * dropped, a flusher can unpark this rbio and run it to completion,
-+ * consuming the initial and hash-list references, while we still read
-+ * it in the fullness recheck below. It must be owned by this function,
-+ * not by the parked list, since the unparker is the thread racing us.
- */
- refcount_inc(&rbio->refs);
- list_add_tail(&rbio->parked_node, &table->parked);
-@@ -1655,7 +1628,7 @@ static void rbio_orig_end_io(struct btrfs_raid_bio *rbio, blk_status_t status)
- rbio->csum_buf = NULL;
- rbio->csum_bitmap = NULL;
-
-- /* Before the cache decision in unlock_stripe(): see cache_rbio(). */
-+ /* Before unlock_stripe()'s cache decision: see rbio_needs_pin(). */
- if (rbio->operation == BTRFS_RBIO_WRITE && status == BLK_STS_OK)
- rbio_mark_written(rbio);
-
-@@ -3517,12 +3490,11 @@ static void rbio_count_rmw_reason(struct btrfs_raid_bio *rbio)
- }
-
- /*
-- * Try to avoid the RMW read phase of a sub-stripe write by zero-filling
-- * the uncovered data sectors. Legal only where the stripe's run says the
-- * sector holds nothing anyone intends to write -- never allocated, or
-- * allocated and abandoned before its write was issued. A run that hands
-- * out more space under us is safe: the newer allocation's write serializes
-- * behind this rbio's stripe lock and lands over the zeros.
-+ * Try to avoid the RMW read phase of a sub-stripe write by zero-filling the
-+ * uncovered data sectors. Legal only where the stripe's run says a sector
-+ * is dead: never allocated, handed back, or allocated with its write still
-+ * to come. That write, like any allocation the run makes after this check,
-+ * serializes behind this rbio's stripe lock and lands over the zeros.
- */
- static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- {
-@@ -3570,14 +3542,10 @@ static bool rmw_try_pad_full(struct btrfs_raid_bio *rbio)
- covered++;
-
- /*
-- * Every data sector this rbio does not cover must be dead: never
-- * handed out, handed back, or handed out with its write still to
-- * come (the oracle's written map; that write replaces the zeros). A
-- * live uncovered sector that HAS been written holds data this write
-- * does not carry, so padding would destroy it: that is a distinct
-- * refusal from the oracle's, and it is the one that says the stripe
-- * was written before -- the stripe pin (cache_rbio()) normally hands
-- * this write those sectors from the cache, so it reads nothing.
-+ * Every uncovered sector must be dead per the run. A live uncovered
-+ * sector that was already written holds data this write does not
-+ * carry, so refuse (UNCOVERED); the stripe pin (rbio_needs_pin())
-+ * normally supplies such sectors from the cache, so nothing is read.
- */
- for (i = 0; i < nsectors; i++) {
- if (rbio->bio_paddrs[i * rbio->sector_nsteps] != INVALID_PADDR)
-@@ -3781,28 +3749,21 @@ static int rmw_block_referenced(struct btrfs_fs_info *fs_info, u64 bytenr,
- }
-
- /*
-- * Decide whether an uncovered read-modify-write is a write hole or only a
-- * cost, by looking at what is actually in the stripe.
-- *
-- * An RMW has read every column this write does not cover, so the rbio is
-- * holding the stripe's on-disk contents. Any tree block found there is
-- * about to have its parity recomputed and rewritten underneath it while its
-- * own sectors stay put -- the classic torn-stripe window. What decides
-- * whether that matters is the block's generation:
-- *
-- * - equal to the generation of the blocks this write carries, and the block
-- * belongs to the transaction now in flight. A crash loses that whole
-- * transaction anyway, so a torn stripe costs nothing that was ever
-- * committed. This is the residual stripe_meta leaves behind.
-+ * Decide whether an uncovered metadata read-modify-write is a write hole or
-+ * only a cost, from the tree blocks it read: their parity is about to be
-+ * rewritten while their own sectors stay put.
- *
-- * - older, and the stripe holds committed metadata. That is a write hole,
-- * and it means the allocator let a stripe be revisited after the
-- * transaction that filled it completed.
-+ * - Same generation as the blocks this write carries (meta_rmw_cur): the
-+ * block belongs to the running transaction, which a crash discards --
-+ * except a log tree block, which is durable once its fsync returns.
-+ * The audit does not tell log blocks apart, so it cannot see a write
-+ * hole over fsynced log blocks; keeping them out of shared stripes is
-+ * stripe_log_run's job.
-+ * - Older, and still referenced by the committed extent tree: a write hole
-+ * over committed metadata (meta_rmw_old).
- *
-- * The comparison is against this rbio's own covered blocks rather than
-- * fs_info's committed generation so that a transaction committing
-- * concurrently cannot skew the verdict: both numbers come from the same
-- * stripe at the same instant.
-+ * Comparing against this rbio's own blocks, not fs_info's committed
-+ * generation, keeps a concurrent commit from skewing the verdict.
- */
- static void audit_uncovered_rmw(struct btrfs_raid_bio *rbio)
- {
-@@ -3812,12 +3773,8 @@ static void audit_uncovered_rmw(struct btrfs_raid_bio *rbio)
- u64 write_gen = 0;
-
- /*
-- * Tree blocks only, which means metadata block groups and system
-- * block groups both: a system chunk carries no METADATA bit, but it
-- * holds the chunk tree, whose blocks have the same header and whose
-- * loss is worse than any other tree's -- without it nothing maps.
-- * A mixed block group's sectors need not be tree blocks at all, so
-- * anything carrying DATA is excluded.
-+ * Tree blocks only: metadata and system groups. A mixed group's
-+ * sectors need not hold tree blocks.
- */
- if (rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA)
- return;
-@@ -3857,14 +3814,10 @@ static void audit_uncovered_rmw(struct btrfs_raid_bio *rbio)
- continue;
- }
- /*
-- * An older header is only a write hole if the block is still
-- * referenced in the committed extent tree: a stripe reclaimed
-- * after every block in it died is claimed fully free and its
-- * dead blocks keep their headers, and a torn write over those
-- * damages nothing a reader can reach. The committed tree is
-- * the witness a degraded read after a crash would consult, so
-- * ask it (no transaction: delayed refs of the running one are
-- * not yet what a crash would see).
-+ * An older header is a write hole only if the committed extent
-+ * tree still references the block: a reclaimed stripe keeps the
-+ * headers of dead blocks, and tearing those harms nothing a
-+ * reader can reach. The commit root is what a crash would see.
- */
- {
- const int stripe_nr = i / rbio->stripe_nsectors;
-@@ -3896,20 +3849,9 @@ static void audit_uncovered_rmw(struct btrfs_raid_bio *rbio)
- }
-
- /*
-- * Report a sub-stripe write that is going out as a read-modify-write.
-- *
-- * With stripe_alloc on, data never gets here: it is either a full stripe or
-- * padded up to one. Metadata, system chunks and anything in a mixed block
-- * group are not covered by the allocator, so those still update stripes in
-- * place -- and every such write is a write hole window, where parity and
-- * data reach the disk separately and a crash between them leaves the stripe
-- * unreconstructible. The mount-time warning says the exposure exists; this
-- * says it is actually happening, and how often.
-- *
-- * Rate limited: a raid56-metadata filesystem does this continuously, and
-- * the point is to make the exposure visible, not to fill the log. Silent
-- * when stripe_alloc is off, where the entire filesystem works this way and
-- * the user has asked for nothing else.
-+ * Count and audit a metadata or system read-modify-write
-+ * (audit_uncovered_rmw()), and warn if it lands in a raid56 group that
-+ * stripe_meta does not cover. Silent when stripe_alloc is off.
- */
- static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
- {
-@@ -3919,11 +3861,7 @@ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
-
- if (!btrfs_test_opt(fs_info, STRIPE_ALLOC))
- return;
-- /*
-- * The exact complement of btrfs_is_stripe_alloc_bg(): everything
-- * that is not data-without-metadata. Note this includes system
-- * chunks, which carry no METADATA bit but are the chunk tree.
-- */
-+ /* Data groups are btrfs_is_stripe_alloc_bg()'s. */
- if ((rbio->bioc->map_type & BTRFS_BLOCK_GROUP_DATA) &&
- !(rbio->bioc->map_type & BTRFS_BLOCK_GROUP_METADATA))
- return;
-@@ -3931,12 +3869,11 @@ static void report_uncovered_rmw(struct btrfs_raid_bio *rbio)
- atomic64_inc(&fs_info->stripe_park_stats.meta_rmw);
- audit_uncovered_rmw(rbio);
- /*
-- * A raid56 metadata group under stripe_meta is covered: its
-- * read-modify-writes are partial writes inside one transaction's
-- * run, counted by the audit as meta_rmw_cur, and the audit warns
-- * by itself should one ever touch a committed block. System chunks
-- * are covered the same way. Only mixed groups are the uncovered case
-- * this message is about.
-+ * Every raid56 metadata and system group is a stripe_meta group while
-+ * stripe_alloc is on, and stripe_alloc refuses to enable on mixed
-+ * groups (btrfs_stripe_alloc_check_support()), so this warning is a
-+ * defensive check: it fires only if a tree block group that should be
-+ * covered is not.
- */
- bg = btrfs_lookup_block_group(fs_info, rbio->bioc->full_stripe_logical);
- if (bg) {
-@@ -3978,18 +3915,11 @@ static void rmw_rbio(struct btrfs_raid_bio *rbio)
- * Either full stripe write, or we have every data sector already
- * cached, can go to write path immediately.
- *
-- * Padding must win over the cache: a stolen cached rbio can carry
-- * all-uptodate pages from the stripe's PREVIOUS life -- before its
-- * extents were freed and the stripe was re-claimed -- and letting
-- * those pages skip the pad path bakes the cache's memory of dead
-- * data into fresh parity while only the bio sectors reach disk.
-- * If any on-disk column then diverges from that memory (device
-- * corruption, or simply free-space columns nobody rewrote), the
-- * stripe is latently unreconstructible. A paddable rbio instead
-- * zero-fills and WRITES every uncovered column, making the stripe
-- * self-consistent on disk regardless of what the cache remembered;
-- * the claimed-stripe invariant (a stripe write depends on nothing
-- * on disk) requires this ordering.
-+ * Try padding before trusting the cache: a cached rbio can hold pages
-+ * from the stripe's previous life, before its extents were freed and
-+ * the stripe re-claimed, and parity computed from them matches the
-+ * disk only if every uncovered column still holds that data. Padding
-+ * writes every uncovered column, so the stripe needs nothing on disk.
- */
- if (!rbio_is_full(rbio) && !rmw_try_pad_full(rbio) &&
- need_read_stripe_sectors(rbio)) {
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 781abadf24362..061f94e4a65ff 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -399,10 +399,9 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
- factor = btrfs_bg_type_to_factor(block_group->flags);
-
- /*
-- * Track the widest raid56 data full stripe as the unit of the
-- * stripe_alloc pessimistic reservation margin. Pure geometry;
-- * whether a margin is actually charged is decided per reservation
-- * by the mount option.
-+ * 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) &&
-@@ -437,23 +436,17 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
- /*
- * stripe_alloc pessimistic reservation margin.
- *
-- * A byte-counted data reservation holds no collateral against the stripe
-- * claim rule: between admission at write() time and the allocation at
-- * writeback, every transaction commit closes open stripe runs and traps
-- * their sub-stripe tails, quietly converting bytes the reservation was
-- * counting on into bytes_stripe_unusable. The reservation cannot fail at
-- * that point -- delalloc writeback gets no second chance -- so pre-pay the
-- * worst case instead: charge one full stripe width for every outstanding
-- * delalloc extent, and release it when the extent is allocated (or its
-- * delalloc range dropped). The actual allocation is optimistic -- extents
-- * pack into shared runs and usually trap nothing -- and the unused margin
-- * returns the moment the extent completes.
-+ * 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(), the same bookkeeping
-- * that sizes metadata reservations, so it stays exact across delalloc
-- * merges and splits. Charges are gated on the mount option but releases
-- * are not (and clamp at zero), so toggling stripe_alloc across a remount
-- * with dirty delalloc drains the counter instead of stranding it.
-+ * 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)
- {
-@@ -474,7 +467,7 @@ void btrfs_stripe_margin_mod(struct btrfs_inode *inode, int mod)
- /* charges and releases both live */
- } else if (mod > 0 || READ_ONCE(sinfo->bytes_stripe_margin) == 0) {
- /*
-- * Option off: never charge, and skip the lock once the
-+ * 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).
- */
-@@ -493,25 +486,14 @@ void btrfs_stripe_margin_mod(struct btrfs_inode *inode, int mod)
- }
-
- /*
-- * The preallocation twin of the delalloc margin. A preallocation has no
-- * outstanding extent to carry a margin, yet its allocation claims
-- * round_up(bytes, stripe) whole stripes: admission charges the roundup
-- * (stripe_claimable_admit()), but between the admission and the claim only
-- * the raw bytes sit in bytes_may_use, and several preallocations in flight
-- * together overran the supply behind writes admitted earlier. Hold one
-- * stripe in the margin from a successful data reservation until the
-- * caller's allocations are done. Returns the bytes held, 0 when the gate
-- * is not in effect; the caller hands it back to the release.
-- */
--/*
-- * Charge one whole stripe of collateral for a preallocation, under
-- * space_info->lock and together with the bytes it is admitted for: the
-- * caller's allocations claim round_up(bytes, stripe) whole stripes, and the
-- * hold keeps that stripe out of the supply the gate shows to everyone else
-- * until the claims land (btrfs_stripe_prealloc_release()). Charged after
-- * the admission, with the lock dropped in between, two sub-stripe
-- * preallocations could both be admitted against one stripe of supply and a
-- * buffered write admitted alongside them found no stripe at writeback.
-+ * 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 round_up(bytes, stripe) 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)
- {
-@@ -718,22 +700,15 @@ static void remove_ticket(struct btrfs_space_info *space_info,
- }
-
- /*
-- * stripe_alloc DATA admission gate. On a raid56 stripe_alloc DATA space_info a
-- * write can only be placed crash-safely in a fully-free whole stripe, so admit a
-- * data reservation only while the whole-stripe supply (bytes_stripe_claimable,
-- * which errs LOW now that the incremental positive credit is gone) covers all
-- * outstanding reservations plus this one. This refuses at reservation time --
-- * before the range becomes delalloc and later parks at writeback with nowhere to
-- * land -- and makes write() -ENOSPC coincide with statfs f_bavail==0 (both on the
-- * whole-stripe bound). Non-stripe_alloc / metadata / non-raid56 space_infos are
-- * unaffected: stripe_margin_unit is 0 unless a raid56 DATA bg exists. Caller
-- * holds space_info->lock.
-- *
-- * Phase 1 is deliberately PESSIMISTIC: it gates on claimable alone, 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 + the
-- * FLUSH_DATA ticket retry). A later phase adds bytes_stripe_open to the bound to
-- * match statfs exactly and recover that space.
-+ * 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.
- */
- static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 bytes,
- bool reloc)
-@@ -755,49 +730,30 @@ static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 byte
-
- if (reloc) {
- /*
-- * Against the whole supply, dedicated group included.
-- * Relocation prefers its dedicated group, but when
-- * that group runs dry the allocator drops the
-- * dedication and moves on to another group; confining
-- * admission to the dedicated group's claimable bytes
-- * refused relocation (ENOSPC after a handful of 16K
-- * clusters, retried every 30 seconds) while hundreds
-- * of megabytes of whole stripes sat in other groups.
-+ * Against the whole supply, dedicated group included:
-+ * when its group runs dry, relocation moves on to
-+ * another.
- */
- bytes = round_up(bytes, unit) + unit;
- } else {
- /* ...and that group is out of reach for everyone else */
- supply -= min(supply, dedicated);
- /*
-- * An allocation of @bytes that opens a run claims
-- * round_up(bytes, unit) whole stripes. A delalloc write's
-- * margin (below) covers that for itself, but a
-- * preallocation holds no margin -- it has no outstanding
-- * extent -- and was admitted for its byte size alone, so
-- * each fallocate() short of a stripe took up to a stripe
-- * more than the gate had charged, out of the supply behind
-- * writes already admitted: at the fill edge those writes
-- * then found no stripe and were dropped. Charge the
-- * roundup. (The excess is not held past admission; a
-- * preallocation allocates in the same call.)
-+ * An allocation that opens a run claims
-+ * round_up(bytes, unit). A delalloc write's margin
-+ * covers that; a preallocation has no margin of its
-+ * own until stripe_hold_locked(), so charge the
-+ * roundup here.
- */
- bytes = round_up(bytes, unit);
- }
- /*
-- * Every outstanding data extent holds a whole-stripe margin
-- * (bytes_stripe_margin) as collateral against the commit that
-- * closes its open run and traps the tail.
-- * btrfs_space_info_used() charges that margin against
-- * total_bytes, but what an admitted write actually draws on is
-- * the whole-stripe supply: left out of this bound, the stripes
-- * behind bytes admitted earlier are lost at the next commit, and
-- * a write that passed admission finds no stripe at writeback
-- * (ENOSPC despite reservation margin, data dropped). The margin
-- * is owed to the writers already admitted, so every later
-- * admission has to respect it -- relocation included: admitted
-- * without it at the fill edge, relocation consumed the whole
-- * stripes that small writes' claims then needed, and those
-- * writes were dropped in bursts that tracked the relocations.
-+ * 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;
-@@ -1349,20 +1305,14 @@ static bool steal_from_global_rsv(struct btrfs_space_info *space_info,
- return false;
-
- /*
-- * stripe_meta: the global reserve is refilled by fiat at every
-- * commit, so its bytes are only as real as the whole stripes behind
-- * them. Once the claimable supply is down to the relocation reserve,
-- * a stolen reservation admits a transaction that consumes fresh
-- * stripes through COW while everything it frees comes back trapped
-- * (an unlink of an inline file returns nothing at all), until a tree
-- * block finds no stripe and the commit aborts. Refuse the steal:
-- * -ENOSPC from an unlink is recoverable, an abort is not, and the
-- * reserve stays with the background relocation that will make room.
-- */
-- /*
-- * Except for the mount-time orphan cleanup: its evictions are bounded
-- * by the orphans on disk, and refusing them fails the mount, which
-- * leaves no way to run the relocation the reserve is kept for.
-+ * stripe_meta: the global reserve is refilled at every commit, but its
-+ * bytes are only as real as the whole stripes behind them. Once the
-+ * claimable supply is down to the relocation reserve, a stolen
-+ * reservation lets a transaction consume fresh stripes through COW
-+ * while its frees come back trapped, until a tree block finds no stripe
-+ * and the commit aborts. Refuse the steal: -ENOSPC is recoverable and
-+ * an abort is not. Mount-time orphan cleanup is exempt: it is bounded,
-+ * and failing it fails the mount, leaving no way to relocate.
- */
- if (space_info->bytes_stripe_reserve && !ticket->mount_cleanup &&
- space_info->bytes_stripe_claimable <
-@@ -2247,21 +2197,11 @@ int btrfs_reserve_metadata_bytes(struct btrfs_space_info *space_info,
- return ret;
- }
-
--/*
-- * Try to reserve data bytes for an allocation.
-- *
-- * @space_info: the space_info we're allocating for
-- * @bytes: number of bytes we need
-- * @flush: how we are allowed to flush
-- *
-- * 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.
-- */
- /*
- * 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 once. Returns true if a chunk was allocated.
-+ * caller retry. Returns true if a chunk was allocated.
- */
- static bool reloc_alloc_data_chunk(struct btrfs_space_info *space_info)
- {
-@@ -2279,6 +2219,16 @@ static bool reloc_alloc_data_chunk(struct btrfs_space_info *space_info)
- return ret > 0;
- }
-
-+/*
-+ * Try to reserve data bytes for an allocation.
-+ *
-+ * @space_info: the space_info we're allocating for
-+ * @bytes: number of bytes we need
-+ * @flush: how we are allowed to flush
-+ *
-+ * 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.
-+ */
- int btrfs_reserve_data_bytes(struct btrfs_space_info *space_info, u64 bytes,
- enum btrfs_reserve_flush_enum flush)
- {
-@@ -2311,17 +2261,12 @@ int btrfs_reserve_data_bytes_held(struct btrfs_space_info *space_info, u64 bytes
- *held = 0;
- ret = __reserve_bytes(space_info, bytes, flush, held);
- /*
-- * Not waiting is right at the stripe_alloc fill edge, where the space
-- * relocation would wait for is what relocation itself frees. It is not
-- * a reason to fail while there is unallocated space for a new chunk:
-- * that made balance fail with ENOSPC on any filesystem whose data chunks
-- * happened to be full.
-- *
-- * One chunk is not always enough: relocation reserves a whole cluster
-- * (up to a full 1 GiB block group of extents) at once, and a new chunk
-- * can be smaller than that -- during a device remove the chunk size cap
-- * follows the shrunk filesystem. Keep allocating while it succeeds;
-- * each success consumes unallocated space, so this ends.
-+ * 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))
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 61f942e0141d0..3667af16afb33 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -158,14 +158,12 @@ struct btrfs_space_info {
- u64 bytes_readonly; /* total bytes that are read only */
- u64 bytes_zone_unusable; /* total bytes that are unusable until
- resetting the device zone */
-- u64 bytes_stripe_unusable; /* total free bytes trapped in partially
-- filled stripes of stripe_alloc block
-- groups; free but not allocatable until
-- the whole stripe frees. Counted in
-- btrfs_space_info_used() so reservations
-- cannot admit writes against it, and
-- subtracted in statfs (from a different
-- base -- the free space cache walk). */
-+ u64 bytes_stripe_unusable; /* free bytes stripe_alloc and
-+ stripe_meta groups cannot allocate:
-+ partially filled stripes, and whole
-+ stripes stranded behind live runs.
-+ Counted as used, and subtracted in
-+ statfs. */
- u64 bytes_stripe_stranded; /* the part of bytes_stripe_unusable that
- is whole stripes stranded behind live
- stripe runs (see the block group's
-@@ -188,33 +186,20 @@ 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.
-- On a stripe_meta METADATA space_info
-- it is instead set at each commit scan
-- to two transactions' worth of whole
-- stripe claims: every group can claim
-- a fresh stripe per transaction for a
-- tree block admitted in bytes. */
-+ u64 bytes_stripe_margin; /* data: one full stripe per
-+ outstanding delalloc extent or
-+ preallocation in flight, pre-paying
-+ the sub-stripe tail a commit can trap
-+ before writeback (see
-+ btrfs_stripe_margin_mod()).
-+ stripe_meta metadata: two
-+ transactions' worth of stripe claims,
-+ set at each commit scan. */
- u64 bytes_stripe_reserve; /* stripe_meta: whole stripes held back
-- from every metadata reservation except
-- the relocation task's, so that any one
-- metadata group's live tree blocks can
-- be moved into whole stripes elsewhere.
-- COW frees trap rather than free
-- stripes, so without it the space_info
-- settles half used, half trapped, with
-- nothing left for reclaim to move
-- into. Counted in
-- btrfs_space_info_used(); recomputed
-+ for relocation (and the transaction
-+ machinery's own reservations), so a
-+ trapped metadata group can always be
-+ moved. Counted as used; recomputed
- at each commit scan. */
-
- u64 max_extent_size; /* This will hold the maximum extent size of
-diff --git a/fs/btrfs/super.c b/fs/btrfs/super.c
-index cc88140377e74..bce3a12032b6a 100644
---- a/fs/btrfs/super.c
-+++ b/fs/btrfs/super.c
-@@ -944,13 +944,8 @@ static int get_default_subvol_objectid(struct btrfs_fs_info *fs_info, u64 *objec
- }
-
- /*
-- * State whether stripe-exclusive allocation is on.
-- *
-- * Nothing said so before. The btrfs.stripe_alloc property applies while the
-- * root directory's inode is read, and no line went to the log, so silence
-- * meant "off" and "on" equally well and the only way to answer the question
-- * was to look at a live filesystem -- no use at all when reading a log after a
-- * crash. Say it once at mount.
-+ * Log once at mount whether stripe-exclusive allocation is on: the property
-+ * is applied silently while the root directory's inode is read.
- */
- static void btrfs_emit_stripe_alloc_state(struct btrfs_fs_info *info)
- {
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 486af39185555..fe6bbffb1b3be 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -521,11 +521,6 @@ static const struct attribute *discard_attrs[] = {
-
- #ifdef CONFIG_BTRFS_DEBUG
-
--/*
-- * Per-filesystem runtime debugging exported via sysfs.
-- *
-- * Path: /sys/fs/btrfs/UUID/debug/
-- */
- /*
- * Audit every data read-modify-write against the committed extent tree
- * (raid56.c): a tree search per RMW, so off by default.
-@@ -587,6 +582,11 @@ static ssize_t btrfs_stripe_rmw_audit_stats_show(struct kobject *kobj,
- BTRFS_ATTR(debug_mount, stripe_rmw_audit_stats,
- btrfs_stripe_rmw_audit_stats_show);
-
-+/*
-+ * Per-filesystem runtime debugging exported via sysfs.
-+ *
-+ * Path: /sys/fs/btrfs/UUID/debug/
-+ */
- static const struct attribute *btrfs_debug_mount_attrs[] = {
- BTRFS_ATTR_PTR(debug_mount, stripe_rmw_audit),
- BTRFS_ATTR_PTR(debug_mount, stripe_rmw_audit_stats),
-@@ -843,10 +843,9 @@ static ssize_t btrfs_force_chunk_alloc_store(struct kobject *kobj,
- BTRFS_ATTR_W(space_info, force_chunk_alloc, btrfs_force_chunk_alloc_store);
-
- /*
-- * Force a full recompute of stripe_unusable across every armed stripe_alloc
-- * block group, ignoring the per-group dirty flag. If the reported value rises
-- * to match a fresh umount/mount scan, groups were being missed by dirty
-- * marking; if it stays put, the live cache genuinely differs from a reload.
-+ * Recompute stripe_unusable for every armed group now, ignoring the
-+ * per-group dirty flags, to check the incremental accounting against a
-+ * full scan.
- */
- static ssize_t btrfs_stripe_unusable_rescan_store(struct kobject *kobj,
- struct kobj_attribute *a,
-@@ -1352,9 +1351,8 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
-
- /*
-- * Park deadlines, ms. Writable so the constants can be swept against a
-- * workload rather than rebuilt per data point; 0 disables parking for that
-- * class. See rbio_try_park().
-+ * Park deadlines, ms; 0 disables parking for that class. See
-+ * rbio_try_park().
- */
- #define BTRFS_PARK_TIMEOUT_ATTR(_name, _field) \
- static ssize_t btrfs_##_name##_show(struct kobject *kobj, \
-@@ -1385,10 +1383,9 @@ BTRFS_ATTR_RW(, _name, btrfs_##_name##_show, btrfs_##_name##_store)
- BTRFS_PARK_TIMEOUT_ATTR(stripe_park_timeout_ms, stripe_park_timeout_ms);
-
- /*
-- * Whether each log commit gets its own private metadata stripe run. Off puts
-- * log tree blocks back in the transaction's shared metadata runs, reopening
-- * the log-tree fsync write hole, so the change can be measured against itself
-- * on one boot.
-+ * Whether each log commit gets its own private metadata stripe run. 0 puts
-+ * log tree blocks back in the transaction's shared metadata runs, which
-+ * reopens the log-tree fsync write hole.
- */
- static ssize_t btrfs_stripe_log_run_show(struct kobject *kobj,
- struct kobj_attribute *a, char *buf)
---
-2.47.3
-
+++ /dev/null
-From 6fa8a30f00c91aba4e3779ea7fb30bc38546a73f Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 10:20:03 -0400
-Subject: [RFC PATCH 106/116] btrfs: stripe_meta: keep waiting for metadata
- runs that do not drain at commit
-To: linux-btrfs@vger.kernel.org
-
-btrfs_retire_meta_stripes() waits, after tree writeback, for the
-committed transaction's metadata runs to drain. It gave up after 60
-seconds, warned, and left the run in place. A run that does not drain
-has a tree block that was freed without reporting to its run, which is an
-accounting bug. Carrying on hid it behind later symptoms: the run's
-stripes stay unclaimable, the group keeps its reference, and making the
-group read-only or removing it trips over the leftover run.
-
-Keep waiting, so the bug shows up as a hung commit where it happens.
-After 60 seconds, warn once and dump the group's runs to say which one.
-End the wait only if the filesystem goes into error, whose wake-up
-already reaches these waiters.
-
-Fixes: 51fcf2348a33f ("btrfs: stripe_meta: allocate tree blocks by whole stripes")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 21 +++++++++++++--------
- 1 file changed, 13 insertions(+), 8 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 96f5daaafd4ec..b9206ccce5fb9 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -3272,6 +3272,7 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
- while (!list_empty(&retire_list)) {
- struct btrfs_open_stripe_run *run;
- bool again = true;
-+ bool warned = false;
-
- bg = list_first_entry(&retire_list, struct btrfs_block_group,
- open_stripe_retire_list);
-@@ -3321,18 +3322,22 @@ void btrfs_retire_meta_stripes(struct btrfs_fs_info *fs_info, u64 transid)
-
- /*
- * Every tree block is on disk, so end_bbio_meta_write() has
-- * reported all of them and this normally does not wait. The
-- * timeout guards against a path that frees a tree block
-- * without reporting it to its run: warn and keep the run,
-- * which costs space, rather than hang the commit.
-+ * reported all of them and this normally does not wait. A run
-+ * that does not drain has a tree block that was freed without
-+ * reporting to its run, an accounting bug: say which runs
-+ * once, and keep waiting. Only a filesystem error ends the
-+ * wait early.
- */
-- if (!wait_var_event_timeout(&bg->open_stripe_runs,
-- !bg_has_undrained_meta_runs(bg, transid),
-- 60 * HZ)) {
-+ while (!wait_var_event_timeout(&bg->open_stripe_runs,
-+ !bg_has_undrained_meta_runs(bg, transid) ||
-+ BTRFS_FS_ERROR(fs_info), 60 * HZ)) {
-+ if (warned)
-+ continue;
- btrfs_warn(fs_info,
--"metadata stripe runs in block group %llu did not drain; a tree block was freed without reporting to its run",
-+"metadata stripe runs in block group %llu do not drain; a tree block was freed without reporting to its run",
- bg->start);
- btrfs_dump_open_stripe_runs(bg);
-+ warned = true;
- }
-
- /* Drained and no longer needed for padding or merging. */
---
-2.47.3
-
+++ /dev/null
-From ea5b896d151b75329a16fb3d1019842f458ab0d7 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 11:19:42 -0400
-Subject: [RFC PATCH 107/116] btrfs: stripe_alloc: remove pad refusal reasons
- that no longer exist
-To: linux-btrfs@vger.kernel.org
-
-BTRFS_STRIPE_PAD_LIVE and BTRFS_STRIPE_PAD_UNALLOCATED are left over from
-when padding decided by the run's frontier. The pad oracle now uses the
-run's live and written maps, and nothing assigns either reason, so the
-data_rmw_live and data_rmw_unallocated stats are always 0, as are
-pad_decline_live and pad_decline_unallocated, which nothing increments.
-
-Remove the two reasons and the four stats, size data_rmw_by[] and the
-audit's hole_by[] for the three reasons left plus "not tried", and index
-them by name in sysfs.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.h | 2 --
- fs/btrfs/fs.h | 17 +++++------------
- fs/btrfs/raid56.c | 2 ++
- fs/btrfs/sysfs.c | 26 ++++++++------------------
- 4 files changed, 15 insertions(+), 32 deletions(-)
-
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 7fc544e4fe208..3695e084e6aba 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -536,8 +536,6 @@ bool btrfs_stripe_run_range_usable(struct btrfs_block_group *bg,
- enum btrfs_stripe_pad_reason {
- BTRFS_STRIPE_PAD_OK = 0,
- BTRFS_STRIPE_PAD_NO_RUN, /* no open run covers the stripe */
-- BTRFS_STRIPE_PAD_LIVE, /* frontier past the stripe: all allocated */
-- BTRFS_STRIPE_PAD_UNALLOCATED, /* frontier has not reached the stripe */
- BTRFS_STRIPE_PAD_UNCOVERED, /* a sector below the frontier is not covered */
- BTRFS_STRIPE_PAD_NR_REASONS,
- };
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index aec2ff64f0704..c277dcc65bd14 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -879,15 +879,8 @@ struct btrfs_fs_info {
- * parked ones.
- */
- atomic64_t data_rmw;
-- /*
-- * Why padding declined: live (the rest of the stripe is
-- * allocated and not yet written), no_run (no open run covers
-- * the stripe), unallocated (the run's frontier has not reached
-- * the stripe).
-- */
-- atomic64_t pad_decline_live;
-+ /* Why padding declined: no open run covers the stripe. */
- atomic64_t pad_decline_no_run;
-- atomic64_t pad_decline_unallocated;
- /*
- * Oracle allowed padding, but a sector below the frontier is
- * not covered by this write: another allocation shares the
-@@ -896,8 +889,8 @@ struct btrfs_fs_info {
- atomic64_t pad_decline_uncovered;
- /*
- * data_rmw split by why padding declined for the rbio that
-- * did it: 0..4 are enum btrfs_stripe_pad_reason (0: the pad
-- * oracle agreed but the data page allocation failed), 5: not
-+ * did it: 0..2 are enum btrfs_stripe_pad_reason (0: the pad
-+ * oracle agreed but the data page allocation failed), 3: not
- * tried (stripe_alloc off, or no memory for the bitmap).
- * data_rmw_norun splits the NO_RUN entry by enum
- * btrfs_stripe_pad_norun; norun_ro counts those in a
-@@ -905,7 +898,7 @@ struct btrfs_fs_info {
- * written by the data reloc inode outside the open run's
- * frontier, disjoint from data_rmw_by[UNCOVERED].
- */
-- atomic64_t data_rmw_by[6];
-+ atomic64_t data_rmw_by[4];
- atomic64_t data_rmw_norun[6];
- atomic64_t data_rmw_norun_ro;
- atomic64_t data_rmw_reloc_writer;
-@@ -962,7 +955,7 @@ struct btrfs_fs_info {
- bool stripe_rmw_audit;
- struct {
- atomic64_t audited;
-- atomic64_t hole_by[6];
-+ atomic64_t hole_by[4];
- atomic64_t hole_sectors;
- atomic64_t hole_reloc_only;
- atomic64_t hole_reloc_sectors;
-diff --git a/fs/btrfs/raid56.c b/fs/btrfs/raid56.c
-index 60e636821c40a..601cb82895b57 100644
---- a/fs/btrfs/raid56.c
-+++ b/fs/btrfs/raid56.c
-@@ -3141,6 +3141,8 @@ static void rbio_record_pad(struct btrfs_raid_bio *rbio,
-
- static_assert(BTRFS_STRIPE_PAD_NR_REASONS + 1 ==
- ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_park_stats.data_rmw_by));
-+static_assert(BTRFS_STRIPE_PAD_NR_REASONS + 1 ==
-+ ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_rmw_audit_stats.hole_by));
- static_assert(BTRFS_STRIPE_NORUN_NR ==
- ARRAY_SIZE(((struct btrfs_fs_info *)0)->stripe_park_stats.data_rmw_norun));
-
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index fe6bbffb1b3be..512b556e36326 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -567,12 +567,10 @@ static ssize_t btrfs_stripe_rmw_audit_stats_show(struct kobject *kobj,
- "data_rmw_reloc_writer_foreign %lld\n"
- "data_rmw_audit_err %lld\n",
- atomic64_read(&fs_info->stripe_rmw_audit_stats.audited),
-- atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[1]),
-- atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[4]),
-- atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[0]) +
-- atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[2]) +
-- atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[3]) +
-- atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[5]),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[BTRFS_STRIPE_PAD_NO_RUN]),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[BTRFS_STRIPE_PAD_UNCOVERED]),
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[BTRFS_STRIPE_PAD_OK]) +
-+ atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_by[BTRFS_STRIPE_PAD_NR_REASONS]),
- atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_sectors),
- atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_reloc_only),
- atomic64_read(&fs_info->stripe_rmw_audit_stats.hole_reloc_sectors),
-@@ -1210,14 +1208,10 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- "padded_unwritten %lld\n"
- "rmw_reads %lld\n"
- "data_rmw %lld\n"
-- "pad_decline_live %lld\n"
- "pad_decline_no_run %lld\n"
-- "pad_decline_unallocated %lld\n"
- "pad_decline_uncovered %lld\n"
- "data_rmw_pad_ok_nomem %lld\n"
- "data_rmw_no_run %lld\n"
-- "data_rmw_live %lld\n"
-- "data_rmw_unallocated %lld\n"
- "data_rmw_uncovered %lld\n"
- "data_rmw_not_tried %lld\n"
- "data_rmw_norun_no_bgs %lld\n"
-@@ -1258,16 +1252,12 @@ static ssize_t btrfs_stripe_park_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_park_stats.padded_unwritten),
- atomic64_read(&fs_info->stripe_park_stats.rmw_reads),
- atomic64_read(&fs_info->stripe_park_stats.data_rmw),
-- atomic64_read(&fs_info->stripe_park_stats.pad_decline_live),
- atomic64_read(&fs_info->stripe_park_stats.pad_decline_no_run),
-- atomic64_read(&fs_info->stripe_park_stats.pad_decline_unallocated),
- atomic64_read(&fs_info->stripe_park_stats.pad_decline_uncovered),
-- atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[0]),
-- atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[1]),
-- atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[2]),
-- atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[3]),
-- atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[4]),
-- atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[5]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[BTRFS_STRIPE_PAD_OK]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[BTRFS_STRIPE_PAD_NO_RUN]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[BTRFS_STRIPE_PAD_UNCOVERED]),
-+ atomic64_read(&fs_info->stripe_park_stats.data_rmw_by[BTRFS_STRIPE_PAD_NR_REASONS]),
- atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[0]),
- atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[1]),
- atomic64_read(&fs_info->stripe_park_stats.data_rmw_norun[2]),
---
-2.47.3
-
+++ /dev/null
-From ba2e08f16cdea789a532d30c88646e3e4f409653 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Fri, 9 Oct 2026 19:13:11 -0400
-Subject: [RFC PATCH 108/116] btrfs: stripe_alloc: count and log ordered
- extents that end with sectors unwritten
-To: linux-btrfs@vger.kernel.org
-
-When an ordered extent reports to its stripe run, sectors it allocated
-that no write reached are marked written so nothing waits for them (a
-failed write, truncated folios, a short direct write, error teardown).
-Whether any of these paths can still leave a waiter stuck in practice is
-not known: the log settle that motivated the marking seals and frees a
-shared LOG run before it would wait.
-
-Count such extents and their unwritten bytes in stripe_run_stats
-(unwritten_on_end, unwritten_on_end_bytes) and log each one, rate
-limited, with the extent's identity, truncated length and flags, to see
-which paths produce them.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 19 +++++++++++++++----
- fs/btrfs/block-group.h | 4 ++--
- fs/btrfs/fs.h | 3 +++
- fs/btrfs/ordered-data.c | 24 ++++++++++++++++++++++--
- fs/btrfs/sysfs.c | 8 ++++++--
- 5 files changed, 48 insertions(+), 10 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index b9206ccce5fb9..8b1d9e34e6714 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -2947,25 +2947,36 @@ struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
- * write, error teardown) will not be written now. Marking it keeps a log
- * settle from waiting for it forever, and a written sector is never padded,
- * so a later partial write to the stripe reads it instead of zeroing it.
-+ *
-+ * Returns the number of allocated sectors that had not been written.
- */
--void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
-- u64 start, u64 num_bytes)
-+u32 btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
-+ u64 start, u64 num_bytes)
- {
- struct btrfs_block_group *bg = run->bg;
- const u32 bits = bg->fs_info->sectorsize_bits;
- unsigned long flags;
- u64 s = start;
- u64 l = num_bytes;
-+ u32 unwritten = 0;
-
- spin_lock_irqsave(&bg->stripe_run_lock, flags);
- ASSERT(run->inflight_bytes >= num_bytes);
- run->inflight_bytes -= num_bytes;
-- if (run_written_range(run, &s, &l))
-- bitmap_set(run->written, (s - run->start) >> bits, l >> bits);
-+ if (run_written_range(run, &s, &l)) {
-+ const u32 first = (s - run->start) >> bits;
-+ const u32 last = first + (l >> bits);
-+
-+ for (u32 i = first; i < last; i++)
-+ if (test_bit(i, run->live) && !test_bit(i, run->written))
-+ unwritten++;
-+ bitmap_set(run->written, first, l >> bits);
-+ }
- /* Under the lock: the run and the group may be gone after it. */
- wake_up_var(&bg->open_stripe_runs);
- open_stripe_run_drain_reported(bg, run);
- spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ return unwritten;
- }
-
- /*
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 3695e084e6aba..d10e4fe15b35a 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -498,8 +498,8 @@ 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,
- u64 num_bytes);
--void btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
-- u64 start, u64 num_bytes);
-+u32 btrfs_open_stripe_write_done_run(struct btrfs_open_stripe_run *run,
-+ u64 start, u64 num_bytes);
- void btrfs_open_stripe_write_done_bytenr(struct btrfs_fs_info *fs_info,
- u64 start, u64 num_bytes);
- struct btrfs_open_stripe_run *btrfs_get_open_stripe_run(
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index c277dcc65bd14..d4688bb524eaf 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -1014,6 +1014,9 @@ struct btrfs_fs_info {
- /* shared runs: frontier stripes sealed at log commit, bytes skipped */
- atomic64_t log_seals;
- atomic64_t log_seal_bytes;
-+ /* ordered extents that ended with allocated sectors unwritten */
-+ atomic64_t unwritten_on_end;
-+ atomic64_t unwritten_on_end_bytes;
- } stripe_run_stats;
- /* BTRFS_STRIPE_RMW_* masks; see btrfs_stripe_allow_rmw(). */
- u32 stripe_rmw_prop;
-diff --git a/fs/btrfs/ordered-data.c b/fs/btrfs/ordered-data.c
-index 5bd8ff43f9d52..cb32eff2fddc0 100644
---- a/fs/btrfs/ordered-data.c
-+++ b/fs/btrfs/ordered-data.c
-@@ -410,12 +410,32 @@ static void finish_ordered_fn(struct btrfs_work *work)
- static void btrfs_ordered_stripe_write_done(struct btrfs_ordered_extent *ordered)
- {
- struct btrfs_open_stripe_run *run = ordered->stripe_run;
-+ struct btrfs_fs_info *fs_info = ordered->inode->root->fs_info;
-+ u32 unwritten;
-
- if (!run)
- return;
- ordered->stripe_run = NULL;
-- btrfs_open_stripe_write_done_run(run, ordered->disk_bytenr,
-- ordered->disk_num_bytes);
-+ unwritten = btrfs_open_stripe_write_done_run(run, ordered->disk_bytenr,
-+ ordered->disk_num_bytes);
-+ if (likely(!unwritten))
-+ return;
-+ /*
-+ * Sectors this extent allocated that no write reached: a failed write,
-+ * truncated folios, a short direct write or error teardown. They are
-+ * now marked written so nothing waits for them. Counted and logged to
-+ * find out which paths produce them in practice.
-+ */
-+ atomic64_inc(&fs_info->stripe_run_stats.unwritten_on_end);
-+ atomic64_add((u64)unwritten << fs_info->sectorsize_bits,
-+ &fs_info->stripe_run_stats.unwritten_on_end_bytes);
-+ btrfs_info_rl(fs_info,
-+"stripe_alloc: ordered extent ended with %u unwritten sectors: root %llu ino %llu file_offset %llu len %llu disk_bytenr %llu disk_num_bytes %llu truncated_len %lld flags 0x%lx",
-+ unwritten, btrfs_root_id(ordered->inode->root),
-+ btrfs_ino(ordered->inode), ordered->file_offset,
-+ ordered->num_bytes, ordered->disk_bytenr,
-+ ordered->disk_num_bytes, (s64)ordered->truncated_len,
-+ ordered->flags);
- }
-
- static bool can_finish_ordered_extent(struct btrfs_ordered_extent *ordered,
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index 512b556e36326..d3231cc95f6dc 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1318,7 +1318,9 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- "log_carry_ranges %lld\n"
- "log_carry_bytes %lld\n"
- "log_seals %lld\n"
-- "log_seal_bytes %lld\n",
-+ "log_seal_bytes %lld\n"
-+ "unwritten_on_end %lld\n"
-+ "unwritten_on_end_bytes %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),
-@@ -1336,7 +1338,9 @@ static ssize_t btrfs_stripe_run_stats_show(struct kobject *kobj,
- atomic64_read(&fs_info->stripe_run_stats.log_carry_ranges),
- atomic64_read(&fs_info->stripe_run_stats.log_carry_bytes),
- atomic64_read(&fs_info->stripe_run_stats.log_seals),
-- atomic64_read(&fs_info->stripe_run_stats.log_seal_bytes));
-+ atomic64_read(&fs_info->stripe_run_stats.log_seal_bytes),
-+ atomic64_read(&fs_info->stripe_run_stats.unwritten_on_end),
-+ atomic64_read(&fs_info->stripe_run_stats.unwritten_on_end_bytes));
- }
- BTRFS_ATTR(, stripe_run_stats, btrfs_stripe_run_stats_show);
-
---
-2.47.3
-
+++ /dev/null
-From 9254f34ffae08be338d71b0b1f244404eb5b99a6 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 10 Oct 2026 00:19:18 -0400
-Subject: [RFC PATCH 109/116] btrfs: stripe_alloc: skip RAID5/6 groups that are
- mapped as RAID1/RAID1C3
-To: linux-btrfs@vger.kernel.org
-
-Since commit 49ba3a3c0d67 ("btrfs: disguise single-data-RAID56 as
-RAID1/RAID1C3"), a RAID5 chunk with one data stripe (two devices) or a
-RAID6 chunk with one (three devices) keeps its RAID5/6 type on disk, in
-the chunk map's on_disk_type and in the block group's flags, but is
-mapped as RAID1/RAID1C3. Such chunks appear when only two or three
-devices have unallocated space, e.g. on devices of unequal size.
-
-stripe_alloc and stripe_meta decide by the block group's flags, so they
-kept opening stripe runs in these groups. Their IO goes down the
-mirrored path and never reaches raid56, so no write ever marked the
-runs' sectors written: every ordered extent there ended with all its
-sectors unwritten, and the groups paid stripe_alloc's trapped-space cost
-for a write hole they do not have.
-
-Record at block group creation whether the chunk map's type differs from
-its on_disk_type in this way (BLOCK_GROUP_FLAG_RAID56_MIRRORED), and
-leave such groups to the normal allocator.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 2 ++
- fs/btrfs/block-group.h | 6 ++++++
- fs/btrfs/extent-tree.c | 13 ++++++++-----
- fs/btrfs/volumes.c | 21 +++++++++++++++++++++
- fs/btrfs/volumes.h | 1 +
- 5 files changed, 38 insertions(+), 5 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 8b1d9e34e6714..48c8d0869edcf 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -5969,6 +5969,8 @@ static struct btrfs_block_group *btrfs_create_block_group(
-
- cache->fs_info = fs_info;
- cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
-+ if (btrfs_chunk_raid56_mirrored(fs_info, start))
-+ set_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &cache->runtime_flags);
- cache->max_claimable_run = (u64)-1;
-
- cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index d10e4fe15b35a..678f39315edb5 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -163,6 +163,12 @@ enum btrfs_block_group_flags {
- * write-hole debug check skips such groups (sticky, debug only).
- */
- BLOCK_GROUP_FLAG_STRIPE_NOCOW_USED,
-+ /*
-+ * A RAID5/6 group with a single data stripe, which is mapped as
-+ * RAID1/RAID1C3 (its chunk map's type differs from on_disk_type). Its
-+ * IO never reaches raid56, so stripe_alloc and stripe_meta skip it.
-+ */
-+ BLOCK_GROUP_FLAG_RAID56_MIRRORED,
- };
-
- enum btrfs_caching_type {
-diff --git a/fs/btrfs/extent-tree.c b/fs/btrfs/extent-tree.c
-index 4178d2541b8ae..379eee5b4aab4 100644
---- a/fs/btrfs/extent-tree.c
-+++ b/fs/btrfs/extent-tree.c
-@@ -4214,14 +4214,16 @@ static int do_allocation_zoned(struct btrfs_block_group *block_group,
- * closes the raid56 write hole; see "Open stripe runs" in block-group.c.
- * Metadata is covered by btrfs_is_stripe_meta_bg(). Mixed groups are
- * excluded: stripe_alloc refuses to enable on them
-- * (btrfs_stripe_alloc_check_support()).
-+ * (btrfs_stripe_alloc_check_support()). So are groups with a single data
-+ * stripe: they are mapped as RAID1/RAID1C3 and have no write hole.
- */
- bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
- {
- return btrfs_test_opt(bg->fs_info, STRIPE_ALLOC) &&
- (bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
- !(bg->flags & BTRFS_BLOCK_GROUP_METADATA) &&
-- (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK);
-+ (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
-+ !test_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &bg->runtime_flags);
- }
-
- /*
-@@ -4230,8 +4232,8 @@ bool btrfs_is_stripe_alloc_bg(const struct btrfs_block_group *bg)
- * The same rule as data: only fully free stripes are claimed, and the
- * partial stripe left at the end of a commit is padded rather than
- * revisited, so no tree block lands in a stripe holding committed blocks.
-- * It applies to every raid56 metadata and system group while stripe_alloc
-- * is on. The costs are a stranded stripe tail per commit, and an
-+ * It applies to every raid56 metadata and system group with more than one
-+ * data stripe while stripe_alloc is on. The costs are a stranded stripe tail per commit, and an
- * allocation failure aborts the transaction instead of failing one write.
- * System chunks carry no METADATA bit but hold the chunk tree, so they are
- * named explicitly.
-@@ -4242,7 +4244,8 @@ bool btrfs_is_stripe_meta_bg(const struct btrfs_block_group *bg)
- (bg->flags & (BTRFS_BLOCK_GROUP_METADATA |
- BTRFS_BLOCK_GROUP_SYSTEM)) &&
- !(bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
-- (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK);
-+ (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
-+ !test_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &bg->runtime_flags);
- }
-
- static int do_allocation_stripe(struct btrfs_block_group *block_group,
-diff --git a/fs/btrfs/volumes.c b/fs/btrfs/volumes.c
-index 6e7419b87ddcd..9f689c4c9d7f8 100644
---- a/fs/btrfs/volumes.c
-+++ b/fs/btrfs/volumes.c
-@@ -6617,6 +6617,27 @@ unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
- return len;
- }
-
-+/*
-+ * Is the chunk at @logical a RAID5/6 chunk with a single data stripe, mapped
-+ * as RAID1/RAID1C3 (see set_real_chunk_type())?
-+ */
-+bool btrfs_chunk_raid56_mirrored(struct btrfs_fs_info *fs_info, u64 logical)
-+{
-+ struct btrfs_chunk_map *map;
-+ bool ret = false;
-+
-+ if (!btrfs_fs_incompat(fs_info, RAID56))
-+ return false;
-+
-+ map = btrfs_get_chunk_map(fs_info, logical, fs_info->sectorsize);
-+ if (!WARN_ON(IS_ERR(map))) {
-+ ret = (map->on_disk_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
-+ !(map->type & BTRFS_BLOCK_GROUP_RAID56_MASK);
-+ btrfs_free_chunk_map(map);
-+ }
-+ return ret;
-+}
-+
- #ifdef CONFIG_BTRFS_EXPERIMENTAL
- static int btrfs_read_preferred(struct btrfs_chunk_map *map, int first, int num_stripes)
- {
-diff --git a/fs/btrfs/volumes.h b/fs/btrfs/volumes.h
-index 982d88264ca5a..f57b73ae996bc 100644
---- a/fs/btrfs/volumes.h
-+++ b/fs/btrfs/volumes.h
-@@ -805,6 +805,7 @@ void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev,
- void btrfs_free_device(struct btrfs_device *device);
- unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
- u64 logical);
-+bool btrfs_chunk_raid56_mirrored(struct btrfs_fs_info *fs_info, u64 logical);
- u64 btrfs_calc_dev_extent_size(const struct btrfs_chunk_map *map);
- int btrfs_nr_parity_stripes(u64 type);
- int btrfs_chunk_alloc_add_chunk_item(struct btrfs_trans_handle *trans,
---
-2.47.3
-
+++ /dev/null
-From 116fcc38d534f50f53f3ae98ee8ee5e328e4b98f Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sat, 10 Oct 2026 14:29:22 -0400
-Subject: [RFC PATCH 110/116] btrfs: stripe_alloc: count single-data-stripe
- groups' free space in write admission
-To: linux-btrfs@vger.kernel.org
-
-stripe_claimable_admit() admits a data write only if it fits in the
-claimable whole stripes of the groups stripe_alloc manages. Since "btrfs:
-stripe_alloc: skip RAID5/6 groups that are mapped as RAID1/RAID1C3",
-single-data-stripe RAID5/6 groups are not among them, yet their flags
-still match the RAID5/6 allocation profile, so writes land there. With
-two of five raid6 devices missing every new data chunk is such a group,
-and every degraded write failed with ENOSPC (r6c3 matrix-sa, 2026-10-10).
-
-Keep a per-space_info count of the free space in writable
-single-data-stripe RAID5/6 data groups and add it to the admission supply.
-The count follows each group's free-space total (ctl->free_space), which
-all free-space changes already go through, and a group is counted only
-while it is writable: btrfs_stripe_unmanaged_sync() runs when the group
-joins its space_info and after each read-only transition. The read-only
-guard treats a counted group's free space as the supply it takes away, as
-it does an armed group's claimable stripes.
-
-Groups of other profiles are not counted: a write allocated for a RAID5/6
-profile cannot use them.
-
-That skip's message overstated what stripe_alloc cost those groups: their
-full stripe is one sector (btrfs_full_stripe_len() reads the chunk map's
-type), so nothing was trapped; it saved per-allocation run bookkeeping and
-the end-of-extent marking of sectors no raid56 write would ever mark.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 23 +++++++++++++----
- fs/btrfs/block-group.h | 21 +++++++++++++++
- fs/btrfs/free-space-cache.c | 51 ++++++++++++++++++++++++++++++++-----
- fs/btrfs/free-space-cache.h | 1 +
- fs/btrfs/space-info.c | 16 +++++++++---
- fs/btrfs/space-info.h | 6 +++++
- 6 files changed, 104 insertions(+), 14 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 48c8d0869edcf..f31bef3c7afd1 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -4801,17 +4801,26 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
- * 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)) {
-+ if (!ret && (READ_ONCE(cache->stripe_unusable_ready) ||
-+ test_bit(BLOCK_GROUP_FLAG_UNMANAGED_COUNTED,
-+ &cache->runtime_flags)) &&
-+ btrfs_test_opt(cache->fs_info, STRIPE_ALLOC) &&
-+ READ_ONCE(cache->fs_info->stripe_margin_unit)) {
- /*
- * 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.
-+ * A group stripe_alloc does not manage supplies its
-+ * free space (bytes_unmanaged_free) instead.
- */
-- const u64 supply = sinfo->bytes_stripe_claimable;
-+ const u64 supply = sinfo->bytes_stripe_claimable +
-+ atomic64_read(&sinfo->bytes_unmanaged_free);
- const u64 mine = min(supply,
-- READ_ONCE(cache->stripe_claimable));
-+ READ_ONCE(cache->stripe_unusable_ready) ?
-+ READ_ONCE(cache->stripe_claimable) :
-+ READ_ONCE(cache->free_space_ctl->free_space));
-
- if (sinfo->bytes_may_use + sinfo->bytes_stripe_margin >
- supply - mine)
-@@ -4863,8 +4872,10 @@ static int inc_block_group_ro(struct btrfs_block_group *cache, bool force)
- * contribution so it is not subtracted twice. Idempotent, so repeated
- * ro increments are harmless.
- */
-- if (!ret)
-+ if (!ret) {
- btrfs_block_group_disarm_stripe_unusable(cache);
-+ btrfs_stripe_unmanaged_sync(cache);
-+ }
- if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
- btrfs_info(cache->fs_info,
- "unable to make block group %llu ro", cache->start);
-@@ -6833,8 +6844,10 @@ void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
- * the current free space (it may have changed while read-only). The
- * scan re-adds this group's trapped free space to the space_info total.
- */
-- if (became_rw)
-+ if (became_rw) {
- btrfs_block_group_init_stripe_unusable(cache);
-+ btrfs_stripe_unmanaged_sync(cache);
-+ }
- }
-
- static int update_block_group_item(struct btrfs_trans_handle *trans,
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 678f39315edb5..1a4d5b8b36f75 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -169,6 +169,12 @@ enum btrfs_block_group_flags {
- * IO never reaches raid56, so stripe_alloc and stripe_meta skip it.
- */
- BLOCK_GROUP_FLAG_RAID56_MIRRORED,
-+ /*
-+ * This group's free space is in its space_info's
-+ * bytes_unmanaged_free (see btrfs_stripe_unmanaged_sync()). Set and
-+ * cleared under the free-space ctl's tree_lock.
-+ */
-+ BLOCK_GROUP_FLAG_UNMANAGED_COUNTED,
- };
-
- enum btrfs_caching_type {
-@@ -431,6 +437,21 @@ static inline u64 btrfs_block_group_end(const struct btrfs_block_group *block_gr
- return (block_group->start + block_group->length);
- }
-
-+/*
-+ * A RAID5/6 data group stripe_alloc does not manage because it has a single
-+ * data stripe and is mapped as RAID1/RAID1C3. Its flags still match the
-+ * RAID5/6 allocation profile, so writes stripe_alloc admits can land there,
-+ * and the admission has to count its free space. Groups of other profiles
-+ * are left out: a write allocated for a RAID5/6 profile cannot use them.
-+ */
-+static inline bool btrfs_stripe_bg_unmanaged(const struct btrfs_block_group *bg)
-+{
-+ return (bg->flags & BTRFS_BLOCK_GROUP_DATA) &&
-+ !(bg->flags & BTRFS_BLOCK_GROUP_METADATA) &&
-+ (bg->flags & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
-+ test_bit(BLOCK_GROUP_FLAG_RAID56_MIRRORED, &bg->runtime_flags);
-+}
-+
- static inline bool btrfs_is_block_group_used(const struct btrfs_block_group *bg)
- {
- lockdep_assert_held(&bg->lock);
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index b7caca10cb10d..0d302853bf0a2 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -550,6 +550,19 @@ tree_search_offset(struct btrfs_free_space_ctl *ctl,
- return entry;
- }
-
-+/*
-+ * Change the group's free-space total, and with it the space_info's
-+ * bytes_unmanaged_free while the group is counted there. Under tree_lock.
-+ */
-+static void free_space_stat_mod(struct btrfs_free_space_ctl *ctl, s64 delta)
-+{
-+ struct btrfs_block_group *bg = ctl->block_group;
-+
-+ ctl->free_space += delta;
-+ if (bg && test_bit(BLOCK_GROUP_FLAG_UNMANAGED_COUNTED, &bg->runtime_flags))
-+ atomic64_add(delta, &bg->space_info->bytes_unmanaged_free);
-+}
-+
- static inline void unlink_free_space(struct btrfs_free_space_ctl *ctl,
- struct btrfs_free_space *info,
- bool update_stat)
-@@ -566,7 +579,7 @@ static inline void unlink_free_space(struct btrfs_free_space_ctl *ctl,
- }
-
- if (update_stat)
-- ctl->free_space -= info->bytes;
-+ free_space_stat_mod(ctl, -(s64)info->bytes);
- }
-
- static int link_free_space(struct btrfs_free_space_ctl *ctl,
-@@ -588,7 +601,7 @@ static int link_free_space(struct btrfs_free_space_ctl *ctl,
- ctl->discardable_bytes[BTRFS_STAT_CURR] += info->bytes;
- }
-
-- ctl->free_space += info->bytes;
-+ free_space_stat_mod(ctl, info->bytes);
- ctl->free_extents++;
- return ret;
- }
-@@ -645,7 +658,7 @@ static inline void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
- }
-
- if (update_stat)
-- ctl->free_space -= bytes;
-+ free_space_stat_mod(ctl, -(s64)bytes);
- }
-
- static void btrfs_bitmap_set_bits(struct btrfs_free_space_ctl *ctl,
-@@ -669,7 +682,7 @@ static void btrfs_bitmap_set_bits(struct btrfs_free_space_ctl *ctl,
- */
- info->max_extent_size = 0;
- info->bytes += bytes;
-- ctl->free_space += bytes;
-+ free_space_stat_mod(ctl, bytes);
-
- relink_bitmap_entry(ctl, info);
-
-@@ -1479,7 +1492,7 @@ static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
- to_unusable = size - to_free;
-
- spin_lock(&ctl->tree_lock);
-- ctl->free_space += to_free;
-+ free_space_stat_mod(ctl, to_free);
- spin_unlock(&ctl->tree_lock);
- /*
- * If the block group is read-only, we should account freed space into
-@@ -2176,6 +2189,32 @@ static void stripe_return_clusters(struct btrfs_block_group *bg)
- spin_unlock(&cluster->refill_lock);
- }
-
-+/*
-+ * Count a writable single-data-stripe RAID5/6 data group, which stripe_alloc
-+ * does not manage, in its space_info's bytes_unmanaged_free, or stop counting
-+ * it once it is read-only. Called when the group joins its space_info and
-+ * after every read-only transition; it re-reads ->ro, so of two racing
-+ * transitions the later call settles the state.
-+ */
-+void btrfs_stripe_unmanaged_sync(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-+ bool want;
-+
-+ if (!btrfs_stripe_bg_unmanaged(bg) || !bg->space_info)
-+ return;
-+
-+ spin_lock(&ctl->tree_lock);
-+ want = !READ_ONCE(bg->ro);
-+ if (want && !test_and_set_bit(BLOCK_GROUP_FLAG_UNMANAGED_COUNTED,
-+ &bg->runtime_flags))
-+ atomic64_add(ctl->free_space, &bg->space_info->bytes_unmanaged_free);
-+ else if (!want && test_and_clear_bit(BLOCK_GROUP_FLAG_UNMANAGED_COUNTED,
-+ &bg->runtime_flags))
-+ atomic64_sub(ctl->free_space, &bg->space_info->bytes_unmanaged_free);
-+ spin_unlock(&ctl->tree_lock);
-+}
-+
- /*
- * Compute a stripe_alloc block group's initial trapped free space once its
- * free space cache is loaded, and enable incremental accounting from here on.
-@@ -3113,7 +3152,7 @@ u64 btrfs_alloc_from_cluster(struct btrfs_block_group *block_group,
- if (!btrfs_free_space_trimmed(entry))
- atomic64_add(bytes, &discard_ctl->discard_bytes_saved);
-
-- ctl->free_space -= bytes;
-+ free_space_stat_mod(ctl, -(s64)bytes);
- if (!entry->bitmap && !btrfs_free_space_trimmed(entry))
- ctl->discardable_bytes[BTRFS_STAT_CURR] -= bytes;
-
-diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
-index 09c41eeb48854..ceb933d51a169 100644
---- a/fs/btrfs/free-space-cache.h
-+++ b/fs/btrfs/free-space-cache.h
-@@ -117,6 +117,7 @@ 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);
- void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
-+void btrfs_stripe_unmanaged_sync(struct btrfs_block_group *block_group);
- void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
- bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg);
- bool btrfs_stripe_bg_wants_compaction(struct btrfs_block_group *bg);
-diff --git a/fs/btrfs/space-info.c b/fs/btrfs/space-info.c
-index 061f94e4a65ff..7859713404ff1 100644
---- a/fs/btrfs/space-info.c
-+++ b/fs/btrfs/space-info.c
-@@ -431,6 +431,8 @@ void btrfs_add_bg_to_space_info(struct btrfs_block_group *block_group)
- down_write(&space_info->groups_sem);
- list_add_tail(&block_group->list, &space_info->block_groups[index]);
- up_write(&space_info->groups_sem);
-+
-+ btrfs_stripe_unmanaged_sync(block_group);
- }
-
- /*
-@@ -725,7 +727,14 @@ static bool stripe_claimable_admit(struct btrfs_space_info *space_info, u64 byte
- * runs can lose at the next commit.
- */
- {
-- u64 supply = space_info->bytes_stripe_claimable;
-+ /*
-+ * Single-data-stripe RAID5/6 groups, which stripe_alloc does
-+ * not manage, take these writes too: count their free space,
-+ * or a degraded filesystem, where every new chunk is one,
-+ * refuses every write.
-+ */
-+ u64 supply = space_info->bytes_stripe_claimable +
-+ atomic64_read(&space_info->bytes_unmanaged_free);
- const u64 dedicated = space_info->bytes_stripe_claimable_reloc;
-
- if (reloc) {
-@@ -843,14 +852,15 @@ 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 stripe_unusable=%llu stripe_stranded=%llu stripe_open=%llu stripe_claimable=%llu stripe_margin=%llu stripe_reserve=%llu",
-+"space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu zone_unusable=%llu stripe_unusable=%llu stripe_stranded=%llu stripe_open=%llu stripe_claimable=%llu stripe_margin=%llu stripe_reserve=%llu unmanaged_free=%lld",
- 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_stripe_unusable, info->bytes_stripe_stranded,
- info->bytes_stripe_open,
- info->bytes_stripe_claimable,
-- info->bytes_stripe_margin, info->bytes_stripe_reserve);
-+ info->bytes_stripe_margin, info->bytes_stripe_reserve,
-+ (s64)atomic64_read(&info->bytes_unmanaged_free));
- }
-
- void btrfs_dump_space_info(struct btrfs_space_info *info, u64 bytes,
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 3667af16afb33..43124031e1926 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -178,6 +178,12 @@ struct btrfs_space_info {
- measured claimable whole-stripe
- bytes; see stripe_claimable in
- struct btrfs_block_group */
-+ atomic64_t bytes_unmanaged_free; /* free bytes in writable
-+ single-data-stripe RAID5/6 data
-+ groups, which stripe_alloc does not
-+ manage (btrfs_stripe_bg_unmanaged());
-+ write admission counts them with the
-+ claimable stripes */
- u64 bytes_stripe_open; /* sum of open stripe runs' unallocated
- remainders. Claimed out of the free
- space cache but not yet allocated;
---
-2.47.3
-
+++ /dev/null
-From 57bd7060bee3be492177305469ddf52aec1cf364 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Sun, 11 Oct 2026 02:50:36 -0400
-Subject: [RFC PATCH 111/116] btrfs: stripe_alloc: account claimable stripes
- while a trim has them out
-To: linux-btrfs@vger.kernel.org
-
-stripe_claimable may only under-count the whole free stripes a scan of the
-free-space tree finds: claims and removals debit it, adds never credit it,
-and the commit rescan is the only upward correction. The rescan WARNs when
-the incremental value is above its scan.
-
-Trimming breaks that. trim_no_bitmap() and trim_bitmaps() take a free
-range out of the tree, drop tree_lock for the discard, and do_trimming()
-adds the range back; neither step touches stripe_claimable. A rescan of
-the group in that window -- at commit, or a forced one -- scans a tree
-without the range and finds fewer claimable stripes than the incremental
-count:
-
- bg 31168921600 incremental stripe_claimable 1176240128 above scanned 1172045824
-
-(misc-next claimable repro with discard=async, once in 2.5 hours; an
-fstrim loop against forced rescans hits it about twice a second on both
-lanes). Until the rescan corrects it, the admission supply counts stripes
-the allocator cannot claim, and the rescan then sets the counter to the
-low scan, where the uncredited re-add leaves it.
-
-Each step of a trim changes exactly the stripes its range belongs to:
-taking the range out makes every one of them that was claimable (wholly
-free and not inside a live run, the scan's rule) unclaimable, and adding
-it back makes claimable every one that is claimable now. Debit and credit
-those in the tree_lock section that unlinks or links the range, so the
-count stays as exact as it was. Rounding instead (debit every touched
-stripe, credit only the ones inside) would over-debit a stripe per
-trimmed sub-stripe hole until the next rescan, and async discard trims
-thousands of those after a delete.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 24 +++++++
- fs/btrfs/block-group.h | 1 +
- fs/btrfs/free-space-cache.c | 135 ++++++++++++++++++++++++++++++++----
- 3 files changed, 146 insertions(+), 14 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index f31bef3c7afd1..53602f27a36af 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -1583,6 +1583,30 @@ u64 btrfs_stripe_run_stranded_stripes(struct btrfs_block_group *bg, u32 *freep,
- return stranded;
- }
-
-+/*
-+ * Is the full stripe at @stripe inside a live run's range, i.e. stranded by
-+ * the rule of btrfs_stripe_run_stranded_stripes()? Caller holds
-+ * ctl->tree_lock.
-+ */
-+bool btrfs_stripe_run_strands(struct btrfs_block_group *bg, u64 stripe)
-+{
-+ const u64 fsl = bg->full_stripe_len;
-+ struct btrfs_open_stripe_run *run;
-+ unsigned long flags;
-+ bool ret = false;
-+
-+ spin_lock_irqsave(&bg->stripe_run_lock, flags);
-+ list_for_each_entry(run, &bg->open_stripe_runs, list) {
-+ if (run->end > run->start &&
-+ stripe < run->end && stripe + fsl > run->start) {
-+ ret = true;
-+ break;
-+ }
-+ }
-+ spin_unlock_irqrestore(&bg->stripe_run_lock, flags);
-+ return ret;
-+}
-+
- /*
- * Parse a stripe_alloc_allow_rmw word list ("nodatacow",
- * "prealloc", "fsync") into its mask. Words are separated by comma,
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 1a4d5b8b36f75..202d9f73678de 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -552,6 +552,7 @@ bool btrfs_stripe_open_run_class(struct btrfs_fs_info *fs_info, u64 logical,
- enum btrfs_stripe_run_class *class);
- 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,
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 0d302853bf0a2..c55d80da64924 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1376,10 +1376,12 @@ static void steal_from_bitmap(struct btrfs_free_space_ctl *ctl,
- static void stripe_claimable_mod(struct btrfs_block_group *bg, s64 delta);
- static u64 stripe_touched_bytes(const struct btrfs_block_group *bg,
- u64 bytenr, u64 size);
-+static void stripe_trim_claimable(struct btrfs_block_group *bg, u64 bytenr,
-+ u64 size, bool out);
-
--static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
-- u64 offset, u64 bytes,
-- enum btrfs_trim_state trim_state)
-+static int add_free_space(struct btrfs_block_group *block_group,
-+ u64 offset, u64 bytes,
-+ enum btrfs_trim_state trim_state, bool trim_return)
- {
- struct btrfs_fs_info *fs_info = block_group->fs_info;
- struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
-@@ -1439,12 +1441,16 @@ static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
- out:
- /*
- * Adding free space never credits stripe_claimable: some add paths
-- * re-add space that was never debited (async discard's re-add, the tail
-- * of btrfs_remove_free_space()'s middle split), and crediting would
-+ * re-add space that was never debited (the tail of
-+ * btrfs_remove_free_space()'s middle split), and crediting would
- * count it twice. The counter may only err low (an early ENOSPC); an
- * over-count admits reservations writeback cannot place. The commit
-- * rescan is the only upward correction.
-+ * rescan is the only upward correction -- except for a trim's return,
-+ * whose range was debited when the trim took it out (see
-+ * stripe_trim_claimable()).
- */
-+ if (!ret && trim_return)
-+ stripe_trim_claimable(block_group, offset, bytes, false);
- btrfs_discard_update_discardable(block_group);
- spin_unlock(&ctl->tree_lock);
-
-@@ -1461,6 +1467,13 @@ static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
- return ret;
- }
-
-+static int __btrfs_add_free_space(struct btrfs_block_group *block_group,
-+ u64 offset, u64 bytes,
-+ enum btrfs_trim_state trim_state)
-+{
-+ return add_free_space(block_group, offset, bytes, trim_state, false);
-+}
-+
- static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
- u64 bytenr, u64 size, bool used)
- {
-@@ -1526,8 +1539,9 @@ static void stripe_unusable_mark_dirty(struct btrfs_block_group *bg);
-
- /*
- * Debit the claimable whole-stripe supply for claims and removals. Returned
-- * free space is never credited here (see __btrfs_add_free_space()); the
-- * commit rescan restores it. Caller holds ctl->tree_lock.
-+ * free space is never credited here (see add_free_space()), save a trim's
-+ * return (stripe_trim_claimable()); the commit rescan restores it. Caller
-+ * holds ctl->tree_lock.
- *
- * The group's value and the space_info total change in one sinfo->lock
- * section, as everywhere else, so that btrfs_scan_stripe_unusable(), which
-@@ -1574,6 +1588,97 @@ static u64 stripe_touched_bytes(const struct btrfs_block_group *bg,
- return aend - astart;
- }
-
-+/* The whole stripes inside [bytenr, bytenr + size). */
-+static u64 stripe_whole_bytes(const struct btrfs_block_group *bg,
-+ u64 bytenr, u64 size)
-+{
-+ const u64 fsl = bg->full_stripe_len;
-+ const u64 rel = bytenr - bg->start;
-+ const u64 astart = div64_u64(rel + fsl - 1, fsl) * fsl;
-+ const u64 aend = div64_u64(rel + size, fsl) * fsl;
-+
-+ return aend > astart ? aend - astart : 0;
-+}
-+
-+/* Is all of [start, end) free? Caller holds ctl->tree_lock. */
-+static bool stripe_range_free(struct btrfs_free_space_ctl *ctl,
-+ u64 start, u64 end)
-+{
-+ const u32 unit = ctl->block_group->fs_info->sectorsize;
-+ u64 pos = start;
-+
-+ while (pos < end) {
-+ struct btrfs_free_space *e = tree_search_offset(ctl, pos, 0, 0);
-+ unsigned long bit;
-+
-+ if (!e)
-+ return false;
-+ if (!e->bitmap) {
-+ /* An extent entry returned here covers pos. */
-+ pos = e->offset + e->bytes;
-+ continue;
-+ }
-+ bit = div_u64(pos - e->offset, unit);
-+ if (!test_bit(bit, e->bitmap))
-+ return false;
-+ pos = e->offset + (u64)find_next_zero_bit(e->bitmap,
-+ BITS_PER_BITMAP, bit) * unit;
-+ }
-+ return true;
-+}
-+
-+/*
-+ * The claimable stripes that [bytenr, bytenr + size) belongs to, counting
-+ * the range itself as free: by the scan's rule (stripe_unusable_scan()),
-+ * every stripe that is wholly free and not inside a live stripe run.
-+ * Caller holds ctl->tree_lock; stripe_run_lock nests inside it.
-+ */
-+static u64 stripe_claimable_with_range(struct btrfs_block_group *bg,
-+ u64 bytenr, u64 size)
-+{
-+ struct btrfs_free_space_ctl *ctl = bg->free_space_ctl;
-+ const u64 fsl = bg->full_stripe_len;
-+ const u64 end = bytenr + size;
-+ const u64 bg_end = btrfs_block_group_end(bg);
-+ u64 whole = 0;
-+ u64 s;
-+
-+ for (s = bg->start + div64_u64(bytenr - bg->start, fsl) * fsl;
-+ s < end && s + fsl <= bg_end; s += fsl) {
-+ if (s < bytenr && !stripe_range_free(ctl, s, bytenr))
-+ continue;
-+ if (s + fsl > end && !stripe_range_free(ctl, end, s + fsl))
-+ continue;
-+ if (!btrfs_stripe_run_strands(bg, s))
-+ whole += fsl;
-+ }
-+ return whole;
-+}
-+
-+/*
-+ * A trim takes a free range out of the tree for the length of its discard
-+ * (trim_no_bitmap(), trim_bitmaps()) and do_trimming() adds it back. A
-+ * rescan in between scans a tree without the range, so the incremental
-+ * count must not include it either. Each step changes exactly the stripes
-+ * the range belongs to: taking it out (@out) makes every one of them that
-+ * was claimable unclaimable, and adding it back makes claimable every one
-+ * that is claimable now. Debit and credit those, in the tree_lock section
-+ * that unlinks or links the range, so the count stays as exact as it was.
-+ * Caller holds ctl->tree_lock; for @out, the range is already unlinked.
-+ */
-+static void stripe_trim_claimable(struct btrfs_block_group *bg, u64 bytenr,
-+ u64 size, bool out)
-+{
-+ s64 delta;
-+
-+ if (!btrfs_is_stripe_alloc_bg(bg) && !btrfs_is_stripe_meta_bg(bg))
-+ return;
-+ if (!READ_ONCE(bg->stripe_unusable_ready) || !size)
-+ return;
-+ delta = stripe_claimable_with_range(bg, bytenr, size);
-+ stripe_claimable_mod(bg, out ? -delta : delta);
-+}
-+
- /*
- * 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
-@@ -3539,13 +3644,12 @@ static int do_trimming(struct btrfs_block_group *block_group,
- }
-
- if (reserved_start < start)
-- __btrfs_add_free_space(block_group, reserved_start,
-- start - reserved_start,
-- reserved_trim_state);
-+ add_free_space(block_group, reserved_start,
-+ start - reserved_start, reserved_trim_state, true);
- if (end < reserved_end)
-- __btrfs_add_free_space(block_group, end, reserved_end - end,
-- reserved_trim_state);
-- __btrfs_add_free_space(block_group, start, bytes, trim_state);
-+ add_free_space(block_group, end, reserved_end - end,
-+ reserved_trim_state, true);
-+ add_free_space(block_group, start, bytes, trim_state, true);
-
- if (!bg_ro) {
- spin_lock(&space_info->lock);
-@@ -3643,6 +3747,8 @@ static int trim_no_bitmap(struct btrfs_block_group *block_group,
- unlink_free_space(ctl, entry, true);
- kmem_cache_free(btrfs_free_space_cachep, entry);
- }
-+ stripe_trim_claimable(block_group, extent_start, extent_bytes,
-+ true);
-
- spin_unlock(&ctl->tree_lock);
-
-@@ -3861,6 +3967,7 @@ static int trim_bitmaps(struct btrfs_block_group *block_group,
- bitmap_clear_bits(ctl, entry, start, bytes, true);
- if (entry->bytes == 0)
- free_bitmap(ctl, entry);
-+ stripe_trim_claimable(block_group, start, bytes, true);
-
- spin_unlock(&ctl->tree_lock);
-
---
-2.47.3
-
+++ /dev/null
-From 7078a366742e3bbb8e50863428b096c3155e0fe3 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 20 Oct 2026 00:14:58 -0400
-Subject: [RFC PATCH 112/116] btrfs: stripe_alloc: do not miss bitmap free
- space when debiting a trim
-To: linux-btrfs@vger.kernel.org
-
-stripe_range_free() decides whether a stripe a trim touches is wholly
-free, so that "account claimable stripes while a trim has them out" can
-debit the stripes a trim takes out and credit the ones it puts back. It
-looks each position up with tree_search_offset(ctl, pos, 0, 0). When the
-last free space entry at or before pos is an extent entry that ends before
-pos, that search returns NULL, even if a bitmap entry whose window covers
-pos has pos's bit set: extent entries and bitmaps share one offset-sorted
-tree, and an extent entry that starts inside a bitmap's window hides the
-bitmap from a non-fuzzy search. btrfs_remove_free_space() and the
-stripe-run claim paths handle this by looking the bitmap up again at
-offset_to_bitmap(); stripe_range_free() does not, and calls such a stripe
-not free.
-
-In a fragmented group (a filesystem the legacy allocator filled, then
-converted with the btrfs.stripe_alloc property) free space is split
-between bitmaps and extent entries inside the same bitmap windows, so the
-miss is common. When the trim takes a range out, a boundary stripe that
-was wholly free is then not debited, and stripe_claimable stays one stripe
-high until the range comes back; a rescan in that window warns
-"incremental stripe_claimable ... above scanned ..." by exactly one full
-stripe. If the tree changes during the discard so that the return finds
-the stripe free, the credit is applied without the debit, and the count
-stays high until the group's next rescan. The over-count is at most two
-stripes per trimmed range, but while it lasts the admission gate can admit
-writes against a stripe that is not there.
-
-Fall back to the bitmap lookup, as the other callers do.
-
-Seen as one 320 KiB "above scanned" WARN in legacy-conversion-repro.sh's
-check phase on misc-next. claimable-trim-miss-test.sh (punch-hole frees,
-an fstrim loop and forced rescans on the converted legacy fixture) on a
-kernel instrumented to compute both lookups: the old one missed one stripe
-in 31 of ~526000 trims that took whole stripes out, in the group that
-warned in the field among others. raid56 has no discard IO, so each miss
-lasts only the ~15 us between unlink and re-add; with those trims held out
-for 500 ms, 30 rescans warned, each by exactly the missed stripe. With
-this lookup and the same delay, 55 such trims, no warning.
-
-Fixes: a1ba776d84f3 ("btrfs: stripe_alloc: account claimable stripes while a trim has them out")
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/free-space-cache.c | 9 +++++++++
- 1 file changed, 9 insertions(+)
-
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index c55d80da64924..7f5d17a727587 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -1611,6 +1611,15 @@ static bool stripe_range_free(struct btrfs_free_space_ctl *ctl,
- struct btrfs_free_space *e = tree_search_offset(ctl, pos, 0, 0);
- unsigned long bit;
-
-+ /*
-+ * An extent entry that starts inside a bitmap's window and
-+ * ends before pos hides that bitmap from the search above;
-+ * look it up by its own offset, as btrfs_remove_free_space()
-+ * does.
-+ */
-+ if (!e)
-+ e = tree_search_offset(ctl, offset_to_bitmap(ctl, pos),
-+ 1, 0);
- if (!e)
- return false;
- if (!e->bitmap) {
---
-2.47.3
-
+++ /dev/null
-From 780cc8af6fc1dd5d42f883ccbf06552a123bfc2e Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 20 Oct 2026 13:04:19 -0400
-Subject: [RFC PATCH 113/116] btrfs: log block group reclaim at debug level
-To: linux-btrfs@vger.kernel.org
-
-The reclaim worker relocates and compacts block groups without a word in
-the kernel log: btrfs_relocate_chunk() is called with verbose=false, and
-the "reclaiming chunk" info message was removed as log spam in a507904090d0
-("btrfs: remove redundant auto reclaim log message"). Only the
-btrfs_reclaim_block_group tracepoint and the reclaim_count/reclaim_errors
-counters in sysfs remain, so a kernel log taken from a test or a user
-report cannot show which groups reclaim moved, or when. Under stripe_alloc
-this hid automatic relocation and compaction from tests that read the log:
-stripe-reclaim-test counted relocation lines and always saw none, and an
-octopus replace stalled behind a reclaim that left no trace.
-
-Log the start of each reclaim (relocate or compact, with the group's
-flags, length, used, reserved and trapped bytes) and its successful end
-with btrfs_debug(), so they are off by default and can be enabled with
-dynamic debug:
-
- echo 'file fs/btrfs/block-group.c format "reclaim: " +p' \
- > /sys/kernel/debug/dynamic_debug/control
-
-Errors are still logged with btrfs_err() as before.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 16 +++++++++++++---
- 1 file changed, 13 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 53602f27a36af..41c717707a440 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -5402,8 +5402,10 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- u64 used;
- u64 reserved;
- u64 old_total;
-+ u64 trapped;
- int ret = 0;
- bool compact = false;
-+ bool compacted = false;
-
- /*
- * A stripe_alloc / stripe_meta group's live extents can only move into
-@@ -5550,12 +5552,17 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- spin_lock(&bg->lock);
- used = bg->used;
- reserved = bg->reserved;
-+ /* Trapped as the reclaim trigger counts it. */
-+ trapped = bg->stripe_unusable -
-+ min(bg->stripe_unusable, bg->stripe_stranded);
- spin_unlock(&bg->lock);
-
- trace_btrfs_reclaim_block_group(bg);
-+ btrfs_debug(fs_info,
-+"reclaim: %s block group %llu flags 0x%llx length %llu used %llu reserved %llu trapped %llu",
-+ compact ? "compacting" : "relocating", bg->start, bg->flags,
-+ bg->length, used, reserved, trapped);
- if (compact) {
-- bool compacted;
--
- ret = btrfs_compact_chunk(fs_info, bg->start, &compacted);
- /*
- * Compacted, the group stays: drop our read-only hold. It
-@@ -5592,8 +5599,11 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- if (space_info->total_bytes < old_total)
- btrfs_set_periodic_reclaim_ready(space_info, true);
- spin_unlock(&space_info->lock);
-- if (!ret)
-+ if (!ret) {
- (*reclaimed)++;
-+ btrfs_debug(fs_info, "reclaim: %s block group %llu",
-+ compacted ? "compacted" : "relocated", bg->start);
-+ }
-
- return ret;
- }
---
-2.47.3
-
+++ /dev/null
-From 301e2700905d9ada252870d02e543f9d7a31a1b0 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Tue, 20 Oct 2026 14:41:37 -0400
-Subject: [RFC PATCH 114/116] btrfs: stripe_alloc: add stripe_reclaim_now to
- reclaim stripes on demand
-To: linux-btrfs@vger.kernel.org
-
-Background reclaim of stripe_alloc / stripe_meta raid56 groups runs when a
-commit-time rescan, or the cleaner's tick at most every five minutes per
-group, finds a group past bg_reclaim_threshold. Nothing lets an operator
-say "reclaim now": during an idle period, before a large write, or for one
-group seen trapped. The only tool is balance, which relocates whole groups
-whatever their state and cannot compact.
-
-Add /sys/fs/btrfs/<uuid>/stripe_reclaim_now (write-only, root):
-
- echo all > stripe_reclaim_now (or "1")
- Queue every stripe_alloc / stripe_meta raid56 group that the
- reclaim predicate picks: relocate below the threshold once enough
- of its free space is trapped, compact above it once stripe_compact
- percent of its length is trapped. The five-minute hysteresis is
- ignored.
-
- echo <start> > stripe_reclaim_now
- Reclaim the group at that logical start (decimal or 0x hex, as
- `btrfs inspect-internal dump-tree -t chunk` and the "reclaim: "
- debug lines print it) whatever its trapped space:
- compact it if it is above the threshold and has trapped stripes,
- relocate it otherwise.
-
-The threshold is the space_info's bg_reclaim_threshold, or 75
-(BTRFS_DEFAULT_RECLAIM_THRESH) where that is 0, the non-zoned default,
-since the request is explicit. Both forms keep the room check: the other
-groups' claimable stripes, plus the one chunk the worker allocates when
-those fall short, must take what moves. The write returns once the groups
-are queued; it does not wait for the reclaim. The worker re-checks its
-thresholds and would drop a group it was asked to reclaim, so a group
-queued by this knob carries the kind of reclaim to do
-(stripe_reclaim_forced), which the worker honours once and clears.
-
-Errors: -ENOENT when no group starts there; -EINVAL for anything but a
-stripe_alloc / stripe_meta raid56 group (balance's vrange filter relocates
-the others); -EBUSY when the group is read-only (a balance or scrub has
-it); -EAGAIN when it is already on a list (queued, unused or new);
--ENOSPC when there is no room; -EROFS on a read-only or errored
-filesystem. The worker takes the balance exclusive operation and gives the
-list back when another holds it, so a request made while a balance,
-replace, resize or device add/remove runs would wait unseen: it fails at
-once with -EAGAIN and nothing is queued; retry when the operation is done.
-The reclaim worker's own hold (a balance with no balance control) is not
-refused, as the worker picks up the new entries.
-
-Expected use: an idle-time job (cron) writes "all"; an operator writes the
-start of one group taken from the "reclaim: " debug lines or from the
-chunk tree. The queued groups are logged at debug level with the same
-"reclaim: " prefix.
-
-There is no in-tree btrfs sysfs documentation; the btrfs-progs sysfs
-chapter should list the file.
-
-Tested with stripe-reclaim-now-test.sh (raid56-wh-harness): with
-background reclaim off nothing moves; one group is relocated alone, and a
-group above the threshold with trapped stripes is compacted; "all"
-reclaims and trapped space falls; no such group, not a number, a raid1
-metadata group and a read-only mount fail with the codes above, and a
-paused balance and a running replace fail with -EAGAIN; data verifies and
-btrfs check is clean.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 166 +++++++++++++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 7 ++
- fs/btrfs/free-space-cache.c | 53 +++++++++---
- fs/btrfs/free-space-cache.h | 9 ++
- fs/btrfs/sysfs.c | 29 +++++++
- 5 files changed, 249 insertions(+), 15 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index 41c717707a440..bca4df2ab3cd4 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -5404,6 +5404,7 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- u64 old_total;
- u64 trapped;
- int ret = 0;
-+ u8 forced = READ_ONCE(bg->stripe_reclaim_forced);
- bool compact = false;
- bool compacted = false;
-
-@@ -5420,7 +5421,8 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- u64 need = READ_ONCE(bg->used);
-
- /* Compaction moves at most half of it. */
-- if (btrfs_stripe_bg_wants_compaction(bg))
-+ if (forced ? forced == STRIPE_RECLAIM_COMPACT :
-+ btrfs_stripe_bg_wants_compaction(bg))
- need /= 2;
- elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
- if (elsewhere < need) {
-@@ -5442,6 +5444,9 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
-
- spin_lock(&space_info->lock);
- spin_lock(&bg->lock);
-+ /* A forced reclaim is done once, or dropped with the group. */
-+ forced = bg->stripe_reclaim_forced;
-+ bg->stripe_reclaim_forced = STRIPE_RECLAIM_NONE;
- if (bg->ro ||
- ((bg->reserved || bg->pinned) &&
- !btrfs_is_stripe_alloc_bg(bg) &&
-@@ -5494,7 +5499,10 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- * check, which is more meaningful when adding to the list in
- * the first place.
- */
-- if (!should_reclaim_block_group(bg, bg->length)) {
-+ if (forced) {
-+ /* stripe_reclaim_now chose already; the thresholds may say no. */
-+ compact = (forced == STRIPE_RECLAIM_COMPACT);
-+ } else if (!should_reclaim_block_group(bg, bg->length)) {
- /*
- * Too full to relocate whole. A stripe_alloc / stripe_meta
- * group whose free space is trapped in partially used stripes
-@@ -5767,6 +5775,160 @@ bool btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
- return true;
- }
-
-+/*
-+ * Room for a forced reclaim beyond the other groups' claimable stripes: the
-+ * one chunk the reclaim worker allocates when they fall short (see
-+ * btrfs_reclaim_block_group()), estimated as the data share of the
-+ * unallocated device space at @bg's width, capped at @bg's length.
-+ */
-+static u64 stripe_reclaim_chunk_room(struct btrfs_block_group *bg)
-+{
-+ struct btrfs_fs_info *fs_info = bg->fs_info;
-+ struct btrfs_chunk_map *map;
-+ u64 unalloc = atomic64_read(&fs_info->free_chunk_space);
-+ u64 room;
-+
-+ map = btrfs_get_chunk_map(fs_info, bg->start, 1);
-+ if (IS_ERR(map))
-+ return 0;
-+ room = div_u64(unalloc * nr_data_stripes(map), map->num_stripes);
-+ btrfs_free_chunk_map(map);
-+ return min(room, bg->length);
-+}
-+
-+/*
-+ * Queue @bg for the reclaim worker with the reclaim it is to do. Returns
-+ * false when the group is already on a list (queued, unused or new).
-+ */
-+static bool stripe_reclaim_now_queue(struct btrfs_block_group *bg,
-+ enum stripe_reclaim_kind kind)
-+{
-+ bool queued;
-+
-+ spin_lock(&bg->lock);
-+ bg->stripe_reclaim_forced = kind;
-+ queued = btrfs_mark_bg_to_reclaim(bg);
-+ if (queued)
-+ bg->stripe_reclaim_jiffies = jiffies ?: 1;
-+ else
-+ bg->stripe_reclaim_forced = STRIPE_RECLAIM_NONE;
-+ spin_unlock(&bg->lock);
-+ if (queued)
-+ btrfs_debug(bg->fs_info,
-+ "reclaim: queued block group %llu to %s (stripe_reclaim_now)",
-+ bg->start, kind == STRIPE_RECLAIM_COMPACT ?
-+ "compact" : "relocate");
-+ return queued;
-+}
-+
-+/*
-+ * /sys/fs/btrfs/<uuid>/stripe_reclaim_now: reclaim stripe_alloc / stripe_meta
-+ * raid56 block groups now, e.g. from an idle-time job, rather than waiting
-+ * for the commit-time rescan and its five-minute hysteresis. The threshold
-+ * is the space_info's bg_reclaim_threshold, or BTRFS_DEFAULT_RECLAIM_THRESH
-+ * where that is 0 (reclaim off), since the request is explicit.
-+ *
-+ * @all: queue every such group the reclaim predicate picks at that
-+ * threshold (relocate below it, compact above it once stripe_compact percent
-+ * is trapped), ignoring the hysteresis.
-+ *
-+ * Otherwise @start names one group (its logical start): it is reclaimed
-+ * whatever the trapped minimums say, compacted if it is above the threshold
-+ * and has trapped stripes, relocated otherwise. -ENOENT: no group starts
-+ * there; -EINVAL: not a stripe_alloc / stripe_meta raid56 group (relocate
-+ * any other group with balance's vrange filter); -EBUSY: the group is
-+ * read-only (balance or scrub hold it); -EAGAIN: it is already on a list
-+ * (queued, unused or new); -ENOSPC: the other groups' claimable stripes plus
-+ * one new chunk cannot take what would move.
-+ *
-+ * Both return once the groups are queued, without waiting for the reclaim.
-+ * The worker takes the balance exclusive operation and gives the list back
-+ * when another operation holds it, so a request made while a balance,
-+ * replace, resize or device add/remove runs fails at once with -EAGAIN
-+ * rather than wait unseen; nothing is queued. The reclaim worker's own hold
-+ * (a balance with no balance control) is not refused: it picks up the new
-+ * entries.
-+ */
-+int btrfs_stripe_reclaim_now(struct btrfs_fs_info *fs_info, bool all, u64 start)
-+{
-+ struct btrfs_space_info *sinfo;
-+ struct btrfs_block_group *bg;
-+ enum btrfs_exclusive_operation op;
-+ enum stripe_reclaim_kind kind;
-+ int queued = 0;
-+ int ret = 0;
-+
-+ if (sb_rdonly(fs_info->sb) || BTRFS_FS_ERROR(fs_info))
-+ return -EROFS;
-+ spin_lock(&fs_info->super_lock);
-+ op = fs_info->exclusive_operation;
-+ spin_unlock(&fs_info->super_lock);
-+ if (op != BTRFS_EXCLOP_NONE &&
-+ (op != BTRFS_EXCLOP_BALANCE || READ_ONCE(fs_info->balance_ctl)))
-+ return -EAGAIN;
-+
-+ if (!all) {
-+ bg = btrfs_lookup_block_group(fs_info, start);
-+ if (!bg)
-+ return -ENOENT;
-+ if (bg->start != start) {
-+ ret = -ENOENT;
-+ } else if (!btrfs_is_stripe_alloc_bg(bg) &&
-+ !btrfs_is_stripe_meta_bg(bg)) {
-+ ret = -EINVAL;
-+ } else if (READ_ONCE(bg->ro)) {
-+ ret = -EBUSY;
-+ } else {
-+ int thresh = READ_ONCE(bg->space_info->bg_reclaim_threshold);
-+
-+ kind = btrfs_stripe_bg_reclaim_now_kind(bg,
-+ thresh > 0 ? thresh : BTRFS_DEFAULT_RECLAIM_THRESH,
-+ true, stripe_reclaim_chunk_room(bg));
-+ if (kind == STRIPE_RECLAIM_NONE)
-+ ret = READ_ONCE(bg->ro) ? -EBUSY : -ENOSPC;
-+ else if (stripe_reclaim_now_queue(bg, kind))
-+ queued = 1;
-+ else
-+ ret = -EAGAIN;
-+ }
-+ btrfs_put_block_group(bg);
-+ if (ret)
-+ return ret;
-+ goto kick;
-+ }
-+
-+ list_for_each_entry(sinfo, &fs_info->space_info, list) {
-+ int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
-+ int raid;
-+
-+ if (thresh <= 0)
-+ thresh = BTRFS_DEFAULT_RECLAIM_THRESH;
-+ down_read(&sinfo->groups_sem);
-+ for (raid = 0; raid < BTRFS_NR_RAID_TYPES; raid++) {
-+ if (!(btrfs_raid_array[raid].bg_flag &
-+ BTRFS_BLOCK_GROUP_RAID56_MASK))
-+ continue;
-+ list_for_each_entry(bg, &sinfo->block_groups[raid], list) {
-+ if (!btrfs_is_stripe_alloc_bg(bg) &&
-+ !btrfs_is_stripe_meta_bg(bg))
-+ continue;
-+ kind = btrfs_stripe_bg_reclaim_now_kind(bg, thresh,
-+ false, stripe_reclaim_chunk_room(bg));
-+ if (kind != STRIPE_RECLAIM_NONE &&
-+ stripe_reclaim_now_queue(bg, kind))
-+ queued++;
-+ }
-+ }
-+ up_read(&sinfo->groups_sem);
-+ }
-+ btrfs_debug(fs_info, "reclaim: stripe_reclaim_now queued %d block groups",
-+ queued);
-+kick:
-+ if (queued)
-+ queue_work(system_dfl_wq, &fs_info->reclaim_bgs_work);
-+ return 0;
-+}
-+
- static int read_bg_from_eb(struct btrfs_fs_info *fs_info, const struct btrfs_key *key,
- const struct btrfs_path *path)
- {
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index 202d9f73678de..bc26b9e875506 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -332,6 +332,12 @@ struct btrfs_block_group {
- u64 stripe_stranded;
- /* jiffies when the reclaim trigger last queued this group (stripe_alloc) */
- unsigned long stripe_reclaim_jiffies;
-+ /*
-+ * Reclaim forced by stripe_reclaim_now (enum stripe_reclaim_kind):
-+ * the reclaim worker does this instead of re-checking its thresholds,
-+ * once, and clears it. Protected by ->lock.
-+ */
-+ u8 stripe_reclaim_forced;
- /*
- * Directly measured claimable supply: bytes of fully free, aligned
- * whole stripes in the free space cache -- exactly what
-@@ -649,6 +655,7 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- void btrfs_reclaim_bgs_work(struct work_struct *work);
- void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info);
- bool btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg);
-+int btrfs_stripe_reclaim_now(struct btrfs_fs_info *fs_info, bool all, u64 start);
- int btrfs_read_block_groups(struct btrfs_fs_info *info);
- struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
- struct btrfs_space_info *space_info,
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index 7f5d17a727587..d41c672f176b5 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2423,19 +2423,15 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
- * and queueing a group with nowhere to move it only costs writers read-only
- * transitions. Counters are read unlocked; the worker re-checks.
- */
--enum stripe_reclaim_kind {
-- STRIPE_RECLAIM_NONE,
-- STRIPE_RECLAIM_RELOCATE,
-- STRIPE_RECLAIM_COMPACT,
--};
--
--static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
-- bool check_room)
-+static enum stripe_reclaim_kind __stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
-+ int thresh, bool force,
-+ bool check_room,
-+ u64 extra_room)
- {
- struct btrfs_space_info *sinfo = bg->space_info;
-- const int thresh = READ_ONCE(sinfo->bg_reclaim_threshold);
-+ const bool ready = READ_ONCE(bg->stripe_unusable_ready);
- const u64 used = READ_ONCE(bg->used);
-- const u64 unusable = READ_ONCE(bg->stripe_unusable);
-+ const u64 unusable = ready ? READ_ONCE(bg->stripe_unusable) : 0;
- /*
- * Stripes stranded behind live runs are trapped for admission but not
- * for reclaim: they come back by themselves when the run is freed, and
-@@ -2447,9 +2443,19 @@ static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group
- u64 elsewhere;
- u64 promised;
-
-- if (thresh <= 0 || bg->ro || !READ_ONCE(bg->stripe_unusable_ready))
-+ if (thresh <= 0 || bg->ro || (!ready && !force))
- return STRIPE_RECLAIM_NONE;
-- if (used >= mult_perc(bg->length, thresh)) {
-+ if (force) {
-+ /*
-+ * Forced (stripe_reclaim_now naming this group): no trapped
-+ * minimum. Compact a group too full to move whole if it has
-+ * any trapped stripe, otherwise relocate it.
-+ */
-+ if (used >= mult_perc(bg->length, thresh) && trapped) {
-+ kind = STRIPE_RECLAIM_COMPACT;
-+ need = used / 2;
-+ }
-+ } else if (used >= mult_perc(bg->length, thresh)) {
- /*
- * Too full to move whole: compact once trapped space reaches
- * stripe_compact percent of the group's length. (A share of
-@@ -2473,7 +2479,15 @@ static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group
- READ_ONCE(sinfo->bytes_stripe_margin);
- elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
- elsewhere -= min(elsewhere, promised);
-- return elsewhere >= need ? kind : STRIPE_RECLAIM_NONE;
-+ return elsewhere + extra_room >= need ? kind : STRIPE_RECLAIM_NONE;
-+}
-+
-+static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
-+ bool check_room)
-+{
-+ return __stripe_bg_reclaim_kind(bg,
-+ READ_ONCE(bg->space_info->bg_reclaim_threshold),
-+ false, check_room, 0);
- }
-
- bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
-@@ -2481,6 +2495,19 @@ bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg)
- return stripe_bg_reclaim_kind(bg, true) != STRIPE_RECLAIM_NONE;
- }
-
-+/*
-+ * For stripe_reclaim_now: the reclaim @bg gets at threshold @thresh, room
-+ * checked with @extra_room bytes (the chunk the worker may allocate) added to
-+ * the other groups' claimable supply. @force drops the trapped minimums: see
-+ * btrfs_stripe_reclaim_now().
-+ */
-+enum stripe_reclaim_kind btrfs_stripe_bg_reclaim_now_kind(struct btrfs_block_group *bg,
-+ int thresh, bool force,
-+ u64 extra_room)
-+{
-+ return __stripe_bg_reclaim_kind(bg, thresh, force, true, extra_room);
-+}
-+
- /*
- * For the reclaim worker, about a group it took: compact it rather than
- * relocate it whole. Room is not re-checked; the worker makes room first,
-diff --git a/fs/btrfs/free-space-cache.h b/fs/btrfs/free-space-cache.h
-index ceb933d51a169..94d60f9efece3 100644
---- a/fs/btrfs/free-space-cache.h
-+++ b/fs/btrfs/free-space-cache.h
-@@ -119,8 +119,17 @@ void btrfs_block_group_init_stripe_unusable(struct btrfs_block_group *block_grou
- void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *block_group);
- void btrfs_stripe_unmanaged_sync(struct btrfs_block_group *block_group);
- void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *block_group);
-+enum stripe_reclaim_kind {
-+ STRIPE_RECLAIM_NONE,
-+ STRIPE_RECLAIM_RELOCATE,
-+ STRIPE_RECLAIM_COMPACT,
-+};
-+
- bool btrfs_stripe_bg_wants_reclaim(struct btrfs_block_group *bg);
- bool btrfs_stripe_bg_wants_compaction(struct btrfs_block_group *bg);
-+enum stripe_reclaim_kind btrfs_stripe_bg_reclaim_now_kind(struct btrfs_block_group *bg,
-+ int thresh, bool force,
-+ u64 extra_room);
- s64 btrfs_stripe_partial_map(struct btrfs_block_group *bg, unsigned long *map,
- u64 nstripes);
- void btrfs_dump_free_space(struct btrfs_block_group *block_group,
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index d3231cc95f6dc..c7885e00033a8 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -1464,6 +1464,34 @@ static ssize_t btrfs_stripe_compact_store(struct kobject *kobj,
- BTRFS_ATTR_RW(, stripe_compact, btrfs_stripe_compact_show,
- btrfs_stripe_compact_store);
-
-+/*
-+ * Reclaim stripe_alloc / stripe_meta raid56 block groups now: "all" (or "1")
-+ * queues every group the reclaim predicate picks, a block group's logical
-+ * start forces that group. See btrfs_stripe_reclaim_now().
-+ */
-+static ssize_t btrfs_stripe_reclaim_now_store(struct kobject *kobj,
-+ struct kobj_attribute *a,
-+ const char *buf, size_t len)
-+{
-+ struct btrfs_fs_info *fs_info = to_fs_info(kobj);
-+ u64 start = 0;
-+ bool all;
-+ int ret;
-+
-+ if (!capable(CAP_SYS_ADMIN))
-+ return -EPERM;
-+
-+ all = sysfs_streq(buf, "all") || sysfs_streq(buf, "1");
-+ if (!all) {
-+ ret = kstrtou64(buf, 0, &start);
-+ if (ret)
-+ return ret;
-+ }
-+ ret = btrfs_stripe_reclaim_now(fs_info, all, start);
-+ return ret ? ret : len;
-+}
-+BTRFS_ATTR_W(, stripe_reclaim_now, btrfs_stripe_reclaim_now_store);
-+
-
-
- static ssize_t btrfs_clone_alignment_show(struct kobject *kobj,
-@@ -1840,6 +1868,7 @@ static const struct attribute *btrfs_attrs[] = {
- BTRFS_ATTR_PTR(, stripe_park_sync_timeout_ms),
- BTRFS_ATTR_PTR(, stripe_park_congestion),
- BTRFS_ATTR_PTR(, stripe_compact),
-+ BTRFS_ATTR_PTR(, stripe_reclaim_now),
- BTRFS_ATTR_PTR(, temp_fsid),
- NULL,
- };
---
-2.47.3
-
+++ /dev/null
-From 1ebbdb45771f2de406763b7b1e9b0d0a11087a4e Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 22 Oct 2026 04:02:52 -0400
-Subject: [RFC PATCH 115/116] btrfs: stripe_alloc: back off block group reclaim
- after repeated ENOSPC
-To: linux-btrfs@vger.kernel.org
-
-At the fill edge every reclaim of a stripe_alloc group fails with -ENOSPC,
-and the worker keeps retrying: a failed group goes back on the reclaim list
-at the end of each run (unless periodic reclaim is on) and is taken again
-at the next kick, and the commit-time rescan and the cleaner tick requeue
-trapped groups every five minutes each. Each attempt makes the group
-read-only, does part of the relocation and fails, all while holding the
-balance exclusive operation.
-
-It showed in two ways:
-
- - The octopus P1 pass (raid5 6 x 3 GiB, misc-next, bhive 2026-10-20):
- with the data space fully allocated and ~2 GiB trapped, reclaim held the
- exclusive operation for over an hour of fsstress and long after it,
- "error relocating chunk ...: -28" repeating (28 attempts, 13 errors in
- one loop), so a resize could not start and the replace failed. The
- worker sat in a metadata reservation (btrfs_block_rsv_refill under
- relocate_block_group): metadata had no room either.
-
- - reclaim-futile-test.sh (raid5 6 x 1 GiB at the edge, fsstress churn):
- 226 reclaim errors in 600 s. Of the -28 returns, relocation's data
- reservation lost the claimable stripes the room check had counted to
- the concurrent writers.
-
-The room check (claimable stripes in the other groups) is an estimate
-taken when the group is queued, and it does not cover metadata. Make
-reclaim give up after reasonable effort instead of grinding:
-
- - After BTRFS_RECLAIM_ENOSPC_STREAK (3) reclaims in a row fail with
- -ENOSPC in a space_info, back off: the worker drops that space_info's
- groups, and the rescan and tick do not queue them, until 10 minutes
- pass, a chunk is added or removed, or the space_info's free space (free
- in its groups plus unallocated) grows by what the last failed group
- held. A group that failed with -ENOSPC is not put back on the list for
- immediate retry. stripe_reclaim_now requests are still tried.
- - The reclaim predicate also requires room for relocation's up-front
- metadata reservation (512 tree blocks, twice RELOCATION_RESERVED_NODES):
- the octopus failure was a metadata ENOSPC that the data-side check
- could not see.
- - /sys/fs/btrfs/<uuid>/allocation/<type>/reclaim_backoffs counts the
- backoffs; the start of one is logged at debug level ("reclaim: ...").
-
-The occupancy of the exclusive operation at the fill edge, which the
-octopus also showed, is the next patch.
-
-Tested: reclaim-futile-test.sh measured 226 reclaim errors in 600 s on the
-lane without this patch (the fill-edge shape that loops; it does not loop
-on every run). With the patch no run logged more than 5 errors per 600 s;
-in one, five relocations failed with -ENOSPC and reclaim backed off once
-(reclaim_backoffs +1), then resumed. stripe-reclaim-test and
-stripe-reclaim-now-test pass.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 97 ++++++++++++++++++++++++++++++++++++-
- fs/btrfs/block-group.h | 1 +
- fs/btrfs/free-space-cache.c | 34 ++++++++++++-
- fs/btrfs/space-info.h | 17 +++++++
- fs/btrfs/sysfs.c | 2 +
- 5 files changed, 148 insertions(+), 3 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index bca4df2ab3cd4..fbd603e5fa416 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -5616,6 +5616,79 @@ static int btrfs_reclaim_block_group(struct btrfs_block_group *bg, int *reclaime
- return ret;
- }
-
-+/*
-+ * Reclaim gives up on a space_info for a while after this many reclaims in a
-+ * row failed with -ENOSPC. Relocating or compacting a group needs room for
-+ * its live data (and metadata reservations for moving it); at the fill edge
-+ * there is none, every attempt fails after doing its work, and retrying each
-+ * failed group on every worker run held the balance exclusive operation for
-+ * over an hour while writers starved (octopus P1, bhive 2026-10-20).
-+ */
-+#define BTRFS_RECLAIM_ENOSPC_STREAK 3
-+#define BTRFS_RECLAIM_BACKOFF (10 * 60 * HZ)
-+
-+/* Free space that a retried reclaim could use: free in groups, unallocated. */
-+static u64 reclaim_free_bytes(const struct btrfs_space_info *space_info)
-+{
-+ return space_info->total_bytes - min(space_info->total_bytes,
-+ space_info->bytes_used) +
-+ atomic64_read(&space_info->fs_info->free_chunk_space);
-+}
-+
-+/*
-+ * Is reclaim backing off for this space_info? The backoff ends when its
-+ * time is up, when a chunk was added or removed, or when free space grew by
-+ * what the last failed group needed.
-+ */
-+bool btrfs_reclaim_backoff_active(struct btrfs_space_info *space_info)
-+{
-+ bool active = false;
-+
-+ spin_lock(&space_info->lock);
-+ if (space_info->reclaim_backoff_until) {
-+ active = time_before(jiffies, space_info->reclaim_backoff_until) &&
-+ space_info->total_bytes == space_info->reclaim_backoff_total &&
-+ reclaim_free_bytes(space_info) < space_info->reclaim_backoff_free;
-+ if (!active) {
-+ space_info->reclaim_backoff_until = 0;
-+ space_info->reclaim_enospc_streak = 0;
-+ }
-+ }
-+ spin_unlock(&space_info->lock);
-+ return active;
-+}
-+
-+/*
-+ * Count a reclaim of @bg that failed with -ENOSPC (@enospc) or succeeded,
-+ * and start the backoff at the end of a streak of failures. @need is what
-+ * the group held: free space growing by that much ends the backoff early.
-+ */
-+static void reclaim_note_result(struct btrfs_block_group *bg, bool enospc, u64 need)
-+{
-+ struct btrfs_space_info *space_info = bg->space_info;
-+ u32 streak;
-+
-+ spin_lock(&space_info->lock);
-+ if (!enospc) {
-+ space_info->reclaim_enospc_streak = 0;
-+ spin_unlock(&space_info->lock);
-+ return;
-+ }
-+ streak = ++space_info->reclaim_enospc_streak;
-+ if (streak >= BTRFS_RECLAIM_ENOSPC_STREAK) {
-+ space_info->reclaim_backoff_until = (jiffies + BTRFS_RECLAIM_BACKOFF) ?: 1;
-+ space_info->reclaim_backoff_total = space_info->total_bytes;
-+ space_info->reclaim_backoff_free = reclaim_free_bytes(space_info) +
-+ max_t(u64, need, SZ_16M);
-+ space_info->reclaim_backoffs++;
-+ }
-+ spin_unlock(&space_info->lock);
-+ if (streak >= BTRFS_RECLAIM_ENOSPC_STREAK)
-+ btrfs_debug(bg->fs_info,
-+"reclaim: %u reclaims failed with ENOSPC (last block group %llu), backing off flags 0x%llx",
-+ streak, bg->start, space_info->flags);
-+}
-+
- void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limit)
- {
- struct btrfs_block_group *bg;
-@@ -5655,6 +5728,7 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- */
- list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
- while (!list_empty(&fs_info->reclaim_bgs)) {
-+ u64 need;
- int ret;
-
- bg = list_first_entry(&fs_info->reclaim_bgs,
-@@ -5664,10 +5738,27 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
-
- space_info = bg->space_info;
- spin_unlock(&fs_info->unused_bgs_lock);
-- ret = btrfs_reclaim_block_group(bg, &reclaimed);
-+ need = READ_ONCE(bg->used);
-+ /*
-+ * Backing off: drop the group rather than requeue it. The
-+ * rescans and usage updates queue it again once reclaim may
-+ * succeed. A stripe_reclaim_now request is tried regardless.
-+ */
-+ if (!READ_ONCE(bg->stripe_reclaim_forced) &&
-+ btrfs_reclaim_backoff_active(space_info)) {
-+ ret = 0;
-+ } else {
-+ int before = reclaimed;
-+
-+ ret = btrfs_reclaim_block_group(bg, &reclaimed);
-+ if (ret == -ENOSPC || reclaimed > before)
-+ reclaim_note_result(bg, ret == -ENOSPC, need);
-+ }
-
-+ /* An ENOSPC failure is not retried at once; see above. */
- if ((btrfs_is_zoned(fs_info) && ret == -EAGAIN) ||
-- (ret && !READ_ONCE(space_info->periodic_reclaim)))
-+ (ret && ret != -ENOSPC &&
-+ !READ_ONCE(space_info->periodic_reclaim)))
- btrfs_link_bg_list(bg, &retry_list);
- btrfs_put_block_group(bg);
-
-@@ -5744,6 +5835,8 @@ static void btrfs_stripe_reclaim_tick(struct btrfs_fs_info *fs_info)
- continue;
- if (!btrfs_stripe_bg_wants_reclaim(bg))
- continue;
-+ if (btrfs_reclaim_backoff_active(sinfo))
-+ break;
- spin_lock(&bg->lock);
- if (btrfs_mark_bg_to_reclaim(bg))
- bg->stripe_reclaim_jiffies = jiffies ?: 1;
-diff --git a/fs/btrfs/block-group.h b/fs/btrfs/block-group.h
-index bc26b9e875506..115d8fa7369af 100644
---- a/fs/btrfs/block-group.h
-+++ b/fs/btrfs/block-group.h
-@@ -655,6 +655,7 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- void btrfs_reclaim_bgs_work(struct work_struct *work);
- void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info);
- bool btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg);
-+bool btrfs_reclaim_backoff_active(struct btrfs_space_info *space_info);
- int btrfs_stripe_reclaim_now(struct btrfs_fs_info *fs_info, bool all, u64 start);
- int btrfs_read_block_groups(struct btrfs_fs_info *info);
- struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
-diff --git a/fs/btrfs/free-space-cache.c b/fs/btrfs/free-space-cache.c
-index d41c672f176b5..33ba40faffe22 100644
---- a/fs/btrfs/free-space-cache.c
-+++ b/fs/btrfs/free-space-cache.c
-@@ -2423,6 +2423,33 @@ void btrfs_block_group_disarm_stripe_unusable(struct btrfs_block_group *bg)
- * and queueing a group with nowhere to move it only costs writers read-only
- * transitions. Counters are read unlocked; the worker re-checks.
- */
-+/*
-+ * Relocation reserves metadata before it moves anything: 256 tree blocks
-+ * up front (RELOCATION_RESERVED_NODES), doubled on its first shortfall. When
-+ * the metadata space_info can neither hold nor overcommit that, relocating
-+ * or compacting a data group fails with -ENOSPC after the group was made
-+ * read-only, while the worker held the exclusive operation (octopus P1 at the
-+ * fill edge, bhive 2026-10-20: the data side had room, metadata had none).
-+ */
-+#define STRIPE_RECLAIM_META_NODES 512
-+
-+static bool stripe_reclaim_meta_room(struct btrfs_fs_info *fs_info)
-+{
-+ struct btrfs_space_info *meta;
-+ const u64 bytes = (u64)fs_info->nodesize * STRIPE_RECLAIM_META_NODES;
-+
-+ bool ok;
-+
-+ meta = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
-+ if (!meta)
-+ return true;
-+ spin_lock(&meta->lock);
-+ ok = btrfs_space_info_used(meta, true) + bytes <= meta->total_bytes ||
-+ btrfs_can_overcommit(meta, bytes, BTRFS_RESERVE_FLUSH_ALL, true);
-+ spin_unlock(&meta->lock);
-+ return ok;
-+}
-+
- static enum stripe_reclaim_kind __stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
- int thresh, bool force,
- bool check_room,
-@@ -2479,7 +2506,9 @@ static enum stripe_reclaim_kind __stripe_bg_reclaim_kind(struct btrfs_block_grou
- READ_ONCE(sinfo->bytes_stripe_margin);
- elsewhere -= min(elsewhere, READ_ONCE(bg->stripe_claimable));
- elsewhere -= min(elsewhere, promised);
-- return elsewhere + extra_room >= need ? kind : STRIPE_RECLAIM_NONE;
-+ if (elsewhere + extra_room < need)
-+ return STRIPE_RECLAIM_NONE;
-+ return stripe_reclaim_meta_room(bg->fs_info) ? kind : STRIPE_RECLAIM_NONE;
- }
-
- static enum stripe_reclaim_kind stripe_bg_reclaim_kind(struct btrfs_block_group *bg,
-@@ -2579,6 +2608,9 @@ void btrfs_block_group_rescan_stripe_unusable(struct btrfs_block_group *bg)
- }
- spin_unlock(&ctl->tree_lock);
- kvfree(freep);
-+ /* Reclaim backing off after ENOSPC: leave the group, the stamp too. */
-+ if (reclaim && btrfs_reclaim_backoff_active(bg->space_info))
-+ reclaim = false;
- if (reclaim) {
- /*
- * Stamp the hysteresis only if the mark lands: a group still on
-diff --git a/fs/btrfs/space-info.h b/fs/btrfs/space-info.h
-index 43124031e1926..65a92994e615c 100644
---- a/fs/btrfs/space-info.h
-+++ b/fs/btrfs/space-info.h
-@@ -282,6 +282,23 @@ struct btrfs_space_info {
- */
- u64 reclaim_errors;
-
-+ /*
-+ * Reclaim backoff after -ENOSPC: once BTRFS_RECLAIM_ENOSPC_STREAK
-+ * reclaims in a row failed for lack of space, the worker leaves this
-+ * space_info's groups alone until reclaim_backoff_until passes, a chunk
-+ * is added or removed (total_bytes leaves reclaim_backoff_total), or
-+ * its free space reaches reclaim_backoff_free. Under ->lock.
-+ */
-+ unsigned long reclaim_backoff_until;
-+ u64 reclaim_backoff_free;
-+ u64 reclaim_backoff_total;
-+ u32 reclaim_enospc_streak;
-+ /*
-+ * Monotonically increasing counter of reclaim backoffs
-+ * Exposed in /sys/fs/<uuid>/allocation/<type>/reclaim_backoffs
-+ */
-+ u64 reclaim_backoffs;
-+
- /*
- * If true, use the dynamic relocation threshold, instead of the
- * fixed bg_reclaim_threshold.
-diff --git a/fs/btrfs/sysfs.c b/fs/btrfs/sysfs.c
-index c7885e00033a8..c4cf426105afc 100644
---- a/fs/btrfs/sysfs.c
-+++ b/fs/btrfs/sysfs.c
-@@ -889,6 +889,7 @@ SPACE_INFO_ATTR(disk_total);
- SPACE_INFO_ATTR(reclaim_count);
- SPACE_INFO_ATTR(reclaim_bytes);
- SPACE_INFO_ATTR(reclaim_errors);
-+SPACE_INFO_ATTR(reclaim_backoffs);
- BTRFS_ATTR_RW(space_info, chunk_size, btrfs_chunk_size_show, btrfs_chunk_size_store);
- BTRFS_ATTR(space_info, size_classes, btrfs_size_classes_show);
-
-@@ -1027,6 +1028,7 @@ static struct attribute *space_info_attrs[] = {
- BTRFS_ATTR_PTR(space_info, reclaim_count),
- BTRFS_ATTR_PTR(space_info, reclaim_bytes),
- BTRFS_ATTR_PTR(space_info, reclaim_errors),
-+ BTRFS_ATTR_PTR(space_info, reclaim_backoffs),
- BTRFS_ATTR_PTR(space_info, periodic_reclaim),
- #ifdef CONFIG_BTRFS_DEBUG
- BTRFS_ATTR_PTR(space_info, force_chunk_alloc),
---
-2.47.3
-
+++ /dev/null
-From bc8cd9cac405fb573a08f798266215560f19b234 Mon Sep 17 00:00:00 2001
-From: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
-Date: Thu, 22 Oct 2026 04:02:53 -0400
-Subject: [RFC PATCH 116/116] btrfs: stripe_alloc: let queued exclusive
- operations in between reclaims
-To: linux-btrfs@vger.kernel.org
-
-The block group reclaim worker runs under the balance exclusive operation.
-At the fill edge, with writers active, each relocation or compaction takes
-tens of seconds (2 to 61 s measured) and the list keeps refilling, so the
-worker held the operation for most of the time writers ran: 84-90% of a
-600 s churn in reclaim-futile-test.sh, and for an hour of fsstress in the
-octopus P1 pass, where a resize and a replace could not start.
-
-btrfs-progs makes this worse than a plain refusal: before it calls the
-ioctl it reads sysfs exclusive_operation. Without --enqueue it gives up
-there; with --enqueue it waits for the notification that
-btrfs_exclop_finish() sends and then calls the ioctl. Either way the
-kernel never sees a refusal, and the worker retakes the operation right
-after each group, before a waiter can get in: on the lane a queued resize
-waited the whole churn (0 of 40 one-shot resizes succeeded, the longest
-refusal 601 s).
-
-Between groups, release the operation (btrfs_exclop_finish() sends the
-sysfs notification) and, if more groups are queued, leave it free for
-BTRFS_RECLAIM_GAP (12 s) before taking it back; if someone took it
-meanwhile, leave the rest of the list for a later run. 12 s comes from
-btrfs-progs: after the notification, check_running_fs_exclop() reopens
-the file and sleeps in a second select() for (remaining % 10) + 1 s "to
-randomize the order" before it re-reads the operation, so a waiter can
-take up to 10 s, plus wakeup latency under load, to get to the ioctl;
-with a 5 s gap about half the queued waiters woke after the worker had
-retaken the operation and waited another group. A progs change that
-re-reads right after the notification (and randomizes only when it loses
-a race) would allow a much shorter gap. With nobody waiting the gap
-costs only reclaim throughput: reclaim resumes after it.
-
-A caller that does reach btrfs_exclop_start() while the worker holds
-the operation (an ioctl user that does not pre-check sysfs) opens a
-BTRFS_RECLAIM_YIELD_WINDOW (60 s, longer than such a caller's retry
-interval and short next to the five-minute reclaim hysteresis) in which
-the worker neither starts nor takes another group. Both are backoffs
-only: no drain or accounting wait is bounded by them.
-
-A group in progress is not interrupted, so a queued operation waits for
-the rest of the current group plus at most one gap. Measured with
-reclaim-futile-test.sh (6 x 1 GiB raid5 at the fill edge, 128 MiB per
-member added, "all" written to stripe_reclaim_now, 600 s of fsstress, a
-no-op `btrfs filesystem resize` every 15 s and a `--enqueue` one every
-60 s), three traced runs per kernel:
-
- without this patch: the worker held the operation for a whole sweep
- (184, 176 and 616 s); the first queued resize waited 184, 176 and about
- 655 s, i.e. for every queued group; one-shot resizes 27/40, 28/40, 0/40.
-
- with it: every queued resize got in at the first hand-off after it
- arrived (one sat through three short groups, 23 s), 0.3-9.4 s after the
- worker's finish; longest queued waits 82, 11 and 23 s (the 82 s one sat
- behind a single 127 s group); one-shot resizes 12/40, 31/40, 27/40.
-
-Reclaim kept its pace: 10, 10 and 14 groups per 10 minutes without the
-patch, 13, 11 and 10 with it.
-
-Assisted-by: Claude:claude-opus-5-5
----
- fs/btrfs/block-group.c | 41 +++++++++++++++++++++++++++++++++++++++--
- fs/btrfs/fs.c | 29 +++++++++++++++++++++++++++++
- fs/btrfs/fs.h | 16 ++++++++++++++++
- 3 files changed, 84 insertions(+), 2 deletions(-)
-
-diff --git a/fs/btrfs/block-group.c b/fs/btrfs/block-group.c
-index fbd603e5fa416..71488e97f4adc 100644
---- a/fs/btrfs/block-group.c
-+++ b/fs/btrfs/block-group.c
-@@ -5689,6 +5689,14 @@ static void reclaim_note_result(struct btrfs_block_group *bg, bool enospc, u64 n
- streak, bg->start, space_info->flags);
- }
-
-+/* A refused operation's retry window is open: see btrfs_exclop_start(). */
-+static bool reclaim_yielding(const struct btrfs_fs_info *fs_info)
-+{
-+ const unsigned long until = READ_ONCE(fs_info->reclaim_yield_until);
-+
-+ return until && time_before(jiffies, until);
-+}
-+
- void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limit)
- {
- struct btrfs_block_group *bg;
-@@ -5706,9 +5714,12 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- if (!btrfs_should_reclaim(fs_info))
- return;
-
-+ if (reclaim_yielding(fs_info))
-+ return;
-+
- guard(super_write)(fs_info->sb);
-
-- if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
-+ if (!btrfs_exclop_start_reclaim(fs_info))
- return;
-
- /*
-@@ -5763,11 +5774,36 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- btrfs_put_block_group(bg);
-
- mutex_unlock(&fs_info->reclaim_bgs_lock);
-+ /*
-+ * Between groups, let a balance, replace or resize that is
-+ * waiting for the exclusive operation have it: a long reclaim
-+ * list must not lock them out for its whole run.
-+ */
-+ btrfs_exclop_finish(fs_info);
- /*
- * Reclaiming all the block groups in the list can take really
- * long. Prioritize cleaning up unused block groups.
- */
- btrfs_delete_unused_bgs(fs_info);
-+ /*
-+ * Leave the exclusive operation free for a moment before the
-+ * next group. btrfs-progs reads sysfs exclusive_operation
-+ * before it calls the ioctl: without --enqueue it gives up
-+ * there, and with it it waits for the notification that
-+ * btrfs_exclop_finish() just sent. Either way the refusal
-+ * never reaches btrfs_exclop_start(), so only a gap lets a
-+ * balance, replace or resize in while the list is long.
-+ */
-+ if (!list_empty_careful(&fs_info->reclaim_bgs))
-+ schedule_timeout_idle(BTRFS_RECLAIM_GAP);
-+ /*
-+ * Someone was refused the exclusive operation while we held
-+ * it: leave the rest of the list to a run after their retry.
-+ */
-+ if (reclaim_yielding(fs_info))
-+ goto out;
-+ if (!btrfs_exclop_start_reclaim(fs_info))
-+ goto out;
- /*
- * If we are interrupted by a balance, we can just bail out. The
- * cleaner thread restart again if necessary.
-@@ -5781,10 +5817,11 @@ void btrfs_reclaim_block_groups(struct btrfs_fs_info *fs_info, unsigned int limi
- spin_unlock(&fs_info->unused_bgs_lock);
- mutex_unlock(&fs_info->reclaim_bgs_lock);
- end:
-+ btrfs_exclop_finish(fs_info);
-+out:
- spin_lock(&fs_info->unused_bgs_lock);
- list_splice_tail(&retry_list, &fs_info->reclaim_bgs);
- spin_unlock(&fs_info->unused_bgs_lock);
-- btrfs_exclop_finish(fs_info);
- }
-
- void btrfs_reclaim_bgs_work(struct work_struct *work)
-diff --git a/fs/btrfs/fs.c b/fs/btrfs/fs.c
-index 75a1217727a7b..9a36fbd24e318 100644
---- a/fs/btrfs/fs.c
-+++ b/fs/btrfs/fs.c
-@@ -183,6 +183,34 @@ bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
- if (fs_info->exclusive_operation == BTRFS_EXCLOP_NONE) {
- fs_info->exclusive_operation = type;
- ret = true;
-+ } else if (test_bit(BTRFS_FS_RECLAIM_EXCLOP, &fs_info->flags)) {
-+ /*
-+ * The block group reclaim worker holds it. It is background
-+ * work: have it stand aside after its current group, long
-+ * enough for the caller to retry.
-+ */
-+ WRITE_ONCE(fs_info->reclaim_yield_until,
-+ (jiffies + BTRFS_RECLAIM_YIELD_WINDOW) ?: 1);
-+ }
-+ spin_unlock(&fs_info->super_lock);
-+
-+ return ret;
-+}
-+
-+/*
-+ * The block group reclaim worker's balance exclusive operation: marked as
-+ * the worker's, so that an operation it refuses makes it yield (see
-+ * btrfs_exclop_start()).
-+ */
-+bool btrfs_exclop_start_reclaim(struct btrfs_fs_info *fs_info)
-+{
-+ bool ret = false;
-+
-+ spin_lock(&fs_info->super_lock);
-+ if (fs_info->exclusive_operation == BTRFS_EXCLOP_NONE) {
-+ fs_info->exclusive_operation = BTRFS_EXCLOP_BALANCE;
-+ set_bit(BTRFS_FS_RECLAIM_EXCLOP, &fs_info->flags);
-+ ret = true;
- }
- spin_unlock(&fs_info->super_lock);
-
-@@ -222,6 +250,7 @@ void btrfs_exclop_finish(struct btrfs_fs_info *fs_info)
- {
- spin_lock(&fs_info->super_lock);
- WRITE_ONCE(fs_info->exclusive_operation, BTRFS_EXCLOP_NONE);
-+ clear_bit(BTRFS_FS_RECLAIM_EXCLOP, &fs_info->flags);
- spin_unlock(&fs_info->super_lock);
- sysfs_notify(&fs_info->fs_devices->fsid_kobj, NULL, "exclusive_operation");
- }
-diff --git a/fs/btrfs/fs.h b/fs/btrfs/fs.h
-index d4688bb524eaf..485363059b1c7 100644
---- a/fs/btrfs/fs.h
-+++ b/fs/btrfs/fs.h
-@@ -241,6 +241,9 @@ enum {
- */
- BTRFS_FS_STRIPE_ALLOC_ENABLING,
-
-+ /* The block group reclaim worker holds the exclusive operation. */
-+ BTRFS_FS_RECLAIM_EXCLOP,
-+
- #if BITS_PER_LONG == 32
- /* Indicate if we have error/warn message printed on 32bit systems */
- BTRFS_FS_32BIT_ERROR,
-@@ -1116,6 +1119,13 @@ struct btrfs_fs_info {
-
- /* Reclaim partially filled block groups in the background */
- struct work_struct reclaim_bgs_work;
-+ /*
-+ * A balance, replace, resize or device add/remove was refused while
-+ * the reclaim worker held the exclusive operation: until this jiffies
-+ * value the worker neither starts nor takes another group, so that the
-+ * caller's retry gets the operation.
-+ */
-+ unsigned long reclaim_yield_until;
- /* Protected by unused_bgs_lock. */
- struct list_head reclaim_bgs;
- int bg_reclaim_threshold;
-@@ -1348,6 +1358,12 @@ static inline unsigned int btrfs_blocks_per_folio(const struct btrfs_fs_info *fs
- }
-
- bool __attribute_const__ btrfs_supported_blocksize(u32 blocksize);
-+/* How long the reclaim worker stands aside after a refused operation. */
-+#define BTRFS_RECLAIM_YIELD_WINDOW (60 * HZ)
-+/* How long it leaves the exclusive operation free between two groups. */
-+#define BTRFS_RECLAIM_GAP (12 * HZ)
-+
-+bool btrfs_exclop_start_reclaim(struct btrfs_fs_info *fs_info);
- bool btrfs_exclop_start(struct btrfs_fs_info *fs_info,
- enum btrfs_exclusive_operation type);
- bool btrfs_exclop_start_try_lock(struct btrfs_fs_info *fs_info,
---
-2.47.3
-
holding committed data; the same rule covers raid56 metadata and system
chunks (stripe_meta), log commits settle the stripes of logged extents, and
an opt-in `stripe_alloc_allow_rmw` policy restores write-in-place for
-isolated nodatacow/prealloc extents. The rest of the 111 patches are the
+isolated nodatacow/prealloc extents. The rest of the patches are the
space accounting, admission, relocation and reclaim work that makes the
claim rule safe at the fill edge, and fixes from two review rounds. A test
verifies it by showing (a) the write hole on the stock allocator and its
(a WARN, a dropped write, an ENOSPC, a hang, a leaked run, a COW where the
policy promises write-in-place).
+Patch numbers in this file are those of the 116-patch export of
+2026-10-25; the last section maps them to the current 85-patch series.
+
Kernel under test for the "Current" column: misc-next zb64 568c45b64012
(uname 7.3.0-rc7+ #5, KASAN + lockdep + BTRFS_DEBUG) unless a row says
otherwise. That kernel is the integration of all 17 misc-next topics
when it is free, and randomize only when the ioctl itself loses the
race (`BTRFS_ERROR_DEV_EXCL_RUN_IN_PROGRESS`). No progs patch written;
want one?
+
+## Patch numbers: the 116-patch export -> the current series
+
+The rows above use the numbers of the 116-patch export of 2026-10-25
+(old 1-116). Old 117-125 are fixes appended on the lane after that
+export. On 2026-10-28 the appended fixes were folded into the patches
+they fix, the generic reclaim parts moved to topics/reclaim-fixes, and the
+series was reordered by subtopic: reclaim-fixes 1-3 plus stripe-alloc
+1-86 ("new"). On 2026-10-30 the review of 2026-10-29 emptied and
+removed new 86 (its sysfs lines moved into new 33, its fs.h hunk into
+the patch that retires those fields), so the series is 1-85; the
+numbers below are otherwise unchanged. A patch split by the reorder lists every new patch that
+carries a part of it. Old 116 (reclaim-fixes 4 for a while) is DO-NOT-UPSTREAM
+(Zygo, 2026-10-29); since 2026-10-30 it is in topics/test-knobs and is
+not exported.
+
+```
+old 1 -> new [1] | btrfs: add btrfs_claim_free_stripe_run() for stripe-exclusive allocati
+old 2 -> new [2] | btrfs: add open stripe run tracking for stripe-exclusive allocation
+old 3 -> new [3] | btrfs: add the stripe_alloc allocation policy for raid56 data
+old 4 -> new [4] | btrfs: stripe_alloc: control the policy with a filesystem property
+old 5 -> new [5] | btrfs: report stripe run data IO through the ordered extent lifecycle
+old 6 -> new [6] | btrfs: retire stripe runs at commit and gate stripe_alloc
+old 7 -> new [58] | btrfs: add a write-hole invariant checker to the raid56 write path
+old 8 -> new [7] | btrfs: account stripe_alloc trapped free space for honest statfs
+old 9 -> new [8] | btrfs: stripe_alloc: keep an open run per size band to trap less
+old 10 -> new [9] | btrfs: stripe_alloc: grow the frontier run instead of stranding its ta
+old 11 -> new [10] | btrfs: raid56: batch stripe_alloc partial writes into full-stripe writ
+old 12 -> folded into old 11 -> new [10] | btrfs: stripe_alloc: never claim stripes covered by a live run
+old 13 -> new [52] | btrfs: stripe_alloc: settle a logged extent's stripes at log commit
+old 14 -> new [11] | btrfs: stripe_alloc: private per-inode stripe runs for log-active inod
+old 15 -> new [55] | btrfs: stripe_alloc: carry an inode's log tail forward at fsync
+old 16 -> folded into old 11 -> new [10] | btrfs: stripe_alloc: kick parked rbios before the fast fsync's writeba
+old 17 -> new [12] | btrfs: raid56: pad sub-stripe writes to full stripes in open runs
+old 18 -> new [36] | btrfs: stripe_alloc: isolate nodatacow and preallocated extents by str
+old 19 -> new [40, 54, 56, 61] | btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated
+old 20 -> new [43] | btrfs: stripe_alloc: persist nocow runs across commits and remounts
+old 21 -> folded into old 19 -> new [40, 54, 56, 61] | btrfs: raid56: do not park sync writes into nocow runs
+old 22 -> new [13] | btrfs: raid56: expose parking statistics in sysfs
+old 23 -> folded into old 11 -> new [10] | btrfs: raid56: skip parking for sync rbios finished by their unplug ba
+old 24 -> new [14, 44, 53] | btrfs: stripe_alloc: count open stripe run remainders against data res
+old 25 -> new [15] | btrfs: stripe_alloc: pessimistic data reservation margin
+old 26 -> new [16] | btrfs: stripe_alloc: claim fully-free stripes that span free space ent
+old 27 -> new [17] | btrfs: stripe_alloc: warn when raid56 metadata is not covered
+old 28 -> new [18, 59] | btrfs: stripe_alloc: report read-modify-write of uncovered stripes
+old 29 -> new [80] | btrfs: raid56: say whether a metadata read-modify-write is a write hol
+old 30 -> new [19, 41, 81] | btrfs: stripe_alloc: tunable park deadlines, and say why padding decli
+old 31 -> new [20, 82] | btrfs: stripe_alloc: trace why padding declined, at the moment it decl
+old 32 -> new [21] | btrfs: stripe_alloc: complete parked writes on allocation coverage, no
+old 33 -> new [22, 42] | btrfs: stripe_alloc: track per-sector liveness and pad from the map
+old 34 -> new [23] | btrfs: stripe_alloc: count claimable whole-stripe supply directly
+old 35 -> new [24, 84] | btrfs: raid56: adaptive park deadline from the parked-rbio backlog
+old 36 -> new [25] | btrfs: stripe_alloc: gate data admission on claimable whole-stripe sup
+old 37 -> folded into old 26 -> new [16] | btrfs: stripe_alloc: cache a failed stripe run scan per block group
+old 38 -> new [68] | btrfs: stripe_meta: allocate tree blocks by whole stripes
+old 39 -> folded into old 7 -> new [58] | btrfs: stripe_alloc: drain the legacy allocator's writes before arming
+old 40 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: keep the admitted bytes placeable when a group go
+old 41 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: never let relocation wait on the whole-stripe gat
+old 42 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: give a queued stripe group a chunk to relocate in
+old 43 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: charge relocation a margin per reservation, not p
+old 44 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: keep the relocation group's stripes out of the ad
+old 45 -> folded into old 3 -> new [3] | btrfs: stripe_alloc: let a data write fall back to the relocation grou
+old 46 -> new [45] | btrfs: stripe_alloc: hand groups full of trapped free space to the rec
+old 47 -> folded into old 46 -> new [45] | btrfs: stripe_alloc: relocate a queued stripe group even while it has
+old 48 -> folded into old 38 -> new [68] | btrfs: stripe_meta: maintain trapped free space for metadata groups li
+old 49 -> folded into old 38 -> new [68] | btrfs: stripe_meta: back the global reserve with usable stripes, and s
+old 50 -> new [72] | btrfs: stripe_meta: hold back whole stripes so tree blocks always land
+old 51 -> folded into old 50 -> new [72] | btrfs: stripe_meta: do not steal from the global reserve below the rel
+old 52 -> folded into old 50 -> new [72] | btrfs: stripe_meta: let the transaction machinery's own reservations d
+old 53 -> folded into old 50 -> new [72] | btrfs: stripe_meta: let a group go read-only for relocation against th
+old 54 -> new [26] | btrfs: stripe_alloc: show per-group trapped bytes in the space info du
+old 55 -> folded into old 29 -> new [80] | btrfs: stripe_alloc: tell a dead tree block from a live one in the met
+old 56 -> folded into old 19 -> new [40, 54, 56, 61] | btrfs: stripe_alloc: do not read an inline backref off a keyed-ref ext
+old 57 -> new [27, 46, 73] | btrfs: stripe_alloc: count whole stripes stranded behind live runs as
+old 58 -> folded into old 20 -> new [43] | btrfs: stripe_alloc: give nocow extents a private run only while they
+old 59 -> new [28, 37] | btrfs: stripe_alloc: count nocow run lifecycles and stranded stripes i
+old 60 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: hold a stripe of margin across a preallocation
+old 61 -> folded into old 50 -> new [72] | btrfs: stripe_meta: carry raid56 metadata groups through a runtime ena
+old 62 -> folded into old 8 -> new [7] | btrfs: stripe_alloc: return a group's allocation cluster before scanni
+old 63 -> folded into old 38 -> new [68] | btrfs: stripe_alloc: release open stripe runs when a mount fails or an
+old 64 -> new [29, 60] | btrfs: stripe_alloc: say at mount whether the policy is on
+old 65 -> new [75] | btrfs: stripe_meta: cover raid56 system chunks
+old 66 -> folded into old 59 -> new [28, 37] | btrfs: stripe_alloc: close dead nocow stripe runs at commit
+old 67 -> folded into old 20 -> new [43] | btrfs: stripe_alloc: do not round a full stripe with power-of-two macr
+old 68 -> folded into old 3 -> new [3] | btrfs: stripe_alloc: do not wait for stripe runs to drain on an errore
+old 69 -> folded into old 3 -> new [3] | btrfs: stripe_alloc: end the commit-time and log drains on an errored
+old 70 -> new [47] | btrfs: stripe_alloc: compact mostly live groups instead of skipping th
+old 71 -> new [62, 83] | btrfs: stripe_alloc: attribute each data read-modify-write to why padd
+old 72 -> new [63] | btrfs: stripe_alloc: optionally audit data read-modify-writes against
+old 73 -> new [30, 48] | btrfs: stripe_alloc: keep relocation's stripe runs until relocation en
+old 74 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: let relocation allocate a data chunk before it fa
+old 75 -> new [31, 38, 69, 85] | btrfs: stripe_alloc: keep a stripe in the rbio cache until its run has
+old 76 -> new [32, 39] | btrfs: stripe_alloc: pad a stripe's allocated sectors whose write is s
+old 77 -> folded into old 4 -> new [4] | btrfs: stripe_alloc: apply the property before tree-log replay
+old 78 -> new [33] | btrfs: stripe_alloc: count refused rbio pins and track rbio cache high
+old 79 -> folded into old 78 -> new [33] | btrfs: stripe_alloc: sweep stale rbio pins, and commit when live pins
+old 80 -> new [64] | btrfs: stripe_alloc: break rbio pins and open stripe runs down by run
+old 81 -> new [77] | btrfs: stripe_alloc: give each log commit its own metadata stripe run
+old 82 -> folded into old 33 -> new [22, 42] | btrfs: stripe_alloc: don't make a parked rbio wait for sectors that wi
+old 83 -> new [57, 78] | btrfs: stripe_alloc: share LOG data runs per log transaction
+old 84 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: let relocation allocate as many data chunks as it
+old 85 -> folded into old 83 -> new [57, 78] | btrfs: stripe_alloc: key private stripe runs by subvolume and inode
+old 86 -> folded into old 3 -> new [3] | btrfs: stripe_alloc: do not treat an allocation error as a found exten
+old 87 -> folded into old 75 -> new [31, 38, 69, 85] | btrfs: stripe_alloc: mark an ended ordered extent's sectors written
+old 88 -> folded into old 83 -> new [57, 78] | btrfs: stripe_alloc: read the shared LOG run mode once per log settle
+old 89 -> folded into old 26 -> new [16] | btrfs: stripe_alloc: remove only the set bits of a bitmap when claimin
+old 90 -> folded into old 20 -> new [43] | btrfs: stripe_alloc: claim a stripe tail in one free space lock sectio
+old 91 -> folded into old 57 -> new [27, 46, 73] | btrfs: stripe_alloc: keep the stripe totals consistent with the groups
+old 92 -> folded into old 20 -> new [43] | btrfs: stripe_alloc: do not delete an unused block group that still ha
+old 93 -> folded into old 81 -> new [77] | btrfs: stripe_meta: commit before waiting for metadata runs when makin
+old 94 -> folded into old 29 -> new [80] | btrfs: raid56: do not read tree blocks under the stripe lock in the me
+old 95 -> folded into old 11 -> new [10] | btrfs: raid56: stop the park timer before destroying the raid56 workqu
+old 96 -> folded into old 3 -> new [3] | btrfs: stripe_alloc: order the filesystem error before waking stripe d
+old 97 -> folded into old 17 -> new [12] | btrfs: raid56: set a padded rbio's data bitmap under bio_list_lock
+old 98 -> folded into old 26 -> new [16] | btrfs: stripe_alloc: forget the failed-claim verdict when a cluster re
+old 99 -> folded into old 4 -> new [4] | btrfs: stripe_alloc: do not let a remount revert the stripe_alloc prop
+old 100 -> folded into old 20 -> new [43] | btrfs: stripe_alloc: do not block a NOWAIT write in the nocow stripe c
+old 101 -> folded into old 26 -> new [16] | btrfs: stripe_alloc: keep the head of a claimed free space entry under
+old 102 -> folded into old 38 -> new [68] | btrfs: stripe_meta: check the block group lookup when freeing an unwri
+old 103 -> folded into old 19 -> new [40, 54, 56, 61] | btrfs: stripe_alloc: remove the unused stripe_rmw_opt field
+old 104 -> new: comment sweep, dissolved into owners | btrfs: stripe_alloc: correct and trim the block group comments
+old 105 -> new: comment sweep, dissolved into owners | btrfs: stripe_alloc: correct and trim the comments outside the block g
+old 106 -> folded into old 81 -> new [77] | btrfs: stripe_meta: keep waiting for metadata runs that do not drain a
+old 107 -> new: comment sweep, dissolved into owners | btrfs: stripe_alloc: remove pad refusal reasons that no longer exist
+old 108 -> new [65, 79] | btrfs: stripe_alloc: count and log ordered extents that end with secto
+old 109 -> new [34, 70, 76] | btrfs: stripe_alloc: skip RAID5/6 groups that are mapped as RAID1/RAID
+old 110 -> folded into old 109 -> new [34, 70, 76] | btrfs: stripe_alloc: count single-data-stripe groups' free space in wr
+old 111 -> folded into old 34 -> new [23] | btrfs: stripe_alloc: account claimable stripes while a trim has them o
+old 112 -> folded into old 34 -> new [23] | btrfs: stripe_alloc: do not miss bitmap free space when debiting a tri
+old 113 -> new: reclaim-fixes 2 (+ new 49) | btrfs: log block group reclaim at debug level
+old 114 -> new [50] | btrfs: stripe_alloc: add stripe_reclaim_now to reclaim stripes on dema
+old 115 -> new: reclaim-fixes 3 (+ new 51) | btrfs: stripe_alloc: back off block group reclaim after repeated ENOSP
+old 116 -> not exported: DO-NOT-UPSTREAM, topics/test-knobs | btrfs: stripe_alloc: let queued exclusive operations in between reclai
+old 117 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: round to full stripes with roundup(), not round_u
+old 118 -> folded into old 108 -> new [65, 79] | btrfs: stripe_alloc: do not log unwritten sectors that are only a trun
+old 119 -> new [66] | btrfs: stripe_alloc: log the space counters when data writeback hits E
+old 120 -> folded into old 25 -> new [15] | btrfs: stripe_alloc: trim split data pieces to the chosen group's stri
+old 121 -> folded into old 50 -> new [72] | btrfs: stripe_alloc: grant data tickets under the data admission rule
+old 122 -> folded into old 36 -> new [25] | btrfs: stripe_alloc: charge a data admission for its data, not its col
+old 123 -> new [35, 67, 74] | btrfs: stripe_alloc: do not count a writeback ENOSPC drop's give-back
+old 124 -> folded into old 73 -> new [30, 48] | btrfs: tests: free the retained relocation run in the open stripe test
+old 125 -> folded into old 6 -> new [6] | btrfs: stripe_alloc: write back whole delalloc ranges, as zoned does
+```