]> git.hungrycats.org Git - linux/log
linux
8 days agoMerge branches (11 topics incl. logical-ino-costs) into misc-next/testing misc-next/testing
Zygo Blaxell [Wed, 11 Nov 2026 04:55:23 +0000 (23:55 -0500)]
Merge branches (11 topics incl. logical-ino-costs) into misc-next/testing

2026-09-21: misc-next/topics/logical-ino-costs combines the former
backref-hang, delayed-ref-fixes and logical-ino topics into one three-patch
series (reducing LOGICAL_INO costs): the add_all_parents() rewind-cycle
hang, the quadratic delayed-ref merge walk, and
BTRFS_LOGICAL_INO_ARGS_COMMIT_ROOT.  Tree unchanged by the restructure.
topics/stripe-alloc is the 2026-09-19 restructure: nine folds, the mount
option erased from history, the property patch moved to #4, plus system
chunks under stripe_meta (65 patches).

Also merges 'misc-next/topics/low-space' (topics/low-space: generic low-space behaviour improvements (reclaim errno)).

Integration of topics/low-space with topics/stripe-alloc, in block-group.c
and space-info.c (octopus only from 2026-09-29; since 2026-10-29 it lives in
topics/low-space, which is restacked on topics/stripe-alloc: "btrfs: hold
block groups free for relocation" carries it; Zygo: "they all have to be
submitted in some order as patches, not merges"):
 - a group held for relocation counts only its claimable whole stripes
   as reserve (resynced at each commit-time stripe rescan); its trapped
   space is in bytes_stripe_unusable already, and counting it twice made
   the metadata space_info read over-full on a full raid6 filesystem;
 - ordinary data writers' whole-stripe admission excludes the held
   groups' stripes; relocation still sees them.
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).

Also merges 'misc-next/topics/nocmtime' (topics/nocmtime: Jeff Layton's "btrfs: fix FMODE_NOCMTIME handling in btrfs", 4 patches; it replaces topics/dedupe-mtime, whose fix its patch 2 contains).

Also merges 'misc-next/topics/dm-stripfault' (topics/dm-stripfault: the stripfault dm target, a raid56 RMW test fixture; drop before upstream).

Also merges 'misc-next/topics/allocator-hints' (topics/allocator-hints: Kai
Krakow's allocator hint series, as on the 6.18 lane with the no-transaction
type store (v2b), replacing the four hint patches formerly carried on
zygo-misc-next-zb64, whose type store deadlocked against device remove).
Ported onto misc-next: btrfs_update_device() is already non-static
upstream (prototype not re-added), and BTRFS_DEV_STATE_TYPE_DIRTY is bit 8
because misc-next uses 6 and 7 (FLUSH_FAILED, ITEM_FOUND).
Also merges 'misc-next/topics/read-policies' (topics/read-policies: Kai
Krakow's read policies and per-device read stats: CONFIG_BTRFS_READ_POLICIES,
queue and queue-adaptive policies, CONFIG_BTRFS_PER_DEVICE_IO_STATS).
Ported onto misc-next: no offload_csum_mode (gone upstream), sysfs.c
includes <linux/string_choices.h> instead of <crypto/hash.h>.
Kconfig and sysfs.c conflicts with allocator-hints resolved as the union,
as on 6.18.

2026-10-07: rebased onto kdave misc-next 9f11e00e8027 ("btrfs: stop reading free space inodes from the commit root"), which kdave force-updated
onto a later 7.3-rc base.  Dropped from topics/raid56-fixes: "btrfs: raid56: do
not verify the content if there is no data checksum" (upstream 05d60d2ee801a).
Both stripe-alloc conflicts and the octopus conflict are Boris Burkov's SYSTEM
space change (e518b02aa180b): our stripe headroom folded into need_system_chunk,
our relocation-reserve bail-out unioned with the system-space one.

2026-10-10 (Zygo): dropped topics/raid6-fixes.  Upstream 49ba3a3c0d67
("btrfs: disguise single-data-RAID56 as RAID1/RAID1C3") maps 3-device RAID6
chunks as RAID1C3, so btrfs never calls lib/raid6 with three disks, and lib/raid6
now treats fewer than RAID6_MIN_DISKS (4) as unsupported.

2026-10-10: topics/stripe-alloc gains the 2026-10-09 review (26 patches):
fixes for the review findings F01-F14 and M01-M12 (run owner keyed by
subvolume, ended ordered extents marked written, unused-group cleanup with
open runs, commit-time and read-only metadata drains without timeout
escapes, stats removals), the comment cleanup, the unwritten-on-end log,
and skipping single-data-stripe RAID5/6 groups with their free space
counted in write admission.  Validated on cand/review-1009/misc-next-zb64
df9f142b8b87: KASAN sanity + directed and full r6c3.

2026-10-11: topics/stripe-alloc gains "account claimable stripes while a
trim has them out" (1 patch): fstrim and async discard took free ranges
out of the tree without touching stripe_claimable, so a rescan in the
window found the incremental count above its scan.  Validated on
cand/trimclaim2/misc-next-zb64 f412553a1ea9: KASAN directed
(incl. trim-claimable-race-test), claimable solo, corrupt-churn x3 (6.18).

2026-10-16: + misc-next/topics/replace-fixes (commit the canceled state when a device replace fails or is canceled).

2026-10-17: the raid56 scrub/replace commits move from
misc-next/topics/raid56-fixes to a new misc-next/topics/raid56-scrub-replace, in safe order:
per-row parity check (unrepaired full stripes still fail with -EIO),
copy original parity of unrepairable rows to the replace target, copy
unrepaired data sectors, copy every sector of raid56 data stripes, avoid
the replace source only for its own stripes, read no-extent sectors from
the replace source, and last the return-0 flip, so there is no bisect
window where replace silently drops P/Q.  misc-next/topics/replace-fixes gains
the dev-replace error-accounting series (uncorrectable read and target
write error counts, cancel progress, resumed-replace WARN fix) and the
ABORT_ON_UNCORRECTABLE start flag.  Tree identical to the tested
candidate refs/cand/r5fix-mn/testing.

2026-10-17 (Zygo): misc-next/topics/raid56-scrub-replace now starts with a copy of
Filipe Manana's "btrfs: scrub: fix lost error return value when scrubbing
raid56 parity stripe" (btrfs/for-next ec0795c045c3, verbatim), so the rebase
drops it once it is in the base.  Tree unchanged.

Also merges 'misc-next/topics/dev-stats' (topics/dev-stats: write dirty device stats when no transaction is running; a behaviour change reviewers may reject, kept droppable on its own).

Also merges 'misc-next/topics/resize-missing' (topics/resize-missing: allow shrinking a missing device so a smaller replacement fits; Qu Wenruo's 2019 patch, rewritten).

Merge topic read-repair-fixes (repair bio end_io for submit failures)

Also merges 'misc-next/topics/reflink-inline-fixes' (copy_inline_to_page() fixes:
zeroing offset in large folios/subpage, decompression error path).

Candidate: + wbkick v5 (stripe-alloc: whole-range writeback under stripe_alloc,
carry qgroup fold, fsleak fold, stripe_whole_bytes removal).

Also merges misc-next/topics/reclaim-fixes (topics/reclaim-fixes: generic block group
reclaim fixes split out of topics/stripe-alloc; its tip is an ancestor of
that topic, so it adds no tree change of its own).

2026-10-30 (Zygo 2026-10-29 rulings, restructure1030; tree unchanged but for the
BTRFS_DEBUG=n build fix folded into "optionally audit data
read-modify-writes against the committed extent tree"):
+ misc-next/topics/test-knobs, stacked on topics/stripe-alloc like a test
fixture: the reclaim exclusive-operation gap (from topics/reclaim-fixes)
and the rbio cache size debug knob (from topics/raid56-fixes), both
DO-NOT-UPSTREAM; the knob now carries its integration with stripe-alloc's
rbio pins and cache prune.  topics/raid56-scrub-replace is restacked on
topics/read-repair-fixes, which now precedes it here; the abort gate
interplay (parity scrub reporting and counting, rebuilt-data writes) is
in its commits instead of this merge.  deadlock-fixes: the relock fix is
folded into "never block on space reservations ...".
Commit messages fixed in stripe-alloc, raid56-scrub-replace and
allocator-hints.

2026-10-30 (Zygo-approved, knobmv1030): in topics/test-knobs' rbio cache size
knob and in this merge, the knob's 3-line btrfs_set_rbio_cache_size()
declaration in raid56.h moves from above raid56-fixes'
btrfs_raid56_uncache_range() to after btrfs_rbio_unpin_stale(), so the
export's revert of the knob from testing applies cleanly.  No other change.

2026-11-08 (Zygo, nc1108): "btrfs: free queued remap chunks when balance
bails out", an independent METADATA_REMAP fix, is split out of
topics/balance-resume into its own topic, misc-next/topics/remap-balance-leak,
standalone on the base and merged right after topics/balance-resume.
topics/balance-resume also gains "btrfs: write the remaining balance limits
back to the balance item" (Zygo 2026-11-08, bl1108).

Also merges 'misc-next/topics/replace-finish-deadlock' (topics/replace-finish-deadlock: two device replace
hangs at replace finishing, bio counter waits in the bio completion workers (read repair) and
across the data csum lookup; both since v6.3).

Also merges 'misc-next/topics/scrub-commit-pause' (topics/scrub-commit-pause: scrub and dev-replace drain their queued stripes and drop their commit-root paths before letting a transaction commit pass; with discard=sync they read extents the commit freed (zeros), spurious scrub errors and a cancelled replace; since v6.6; independent of the other topics).

The merge conflicts in fs/btrfs/scrub.c: the new scrub_pause_point()
goes in front of scrub_raid56_parity_stripe(), where
topics/raid56-scrub-replace adds scrub_raid56_copy_parity_rows(); both
are kept, the copy helper first.

2026-11-11 (Zygo, rm1111): misc-next/topics/remap-balance-leak is merged into
topics/balance-resume and no longer exists: its three fixes (free the
queued remap chunks, give their limit back, count METADATA_REMAP chunks as
metadata in the limit_min check) follow the limit_min-range patch, and
"btrfs: do not write queued remap chunks as processed to the balance item"
stays its own commit after the limit write-back.  The tree is identical
to the gated rm1111 candidate testing 572669889341, which adds the give-back,
the limit_min and the on-disk remap fixes to the previous testing.

7 days agobtrfs: allocator hints: make the available space estimates honor the hints misc-next/topics/allocator-hints
Zygo Blaxell [Sun, 18 Oct 2026 19:50:43 +0000 (15:50 -0400)]
btrfs: allocator hints: make the available space estimates honor the hints

The chunk allocator keeps data chunks off METADATA_ONLY and NONE_ONLY
devices and metadata and system chunks off DATA_ONLY and NONE_ONLY
devices (gather_device_info()).  The available space estimates do not:
btrfs_update_per_profile_avail() simulates chunk allocation over every
writable device, and statfs adds up every device's unallocated space.
The space of a device a hint excludes is counted as available although
no chunk of that type can ever be made from it.

Metadata overcommit trusts that estimate (calc_available_free_space()),
so once the devices metadata may use are full, reservations are granted
against chunks that cannot be allocated, and the transactions that use
them abort.  Reproducer (raid56-wh-harness alloc-hints-space-test.sh):
raid1 data and metadata on three devices of 6, 3 and 6 GiB, devid 3 set
to NONE_ONLY (5) and emptied with a full balance, then data written
until ENOSPC (devid 2 fills while devid 1 still has 3 GiB) and small
files created until ENOSPC:

  BTRFS: error (device loop2 state A) in btrfs_finish_one_ordered:3410: errno=-28 No space left
  BTRFS error (device loop2 state EA): Transaction 29 aborted (-ENOSPC)
  BTRFS info (device loop2 state EA): forced readonly

and, after a remount, a second abort from __btrfs_update_delayed_inode()
while the files were read back.  The files written since the last
commit were lost.  statfs reported 3103 MiB available at the data ENOSPC.
The same filesystem without devid 3 (6 + 3 GiB, no hints) fills
metadata to a clean ENOSPC and reports 55 MiB.

Give the estimates the allocator's view of the hints:

- btrfs_dev_alloc_hint() decides whether a chunk type may use a device
  and returns its tier; btrfs_select_hint_tiers() keeps the tiers a
  chunk would use.  gather_device_info() now uses both instead of its
  open-coded copy, so the rules live in one place.
- The per-profile estimate is kept separately for data and for metadata
  and system chunks; alloc_virtual_chunk() skips the devices the hints
  exclude for the type and picks hint tiers the way the allocator does.
  btrfs_get_per_profile_avail() takes the block group type.  Mixed block
  groups ignore the hints, as in the allocator.
- statfs leaves out devices that data chunks may not use.  Only the
  available space changes: f_bavail (df Avail) leaves out the
  unallocated space of those devices, while f_blocks (df Size) and
  f_bfree (and so df Used) still count every device, including the ones
  the hints keep data off.  On a filesystem with a METADATA_ONLY device,
  for example, Size minus Used is larger than Avail by about that
  device's unallocated space.
- A type change recomputes the estimate.

PREFERRED_NONE devices still count: the allocator uses them as the last
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.

With this change the reproducer fills metadata to a clean ENOSPC with no
abort and no lost files, and statfs reports the space data can really
use.

Assisted-by: Claude:claude-opus-5-5
7 days agobtrfs: allocator hints: don't run a transaction from the type store
Zygo Blaxell [Sun, 4 Oct 2026 14:55:00 +0000 (10:55 -0400)]
btrfs: allocator hints: don't run a transaction from the type store

btrfs_devinfo_type_store() starts and commits a transaction while kernfs
holds the attribute active.  btrfs_rm_device() removes the device's
sysfs directory, draining that attribute, while it holds its own
transaction handle and fs_devices->device_list_mutex.  A type write
racing a device remove can deadlock:

  rm_device: transaction handle, device_list_mutex -> drain devinfo/<id>/type
  type store: devinfo/<id>/type active -> commit waits for rm_device's handle

Lockdep reports the cycle (kn->active -> btrfs_trans_num_writers ->
btrfs_trans_num_extwriters -> device_list_mutex) with a type writer
looping during 'btrfs device remove'.  Joining the transaction without
committing does not help: a chunk allocation during the dev item update
makes the end of the transaction take device_list_mutex.

Do what the label and feature stores do and keep transactions out of
sysfs.  The store sets device->type under chunk_mutex (which also orders
it against chunk allocation and against the end of a device replace),
marks the device BTRFS_DEV_STATE_TYPE_DIRTY and requests a commit.
btrfs_update_dirty_device_types() writes the dirty dev items at the start
of the next commit, under device_list_mutex, after the transaction
handle, the same order as btrfs_rm_device() and btrfs_run_dev_stats(), with the
chunk tree space reserved beforehand (btrfs_reserve_chunk_metadata(), as
btrfs_grow_device() does; it takes chunk_mutex, so before the mutex).  A
dev item already deleted by a device remove is skipped.  A dev item that
cannot be written stays dirty, with a rate-limited warning, and is retried
at the next commit: a hint is not worth aborting the transaction for.  The
hint takes effect for new chunks at once and reaches the disk at the next
commit, sync or unmount.

Taking chunk_mutex in the store also closes the race at the end of a
device replace: the finish moves the hint and the dirty bit to the
target under the same mutex, so a hint change on the source either
reaches the target or, once the source has the replace devid, returns
-EBUSY.  The replace target (devid 0, no dev item) still returns -EBUSY.
Also check sb_rdonly() before BTRFS_FS_OPEN, so a read-only mount
reports -EROFS rather than -EBUSY, 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
7 days agobtrfs: allocator hints: keep the hint across device replace
Zygo Blaxell [Sun, 4 Oct 2026 04:44:58 +0000 (00:44 -0400)]
btrfs: allocator hints: keep the hint across device replace

Device replace drops the allocation hint, and changing a hint during a
replace can abort the transaction.

The replace target takes over the source's dev item when the replace
finishes, but not the in-memory device->type.  The on-disk item keeps the
hint only until the next btrfs_update_device() on the new device (any
chunk allocation on it), which writes type 0 over it.  Copy the type
together with the devid, under the same locks.

During a replace, the target is visible as devinfo/0 and has no dev item.
After the finish, the source's devid is BTRFS_DEV_REPLACE_DEVID until its
sysfs directory goes away.  A write to 'type' on either device makes
btrfs_update_device() miss the dev item (-ENOENT), and the store aborts
the transaction, forcing the filesystem read-only in the middle of the
replace.  Device remove has the same window between deleting the dev
item and removing the sysfs directory.

Return -EBUSY for the replace target and for a device with the replace
devid.  An -ENOENT that still gets past these checks (remove, or a
replace that finishes after them) ends the transaction without aborting
it and returns -ENODEV.

The source's hint can still be changed during a replace, and the target
inherits it at the finish, so a replace can move to a device of a
different type, e.g. SSD to HDD.  A write that races the finish can be
lost: it misses the dev item and returns -ENODEV, or the finish has
already copied the old type.  That is tolerable, and the next patch
closes the window.

Assisted-by: Claude:claude-opus-5-5
7 days agobtrfs: allocator hints: define the hint values unconditionally in the UAPI header
Zygo Blaxell [Sun, 4 Oct 2026 04:44:02 +0000 (00:44 -0400)]
btrfs: allocator hints: define the hint values unconditionally in the UAPI header

The BTRFS_DEV_ALLOCATION_* values sit in include/uapi/linux/btrfs_tree.h
inside #ifdef CONFIG_BTRFS_ALLOCATOR_HINTS, to keep them away from
userspace until the interface is settled.  A CONFIG_ symbol in a UAPI
header is rejected by scripts/headers_install.sh:

  error: include/uapi/linux/btrfs_tree.h: leak CONFIG_BTRFS_ALLOCATOR_HINTS to user-space

so 'make headers_install' (and the deb/rpm package targets, which run
it) fail with the patch set applied.

The values are on-disk format: they give the meaning of the low bits of
dev_item.type, and userspace (btrfs-progs) needs them to read and set a
device's hint.  Defining them changes no userspace-visible structure.
So drop the guard and always export the values.  The code that acts on
the hints stays under CONFIG_BTRFS_ALLOCATOR_HINTS.

Assisted-by: Claude:claude-opus-5-5
9 days agobtrfs: scrub: do not let a transaction commit pass under queued stripes misc-next/topics/scrub-commit-pause
Zygo Blaxell [Wed, 11 Nov 2026 03:12:36 +0000 (22:12 -0500)]
btrfs: scrub: do not let a transaction commit pass under queued stripes

Scrub and dev-replace find extents in the commit root of the extent tree,
through paths kept in the scrub context for the whole block group
(sctx->extent_path, sctx->csum_path), and fill up to SCRUB_TOTAL_STRIPES
stripes before the last of them is read.  A transaction commit waits in
btrfs_scrub_pause() until the scrub reaches the top of the
scrub_simple_mirror() loop, and then switches the commit roots and unpins
the extents the transaction freed before btrfs_scrub_continue().  With
discard=sync btrfs_finish_extent_commit() also discards them.

Nothing on the scrub side notices.  The stripes it queued before the pause
are read afterwards, and the search continues in a leaf of the old commit
root, so the scrub reads extents that are no longer allocated.  Without
discard that is harmless: the block group is read-only while it is
scrubbed, so the freed range is not reused and still holds what the scrub
expects.  With discard=sync the range reads back zeros on every mirror:

  BTRFS warning (device loop0): scrub: tree block 65617920 mirror 1 has bad bytenr, has 0 want 65617920
  BTRFS error (device loop0): scrub: unable to fixup (regular) error at logical 65617920 on dev /dev/loop0 physical 65617920
  BTRFS error (device loop0): scrub: stripe 65601536 has unrepaired metadata sector at logical 65617920
  BTRFS error (device loop0): btrfs_scrub_dev(/dev/loop0, 1, /dev/mapper/rddelay) failed -5

A scrub reports uncorrectable errors on a healthy filesystem, and a
dev-replace cancels on the first such metadata sector.  The freed blocks
are not referenced by anything, so no reader of the filesystem sees them;
btrfs check and a second scrub after the churn are clean.

Before a pause, finish the queued stripes and release both paths, so that
a commit can only pass with nothing of the scrub's still referring to the
old commit root, and the next search starts from the new one.  The parity
scrub of RAID56 has its own paths, but its pause point is reached with data
stripes queued too, so it uses the same helper.

The stale path came with 1dc4888e725d ("btrfs: scrub: avoid unnecessary
extent tree search preparing stripes"); the queued stripes are older.

scrub-stale-extent-test.sh (raid56-wh-harness) fills a raid1 filesystem
(nodesize 64K) with 100000 small files, mounts it with discard=sync, and
runs a scrub or a replace while the files are rewritten, deleted and
renamed and the filesystem is synced every 50 ms.  On v7.3.3 10 of 10
replaces cancel and 5 of 10 scrubs report uncorrectable errors; with this
patch 0 of 30 each.  Without discard, or with discard=async, nothing shows.

Fixes: 1dc4888e725d ("btrfs: scrub: avoid unnecessary extent tree search preparing stripes")
Assisted-by: Claude:claude-opus-5-5
9 days agobtrfs: do not hold the bio counter across the data csum lookup misc-next/topics/replace-finish-deadlock
Zygo Blaxell [Mon, 9 Nov 2026 01:40:09 +0000 (20:40 -0500)]
btrfs: do not hold the bio counter across the data csum lookup

Device replace can hang forever at the end, after "replace status"
already reports it finished, when data is read while it finishes.
This happens with any RAID profile:

  btrfs replace start   btrfs_rm_dev_replace_blocked <- btrfs_dev_replace_finishing
  reader                btrfs_bio_counter_inc_blocked <- btrfs_submit_bbio
                        <- read_extent_buffer_pages <- read_block_for_search
                        <- btrfs_search_slot <- btrfs_lookup_csum
                        <- btrfs_lookup_bio_sums <- btrfs_submit_bbio
                        <- btrfs_dio_submit_io

btrfs_submit_chunk() takes the bio counter before mapping the bio, and
for a data read it then looks up the data checksums.  When the csum tree
leaf is not cached, the lookup reads it, and that read goes through
btrfs_submit_chunk() and btrfs_bio_counter_inc_blocked() again.  If
btrfs_dev_replace_finishing() has set BTRFS_FS_STATE_DEV_REPLACING in
between, the reader sleeps on the second reference while it holds the
first, and replace finishing waits for the first to be dropped.  Every
other bio submission then blocks behind them.

It was reproduced on a 4-device RAID5 with one device missing,
mounted with thread_pool=64, 8 O_DIRECT readers and 2 writers:
replacing the missing device hung in round 7.  The counter was 2, and
exactly two readers were sleeping in the nested
btrfs_bio_counter_inc_blocked() under btrfs_lookup_bio_sums().

The counter only keeps the result of btrfs_map_block() valid until the
bio is submitted.  So drop it, and the mapping, for the csum lookup, take
it again afterwards and map the bio again.  That costs one more
btrfs_map_block() call per data read bio.  The mirror picked by the first
mapping is passed back in, so the bio is mapped to the same copy.

Fixes: 1c2b3ee3b0ec4 ("btrfs: pre-load data checksum for reads in btrfs_submit_bio")
Assisted-by: Claude:claude-opus-5-5
9 days agobtrfs: do not wait for device replace in the bio completion workers
Zygo Blaxell [Tue, 10 Nov 2026 04:44:08 +0000 (23:44 -0500)]
btrfs: do not wait for device replace in the bio completion workers

Device replace can hang forever at the end, after "replace status"
already reports it finished, when data that needs read repair is read
while it finishes:

  btrfs replace start   btrfs_rm_dev_replace_blocked <- btrfs_dev_replace_finishing
  btrfs-rmw (all 8)     btrfs_bio_counter_inc_blocked <- btrfs_repair_bbio_failure
                        <- btrfs_check_read_bio <- btrfs_raid56_end_io
                        <- rbio_orig_end_io <- recover_rbio

and every other task submitting bios to the filesystem blocks behind
them.

btrfs_dev_replace_finishing() sets BTRFS_FS_STATE_DEV_REPLACING and
waits for the bio counter to drop to zero.  Every bio that
btrfs_submit_chunk() counted keeps its reference until its completion
runs: a RAID56 bio until btrfs_raid56_end_io() runs in the btrfs-rmw
worker that completes its rbio, a mirrored write until
orig_write_end_io_work() runs in btrfs-endio.  Both workqueues run at
most thread_pool workers at a time.

Read repair runs in those same workers: btrfs_check_read_bio() is called
by simple_end_io_work() in btrfs-endio and by btrfs_raid56_end_io() in
btrfs-rmw.  It takes the bio counter when it submits a repair read to
the next mirror (repair_one_sector() and btrfs_end_repair_bio(), through
btrfs_submit_chunk()), and when it writes the good copy back
(btrfs_repair_bbio_failure()).  While replace finishing has the flag
set, both wait for replace to finish.  Once every worker of the pool
waits there, the counted bios queued behind them never complete, and
replace never finishes.

This is easy to hit when a missing device is replaced while its data is
read: each such read fails, is repaired by a rebuild read through
btrfs-rmw, and writes the rebuilt block back to the replace target.  On
a 4-device RAID5 with one device missing, 8 O_DIRECT readers and 2
writers, it hangs in about half the replaces.  At one hang the counter
was 15: 2 rebuild rbios queued on btrfs-rmw behind the 8 workers waiting
in the write-back, and 13 rebuild rbios waiting for the stripe locks
those 2 hold, one bio each.  On RAID6, a repair read that rebuilds a
sector from P and fails its csum goes on to rebuild from Q, and that
submission waits the same way: with the P strips corrupted, the same
test hung in the first replace, with all 8 btrfs-rmw workers in
btrfs_end_repair_bio() -> btrfs_submit_bbio() and a counter of 68 = 23
rebuild rbios queued on btrfs-rmw + 45 waiting for their stripe locks.

Run the parts of read repair that take the bio counter in a new
workqueue, btrfs-repair, that no bio completion waits for.  A worker
that waits there for replace to finish holds nothing replace waits for:
the repair bbio is not submitted yet, and the read being repaired is
held back by fbio->repair_count, which is not counted.

As before, the read being repaired completes once the write-back is
done; while replace finishes, that is once replace has finished.

Fixes: 7609afac67754 ("btrfs: handle checksum validation and repair at the storage layer")
Assisted-by: Claude:claude-opus-5-5
11 days agobtrfs: keep the old resume filters for balance items without a vrange misc-next/topics/balance-resume
Zygo Blaxell [Tue, 13 Oct 2026 18:24:01 +0000 (14:24 -0400)]
btrfs: keep the old resume filters for balance items without a vrange

This patch is optional.  It is offered so that reviewers can take it or
drop it; the author's preference is to drop it.  The previous patches do
not depend on it.

A balance item written by a kernel without the vrange bound has no vrange
filter.  With the previous patch alone, a balance that was paused or
interrupted on such a kernel and is resumed on a new one restarts from
the beginning: every block group the original request selects is
relocated again, including the ones the interrupted run created.

This patch restores the old resume adjustments for exactly those items.
When a chunk type has no vrange filter in the stored item, the resume
changes its arguments as before: it adds the soft filter if the type is
being converted, and usage=90 if it has no usage, usage range or convert
filter.  This is decided when the item is recovered at mount, before
the previous patch adds the bound, and is written back with the bound.
A chunk type with a vrange, which is every balance started by a kernel
with the previous patch and any balance the user gave a vrange, relies
on the vrange and is resumed unchanged.

The trade-off: the legacy resume neither completes the original request
(block groups more than 90% full are skipped, and so are the ones being
converted that already had the target profile) nor avoids much work on a
filesystem that is more than 90% full, and keeping it adds a layer of
surprising behavior and code for a case that only arises once, when a
balance spans the kernel upgrade.  Without it, such a balance repeats
work but skips nothing.

Assisted-by: Claude:claude-opus-5-5
8 days agobtrfs: do not write queued remap chunks as processed to the balance item
Zygo Blaxell [Wed, 11 Nov 2026 05:32:39 +0000 (00:32 -0500)]
btrfs: do not write queued remap chunks as processed to the balance item

The balance item gets the remaining limits after each processed chunk
(count_limited_chunk()).  METADATA_REMAP chunks are not processed in the
chunk walk: __btrfs_balance() queues them and balances them after the
walk, but should_balance_chunk() has already counted them down from the
metadata limit when it selected them.  Any limited chunk processed after
that writes the item with the queued chunks counted as done.  If the
balance stops before the end of the walk, by a pause, an unmount or a
crash, the queue is gone, and the balance resumed from the item has too
little left of its metadata limit to balance the chunks it never
balanced: with -mlimit=1..1 and the remap chunk selected as the one
metadata chunk, the resumed balance balances no metadata chunk.

Write the item with the queued chunks added back to the metadata limit
(limit, or limit_max of a range, as should_balance_chunk() counted them).
The in-memory limit is not changed: the walk needs it to stop selecting
chunks once the limit is used up.

Assisted-by: Claude:claude-opus-5-5
11 days agobtrfs: write the remaining balance limits back to the balance item
Zygo Blaxell [Mon, 9 Nov 2026 03:24:56 +0000 (22:24 -0500)]
btrfs: write the remaining balance limits back to the balance item

The limit filters are counted down in memory: should_balance_chunk()
decrements limit, or limit_max of a limit_min..limit_max range, for every
chunk that passes the other filters, and __btrfs_balance() restores them
after its counting pass.  A balance resumed after a pause continues with
what is left.  The balance item is never updated, so a balance resumed
after an unmount or a crash starts again from the limits that were given:
every resume can relocate up to limit more chunks.  The minimum shifts
too: the counting pass of the resume sees only the chunks that are left,
which can be fewer than limit_min, and the resume then relocates nothing.

Count a chunk against both ends of the range, and write the remaining
limits to the balance item, once the chunk has been processed.  limit and
limit_max are still decremented when the chunk is selected, as before,
and limit_min is now decremented (down to 0) when it has been processed,
after the limit_min check has let it through, so limit_min means the
remaining minimum, on disk and in memory.  A resume after an unmount or a
crash then continues from the remaining limits, like a resume after a
pause, and its limit_min check compares the chunks that are left with the
minimum that is left.  The values written are those of the real pass:
the counting pass returns to the loop before any chunk is processed, and
its decrements are undone before the real pass starts.

A chunk counts as processed when its relocation has returned for that
chunk: relocated, or left in place by ENOSPC or an active swapfile.  This
is what the in-memory limit has always counted, so a resume after an
unmount or a crash now behaves exactly like a resume after a pause.  A
pause cannot stop a chunk halfway: the pause request is checked between
chunks, so the chunk being relocated is processed and written first.  A
cancel or a fatal signal can stop a relocation, but it also ends the
balance and deletes the item.  If the item cannot be written, the balance
stops with the error, like any other error in the loop, and its item is
deleted; if the item survives that (an aborted transaction), it holds
the last committed limits, within the bound below.

The update takes its own handle on the running transaction once the
relocation has returned, and ends it without committing.  The
transaction that removed the relocated chunk has ended by then, and is
usually still the running one, so both changes usually commit together,
and the update can never commit before the removal.  A crash in between
loses the count of that one chunk, and the resumed balance can relocate
one chunk more than requested, never one fewer.  Making the update part
of the removal's transaction would mean passing the balance into
btrfs_relocate_chunk(), which device shrink and removal also use.

Only chunk types with a limit filter write the item, once per processed
chunk; a balance without limits makes no more writes than before.  The
remaining limits are visible: the BTRFS_IOC_BALANCE_PROGRESS ioctl
already returned them during the balance and now returns the same values
after a remount, and the "balance: resume" log line shows them.

Assisted-by: Claude:claude-opus-5-5
11 days agobtrfs: replace the balance resume heuristics with a vrange bound
Zygo Blaxell [Wed, 16 Sep 2026 06:29:10 +0000 (02:29 -0400)]
btrfs: replace the balance resume heuristics with a vrange bound

When a balance is resumed after a pause or an unmount,
update_balance_args() adds a usage=90 filter to every chunk type that is
not being converted.  That changes the set of block groups the original
request selected.  It skips full block groups the interrupted balance had
not reached yet, so the resumed balance can finish without having done
what was asked, and it selects again any block group the interrupted
balance created that is less than 90% full, relocating the same data a
second time.  For the chunk types that are being converted it adds the
soft filter instead, so the resume does not convert again the block
groups the interrupted balance converted, but it also skips the ones
that already had the target profile when the balance started, which the
original request selected.

Replace it with a bound fixed when the balance starts.  Before the
balance item is written, limit the vrange filter of each chunk type to
the addresses below the next chunk to be allocated: add a 0..end range
when the request had no vrange filter, or lower the end of the one it
had.  Every block group that existed when the balance started stays
selected until the balance relocates it.

New chunks are allocated after the last chunk, but relocation can remove
the highest chunks without allocating any (their data fits in free space
lower down), and the next chunk would then reuse their addresses, below
the bound.  A resumed balance would select it again, although the
interrupted one, walking downward, never would have.  So while a balance
item exists, find_next_chunk() never returns an address below the bound:
an in-memory floor, set when the balance starts and when the balance
item is recovered at mount, and cleared when the item is deleted.  Every
chunk allocated in that time, relocation targets included, stays outside
the range, on the first run and after a resume.  The gap the floor can
leave in the logical address space is harmless.

A resume now uses the arguments exactly as they were stored: the bound
already keeps out every block group the interrupted balance created,
converted ones included, so neither the usage filter nor the soft filter
is needed, and update_balance_args() goes away.

The bound does not move as the balance progresses.  Block groups the
balance has relocated are gone, so on resume the walk only revisits the
chunks it left in place above the point where it stopped (filtered out,
ENOSPC, active swapfile) and checks them against the filters again.
Nothing is skipped.

Because the bound is written with the balance item and never changes,
there is no progress to persist: a resume after an unmount or a crash
needs no extra writes.

A balance item recovered at mount is limited in the same way before the
floor is set from it: a vrange 0..end is added to each chunk type that
has none, and a vrange that ends above the next chunk is lowered to it.
That covers items written by older kernels, which have no vrange or a
vrange the user gave, which can end anywhere (a 1 TiB end would put
every new chunk at 1 TiB and above).  A bound written by this kernel
changes only when relocation removed the highest chunks and allocated
none above it; no chunk exists between the next chunk and the old end,
so lowering it drops nothing.  When the recovered arguments change,
they are written back to the balance item once, when the balance
resumes, so a resume that is interrupted again resumes with the same
bound and not with a new one that includes the chunks the first resume
allocated.  If that write fails, the balance is not resumed: as for the
other errors at that point, it ends with the error logged, and its item
is deleted.  Nothing has been relocated yet, so if the item survives (the
delete fails too, or the system crashes first), the next mount bounds it
again to the same chunks.

A balance item written by an older kernel therefore resumes with the
bound and without the usage or soft filter: the resumed balance restarts
from the beginning, relocating again every block group the request
selects, including the ones the interrupted run created or converted,
but it skips none.

The bound is visible: `btrfs balance status -v`, the
BTRFS_IOC_BALANCE_PROGRESS ioctl and the "balance: start" and "balance:
resume" log lines show a vrange the user did not give.

Assisted-by: Codex:gpt-5
Assisted-by: Claude:claude-opus-5-5
8 days agobtrfs: count METADATA_REMAP chunks as metadata in the balance limit_min check
Zygo Blaxell [Wed, 11 Nov 2026 05:32:39 +0000 (00:32 -0500)]
btrfs: count METADATA_REMAP chunks as metadata in the balance limit_min check

should_balance_chunk() already treats a METADATA_REMAP chunk as a
metadata chunk: the metadata type flag selects it, the metadata filters
apply to it, and it is charged against the metadata limit or limit_max
when it is selected, so the remap chunks queued by __btrfs_balance()
stay within the MAX of -mlimit=MIN..MAX.  The counting pass of
__btrfs_balance() also counts it in count_meta.

The limit_min check in the second pass is the only place that tests the
raw METADATA bit, which a METADATA_REMAP chunk does not have.  With
-mlimit=MIN..MAX and fewer than MIN matching metadata chunks, the
balance skips every METADATA chunk, as asked, but still relocates the
METADATA_REMAP chunk.

Test the METADATA_REMAP bit in that check as well, so that remap chunks
count as metadata in both passes and the limit bounds the total number
of block groups relocated.

Fixes: 81e5a4551c32 ("btrfs: allow balancing remap tree")
Assisted-by: Claude:claude-opus-5-5
8 days agobtrfs: give back the limit of queued remap chunks when balance bails out
Zygo Blaxell [Wed, 11 Nov 2026 05:32:31 +0000 (00:32 -0500)]
btrfs: give back the limit of queued remap chunks when balance bails out

__btrfs_balance() does not relocate METADATA_REMAP chunks in its chunk
walk: it queues them and balances them all after the walk, in
balance_remap_chunks().  should_balance_chunk() selects them as metadata
chunks, and a metadata limit filter counts them down when it selects
them, like any other chunk.

A pause request ends the walk at the error label, which drops the queue:
the queued chunks are not balanced, but the metadata limit still counts
them.  The balance control stays in memory for the resume, which then
sees the chunks again and finds the limit already used up for them.  For
example, with -mlimit=1 and the remap chunk selected as the one metadata
chunk, a balance paused while it relocates the data chunks below the
remap chunk relocates no metadata chunk at all after the resume.

Add the dropped chunks back to the metadata limit (limit, or limit_max of
a range, whichever should_balance_chunk() counted down) at the error
label.  For the other ways out through the label (cancel, errors) the
balance ends and the count does not matter.

Fixes: 81e5a4551c32 ("btrfs: allow balancing remap tree")
Assisted-by: Claude:claude-opus-5-5
11 days agobtrfs: honor FMODE_NOCMTIME when cloning misc-next/topics/nocmtime
Jeff Layton [Thu, 5 Nov 2026 20:07:45 +0000 (15:07 -0500)]
btrfs: honor FMODE_NOCMTIME when cloning

btrfs_remap_file_range() calls generic_remap_file_range_prep() through
btrfs_remap_file_range_prep(). The file_modified() call in
generic_remap_file_range_prep() skips the c/mtime update for
FMODE_NOCMTIME files, but btrfs_clone_files() then always tells
btrfs_clone() to update the c/mtime of the destination.

nfsd sets FMODE_NOCMTIME while a client holds delegated timestamps. Thus
a CLONE from the holder advances the server's ctime, and the times that
the holder returns cannot move it back.

Pass no_time_update for FMODE_NOCMTIME destinations, as dedupe already
does. Make btrfs_should_update_cmtime() available to reflink.c.

Fixes: e5e9b24ab8fa ("nfsd: freeze c/mtime updates with outstanding WRITE_ATTRS delegation")
Signed-off-by: Jeff Layton <jlayton@kernel.org>
Link: https://lore.kernel.org/r/20261105-delegts-btrfs-v1-4-a42a2b93cdc2@kernel.org
11 days agobtrfs: honor FMODE_NOCMTIME in fallocate
Jeff Layton [Thu, 5 Nov 2026 20:07:44 +0000 (15:07 -0500)]
btrfs: honor FMODE_NOCMTIME in fallocate

btrfs_fallocate() calls file_modified(), which skips the c/mtime update
for FMODE_NOCMTIME files. But the helpers that btrfs_fallocate() calls
update the times anyway:

- btrfs_prealloc_file_range() sets ctime. Its
  insert_prealloc_file_extent() tells btrfs_replace_file_extents() to
  update c/mtime.
- btrfs_fallocate_update_isize() sets ctime.

btrfs_zero_range() also calls these helpers. nfsd sets FMODE_NOCMTIME
while a client holds delegated timestamps. Thus an ALLOCATE from the
holder advances the server's ctime, and the times that the holder
returns cannot move it back.

Pass an update_times flag from btrfs_fallocate() to these helpers. Set
the flag from btrfs_should_update_cmtime(). Relocation still updates the
times.

btrfs_fallocate_update_isize() never incremented i_version. When a size
extension stayed within existing preallocation, only the ctime update
changed the NFS change attribute. Increment i_version unconditionally
there, as btrfs_prealloc_file_range() does.

Fixes: e5e9b24ab8fa ("nfsd: freeze c/mtime updates with outstanding WRITE_ATTRS delegation")
Signed-off-by: Jeff Layton <jlayton@kernel.org>
Link: https://lore.kernel.org/r/20261105-delegts-btrfs-v1-3-a42a2b93cdc2@kernel.org
11 days agobtrfs: honor FMODE_NOCMTIME when punching holes
Jeff Layton [Thu, 5 Nov 2026 20:07:43 +0000 (15:07 -0500)]
btrfs: honor FMODE_NOCMTIME when punching holes

btrfs_punch_hole() calls file_modified(), which skips the c/mtime update
for FMODE_NOCMTIME files. But btrfs_punch_hole() then updates c/mtime
itself in two places: after it replaces the extents, and in the
partial-block path. Also, when extent_info is NULL,
btrfs_replace_file_extents() updates c/mtime for each transaction.

nfsd sets FMODE_NOCMTIME while a client holds delegated timestamps. Thus
a DEALLOCATE from the holder advances the server's ctime, and the times
that the holder returns cannot move it back.

- Add btrfs_should_update_cmtime() and use it in btrfs_write_check() too.
- Replace btrfs_replace_extent_info::update_times with an update_times
  argument to btrfs_replace_file_extents(). This lets the NULL
  extent_info (hole punch) case skip the update.
- In btrfs_punch_hole(), skip the c/mtime updates for FMODE_NOCMTIME
  files.

The reflink caller that passes a NULL extent_info for a trailing hole
now also honors no_time_update, as clone_finish_inode_update() does.

Fixes: e5e9b24ab8fa ("nfsd: freeze c/mtime updates with outstanding WRITE_ATTRS delegation")
Signed-off-by: Jeff Layton <jlayton@kernel.org>
Link: https://lore.kernel.org/r/20261105-delegts-btrfs-v1-2-a42a2b93cdc2@kernel.org
11 days agobtrfs: honor FMODE_NOCMTIME in btrfs_write_check()
Jeff Layton [Thu, 5 Nov 2026 20:07:42 +0000 (15:07 -0500)]
btrfs: honor FMODE_NOCMTIME in btrfs_write_check()

btrfs_write_check() open-codes the c/mtime update and checks only
IS_NOCMTIME(inode). file_update_time() also skips the update when the
file has FMODE_NOCMTIME. nfsd sets this flag on files that have a
delegation with delegated timestamps.

Thus, on a btrfs export, WRITEs from the delegation holder update the
server's c/mtime. When the holder returns its times, nfsd restores the
mtime. nfsd cannot move ctime backward, so ctime stays newer than the
time that the holder reported. Over NFSv4.2, git test t1092 finds a
stat-dirty file.

Skip the update for FMODE_NOCMTIME files too.

Fixes: e5e9b24ab8fa ("nfsd: freeze c/mtime updates with outstanding WRITE_ATTRS delegation")
Signed-off-by: Jeff Layton <jlayton@kernel.org>
Link: https://lore.kernel.org/r/20261105-delegts-btrfs-v1-1-a42a2b93cdc2@kernel.org
13 days agobtrfs: prefer aligned dev_extent holes when allocating chunks misc-next/topics/dev-extent-defrag
Zygo Blaxell [Wed, 14 Feb 2024 05:10:23 +0000 (00:10 -0500)]
btrfs: prefer aligned dev_extent holes when allocating chunks

With the previous patch, the data, metadata and system chunk sizes can
all be set to 1 GiB, so that every dev_extent is 1 GiB long.  The holes
between them are only 1 GiB long as well if the dev_extents also start
on a common grid.  Every device reserves its first 1 MiB, so that grid
is N GiB + 1 MiB.  A dev_extent placed off the grid splits the holes on
either side into pieces shorter than 1 GiB, and the fragmentation
described in the previous patch can start from there.

find_free_dev_extent() takes the first hole that is large enough,
wherever it starts.  Make it prefer a hole on the grid: walk the holes in
device order as before, and take the first one that is large enough and
starts at N GiB + 1 MiB.  If there is none, take the first hole that is
large enough, which is what the function returned before.  If no hole is
large enough, the largest hole is still returned, with -ENOSPC.  The
hole after the last dev_extent is checked the same way.

Unless a hole on the grid is found, the search now visits every
dev_extent of the device instead of stopping at the first hole that is
large enough.

On a device where every dev_extent is 1 GiB long and on the grid, every
hole starts on the grid too, and the result is the same as before.  On a
device that has off-grid dev_extents, new chunks fill the aligned holes
first, so balancing the off-grid ones moves them onto the grid.

Assisted-by: Claude:claude-opus-5-5
13 days agobtrfs: relocation: reserve all of a folio's slices before dirtying any misc-next/topics/deadlock-fixes
Zygo Blaxell [Sun, 16 Aug 2026 20:26:54 +0000 (16:26 -0400)]
btrfs: relocation: reserve all of a folio's slices before dirtying any

relocate_one_folio() locks the target folio and then, for each cluster
extent slice inside it, takes a flushing delalloc metadata reservation,
marks the slice delalloc and re-dirties it.  From the second slice on,
the flushing reservation runs while we hold a locked, partially dirty
folio: under pressure it sleeps waiting for a reservation ticket, and
the flush states that ticket depends on -- FLUSH_DELALLOC writing back
the relocation inode (the data reloc root sits on
fs_info->delalloc_roots like any other, and BTRFS_INODE_NO_DELALLOC_FLUSH
is only honoured under in_reclaim_context), or a transaction commit,
which with flushoncommit waits for the same writeback -- block in
__folio_lock() on the folio we hold.  Note the extent lock is released
at the end of every slice iteration, so the folio lock is the resource
still held across the next reservation.  Relocation wedges the
filesystem in exactly the situation (space pressure) that balance is
usually run to relieve.

Reproduced on a plain single-device filesystem (mkfs.btrfs -d single -m
single, mounted -o noatime,max_inline=0,flushoncommit) by filling a
block group with 4K extents and running balance against concurrent
rewrites, snapshots and fsstress under space pressure.  In the capture
below the task blocked on the folio is the async reclaim worker itself
-- the worker whose job is to serve the ticket the balance task is
waiting for -- so the cycle closes with no third party and without
needing flushoncommit at all; flush_space()'s FLUSH_DELALLOC state
alone suffices.  Commits were frozen at 5519:

  == 2439077 (btrfs) -- balance, blocked on the ticket ==
  reserve_bytes+0x612/0xa00
  btrfs_reserve_metadata_bytes+0x21/0x120
  btrfs_delalloc_reserve_metadata+0x134/0x330
  relocate_file_extent_cluster+0x3f5/0x8f0  <- relocate_one_folio inlined
  relocate_data_extent.constprop.0+0x15e/0x190
  relocate_block_group+0x448/0x610
  btrfs_relocate_block_group+0xa9f/0x2710
  btrfs_relocate_chunk+0x52/0x200
  btrfs_balance+0xd6d/0x1f30
  btrfs_ioctl+0x185c/0x2a60
  __x64_sys_ioctl+0xa5/0x100

  == 1759399 (kworker/u32:11+events_unbound) -- must serve that ticket ==
  folio_wait_bit_common+0x177/0x3a0
  __folio_lock+0x17/0x30
  lock_delalloc_folios+0x1cc/0x2d0
  find_lock_delalloc_range+0x148/0x2a0
  writepage_delalloc+0x29c/0x980
  extent_write_cache_pages+0x333/0xc50
  btrfs_writepages+0x67/0xd0
  do_writepages+0xb7/0x180
  filemap_writeback+0xd1/0x100
  filemap_flush_nr+0x1f/0x30
  start_delalloc_inodes+0xd3/0x400
  btrfs_start_delalloc_roots+0x184/0x270
  flush_space+0x3a8/0x690
  do_async_reclaim_metadata_space+0x92/0x170
  btrfs_async_reclaim_metadata_space+0x64/0x90

A second capture of the same run shows the longer route, via a
wb_workfn writeback thread in __folio_lock() under
extent_write_cache_pages() with the commit waiting on it.

One slice per folio -- the 4K page, 4K sectorsize, order-0 case --
cannot deadlock: the single reservation happens while the folio is
still clean, and writeback has no business with a clean folio.
Multiple slices per folio need folio_size > extent size.  That was
originally only reachable with sub-page sector sizes, but
041c39da53c2 ("btrfs: enable large data folios for data reloc inode")
made it reachable on 4K pages under CONFIG_BTRFS_EXPERIMENTAL, and
9bce95edb1b4 ("btrfs: move large data folios out of experimental
features") makes it reachable in default builds: on 4K sectors
calc_block_max_order() yields order 6, so this loop can be handed a
256K folio spanning up to 64 slices.

Restructure the function to take all of the folio's slice reservations
up front, while the folio is still clean, keeping the per-slice
reservation granularity (each slice becomes its own delalloc extent
because of EXTENT_BOUNDARY, so per-slice accounting is the accurate
form).  A clean folio carries no dirty tag, so writeback never returns
it and never asks for its lock, and its range has no EXTENT_DELALLOC
yet, so find_lock_delalloc_range() cannot reach it either; flushing
there is safe.  The dirtying loop then consumes the reservations
without ever flushing under a dirty folio, and unwinding on error walks
the same slice geometry so reserve/release pair exactly.  ENOSPC
semantics are unchanged: the up-front reservations flush exactly like
the old in-loop ones, just at a point where flushing can still make
progress.

This relies on prealloc_file_extent_cluster() calling
filemap_invalidate_inode() with flush=true for the cluster range: a
folio shared with the previous cluster is written back and dropped
there, so it is genuinely clean when we reserve for it here.

The deadlock is a race -- the reservation has to ticket while
relocation is between slices of one folio -- so single runs prove
little in either direction.  Over repeated 15-minute runs of the above
workload, three viable runs on the unfixed kernel deadlocked twice,
while three on the fixed kernel completed with no occurrence, and with
the relocating task still observed blocked on a metadata reservation
ticket and no writeback task ever blocked on a folio: the reservation
still tickets and still flushes, it just no longer traps the flusher.

Fixes: c2832898126f ("btrfs: make relocate_one_page() handle subpage case")
Assisted-by: Claude:claude-fable-5
Assisted-by: Claude:claude-opus-5-5
13 days agobtrfs: reflink: never block on space reservations while the locked range has delalloc
Zygo Blaxell [Sun, 16 Aug 2026 07:31:14 +0000 (03:31 -0400)]
btrfs: reflink: never block on space reservations while the locked range has delalloc

The previous commit made clone_copy_inline_extent() take its transaction
handle before dirtying a folio in the locked destination range, closing a
flushoncommit deadlock for the single-extent inline clone.  Two gaps
remained, and one of them was captured live on a test box within hours:

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

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

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

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

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

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

Fixes: 05a5a7621ce6 ("Btrfs: implement full reflink support for inline extents")
Assisted-by: Claude:claude-fable-5
Assisted-by: Claude:claude-opus-5-5
13 days agobtrfs: fix flushoncommit deadlock when cloning an inline extent inside i_size
Zygo Blaxell [Sun, 16 Aug 2026 02:21:10 +0000 (22:21 -0400)]
btrfs: fix flushoncommit deadlock when cloning an inline extent inside i_size

Commit b48c980b6a7e ("btrfs: fix deadlock between reflink and transaction
commit when using flushoncommit") fixed a deadlock between a transaction
commit and a reflink that copied an inline extent's data to a folio beyond
the destination's i_size: commit-time delalloc flushing tries to invalidate
the beyond-EOF folio and blocks on the extent range lock held by the
reflink task, which itself waits for the commit when starting a transaction
to update the inode item.

The same cycle still triggers when the destination offset is inside i_size
(e.g. deduplicating a small file into a larger one, where the destination
inode's i_size exceeds the inline extent's length):
clone_copy_inline_extent() copies the inline data to a folio - dirtying it
inside the range that stays locked in the io tree for the whole clone - and
only then starts a transaction. If a commit has reached
TRANS_STATE_COMMIT_START by that point, the reflink task blocks in
wait_current_trans() while holding the range lock. With flushoncommit the
committing task flushes dirty inodes through the generic writeback path,
which knows nothing about BTRFS_INODE_NO_DELALLOC_FLUSH, and the flusher
blocks forever in find_lock_delalloc_range() on the locked range - writing
the folio back rather than invalidating it, since it is inside i_size:

  reflink:   holds the dst range lock, blocked in wait_current_trans()
  committer: btrfs_commit_transaction() -> btrfs_start_delalloc_flush()
             -> try_to_writeback_inodes_sb(), waiting for the flusher
  flusher:   writepage_delalloc() -> find_lock_delalloc_range(), blocked
             on the dst range lock

Reproduced on a plain single-device filesystem mounted with
-o flushoncommit,compress=zstd in under a minute by running concurrently:
truncating rewrites of small compressible files with fsync, FIDEDUPERANGE
over the same files (inline source extents are the essential ingredient)
and a "btrfs filesystem sync" loop.

Fix it by reserving space and starting the transaction before copying the
inline data into the folio. While the locked range is still clean the
flusher has no reason to touch it, so blocking on the transaction start is
safe, and once the handle is held the reflink task can no longer block
waiting for a commit. The space reservation moves out of
copy_inline_to_page() so it stays ordered before the transaction start,
since reserving space may itself flush and wait for a commit. The i_size
update from commit b48c980b6a7e is kept right after the copy so a folio
dirtied beyond EOF is still written back instead of being discarded by
folio invalidation.

Fixes: 05a5a7621ce6 ("Btrfs: implement full reflink support for inline extents")
Assisted-by: Claude:claude-fable-5
Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: props: keep compressing inodes with legacy compression property values misc-next/topics/compress-fixes
Zygo Blaxell [Tue, 3 Nov 2026 23:41:31 +0000 (18:41 -0500)]
btrfs: props: keep compressing inodes with legacy compression property values

Older kernels matched btrfs.compression values by algorithm name prefix
only, both in the property validator and in prop_compression_apply(),
so values such as "zstd:banana", "zstd:", "zstd:3x", "zstdgarbage", or
anything longer than BTRFS_COMPRESS_PROP_MAX_LEN were accepted, stored
verbatim, and compressed with the named algorithm.  Such values are
still found on existing filesystems.

Since per-inode compression levels were added, prop_compression_apply()
parses the value strictly and rejects these with -EINVAL.  The property is
loaded with the inode, and inode_prop_iterator() only warns about a
failed apply, so these inodes silently stop compressing, with a warning
every time the inode is loaded.

Keep compressing them as older kernels did:  in prop_compression_apply(),
match the algorithm by name prefix again, and treat a level suffix that
does not parse, or a value too long to hold a valid level, as an
unspecified level (prop_compress_level = 0).  The compression paths then
pick the level as for a value with no level at all:  the mount option's
level if the mount option uses the same algorithm, otherwise the
algorithm's default level.

setxattr still goes through prop_compression_validate(), which keeps
rejecting these values, so only values that are already stored take this
path.

Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: props: reject NUL bytes in btrfs.compression values
Zygo Blaxell [Tue, 3 Nov 2026 23:41:30 +0000 (18:41 -0500)]
btrfs: props: reject NUL bytes in btrfs.compression values

The btrfs.compression xattr value is length-delimited, and
prop_compression_validate() copies it into a NUL-terminated buffer before
btrfs_compress_is_valid_type() parses it.  An embedded NUL byte ends the
string early in the copy, so a value such as "zstd:3" followed by a NUL
and arbitrary junk passes validation and is stored verbatim, junk and
all, where getxattr returns it.

No algorithm name or level contains a NUL byte, so reject such values
before the copy.  "no" and "none" were already compared with an exact
length and are not affected.

Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: allow NODATACOW | NOCOMPRESS
Zygo Blaxell [Sun, 17 Aug 2025 20:57:07 +0000 (16:57 -0400)]
btrfs: allow NODATACOW | NOCOMPRESS

Commit f37c563bab42 ("btrfs: add missing check for nocow and compression
inode flags") added conflict checks for certain inode flag combinations,
and commit 0e852ab8974c ("btrfs: do not allow compression on nodatacow
files") extended the same logic to xattrs.

Both commits also forbade the combination of FS_NOCOW_FL (NODATACOW)
and FS_NOCOMP_FL (NOCOMPRESS).  This restriction is undocumented, has
no technical basis, and provides no benefit.  NODATACOW files cannot be
compressed in any case, so the NOCOMPRESS bit is a no-op:  behavior is
the same whether the flag is present or not.

Forcing an unnecessary conflict makes inode flags harder to use.
Portable applications may inherit COMPRESS, NOCOMPRESS, or NODATACOW bits
from parent directories and combine them with unrelated flags such as
IMMUTABLE or NOATIME.  Rejecting otherwise valid flag sets with EINVAL
creates surprises for applications that do not know about btrfs-specific
interactions and only touch the flags they care about.

Fix by permitting the combination of NODATACOW and NOCOMPRESS, both via
FS_IOC_SETFLAGS and by setting btrfs.compression to "no"/"none" through
xattrs.

Fixes: f37c563bab42 ("btrfs: add missing check for nocow and compression inode flags")
Fixes: 0e852ab8974c ("btrfs: do not allow compression on nodatacow files")
Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: fix nodatacow vs compression inode flag conflict check
Zygo Blaxell [Sun, 17 Aug 2025 02:20:01 +0000 (22:20 -0400)]
btrfs: fix nodatacow vs compression inode flag conflict check

Applications expect inode flags to be orthogonal: changes can be combined
or applied separately in any order, as long as each intermediate state is
valid and unchanged flags are left untouched.

Commit f37c563bab42 ("btrfs: add missing check for nocow and compression
inode flags") intended to forbid combining FS_NOCOW_FL with either
FS_NOCOMP_FL or FS_COMPR_FL. The implementation contained a bug and
introduced multiple regressions.

Bug: FS_NOCOW_FL (+C) and FS_NOCOMP_FL (+m) can still be set together in
a single FS_IOC_SETFLAGS call, even though the commit message states this
combination should be rejected.

Regression 1: Switching from +C+m back to -C-m only works if both flag
changes are combined into one ioctl; separate -C and -m calls are
rejected.

Regression 2: Switching between +C-c and -C+c only works if the changes
are split across multiple ioctls; a combined -C+c call is rejected.

Regression 3: Inodes created on kernels before commit f37c563bab42
("btrfs: add missing check for nocow and compression inode flags") with
both COMPR and NOCOW set cannot have any other fsattrs changed on newer
kernels. Even unrelated operations (such as adding +i, or clearing just
one of the compression bits) fail with EINVAL, because the conflict
check rejects the entire ioctl whenever conflicting bits are present,
even if those bits are not being modified. This makes it impossible to
manage older files without first undoing their existing flags.

Fix by:
 * Rewriting the conflict checks so FS_NOCOW_FL cannot be combined with
   FS_NOCOMP_FL or FS_COMPR_FL in any ioctl (fixes the original bug and
   regressions 1-2).
 * Allowing existing conflicting flags to remain if they are not modified
   by the ioctl (fixes regression 3).
 * Moving the check later in the flag-validation sequence so that it
   occurs after handling the long-standing rule that FS_NOCOW_FL changes
   are silently ignored on non-empty files. This preserves the pre-existing
   behavior while still applying the corrected conflict logic.

Also commit the new inode flags to the inode before setting the
compression property, restoring them if the property cannot be set:
property validation rejects compression on nodatacow inodes based on
the inode's current flags, which would otherwise reject a single ioctl
that both clears NOCOW and sets COMPR (regression 2) even with the
conflict check corrected.

Fixes: f37c563bab42 ("btrfs: add missing check for nocow and compression inode flags")
Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
2 weeks agobtrfs: preserve btrfs.compression when setting inode flags
koraynilay [Tue, 3 Nov 2026 19:47:34 +0000 (20:47 +0100)]
btrfs: preserve btrfs.compression when setting inode flags

Commit e8a0095c7df170 ("btrfs: preserve the compression property when
other inode flags change") fixed an issue where any call to
FS_IOC_SETFLAGS (e.g. via chattr) would overwrite the btrfs.compression
property with the mount default compression type, even when no flag bits
change and even for flags unrelated to compression.

Update the fixed code to also preserve the newly introduced level
specification by using the new btrfs_compress_typelevel2str() helper.

Also move BTRFS_COMPRESS_PROP_MAX_LEN from props.c to props.h so it can
be used by ioctl.c, since it now requires a temporary buffer to write the
property string to.

[ Commit message and code adapted from Zygo's patch for this same issue ]

Reported-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Suggested-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Assisted-by: Gemini:3.1-pro antigravity-cli-1.1.7
Signed-off-by: koraynilay <koray.fra@gmail.com>
Link: https://lore.kernel.org/r/20261103194734.598182-7-koray.fra@gmail.com
2 weeks agobtrfs: add btrfs_compress_typelevel2str() helper
koraynilay [Tue, 3 Nov 2026 19:47:33 +0000 (20:47 +0100)]
btrfs: add btrfs_compress_typelevel2str() helper

Add the type:level equivalent of btrfs_compress_type2str() and use it
in prop_compression_extract() .

Signed-off-by: koraynilay <koray.fra@gmail.com>
Link: https://lore.kernel.org/r/20261103194734.598182-6-koray.fra@gmail.com
2 weeks agobtrfs: support inheritance for per-inode compression levels
koraynilay [Tue, 3 Nov 2026 19:47:32 +0000 (20:47 +0100)]
btrfs: support inheritance for per-inode compression levels

Change prop_handler's extract() signature to take an output buffer and
its length. This allows for the algo:level string to be generated
dynamically, but now the caller is in charge of managing that buffer
memory. Before this patch prop_compression_extract() would return only
the address of statically compiled string without being able to add the
level, now it concatenates the level to that statically compiled string.

This signature change is fine because the only currently supported prop
is compression, so there is only 1 extract() function.

Assisted-by: Gemini:3.1-pro antigravity-cli-1.1.5
Signed-off-by: koraynilay <koray.fra@gmail.com>
Link: https://lore.kernel.org/r/20261103194734.598182-5-koray.fra@gmail.com
2 weeks agobtrfs: add per-inode compression levels in xattrs
koraynilay [Tue, 3 Nov 2026 19:47:31 +0000 (20:47 +0100)]
btrfs: add per-inode compression levels in xattrs

Add support for specifying algo:level using
btrfs property set /path/to/file compression "algo:level".

Add a signed 8 bit prop_compress_level property to btrfs_inode, which
can support from level -128 to 127, plenty for the currently supported
algo:level(s).

Change prop_compression_apply() to use the already present
btrfs_match_compress_type() and btrfs_compress_str2level() to parse the
xattr, using a stack-based buffer and memcpy() to convert the
user-supplied xattr value to a NUL-terminated string to be used by
btrfs_compress_str2level().

Assisted-by: Gemini:3.1-pro antigravity-cli-1.1.5
Signed-off-by: koraynilay <koray.fra@gmail.com>
Link: https://lore.kernel.org/r/20261103194734.598182-4-koray.fra@gmail.com
2 weeks agobtrfs: also validate compression levels in btrfs_compress_is_valid_type()
koraynilay [Tue, 3 Nov 2026 19:47:30 +0000 (20:47 +0100)]
btrfs: also validate compression levels in btrfs_compress_is_valid_type()

Change btrfs_compress_is_valid_type() to use btrfs_match_compress_type()
and btrfs_compress_str2level() instead of a simple strncmp(), which would
validate even incorrect strings (e.g. "zstd:invalid" or "zstdinvalid").

This also makes the function validate levels in the same way the
compress= option gets parsed, allowing bigger or smaller values, but
still clamping them to the min or max supported.

Furthermore, remove the len parameter, since now it requires a
NUL-terminated string because of btrfs_compress_str2level(); this change
is fine because btrfs_compress_is_valid_type() is used only once in
props.c by prop_compression_validate(), which now uses a stack-based
buffer and memcpy() to convert the user-supplied xattr value to a
NUL-terminated string.

Assisted-by: Gemini:3.1-pro antigravity-cli-1.1.5
Signed-off-by: koraynilay <koray.fra@gmail.com>
Link: https://lore.kernel.org/r/20261103194734.598182-3-koray.fra@gmail.com
2 weeks agobtrfs: export btrfs_match_compress_type(), move it to compression.h
koraynilay [Tue, 3 Nov 2026 19:47:29 +0000 (20:47 +0100)]
btrfs: export btrfs_match_compress_type(), move it to compression.h

Export btrfs_match_compress_type() from being a static and locally used
function in super.c and move it to compression.c, exporting it in
compression.h.  This allows it to be used in the next patches as
validation for compression algorithm names.

Assisted-by: Gemini:3.1-pro antigravity-cli-1.1.5
Signed-off-by: koraynilay <koray.fra@gmail.com>
Link: https://lore.kernel.org/r/20261103194734.598182-2-koray.fra@gmail.com
2 weeks agobtrfs: dont propagate nodatacow mount option on files with inherited compression
Filipe Manana [Mon, 2 Nov 2026 19:55:04 +0000 (19:55 +0000)]
btrfs: dont propagate nodatacow mount option on files with inherited compression

If we set the compression property on a directory and the filesystem was
mounted with the nodatacow option, then when creating a file under that
directory we get both the compression and nodatacow attributes set on the
file. These are incompatible attributes as compression requires COW.

This has a couple unexpected behaviours:

1) If later a user sets another attribute on the file, like immutability
   or append writing mode for example, the chattr command will fail with
   -EINVAL since we in the setattr callback (btrfs_fileattr_set()) we do
   some validation, through a call to check_fsflags(), that rejects having
   both the nodatacow and compression flags set.

   I.e, doing a simple:

     $ chattr +i file
     /usr/bin/chattr: Invalid argument while setting flags on file

2) The file ends up not being compressed, which is unexpected since the
   compression attribute set on a directory/file should have precedence
   over the global nodatacow mount option.

Example reproducer:

   $ cat test.sh
   #!/bin/bash

   DEV=/dev/sdi
   MNT=/mnt/sdi

   mkfs.btrfs -f $DEV
   mount -o nodatacow $DEV $MNT

  # Create a directory with the compression attribute, so that all files
  # created under it inherit the compression attribute.
  mkdir $MNT/dir
  chattr +c $MNT/dir

  # Now create a file with some data inside the directory.
  xfs_io -f -c "pwrite 0 128K" $MNT/dir/foo

  # Now try to make the file immutable, it should work.
  chattr +i $MNT/dir/foo

  umount $MNT

  # Check the file has a compressed extent. It should have since
  # despite the fs being mounted with nodatacow, the directory has
  # the compression flag set and so that should take priority and
  # it's what makes sense.
  btrfs inspect-internal dump-tree -t 5 $DEV | grep -A 5 'EXTENT_DATA 0'

Running it:

  $ ./test.sh
  (...)
  chattr: Invalid argument while setting flags on /mnt/sdi/dir/foo
        item 11 key (258 EXTENT_DATA 0) itemoff 15529 itemsize 53
             generation 9 type 1 (regular)
             extent data disk byte 13631488 nr 131072
             extent data offset 0 nr 131072 ram 131072
             extent compression 0 (none)
             extent encryption 0

Fix this by updating btrfs_create_new_inode() to not apply the mount
options nodatacow and nodatasum on a file that has inherited compression
from its parent directory.

A test case will follow soon for fstests.

Signed-off-by: Filipe Manana <fdmanana@suse.com>
Link: https://lore.kernel.org/r/1c729c63075e727042efdeb07df10a70b0ba1a0d.1793647368.git.fdmanana@suse.com
Reviewed-by: Qu Wenruo <wqu@suse.com>
2 weeks agobtrfs: honor allocator hints for fixed-width mirrors
KeinNiemand [Sun, 30 Aug 2026 12:50:54 +0000 (14:50 +0200)]
btrfs: honor allocator hints for fixed-width mirrors

gather_device_info() admits complete allocation-hint groups until it
has at least devs_min devices. It then clears the hints and sorts the
admitted devices globally by max_avail. For a fixed-width mirrored
profile, that second sort can move preferred devices past the later
devs_max cutoff.

RAID1, RAID1C3 and RAID1C4 currently use exactly devs_min devices.
Limit the hint-ordered prefix to that fixed count before clearing the
hints. Devices within each hint group are already ordered by max_avail,
so this keeps the best devices needed from the final group.
The existing second sort then restores the max_avail ordering expected
by stripe-size calculation over the selected devices only.

Check that devs_min and devs_max match instead of relying on the
current RAID1 profile definitions implicitly. If a future RAID1 profile
becomes variable-width, it will retain the existing whole-group
behavior.

Leave all other profiles unchanged, in particular the wide striped
profiles that need the complete final candidate group.

A preferred device remains eligible while it has at least
dev_extent_min free. It can therefore constrain stripe_size and produce
a small block group. This behavior already exists when the preferred
tier alone satisfies the profile; this change intentionally extends it
to fixed-width mirrors assembled from multiple hint tiers.

v2:
- Document the possible chunk-size constraint from a nearly full
  preferred device.

Assisted-by: Codex:GPT-5
Assisted-by: Codex:gpt-5.6-sol
Signed-off-by: KeinNiemand <18308201+KeinNiemand@users.noreply.github.com>
Signed-off-by: Kai Krakow <kai@kaishome.de>
2 weeks agobtrfs: add allocator_hint to disable allocation completely
Kai Krakow [Fri, 10 Jul 2026 21:51:46 +0000 (23:51 +0200)]
btrfs: add allocator_hint to disable allocation completely

This is useful where you want to prevent new allocations of chunks to a
set of multiple disks which are going to be removed from the pool. This
acts as a multiple `btrfs dev remove` on steroids that can remove
multiple disks in parallel without moving data to disks which would be
removed in the next round. In such cases, it will avoid moving the same
data multiple times, and thus avoid placing it on potentially bad
disks.

The restriction applies to non-mixed block groups. Mixed data and
metadata block groups intentionally ignore allocator hints. Device
replace does not copy the hint to the target device, so reapply it
after replacement.

v2:
- Clarify the mixed-block-group scope and device replace behavior.

Thanks to @Zygo for the explanation and suggestion.

Link: https://github.com/kdave/btrfs-progs/issues/907#issuecomment-2520897104
Signed-off-by: Kai Krakow <kai@kaishome.de>
2 weeks agobtrfs: add allocator_hint for no allocation preferred
Kai Krakow [Fri, 10 Jul 2026 22:09:55 +0000 (00:09 +0200)]
btrfs: add allocator_hint for no allocation preferred

This is useful where you want to avoid new allocations of chunks on a
disk which is going to be removed from the pool anyways, e.g. due to
bad blocks or because it's slow.

The preference applies to non-mixed block groups. Mixed data and
metadata block groups intentionally ignore allocator hints.

v2:
- Clarify that mixed block groups are outside the allocator-hints
  scope.

Signed-off-by: Kai Krakow <kai@kaishome.de>
2 weeks agobtrfs: add allocator_hint mode
Kai Krakow [Fri, 10 Jul 2026 22:18:02 +0000 (00:18 +0200)]
btrfs: add allocator_hint mode

When this mode is enabled, the chunk allocation policy is modified as
follows:

Each disk may have a different tag:
- BTRFS_DEV_ALLOCATION_PREFERRED_METADATA
- BTRFS_DEV_ALLOCATION_METADATA_ONLY
- BTRFS_DEV_ALLOCATION_DATA_ONLY
- BTRFS_DEV_ALLOCATION_PREFERRED_DATA (default)

Where:
- ALLOCATION_PREFERRED_X means that it is preferred to use this disk
  for the X chunk type (the other type may be allowed when the space is
  low)
- ALLOCATION_X_ONLY means that it is used *only* for the X chunk type.
  This means also that it is a preferred choice.

Each time the allocator allocates a chunk of type X, first it takes the
disks tagged as ALLOCATION_X_ONLY or ALLOCATION_PREFERRED_X.

If the space is not enough, it uses also the disks tagged as
ALLOCATION_METADATA_ONLY.

If the space is not enough, it uses also the other disks, with the
exception of the one marked as ALLOCATION_PREFERRED_Y, where Y is the
other type of chunk (i.e. not X).

Mixed data and metadata block groups intentionally ignore all hints. They
cannot separate the two chunk classes and are outside the tiering use case
targeted by this feature.

The current type-based interface also has two known limitations: device
replace does not copy hints to the target device, and hint updates are not
serialized with concurrent chunk allocation.

v2:
- Document the mixed-block-group scope and the limitations of the
  type-based interface.

Co-authored-by: Goffredo Baroncelli <kreijack@inwind.it>
Signed-off-by: Kai Krakow <kai@kaishome.de>
2 weeks agobtrfs: change the DEV_ITEM 'type' field via sysfs
Kai Krakow [Fri, 10 Jul 2026 22:25:21 +0000 (00:25 +0200)]
btrfs: change the DEV_ITEM 'type' field via sysfs

Known limitations:

- Device replace does not copy the allocation hint to the target
  device. Users must reapply it after replacement.
- The sysfs update is not serialized with chunk allocation through
  chunk_mutex, so an allocation concurrent with an update may observe
  either value.

A future revision should replace the type field with dedicated
transactional structures. Transactions should not be triggered directly
from sysfs writes, see:

https://lore.kernel.org/linux-btrfs/20251213200920.1808679-1-kai@kaishome.de/

v2:
- Adds a check to prevent modification while the file system is still
  mounting.

v3:
- Accept only valid allocation hint types

v4:
- Document the device replace and chunk allocation synchronization
  limitations of the current type-based interface.

Link: https://github.com/kakra/linux/pull/36#issuecomment-3406301805
Reported-by: Eli Venter <eli@genedx.com>
Co-authored-by: Goffredo Baroncelli <kreijack@inwind.it>
Signed-off-by: Kai Krakow <kai@kaishome.de>
2 weeks agobtrfs: export dev_item.type in /sys/fs/btrfs/<uuid>/devinfo/<devid>/type
Kai Krakow [Fri, 10 Jul 2026 22:22:50 +0000 (00:22 +0200)]
btrfs: export dev_item.type in /sys/fs/btrfs/<uuid>/devinfo/<devid>/type

Co-authored-by: Goffredo Baroncelli <kreijack@inwind.it>
Signed-off-by: Kai Krakow <kai@kaishome.de>
2 weeks agobtrfs: add flags to give a hint to the chunk allocator
Kai Krakow [Fri, 10 Jul 2026 22:51:17 +0000 (00:51 +0200)]
btrfs: add flags to give a hint to the chunk allocator

Add the following flags to give a hint about which chunk should be
allocated on which a disk.

The following flags are created:

- BTRFS_DEV_ALLOCATION_PREFERRED_DATA
  preferred data chunk, but metadata chunk allowed
- BTRFS_DEV_ALLOCATION_PREFERRED_METADATA
  preferred metadata chunk, but data chunk allowed
- BTRFS_DEV_ALLOCATION_METADATA_ONLY
  only metadata chunk allowed
- BTRFS_DEV_ALLOCATION_DATA_ONLY
  only data chunk allowed

Co-authored-by: Goffredo Baroncelli <kreijack@inwind.it>
Signed-off-by: Kai Krakow <kai@kaishome.de>
2 weeks agobtrfs: add new Kconfig option for btrfs allocator hints
Kai Krakow [Fri, 10 Jul 2026 21:49:05 +0000 (23:49 +0200)]
btrfs: add new Kconfig option for btrfs allocator hints

Signed-off-by: Kai Krakow <kai@kaishome.de>
2 weeks agobtrfs: scrub: stop scrub and device replace when the filesystem has an error misc-next/topics/replace-fixes
Zygo Blaxell [Thu, 29 Oct 2026 21:52:59 +0000 (17:52 -0400)]
btrfs: scrub: stop scrub and device replace when the filesystem has an error

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
2 weeks agobtrfs: mount a single device filesystem with a device replace in progress
Zygo Blaxell [Thu, 29 Oct 2026 16:17:21 +0000 (12:17 -0400)]
btrfs: mount a single device filesystem with a device replace in progress

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
2 weeks agobtrfs: dev-replace: optionally abort on uncorrectable read errors
Zygo Blaxell [Fri, 16 Oct 2026 17:02:21 +0000 (13:02 -0400)]
btrfs: dev-replace: optionally abort on uncorrectable read errors

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
2 weeks agobtrfs: dev-replace: report the progress of a canceled replace
Zygo Blaxell [Fri, 16 Oct 2026 08:07:34 +0000 (04:07 -0400)]
btrfs: dev-replace: report the progress of a canceled replace

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
2 weeks agobtrfs: dev-replace: do not skip the rest of a chunk when resuming a replace
Zygo Blaxell [Thu, 29 Oct 2026 16:17:20 +0000 (12:17 -0400)]
btrfs: dev-replace: do not skip the rest of a chunk when resuming a replace

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
2 weeks agobtrfs: dev-replace: count write errors to the target again
Zygo Blaxell [Fri, 16 Oct 2026 08:07:34 +0000 (04:07 -0400)]
btrfs: dev-replace: count write errors to the target again

btrfs_dev_replace::num_write_errors is reported by the dev-replace status
ioctl, and scrub_enumerate_chunks() stops a replace with -EIO once it is
non-zero, so that a target that fails writes does not silently end up as
the new device.  Since the dev-replace writeback moved to the
scrub_stripe infrastructure nothing increments it: status always shows 0
write errors, and the abort never happens.

After the replace writes of a stripe have completed, add the sectors
whose write failed.  The stripe's write_error_bitmap also collects failed
repair writes to the source device, so clear it before the replace
writes are submitted.

Fixes: e02ee89baa66c ("btrfs: scrub: switch scrub_simple_mirror() to scrub_stripe infrastructure")
Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: dev-replace: do not warn when a resumed replace fails
Zygo Blaxell [Fri, 16 Oct 2026 17:58:22 +0000 (13:58 -0400)]
btrfs: dev-replace: do not warn when a resumed replace fails

btrfs_dev_replace_kthread() continues a replace at mount time and warns
when btrfs_dev_replace_finishing() returns anything other than 0 or
-ECANCELED.  When the scrub fails, btrfs_dev_replace_finishing() cancels
the replace, logs "btrfs_scrub_dev(...) failed %d" and returns the scrub's
error, so the warning fires for ordinary replace failures that the ioctl
path just returns to userspace: -EROFS after a filesystem error, -ENOMEM,
and -EIO once write errors to the target stop the replace again.

The failure is already logged and recorded as a canceled replace.  Drop
the WARN_ON.

Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: dev-replace: count uncorrectable read errors
Zygo Blaxell [Fri, 16 Oct 2026 08:07:34 +0000 (04:07 -0400)]
btrfs: dev-replace: count uncorrectable read errors

btrfs_dev_replace::num_uncorrectable_read_errors is reported by the
dev-replace status ioctl ("uncorr. read errs" in btrfs replace status)
and stored in the dev_replace item, but nothing increments it.

Even before v4.19 only two replace paths counted it: the nodatasum fixup
worker, when it could not repair a sector through the page cache, and
the nocow copy worker, when it could not write a range to the target.
Uncorrectable sectors with checksums, data or metadata, went through
scrub_handle_errored_block(), which counted them in the scrub stats but
not here.  Both paths were removed in v4.19, by commits 9bebe665c3e4
("btrfs: scrub: Remove unused copy_nocow_pages and its callchain") and
8b9b6f255485 ("btrfs: scrub: cleanup the remaining nodatasum fixup
code"), and the scrub_stripe based scrub never counted it either.  Status
always shows 0, however many sectors could not be copied.

Count the sectors that flush_scrub_stripes() does not write to the
replace target because they are covered by an extent but could not be
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
2 weeks agobtrfs: scrub: do not count write errors twice, or on the wrong device
Zygo Blaxell [Fri, 16 Oct 2026 08:07:33 +0000 (04:07 -0400)]
btrfs: scrub: do not count write errors twice, or on the wrong device

scrub_write_endio() increments the write error counter of stripe->dev
for every sector of a failed write.  The bio layer has already counted
the failure: scrub writes are submitted through
btrfs_submit_repair_write() to a single device, and btrfs_simple_end_io()
calls btrfs_log_dev_io_error() on that device.

For a repair write the device is stripe->dev, so the error is counted
twice.  For a dev-replace write the bio goes to the replace target, which
the bio layer charges correctly, while scrub_write_endio() also charges
the source device, which did not fail.

Drop the extra accounting in scrub_write_endio(); the write_error_bitmap
it maintains is unchanged.

Fixes: ec1f3a207cdf3 ("btrfs: scrub: update device stats when an error is detected")
Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: commit the canceled state when a device replace fails or is canceled
Zygo Blaxell [Fri, 16 Oct 2026 05:19:17 +0000 (01:19 -0400)]
btrfs: commit the canceled state when a device replace fails or is canceled

When the scrub copying a device replace returns an error, including
-ECANCELED from "btrfs replace cancel" on a running replace,
btrfs_dev_replace_finishing() sets the replace state to CANCELED, marks
the dev_replace item for writeback and destroys the target device, but
returns without committing a transaction.

If no other transaction commits before the filesystem is unmounted (an
idle filesystem), the item on disk still says STARTED.  The next mount
then tries to resume the replace and 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

Commit a transaction after the cleanup, as btrfs_dev_replace_cancel()
already does when it cancels a suspended replace, so the CANCELED state
reaches the disk.  A failure to commit is only logged: the replace has
already failed, and its return value is the scrub error.

Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: don't trim the target of a device replace
Josef Bacik [Tue, 3 Nov 2026 15:05:20 +0000 (15:05 +0000)]
btrfs: don't trim the target of a device replace

FITRIM also discards the space of every device that is not allocated to a
chunk. btrfs_trim_free_extents() goes over fs_devices->devices and, for
each device that is writeable, discards the ranges that have neither
CHUNK_ALLOCATED nor CHUNK_TRIMMED set in device->alloc_state.

The target device of a running replace operation is on that list and it is
writeable. But its alloc_state is empty. The allocated ranges of the
source device are only copied to it by btrfs_set_target_alloc_state(),
when the replace finishes. Until then the whole device looks unallocated,
so an fstrim discards everything that was copied to it so far, and what is
being written to it in parallel to the source device.

The replace finishes without any error and the source device is dropped.
With a single device filesystem, 700M of data and fstrim called in a loop
while the replace runs:

  BTRFS info: dev_replace from /dev/vdb (devid 1) to /dev/vdc finished
  BTRFS error: bad tree block start, mirror 1 want 30638080 have 0
  BTRFS error: bad tree block start, mirror 2 want 30638080 have 0
  BTRFS info: scrub: not finished on devid 1 with status: -5

Skip the target device. The flag is cleared with the device list mutex
held, after the alloc_state was set up, and the trimming code holds that
mutex while it works on a device.

Fixes: 499f377f49f0 ("btrfs: iterate over unused chunk space in FITRIM")
CC: stable@vger.kernel.org
Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
Link: https://lore.kernel.org/r/20261103-b4-btrfs-data-integrity-v2-5-577dc2690061@toxicpanda.com
2 weeks agoDO-NOT-UPSTREAM: btrfs: raid56: debug knob for the rbio stripe cache size misc-next/topics/test-knobs
Zygo Blaxell [Thu, 1 Oct 2026 07:54:55 +0000 (03:54 -0400)]
DO-NOT-UPSTREAM: btrfs: raid56: debug knob for the rbio stripe cache size

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, except for the stripes stripe_alloc pins there until their run
has written all of them.  Lowering it empties the cache, and cache_rbio()
passes the limit to rbio_cache_prune(), which prunes as far as needed, so
a lowered limit holds.

It sits in topics/test-knobs, on top of topics/stripe-alloc, whose rbio
pins and cache prune it adapts to.

Assisted-by: Claude:claude-opus-5-5
2 weeks agoDO-NOT-UPSTREAM: btrfs: let queued exclusive operations in between block group reclaims
Zygo Blaxell [Thu, 22 Oct 2026 08:02:53 +0000 (04:02 -0400)]
DO-NOT-UPSTREAM: btrfs: let queued exclusive operations in between block group reclaims

DO-NOT-UPSTREAM: this works around the reclaim worker starving queued
exclusive operations.  Whether upstream wants to do anything about that
starvation, and what, is upstream's decision; this stays on our lanes.

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).

After each group that was relocated (or failed to be), 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.  A group that was skipped or dropped (the
backoff, or the checks before relocation) held the operation only
briefly and gets no gap.  Neither does a filesystem that is closing or
has failed: the worker only drops the rest of the list there, and
close_ctree() waits for it in cancel_work_sync().  Nor does the last
group a limited call may reclaim (the zoned RECLAIM_ZONES flush): the
loop ends there and releases the operation anyway.  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 (before
the gap was limited to relocated groups) 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
2 weeks agobtrfs: relocation: flush fully before failing a merge reservation misc-next/topics/low-space
Zygo Blaxell [Wed, 21 Oct 2026 16:48:13 +0000 (12:48 -0400)]
btrfs: relocation: flush fully before failing a merge reservation

merge_reloc_root() refills the relocation block reserve before each step
of the merge.  Since 44d354abf33e ("btrfs: relocation: review the call
sites which can be interrupted by signal") it does so with
BTRFS_RESERVE_FLUSH_LIMIT.  FLUSH_LIMIT only flushes delayed items and
tries to allocate a chunk.  It does not run delayed refs, does not flush
delalloc, does not commit the transaction to unpin what the merge and
everybody else freed, and never falls back to the global reserve.  A
failure here is fatal: merge_reloc_roots() handles it with
btrfs_handle_fs_error() and the filesystem goes read-only.

The merge routinely needs more than prepare_to_merge() reserved for it,
and refills from free space.  On a filesystem with every device
allocated, metadata free space is all in other tasks' reservations, and
the refill loses:

  BTRFS: error (device dm-6) in merge_reloc_roots:2053: errno=-28 No space left
  BTRFS info (device dm-6 state E): forced readonly
  BTRFS error (device dm-6 state EA): error relocating chunk 14022541312: -28

This is the reclaim worker relocating a data block group of a 6-device
raid5 filesystem (metadata raid1) with 6 MiB unallocated, under
fsstress.  A trace of the failing merge: prepare_to_merge() reserved 704
KiB, the merge used it up and refilled 14 times (560 KiB more), and the
15th refill, for 32 KiB, failed.  At that moment the metadata space_info
(256 MiB) had 160 MiB used, 9 MiB pinned and 86 MiB in may_use, of which
27 MiB was the untouched global reserve: 16 KiB free.  Background
reclaim is optional work; it took the filesystem down.

Refill with BTRFS_RESERVE_FLUSH_EVICT instead.

Why FLUSH_LIMIT was chosen.  This refill used FLUSH_ALL from
08e007d2e577 ("Btrfs: improve the noflush reservation") until
44d354abf33e.  That commit changed it only so that a fatal signal cannot
interrupt the merge:  FLUSH_ALL waits for its ticket killably and
returns -EINTR, which here would turn a killed balance into a read-only
filesystem.  Its message already notes that the change "can be
ENOSPC-prone", and it shrank min_reserved to compensate.  No deadlock
was given as a reason.

Why not another mode.  No existing mode is "run delayed refs and commit,
but neither flush delalloc nor steal, and do not wait killably":
- FLUSH_LIMIT does not run delayed refs, which is what the merge refills
  that needed flushing in testing needed.
- FLUSH_ALL and FLUSH_ALL_STEAL flush delalloc and commit too, through
  the async reclaim worker, and wait killably.  That brings back the
  -EINTR that 44d354abf33e removed.
- FLUSH_EVICT is the priority flusher with the full list: delayed items,
  delayed refs, delalloc, chunk allocation and a commit, in that order,
  run in the caller's context.  It stops at the first state that serves
  the ticket, does not wait killably, and steals from the global reserve
  only after all of them have failed.
In testing, every merge refill that needed flushing was served by the
delayed-ref states (5 of 6 tickets; the sixth needed only delayed
items).  None reached delalloc, the commit or the steal.  Those states
run only where the old code forced the filesystem read-only.

Deadlock analysis.  At the refill the merging task holds:
- No transaction handle.  The previous step ended its transaction with
  btrfs_end_transaction_throttle(), and the first step has not started
  one, so current->journal_info is NULL, as FLUSH_EVICT requires.
- No tree locks.  The path into the reloc tree holds references only
  (the reloc tree is walked without locks, and btrfs_unlock_up_safe()
  dropped the locks of the resume search). replace_path() unlocks the
  subvolume tree before it returns.
- Not reloc_mutex. merge_reloc_roots() takes it only around its list
  splices.
- These locks from its callers: cleaner_mutex (do_nonremap_reloc()),
  reclaim_bgs_lock, the exclusive operation, and sb_start_write for a
  data block group.  Writeback, ordered extent completion and
  transaction commit take none of them.  The other takers of
  reclaim_bgs_lock either use trylock (unused block group deletion, the
  reclaim worker) or are relocation entry points (balance, system chunk
  relocation, device shrink, zoned repair).  Those take it with no
  transaction handle held, and the exclusive operation serializes them
  with this one anyway.  The other takers of cleaner_mutex are the
  cleaner (trylock), mount and unmount (btrfs_start_pre_rw_mount(),
  btrfs_commit_super()) and the quota ioctl, which takes it before
  starting a transaction.  So no flush or commit can wait on a lock that
  the merging task holds.

The same task already does each of these things in the same lock
context:
- prepare_to_merge() reserves with FLUSH_ALL, waiting while the async
  reclaim worker flushes delalloc and commits, and then commits itself.
- relocate_block_group() commits again after the merge.
- btrfs_end_transaction_throttle() at the end of every merge step runs
  delayed iputs.  An evicted inode reserves with FLUSH_EVICT from right
  there.

A commit in the middle of the merge is legal.  The transaction kthread,
sync and other tasks already commit between merge steps.  Each step
saves drop_progress and drop_level before it ends its transaction, and
the commit writes them to the reloc root item through
btrfs_update_reloc_root(). init_reloc_root() creates nothing while
rc->merge_reloc_tree is set. btrfs_end_transaction_throttle() used to
commit from this loop itself, until 302167c50b32 ("btrfs: don't end the
transaction for delayed refs in throttle").

DATA_RELOC inode.  In the UPDATE_DATA_PTRS stage its delalloc was
written back and waited for, and its page cache invalidated, before the
stage started (do_nonremap_reloc()), so there is nothing to flush.  In
the MOVE_DATA_EXTENTS stage its dirty pages may still be unwritten
during the merge.  Flushing them from here is the same writeback that
the flusher threads, sync, or another task's FLUSH_ALL or FLUSH_EVICT
ticket may start at any time.  It is also what do_nonremap_reloc() waits
for right after relocate_block_group() returns.  Completing its ordered
extents joins a transaction on the data reloc root, which is not
shareable, so it does not take reloc_mutex.

The steal is bounded. steal_from_global_rsv() leaves 10% of the global
reserve, and each steal is at most min_reserved, which is two nodes per
level of the reloc root (64 KiB in the trace above).  A merge that fails
here takes the filesystem read-only.  Keeping it writable is what the
global reserve is for, as it is for eviction.

If even the global reserve cannot cover the refill, the merge fails as
before.

Reproduced with reloc-merge-enospc-test.sh (raid56-wh-harness): the
octopus P1 sequence on 6 x 3 GiB, fsstress until the reclaim worker's
relocations, plain relocations or balances run at the fill edge.  On the
base, 3 of 3 reclaim runs went read-only in merge_reloc_roots().  With
the patch, 6 runs had no merge failure.

Fixes: 44d354abf33e ("btrfs: relocation: review the call sites which can be interrupted by signal")
Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: hold block groups free for relocation
Zygo Blaxell [Mon, 28 Sep 2026 22:14:56 +0000 (18:14 -0400)]
btrfs: hold block groups free for relocation

Relocating a block group needs somewhere to write its live data, and a
filesystem short of free space is exactly when block groups need to be
relocated: automatic reclaim, balance, device shrink and removal.  When
ordinary writers have taken every free byte, relocation fails with
-ENOSPC and the space it would have recovered stays out of reach, so a
full filesystem can stay full until an administrator frees space by
hand.  Zoned filesystems already avoid this for data by dedicating a
block group to relocation (data_reloc_bg); regular filesystems have
nothing, for data or metadata.

Keep, per space_info, a set of block groups held 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().  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 (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
   (relocating an empty held group only deletes the reserve), and a held
   group that goes read-only leaves the set.

 - The relocating task keeps its exemption through the removal of the
   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,
   a failed tree block allocation aborts the transaction, and relocating
   a metadata group leaves delayed refs and commit work that tasks other
   than the relocating one run; without this their tree blocks aborted
   the transaction on a full filesystem.  Data allocations have no such
   fallback: a data writer gets ENOSPC.

 - 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
   transition fails; otherwise every scrub of a full filesystem handed
   the reserve to whoever wrote next.

 - The refill after a relocation commits the removal of the source group
   first: its device extents can be allocated again only then, and a
   refill before that claimed a sliver of a chunk from the leftovers.

 - While a device shrink or removal runs, the reserve takes only empty
   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
chunk can come out smaller than the caps when the devices are nearly
full, and a target no chunk can reach would allocate another chunk for
the reserve on every retry.  A larger group appearing later raises the
target by itself.  Block groups differ in size (on RAID5/6 the stripe
width follows the devices that have free space), so the reserve is a
set of groups whose free bytes add up to the target, not one group.
It is established at read-write mount after log replay and orphan
cleanup, from empty groups (largest first) or a new chunk while
unallocated space exists; refilled after every relocation from the raw
space the relocated group released, and by the cleaner; and groups
leave it, the least free first, only while the rest still covers the
target.  If it cannot be established the filesystem says so once and
carries on without it.

The reserve is off by default: allocation/<type>/reloc_reserve turns it
on (empty groups are taken at once, a chunk for the rest at the
cleaner's next pass), and allocation/<type>/{bytes_reloc_reserve,
reloc_reserve_target} show its state.  It stays off on zoned
filesystems, which have their own data relocation block group, and for
system, remap tree and mixed block groups.

The cost is capacity: the reserve holds one largest block group's worth
of space per space_info -- up to 10% of the writable space on small
filesystems, where the chunk allocator caps a chunk at that -- and a
filesystem needs room for the reserve beside its working block groups.

Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: print the error when reclaim fails to relocate a block group
Zygo Blaxell [Sun, 27 Sep 2026 19:02:40 +0000 (15:02 -0400)]
btrfs: print the error when reclaim fails to relocate a block group

When the background reclaim of a block group fails, the error is logged
as just "error relocating chunk <start>".  The reclaim worker retries
the group on its next pass, so a persistent failure shows up as the same
line every 30 seconds with nothing saying why: -ENOSPC from a
reservation, -EIO from a bad read, and -ETXTBSY from an active swapfile
all look alike, and telling them apart takes tracing the relocation
path.

Print the error code.

Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: stripe_alloc: keep a stripe in the rbio cache until its run has written all... misc-next/topics/stripe-alloc
Zygo Blaxell [Thu, 1 Oct 2026 16:14:49 +0000 (12:14 -0400)]
btrfs: stripe_alloc: keep a stripe in the rbio cache until its run has written all of it (debug_meta part)

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
2 weeks agobtrfs: raid56: adaptive park deadline from the parked-rbio backlog (debug_meta part)
Zygo Blaxell [Sat, 19 Sep 2026 17:17:55 +0000 (13:17 -0400)]
btrfs: raid56: adaptive park deadline from the parked-rbio backlog (debug_meta part)

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
2 weeks agobtrfs: stripe_alloc: attribute each data read-modify-write to why padding declined...
Zygo Blaxell [Wed, 30 Sep 2026 22:07:52 +0000 (18:07 -0400)]
btrfs: stripe_alloc: attribute each data read-modify-write to why padding declined (debug_meta part)

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
2 weeks agobtrfs: stripe_alloc: trace why padding declined, at the moment it declined (debug_met...
Zygo Blaxell [Sat, 19 Sep 2026 17:17:51 +0000 (13:17 -0400)]
btrfs: stripe_alloc: trace why padding declined, at the moment it declined (debug_meta part)

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
2 weeks agobtrfs: stripe_alloc: tunable park deadlines, and say why padding declined (debug_meta...
Zygo Blaxell [Sat, 19 Sep 2026 17:17:50 +0000 (13:17 -0400)]
btrfs: stripe_alloc: tunable park deadlines, and say why padding declined (debug_meta part)

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
2 weeks agobtrfs: raid56: say whether a metadata read-modify-write is a write hole
Zygo Blaxell [Sat, 19 Sep 2026 17:17:49 +0000 (13:17 -0400)]
btrfs: raid56: say whether a metadata read-modify-write is a write hole

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
2 weeks agobtrfs: stripe_alloc: count and log ordered extents that end with sectors unwritten...
Zygo Blaxell [Fri, 9 Oct 2026 23:13:11 +0000 (19:13 -0400)]
btrfs: stripe_alloc: count and log ordered extents that end with sectors unwritten (debug_meta part)

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
2 weeks agobtrfs: stripe_alloc: share LOG data runs per log transaction (stripe_meta part)
Zygo Blaxell [Tue, 6 Oct 2026 04:11:38 +0000 (00:11 -0400)]
btrfs: stripe_alloc: share LOG data runs per log transaction (stripe_meta part)

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
2 weeks agobtrfs: stripe_alloc: give each log commit its own metadata stripe run
Zygo Blaxell [Mon, 5 Oct 2026 03:16:03 +0000 (23:16 -0400)]
btrfs: stripe_alloc: give each log commit its own metadata stripe run

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
2 weeks agobtrfs: stripe_alloc: skip RAID5/6 groups that are mapped as RAID1/RAID1C3 (stripe_met...
Zygo Blaxell [Sat, 10 Oct 2026 04:19:18 +0000 (00:19 -0400)]
btrfs: stripe_alloc: skip RAID5/6 groups that are mapped as RAID1/RAID1C3 (stripe_meta part 2)

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
2 weeks agobtrfs: stripe_meta: cover raid56 system chunks
Zygo Blaxell [Sun, 20 Sep 2026 05:33:09 +0000 (01:33 -0400)]
btrfs: stripe_meta: cover raid56 system chunks

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
2 weeks agobtrfs: stripe_alloc: do not count a writeback ENOSPC drop's give-back as supply ...
Zygo Blaxell [Sun, 25 Oct 2026 10:27:49 +0000 (06:27 -0400)]
btrfs: stripe_alloc: do not count a writeback ENOSPC drop's give-back as supply (stripe_meta part)

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
2 weeks agobtrfs: stripe_alloc: count whole stripes stranded behind live runs as trapped (stripe...
Zygo Blaxell [Sat, 19 Sep 2026 17:18:19 +0000 (13:18 -0400)]
btrfs: stripe_alloc: count whole stripes stranded behind live runs as trapped (stripe_meta part)

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
2 weeks agobtrfs: stripe_meta: hold back whole stripes so tree blocks always land and trapped...
Zygo Blaxell [Sat, 19 Sep 2026 17:18:12 +0000 (13:18 -0400)]
btrfs: stripe_meta: hold back whole stripes so tree blocks always land and trapped groups can be reclaimed

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
2 weeks agobtrfs: stripe_meta: extend stripe reclaim to metadata block groups
Zygo Blaxell [Thu, 22 Oct 2026 20:47:05 +0000 (16:47 -0400)]
btrfs: stripe_meta: extend stripe reclaim to metadata block groups

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
2 weeks agobtrfs: stripe_alloc: skip RAID5/6 groups that are mapped as RAID1/RAID1C3 (stripe_met...
Zygo Blaxell [Sat, 10 Oct 2026 04:19:18 +0000 (00:19 -0400)]
btrfs: stripe_alloc: skip RAID5/6 groups that are mapped as RAID1/RAID1C3 (stripe_meta part)

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
2 weeks agobtrfs: stripe_alloc: keep a stripe in the rbio cache until its run has written all...
Zygo Blaxell [Thu, 1 Oct 2026 16:14:49 +0000 (12:14 -0400)]
btrfs: stripe_alloc: keep a stripe in the rbio cache until its run has written all of it (stripe_meta part)

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
2 weeks agobtrfs: stripe_meta: allocate tree blocks by whole stripes
Zygo Blaxell [Sat, 19 Sep 2026 17:17:58 +0000 (13:17 -0400)]
btrfs: stripe_meta: allocate tree blocks by whole stripes

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
12 days agobtrfs: raid56: pass REQ_META to per-device bios
Mark Korenberg [Fri, 6 Nov 2026 17:33:10 +0000 (22:33 +0500)]
btrfs: raid56: pass REQ_META to per-device bios

RAID5/6 writes, and reads that need a rebuild, go through an rbio,
which builds new per-device bios from a bare REQ_OP_READ or
REQ_OP_WRITE.  So all tree block writes on RAID5/6 lose REQ_META, while
on the other profiles the per-device bios are clones and keep it.  The
same goes for a tree block read rebuilt from the other stripes, for
example with a missing device.

Pass REQ_META on to all per-device bios of an rbio, data and P/Q alike,
if any bio it serves has it.  Scrub and relocation do not set REQ_META,
so their rbios stay untagged, as do rbios that only serve file data.

Signed-off-by: Mark Korenberg <socketpair@gmail.com>
Link: https://lore.kernel.org/r/20261106-btrfs-sb-read-req-meta-v2-2-71c1afaf5c67@gmail.com
2 weeks agobtrfs: stripe_alloc: do not count a writeback ENOSPC drop's give-back as supply ...
Zygo Blaxell [Sun, 25 Oct 2026 10:27:49 +0000 (06:27 -0400)]
btrfs: stripe_alloc: do not count a writeback ENOSPC drop's give-back as supply (debug part)

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
2 weeks agobtrfs: stripe_alloc: log the space counters when data writeback hits ENOSPC
Zygo Blaxell [Sun, 25 Oct 2026 08:48:50 +0000 (04:48 -0400)]
btrfs: stripe_alloc: log the space counters when data writeback hits ENOSPC

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
2 weeks agobtrfs: stripe_alloc: count and log ordered extents that end with sectors unwritten
Zygo Blaxell [Fri, 9 Oct 2026 23:13:11 +0000 (19:13 -0400)]
btrfs: stripe_alloc: count and log ordered extents that end with sectors unwritten

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
2 weeks agobtrfs: stripe_alloc: break rbio pins and open stripe runs down by run class
Zygo Blaxell [Sun, 4 Oct 2026 21:46:19 +0000 (17:46 -0400)]
btrfs: stripe_alloc: break rbio pins and open stripe runs down by run class

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
2 weeks agobtrfs: stripe_alloc: optionally audit data read-modify-writes against the committed...
Zygo Blaxell [Wed, 30 Sep 2026 22:07:56 +0000 (18:07 -0400)]
btrfs: stripe_alloc: optionally audit data read-modify-writes against the committed extent tree

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
2 weeks agobtrfs: stripe_alloc: attribute each data read-modify-write to why padding declined
Zygo Blaxell [Wed, 30 Sep 2026 22:07:52 +0000 (18:07 -0400)]
btrfs: stripe_alloc: attribute each data read-modify-write to why padding declined

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
2 weeks agobtrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow extents...
Zygo Blaxell [Sat, 19 Sep 2026 17:17:40 +0000 (13:17 -0400)]
btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow extents (debug part)

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
2 weeks agobtrfs: stripe_alloc: say at mount whether the policy is on (debug part)
Zygo Blaxell [Sat, 19 Sep 2026 17:18:25 +0000 (13:18 -0400)]
btrfs: stripe_alloc: say at mount whether the policy is on (debug part)

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
2 weeks agobtrfs: stripe_alloc: report read-modify-write of uncovered stripes (debug part)
Zygo Blaxell [Sat, 19 Sep 2026 17:17:48 +0000 (13:17 -0400)]
btrfs: stripe_alloc: report read-modify-write of uncovered stripes (debug part)

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
2 weeks agobtrfs: add a write-hole invariant checker to the raid56 write path
Zygo Blaxell [Sat, 19 Sep 2026 17:17:27 +0000 (13:17 -0400)]
btrfs: add a write-hole invariant checker to the raid56 write path

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
2 weeks agobtrfs: stripe_alloc: share LOG data runs per log transaction
Zygo Blaxell [Tue, 6 Oct 2026 04:11:38 +0000 (00:11 -0400)]
btrfs: stripe_alloc: share LOG data runs per log transaction

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
2 weeks agobtrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow extents...
Zygo Blaxell [Sat, 19 Sep 2026 17:17:40 +0000 (13:17 -0400)]
btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow extents (fsync part 2)

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
2 weeks agobtrfs: stripe_alloc: carry an inode's log tail forward at fsync
Zygo Blaxell [Sat, 19 Sep 2026 17:17:37 +0000 (13:17 -0400)]
btrfs: stripe_alloc: carry an inode's log tail forward at fsync

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
2 weeks agobtrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow extents...
Zygo Blaxell [Sat, 19 Sep 2026 17:17:40 +0000 (13:17 -0400)]
btrfs: stripe_alloc: allow-rmw policy, and write-in-place for isolated nocow extents (fsync part)

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
2 weeks agobtrfs: stripe_alloc: count open stripe run remainders against data reservations ...
Zygo Blaxell [Sat, 19 Sep 2026 17:17:45 +0000 (13:17 -0400)]
btrfs: stripe_alloc: count open stripe run remainders against data reservations (fsync part)

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
2 weeks agobtrfs: stripe_alloc: settle a logged extent's stripes at log commit
Zygo Blaxell [Sat, 19 Sep 2026 17:17:31 +0000 (13:17 -0400)]
btrfs: stripe_alloc: settle a logged extent's stripes at log commit

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
2 weeks agobtrfs: stripe_alloc: back off stripe reclaim after repeated ENOSPC
Zygo Blaxell [Thu, 22 Oct 2026 08:02:52 +0000 (04:02 -0400)]
btrfs: stripe_alloc: back off stripe reclaim after repeated ENOSPC

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
2 weeks agobtrfs: stripe_alloc: add stripe_reclaim_now to reclaim stripes on demand
Zygo Blaxell [Tue, 20 Oct 2026 18:41:37 +0000 (14:41 -0400)]
btrfs: stripe_alloc: add stripe_reclaim_now to reclaim stripes on demand

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
2 weeks agobtrfs: stripe_alloc: log compaction and trapped bytes in the reclaim log
Zygo Blaxell [Tue, 20 Oct 2026 17:04:19 +0000 (13:04 -0400)]
btrfs: stripe_alloc: log compaction and trapped bytes in the reclaim log

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
2 weeks agobtrfs: stripe_alloc: keep relocation's stripe runs until relocation ends (reclaim...
Zygo Blaxell [Thu, 1 Oct 2026 04:57:50 +0000 (00:57 -0400)]
btrfs: stripe_alloc: keep relocation's stripe runs until relocation ends (reclaim part)

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
2 weeks agobtrfs: stripe_alloc: compact mostly live groups instead of skipping them
Zygo Blaxell [Tue, 29 Sep 2026 09:29:38 +0000 (05:29 -0400)]
btrfs: stripe_alloc: compact mostly live groups instead of skipping them

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
2 weeks agobtrfs: stripe_alloc: count whole stripes stranded behind live runs as trapped (reclai...
Zygo Blaxell [Sat, 19 Sep 2026 17:18:19 +0000 (13:18 -0400)]
btrfs: stripe_alloc: count whole stripes stranded behind live runs as trapped (reclaim part)

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
2 weeks agobtrfs: stripe_alloc: hand groups full of trapped free space to the reclaim worker
Zygo Blaxell [Sat, 19 Sep 2026 17:18:06 +0000 (13:18 -0400)]
btrfs: stripe_alloc: hand groups full of trapped free space to the reclaim worker

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
2 weeks agobtrfs: stripe_alloc: count open stripe run remainders against data reservations ...
Zygo Blaxell [Sat, 19 Sep 2026 17:17:45 +0000 (13:17 -0400)]
btrfs: stripe_alloc: count open stripe run remainders against data reservations (allow_rmw part)

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