]> git.hungrycats.org Git - linux/log
linux
3 months agoMerge branch 'topics/stripe-alloc' into testing testing
Zygo Blaxell [Sat, 15 Aug 2026 05:56:52 +0000 (01:56 -0400)]
Merge branch 'topics/stripe-alloc' into testing

3 months agobtrfs: stripe_alloc: gate data admission on claimable whole-stripe supply topics/stripe-alloc
Zygo Blaxell [Fri, 14 Aug 2026 01:12:04 +0000 (21:12 -0400)]
btrfs: stripe_alloc: gate data admission on claimable whole-stripe supply

Wire stripe_claimable into the DATA reservation path so write() returns -ENOSPC
when there is no fully-free whole stripe to place the write crash-safely --
matching statfs f_bavail, which already subtracts the trapped partial-stripe
space.  Add stripe_claimable_admit() and AND it into the two data-admit sites:
__reserve_bytes() and btrfs_try_granting_tickets() (the latter is required, or a
flushed data ticket would be granted by the plain used<=total rule, bypassing the
gate).  Scoped to raid56 stripe_alloc DATA (stripe_margin_unit != 0); metadata,
non-raid56 and zoned space_infos are unaffected.

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

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

Assisted-by: Claude:claude-opus-4-8
3 months agobtrfs: stripe_alloc: drop incremental claimable credit to end the over-count
Zygo Blaxell [Fri, 14 Aug 2026 00:04:59 +0000 (20:04 -0400)]
btrfs: stripe_alloc: drop incremental claimable credit to end the over-count

The rule-1 credit in __btrfs_add_free_space credited whole stripes on every add,
but several add paths re-add free space that a low-level remove never
de-credited: the async-discard trim (unlink_free_space / bitmap_clear_bits, then
do_trimming re-adds via __btrfs_add_free_space) and btrfs_remove_free_space's
middle-split tail re-add.  The double-credit drives bg->stripe_claimable ABOVE
the authoritative per-commit scan (the "incremental stripe_claimable %llu above
scanned %llu" WARN) -- the over-count direction that is unsafe once admission
gates on the counter, where a reservation admitted against phantom supply is
dropped at writeback.

Drop the positive incremental credit entirely.  The incremental rules now only
ever DEBIT (removes round out, claims are exact -- both err low); the per-commit
rescan is the sole upward correction.  stripe_claimable can therefore only
under-count between commits (early, clean write()-time ENOSPC -- the
deliberately-safe direction) and never over-count, structurally, regardless of
which re-add path forgets to de-credit.

Reproduced with compress+autodefrag+discard=async on a legacy-converted raid5
fs (incremental ~= 2x scanned); credit_return attribution confirmed the phantom
entered through do_trimming's re-add, not the open-stripe allocator returns.

Assisted-by: Claude:claude-opus-4-8
3 months agobtrfs: stripe_alloc: rate-limit the claimable-above-scanned WARN
Zygo Blaxell [Wed, 12 Aug 2026 15:09:21 +0000 (11:09 -0400)]
btrfs: stripe_alloc: rate-limit the claimable-above-scanned WARN

The rescan WARN that catches incremental stripe_claimable exceeding the
authoritative scan (the missed-consumption direction) was WARN_ONCE.  A
persistent accounting gap recurs on every commit, so _ONCE reports only the
first and hides that it is ongoing -- exactly the case for a filesystem
carrying extents allocated by the legacy raid56 code before the stripe_alloc
property was set at runtime: the incremental rules were shaped for
stripe-disciplined layout, not legacy packing, and over-credit claimable each
commit until the layout is relocated.  WARN_RATELIMIT keeps the taint and
backtrace but lets the recurrence show in the field under a rate limit; the
clamp to the scanned value keeps every rescan authoritative regardless.

Assisted-by: Claude:claude-opus-4-8
3 months agobtrfs: raid56: adaptive park deadline from the parked-rbio backlog
Zygo Blaxell [Tue, 11 Aug 2026 05:41:53 +0000 (01:41 -0400)]
btrfs: raid56: adaptive park deadline from the parked-rbio backlog

Full-stripe batching parks a sub-stripe write's rbio for a deadline so the
writes that fill the rest of its stripe can merge into it, turning a
read-modify-write into one full-stripe write.  The deadline is a fixed
per-filesystem value.  It is long enough to catch those merges, but at a
small-file fill to ENOSPC -- where a run's stripes never fill because each
file's neighbours land in the next file's stripe rather than this one --
every partial write waits the deadline out, and then its 10x stuck cap, on
an arrival that never comes before padding to a full stripe and going down.
Lowering the deadline globally fixes that fill but throws away the merges
the deadline exists to catch on ordinary moderate writes.

Feed the deadline back from the parking machinery's own backlog instead of
guessing at the workload.  Track stripe_parked_now, the number of
currently-parked rbios, incremented as a partial write parks and
decremented as it unparks.  When it runs ahead of the stripe_park_congestion
knob (0 disables it, the default), a new async partial write takes the short
sync deadline through the existing sync-park path rather than the full one.
This is negative feedback: the shorter deadline drains the backlog, so once
it falls back below the knob later writes regain the full deadline and full-
stripe batching.  No space-state estimate is needed -- a small-file flood
builds the backlog directly, while a large sequential fill (already full
stripes, never parked) and a moderate steady stream do not.

Measured on an eight-device raid5.  A small-file balance-reclaim soak that
times out at the default deadline completes at a congestion of 4; on a
throttled moderate stream, where the backlog stays low, a congestion of 32
never trips, keeps the full deadline, and merges three times as much with
38% fewer RMW reads as the same filesystem under a flat 3ms deadline.  The
gauge and a congestion_short counter join the stripe_park_stats sysfs file
so the knob can be set from measurement.  Off by default, and no data-path
change: a shortened park still pads or reads exactly as it would have, only
sooner.

Assisted-by: Claude:claude-opus-4-8
3 months agoMerge branches 'topics/backref-hang', 'topics/compress-fixes', 'topics/dev-extent...
Zygo Blaxell [Sun, 9 Aug 2026 20:04:26 +0000 (16:04 -0400)]
Merge branches 'topics/backref-hang', 'topics/compress-fixes', 'topics/dev-extent-defrag', 'topics/prealloc-size', 'topics/raid56-fixes' and 'topics/stripe-meta' into testing

3 months agobtrfs: stripe_meta: allocate tree blocks by whole stripes topics/stripe-meta
Zygo Blaxell [Sun, 9 Aug 2026 20:04:23 +0000 (16:04 -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.  Behind its own mount
option, stripe_meta, because it costs a stranded stripe tail per commit
and because a metadata allocation that fails aborts the transaction rather
than failing one write.

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.

Also carries, pending their own patches: the rbio io_done completion
(fixes a wake-after-free against the embedded waitqueue), stale rbio
cache invalidation when extents are freed (btrfs_raid56_uncache_range),
and a verify_one_sector guard for sectors with no csum to check against.
These are raid56 fixes, not stripe_meta machinery, and should move to
their own topic.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: count claimable whole-stripe supply directly
Zygo Blaxell [Sun, 9 Aug 2026 20:04:21 +0000 (16:04 -0400)]
btrfs: stripe_alloc: count claimable whole-stripe supply directly

Data reservations are admitted against arithmetic -- free space minus
trapped fragments minus open-run remainders minus a per-extent margin --
and under sustained near-full churn the arithmetic and the claim rule
disagree for long enough that admitted buffered writes reach writeback
with nothing claimable left: measured, ~5.2-5.5k reserved writebacks
dropped per fsstress churn run, silently for anything not waiting on
fsync.  Stock refuses the same write()s up front.  Nothing between
"durable by fsync" and "refused by write()" is acceptable when an
operator accident fills the disk.

First step, accounting only: measure the constraint instead of deriving
it.  bg->stripe_claimable counts bytes of fully free whole stripes --
exactly what btrfs_claim_free_stripe_run() can take, the complement of
stripe_unusable within each stripe.  The commit rescan derives it from
the same pass that computes trapped bytes (free minus trapped) and is
the authority; incremental maintenance under ctl->tree_lock uses blind
rules that only ever err by counting claimable LOW: returned ranges add
only their interior whole stripes, removals round their decrement OUT
to every touched stripe, claims subtract exactly what they took.  A
WARN at rescan catches the dangerous direction (incremental above
scanned), localizing any missed consumption site.

The space_info aggregate bytes_stripe_claimable follows the
stripe_unusable pattern (incremental between commits, re-totaled from
armed groups at the rescan), shows in the ENOSPC dump and in sysfs.
No admission change yet; that comes once the counter proves accurate
under the fill, churn, balance and reclaim suites.  The by-size
fast-fail in the claim keeps its early exit: the point of measuring is
to make such inputs trustworthy, not to search harder around them.

Data block groups only for now; raid56 metadata and mixed block groups
join when the data counter has settled.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: track per-sector liveness and pad from the map
Zygo Blaxell [Sun, 9 Aug 2026 03:14:23 +0000 (23:14 -0400)]
btrfs: stripe_alloc: track per-sector liveness and pad from the map

Padding used to ask where the run's allocation frontier was, which
cannot see an allocation abandoned below it -- a reservation released, an
allocation the finder discarded, an extent freed before its write was
ever issued.  Runs now carry a bit per sector, set at allocation and
cleared by the new btrfs_open_stripe_write_abandoned() report, and
padding fills exactly the sectors that are dead: this replaces
btrfs_stripe_run_pad_start() with btrfs_stripe_run_pad_mask().  The map
is sized once, with headroom for frontier growth, because the growth
path holds the run lock where nothing may sleep; a run that would
outgrow its map stops growing instead.  A closed run's final stripe
overhangs its shrunk end by construction, and those sectors -- the
returned tail, unclaimable while the stripe holds live data -- are dead
and paddable too.

The abandonment report is what closes a writeback ENOSPC race the
fsync-heavy near-full workload hits: an allocation undone without a
report left phantom inflight bytes and phantom-live sectors, and
reservations admitted against that state failed at writeback
(cow_file_range -28) where stock refuses the write() up front.  With
the report in place the same workload shows zero writeback failures at
every reservation margin setting, including margin disabled.

Claiming also learns an O(1) fast fail: the by-size index walk is
extracted into find_free_stripe_run(), stopping at the first entry whose
largest contiguous free run cannot hold a full stripe -- near-full, where
free space degenerates into many sub-stripe holes, this replaces a scan
of the whole tree on every allocation.

Moved out of the stripe_meta patch, which needs all of this for tree
blocks but introduced it tangled with the metadata machinery; data wants
it on its own.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: park partial writes against draining runs too
Zygo Blaxell [Sat, 8 Aug 2026 17:14:14 +0000 (13:14 -0400)]
btrfs: stripe_alloc: park partial writes against draining runs too

Parking has required the stripe to lie in an OPEN run, but a run closes
the moment it is fully allocated -- typically milliseconds before its
last writes reach the raid56 layer.  Those tail writes arrive to a
draining run, cannot park, and cannot pad (every sector of their stripe
is allocated), so they read-modify-write.  Measured on the buffered-fill
workload, this stranded population -- not expired or kicked parks -- is
nearly all of stripe_alloc's data RMW: 13980 of 14658 RMW reads happen
in the pure async seed phase, and only 73 of 2006 RMW rbios had ever
been parked.  It is also why stretching the park deadline 20x barely
moved the numbers: deadlines govern parks, and these writes never got
one.

With completion-driven parking, a draining run is in fact the safest
thing to park against: its frozen frontier gives an exact allocation
ceiling, everything below the ceiling is inflight IO that the commit
drain already waits for (arrival guaranteed), and everything above it is
dead space the pad may fill -- the pad oracle has always accepted a
closed run's frontier stripe.  Relax the parking gate to accept any run,
open or draining, that covers the stripe.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: complete parked writes on allocation coverage, not clocks
Zygo Blaxell [Sat, 8 Aug 2026 15:27:36 +0000 (11:27 -0400)]
btrfs: stripe_alloc: complete parked writes on allocation coverage, not clocks

A parked partial-stripe write goes down its RMW path when its deadline
expires or a retirement flush kicks it, even when every byte it is
missing below the run's frontier belongs to an allocation whose data IO
is already in flight -- allocation happens at writeback submission, and
the commit's retirement drain waits for exactly those arrivals.  Timing
out such a park buys nothing and costs a stripe read plus a second write
of the same stripe: measured on an 8-device raid5 buffered fill, the
100ms deadline turns ~2200 parked stripes per 2GB into read-modify-
writes (pad_decline_live), and stretching the clock 20x recovers only
14% -- the clock is the wrong instrument.

Replace the clock with a coverage test.  A parked rbio is ready when its
gathered bios cover everything the covering run has allocated inside its
stripe (btrfs_stripe_run_alloc_ceiling); the remainder lies at or past
the frontier, so the existing pad turns it into a single full-stripe
write with no read phase.  Merges check readiness as they land, the park
timer holds unready parks instead of expiring them, and run-retirement
flushes leave unready parks parked: the retirement has already closed
the run (freezing the allocated prefix) and its drain waits on the very
arrivals that will complete them.  Waiter-driven flushes (fsync's
pre-writeback kick, ordered-extent waits) and sync parks keep today's
forced behaviour: a blocked waiter's latency beats a saved stripe read.

A stuck cap (10x the park deadline) bounds the wait when an arrival can
never come: a writeback error abandoned the allocation, or the stripe
was already written once by a forced sync park.  Such parks are forced
down the old path and counted.

New sysfs stripe_park_stats counters: unparked_ready (parks completed by
the coverage test) and stuck (parks forced at the cap).

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: trace why padding declined, at the moment it declined
Zygo Blaxell [Sat, 8 Aug 2026 07:57:22 +0000 (03:57 -0400)]
btrfs: stripe_alloc: trace why padding declined, at the moment it declined

The counters say how often padding refused and broadly why, but not what
the run looked like when it happened, and reconstructing that from the
extent tree afterwards cannot distinguish "the stripe was already
allocated when this write arrived" from "it was allocated shortly after".
Those want different fixes, so record the decision where it is made.

Also count the second refusal, which had no counter at all: the oracle can
allow padding and the sector walk still refuse, because a sector below the
frontier is not covered by this write.  That is the case where another
allocation shares the stripe and its data is not in this rbio -- a
different thing from the oracle finding the whole stripe allocated.

The tracepoint carries the stripe, how much of it this write covers, the
refusal reason, and the run's start/end/frontier/inflight, so a trace says
directly whether the frontier had already run past the stripe when the
write showed up.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: tunable park deadlines, and say why padding declined
Zygo Blaxell [Sat, 8 Aug 2026 06:03:40 +0000 (02:03 -0400)]
btrfs: stripe_alloc: tunable park deadlines, and say why padding declined

The deadline constants are meant to be judged "from measurements rather
than taste", but they are compile-time, so every data point costs a kernel
build and a reboot.  Measuring a buffered fill -- dd, no fsync, so nothing
kicks the park and the backstop is the only exit -- found 1861 of 3984
parks expiring at the 100ms deadline, which is precisely the no-waiter case
the constant exists for and the one with no numbers behind it.

Expose both deadlines as writable sysfs files, clamped to 60s because a
parked rbio holds its stripe lock, with 0 disabling parking for that class
(useful as an experiment in itself):

  /sys/fs/btrfs/<uuid>/stripe_park_timeout_ms       (default 100)
  /sys/fs/btrfs/<uuid>/stripe_park_sync_timeout_ms  (default 3)

Add the counters the stats file cannot supply.  rmw_reads counts only
parked writes that still had to read, so it cannot answer "does this
workload read-modify-write at all"; data_rmw counts every data RMW, which
with allow_rmw empty on a covered block group is the number the
stripe-exclusive claim is about, and it should be zero.

And record why padding refused, because the reasons are different defects:
the rest of the stripe is allocated and its data has not arrived yet
(wait longer, or kick when the frontier advances); no open run covers the
stripe, so the run closed before its own write went down; or the frontier
never reached the stripe at all.  Attributing them turns "some RMW
remains" into a specific thing to fix.

No behaviour change at the defaults.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: raid56: say whether a metadata read-modify-write is a write hole
Zygo Blaxell [Wed, 5 Aug 2026 22:15:06 +0000 (18:15 -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

This trusts nothing the allocator says about itself.  The stripe runs, the
liveness map and the drain accounting are all bookkeeping that could be
wrong in the same way twice; the header in the sector is what a degraded
read would actually have to reconstruct.

On a 3-device raid5 filesystem with raid5 metadata, 6000 small files with
periodic syncs and then a third rewritten, plain stripe_alloc reports 249
sub-stripe metadata writes of which 174 rewrite parity over committed tree
blocks.  Adding stripe_meta leaves 37 sub-stripe writes and none of them.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: report read-modify-write of uncovered stripes
Zygo Blaxell [Tue, 4 Aug 2026 19:51:54 +0000 (15:51 -0400)]
btrfs: stripe_alloc: report read-modify-write of uncovered stripes

The mount-time warning says which block groups stripe_alloc does not
cover.  It cannot say whether anything is actually landing there, and on
a filesystem with raid56 metadata that is the interesting question: every
sub-stripe write to an uncovered stripe is a write hole window, where
parity and data reach the disk separately and a crash in between leaves
the stripe unreconstructible.

Report it from the one place that knows the write is going out as a
read-modify-write rather than as a full or padded stripe.  Rate limited,
because a raid56-metadata filesystem does this continuously and the point
is to make the exposure visible rather than to fill the log, and paired
with a meta_rmw counter in the existing stripe_park_stats sysfs file so
the rate can be read off without grepping dmesg.

Silent when stripe_alloc is off: there the whole filesystem works this
way and the user has asked for nothing else.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: warn at mount when raid56 metadata is not covered
Zygo Blaxell [Tue, 4 Aug 2026 06:43:20 +0000 (02:43 -0400)]
btrfs: stripe_alloc: warn at mount when raid56 metadata is not covered

stripe_alloc closes the write hole for raid56 data.  It does nothing for
raid56 metadata, which keeps read-modify-write and keeps the hole, and
on a mixed-block-group filesystem it now does nothing at all.  A user
who mounts -o stripe_alloc on -d raid5 -m raid5 has every reason to
believe the filesystem is covered, and finds out otherwise only after a
crash on a degraded array -- with metadata damage, which is worse than
the data damage they were protecting against.

Say it once at mount, after the block groups are read, so the message
reflects what is actually on disk rather than what was asked for.  A
warning, not an error: the data guarantee is real and worth having on
its own, and a filesystem can be converted to raid1c3/raid1c4 metadata
without unmounting.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: claim fully-free stripes that span free space entries
Zygo Blaxell [Fri, 7 Aug 2026 01:35:56 +0000 (21:35 -0400)]
btrfs: stripe_alloc: claim fully-free stripes that span free space entries

The claim fast path searches single entries, so a fully-free full
stripe whose free space spans an entry boundary -- an extent entry
adjoining a bitmap, or two neighbouring bitmap windows -- was
unclaimable.  stripe_unusable accounting is entry-blind and counts
exactly those stripes as claimable, so admission reserves data against
them; at writeback the claim finds nothing, cow_file_range() gets
-ENOSPC, and the already-dirtied pages are dropped.  full_stripe_len
is not a power of two, so stripe boundaries drift through the fixed
128M bitmap windows and a straddling stripe is a certainty near full,
not a corner case.

Observed live at the raid6 fill edge (rolling-failure, then isolated
by fill-edge-debug with enospc_debug): two 384K stripes, each
straddling a bitmap window boundary, held the space_info accounting
786432 bytes above what the claim could reach, and every writeback
allocation against that phantom margin failed -ENOSPC while ~991MB of
genuinely trapped free space sat in the cache.  The reservation margin
cannot absorb this: the gap is per straddling stripe, not per
outstanding extent.

Add an entry-blind slow path: one offset-ordered walk accumulating
contiguous free coverage across entry boundaries, and a piecewise
removal that runs in the same tree_lock critical section as the find,
so a racing claimer cannot see a half-removed run.  The fast path is
unchanged and still serves the common case; the slow path runs only
after it fails, which is the near-full case where a stranded stripe
matters most.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: props: validate compression property values strictly topics/compress-fixes
Zygo Blaxell [Sun, 19 Jul 2026 18:33:53 +0000 (14:33 -0400)]
btrfs: props: validate compression property values strictly

The btrfs.compression property validator matches only the algorithm
name prefix, so values like "zstdgarbage" or "zstd:banana" are accepted
and stored verbatim.  Now that ":level" suffixes are meaningful,
validate new values strictly:  accept exactly an algorithm name,
optionally followed by a ":level" suffix that btrfs_compress_str2level()
can parse, mirroring the mount option validation from commit
b98b20830057 ("btrfs: reject invalid compression level").  Out of range
levels are clamped, also matching the mount options.  "no" and "none"
are accepted as before.  Embedded NUL bytes are rejected before parsing
the length-delimited xattr value:  otherwise the temporary
NUL-terminated suffix buffer would let a value such as "zstd:3" followed
by a NUL and junk pass validation and be stored verbatim.

Values stored by old kernels are not affected:  property loading goes
through the apply hook, which remains permissive, so existing inodes
with sloppy stored values keep working; only new setxattr calls see the
stricter checks.

This is a user-visible behavior change:  applications that set malformed
property values, which were previously accepted and ignored, will now
receive EINVAL.  It is split into its own commit so that it can be
accepted or rejected independently of per-inode compression level
support.

Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Assisted-by: Claude:claude-fable-5
Assisted-by: Codex:gpt-5
3 months agobtrfs: props: add per-inode compression level support
Zygo Blaxell [Fri, 7 Aug 2026 01:39:01 +0000 (21:39 -0400)]
btrfs: props: add per-inode compression level support

Setting a per-file compression level is an often requested feature, and
the btrfs.compression property has silently accepted level suffixes
("zstd:9") since compression types were added to it:  the property
validator only matches the algorithm name prefix, the verbatim string is
stored in the xattr and returned by getxattr, and everything after the
algorithm name is ignored when the value is parsed into the in-memory
compression type.

All of the pieces needed to honor the level already exist:  the level is
a per-call argument down the whole compression path, per-inode levels
are already implemented for the defrag ioctl (defrag_compress_level),
and btrfs_compress_str2level() already parses and clamps ":level"
suffixes for the mount options.  Wire the property path up to them:

 * Cache the parsed level in a new btrfs_inode::prop_compress_level,
   with 0 meaning no level was specified, in which case the level from
   the mount options is used as before.  The field is signed to allow
   negative (realtime) zstd levels.

 * Parse an optional ":level" suffix in prop_compression_apply().
   Values stored by old kernels were never validated, so an unparseable
   suffix falls back to the default level rather than making the inode's
   properties fail to load.  Levels for lzo parse and clamp to nothing,
   matching commit 6db1df415d73 ("btrfs: accept and ignore compression
   level for lzo").

 * Use the level in compress_file_range() and the inline compression
   path in run_delalloc_inline().  The defrag ioctl retains precedence.

 * Regenerate the canonical "type:level" string with a new helper,
   btrfs_prop_compression_extract(), so that directory inheritance
   propagates the level to new inodes, and so that FS_IOC_SETFLAGS,
   which rewrites the property when setting FS_COMPR_FL, preserves the
   level instead of truncating the value to the bare algorithm name.
   The prop_handler extract hook itself is unchanged: it still returns
   a static string, and the inheritance loop regenerates the leveled
   value only for the compression property.

There is no disk format change:  the level lives in the already-existing
xattr value string.  Note that levels stored by old kernels (which were
accepted but ignored) become effective after this change.

Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Assisted-by: Claude:claude-fable-5
3 months agobtrfs: raid56: verify reconstructed tree blocks topics/raid56-fixes
Zygo Blaxell [Wed, 5 Aug 2026 06:59:50 +0000 (02:59 -0400)]
btrfs: raid56: verify reconstructed tree blocks

Data sectors recovered from parity are checked against the csum tree
before they are trusted: recover_vertical() calls verify_one_sector() for
each rebuilt sector, and a mismatch fails the read.  Metadata gets none of
that.  fill_data_csums() returns early for anything that is not a data
block group, so csum_bitmap is NULL, and verify_one_sector() then returns
success without looking at anything:

if (!rbio->csum_bitmap || !rbio->csum_buf)
return 0;

So a metadata rbio reconstructs a lost column, marks it uptodate having
verified nothing, and hands it back.  A wrong reconstruction is caught
much later by validate_extent_buffer(), one layer up, after the block has
already been returned and cached -- and in the raid6 case, where several
candidate reconstructions exist, raid56 cannot tell which one is right
because it has no way to check any of them.

A tree block can be verified, just not a sector at a time: its csum lives
in its own header and covers the whole nodesize block, so the check has to
wait until every sector of the block has been recovered.  Do it after the
vertical recovery loop rather than inside it.  A tree block never straddles
a column -- nodesize and BTRFS_STRIPE_LEN are both powers of two with
nodesize <= BTRFS_STRIPE_LEN, and full stripes are stripe-length aligned,
so each column starts on a nodesize boundary and tree blocks tile it
exactly.

Only the blocks the caller asked for are checked.  Those are known to be
live tree blocks; the rest of a stripe may be free space, which has no
header and would fail every test.  For the same reason this runs only when
rebuilding a read: recover_sectors() is also reached from the
read-modify-write path, where the sectors actually reconstructed are the
ones read off the surviving columns and any of them may be free space.  A
reconstruction feeding an RMW's parity therefore stays unverified; knowing
which ranges hold live metadata is not something this layer can do.

Tested with a 3-device raid5 filesystem with raid5 metadata, 3000 files:
each device in turn missing and corrupted recovers byte-exactly, and with
two devices corrupted -- where reconstruction necessarily produces a wrong
block -- raid56 now rejects it itself:

  raid56: reconstructed tree block 40796160 has bytenr 8993213254959039756,
  cannot be trusted

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: raid56: drop cached rbios when their stripes' extents are freed
Zygo Blaxell [Mon, 3 Aug 2026 07:24:38 +0000 (03:24 -0400)]
btrfs: raid56: drop cached rbios when their stripes' extents are freed

A cached rbio keeps an in-memory copy of its full stripe's data
sectors so that a later sub-stripe write can steal the pages (see
steal_rbio()) and skip the RMW read.  That is only safe while the
cache and the disk agree.  Nothing invalidates cache entries when the
stripe's extents are freed, so an entry can outlive the data it
describes: the space is reallocated, a sub-stripe write to the reused
stripe steals the stale pages, and parity is generated from the
cache's memory of the stripe's previous life instead of from disk.

If the on-disk content diverged from that memory in the meantime, the
result is silent, latent damage.  The divergence does not require a
second write: a device error that corrupts a column holding only
freed data is invisible (no live extent, no csum to fail, nothing for
scrub to check), but the stale cached copy of that column predates
the corruption.  The poisoned write then produces parity consistent
with the cache's memory and inconsistent with the actual on-disk
column.  Every read of the live data still passes csum and scrub
reports nothing, so the loss surfaces only when a device failure
forces reconstruction -- which XORs the real on-disk garbage against
parity that remembers different bytes, and hands back trash.

This was found and proven byte-exactly on a raid5 test array: a
stripe's parity solved uniquely as the XOR of fresh data with the
PRE-corruption content of a free-space column -- bytes that existed
nowhere on disk at write time and could only have come from the rbio
cache.  The resulting single-column loss was undetectable by scrub
and unrecoverable by reconstruction.

Drop cache entries overlapping freed extents at unpin time, when the
space returns to circulation.  The walk is gated on raid56 block
groups, so filesystems without raid56 never touch it, and the LRU
list is bounded (RBIO_CACHE_SIZE entries).

The cost of dropping entries was measured on an instrumented stock
kernel that marks affected entries instead of dropping them, and
counts a reintroduced RMW full-stripe read whenever a read-skip was
only possible because of a marked entry.  In a worst-case free-heavy
small-file churn on a 5-device raid5 array with raid5 metadata --
conditions chosen to flatter the cache, and it delivers, with 87% of
sub-stripe RMWs skipping their read -- only 1% of those skips (64 of
6430) were enabled by entries this patch drops, costing 0.04-0.12
MB/s of extra reads against the workload's own 0.3-0.7 MB/s of
writes.  93% of the entries the patch drops were evicted without
ever being stolen again.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: pessimistic data reservation margin
Zygo Blaxell [Mon, 3 Aug 2026 07:22:52 +0000 (03:22 -0400)]
btrfs: stripe_alloc: pessimistic data reservation margin

A byte-counted data reservation holds no collateral against the stripe
claim rule.  Between admission at write() time and the allocation at
writeback, the trapped-space picture keeps moving: commits close open
stripe runs and trap their sub-stripe tails, and free space returning
mid-transaction (unpinned deletions, same-transaction frees, drained
run tails, freed reservations) lands in the free space cache as
fragments the claim rule can never hand out but that no counter yet
reflects.  The counters were honest at every instant for NEW
admissions while OLD admissions were left holding air; delalloc
writeback gets no second chance, so the pages were dropped.  Measured
at the fill edge: ~19 MiB of orphaned bytes_may_use with accounting
and allocator in perfect agreement, and in a later round the admitted
may_use+margin exactly equaled the phantom mid-transaction fragments.

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

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

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

- Every btrfs_add_free_space() into an armed group counts the added
  range's sub-stripe head and tail fragments as trapped immediately;
  whole stripes fully inside the range are trivially fully free and
  stay claimable.  A bounded overcount in the safe direction, never
  an undercount; the commit rescan remains the authority and
  reconciles (and now grants tickets when it lowers the counter,
  since admission waiters may be blocked on exactly that headroom).
  This subsumes the per-callsite immediate tail counting, which
  missed two drain-return paths and miscomputed fragments
  (round_up() on the non-power-of-two 448K stripe width).

- When a margin-backed data allocation must split across free space
  fragments, every non-final piece is kept a whole-stripe multiple
  (rounddown; the width is not a power of two), so at most one piece
  per delalloc extent can strand a tail -- the margin pre-paid
  exactly one.

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

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

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

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: count open stripe run remainders against data reservations
Zygo Blaxell [Sun, 2 Aug 2026 07:35:36 +0000 (03:35 -0400)]
btrfs: stripe_alloc: count open stripe run remainders against data reservations

Close the remaining reservation-vs-allocation windows the commit-time
stripe_unusable rescan cannot see:

- bytes_stripe_open (new): the sum of open runs' unallocated
  remainders, maintained per block group under stripe_run_lock at
  every open/alloc/grow/close, synced into the space_info after each
  mutation, and counted in btrfs_space_info_used().  Claimed bytes are
  invisible to the free space cache and will either be allocated or
  become trapped tails at close, so reservations must not be admitted
  against them.

- On close, the sub-stripe head of a returned tail is added to
  bytes_stripe_unusable immediately instead of waiting for the commit
  rescan (which overwrites with the authoritative cache-derived total,
  so the increment self-reconciles).  Without this, reservations race
  the retire-to-rescan window inside every commit and admit writes
  against freshly trapped tails.

Measured on the fill-to-ENOSPC rolling test before this change (with
only the bytes_stripe_unusable accounting): tree 'b' still lost 3.3%
(8532 blocks) and tree 'c' 30% (62371 blocks) to silent writeback
allocation failure as trapping compounded.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: raid56: skip parking for sync rbios finished by their unplug batch
Zygo Blaxell [Fri, 31 Jul 2026 08:41:19 +0000 (04:41 -0400)]
btrfs: raid56: skip parking for sync rbios finished by their unplug batch

Parking exists to widen the merge window, and for plugged submissions
the unplug callback is the natural end of that window from the
submitter's side: once raid_unplug() has sorted and merged the batch,
nothing more is coming from it.  A sync rbio parked after that point --
a sync(2) or WB_SYNC_ALL sweep, whose whole flush shares one plug --
has a waiter behind it and can only sit out the sync deadline.  Mark
rbios leaving an unplug batch and let sync ones skip parking.

Unplugged sync submissions (the fsync flush) still park: their sibling
bios arrive one by one and merge into the parked rbio, and the fsync
path kicks it as soon as they have all been submitted, so parking there
is the merge mechanism and the deadline already never fires.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: raid56: expose parking statistics in sysfs
Zygo Blaxell [Fri, 31 Jul 2026 08:41:19 +0000 (04:41 -0400)]
btrfs: raid56: expose parking statistics in sysfs

/sys/fs/btrfs/<uuid>/stripe_park_stats reports lifetime counters for
the parking machinery: rbios parked, bytes merged into parked rbios,
and how each park ended (filled to a full stripe, kicked by a waiter or
a settle/retire flush, or expired at its deadline), plus how many
flushed writes were padded to full stripes versus still needing the
RMW read phase.  The filled/kicked/expired split shows directly whether
the deadlines are sized right for a given system -- expired parks that
later reappear as rmw_reads are the batching the window failed to
capture -- so any future retuning (or an adaptive deadline) can argue
from measurements instead of taste.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: raid56: do not park sync writes into nocow runs
Zygo Blaxell [Fri, 31 Jul 2026 05:08:44 +0000 (01:08 -0400)]
btrfs: raid56: do not park sync writes into nocow runs

An in-place overwrite of a nodatacow file under stripe_alloc parked
like any partial write, but with a waiter behind it and nothing worth
merging: in-place overwrites arrive one fsync at a time, and unlike
the datacow fsync path nothing kicks the parked rbio before the page
writeback wait, so every fsync ate the full sync park deadline.
Measured against stock nodatacow on the same rig, that deadline was
the bulk of a ~3.7ms per-fsync regression.  Skip parking for sync
writes whose stripe belongs to a NOCOW-class run; async writeback
still parks and merges there.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: persist nocow runs across commits and remounts
Zygo Blaxell [Fri, 31 Jul 2026 03:51:51 +0000 (23:51 -0400)]
btrfs: stripe_alloc: persist nocow runs across commits and remounts

A nodatacow inode's private stripe run used to close at every
transaction commit like all runs, so a slowly appended nocow file burned
a fresh stripe per commit -- and after a remount its partial stripe's
free tail was abandoned outright.  Neither cost buys anything: the run
machinery's commit-time closing exists for invariant I2, and a nocow
stripe holds only the owner's write-hole-waived data, so there is
nothing for I2 to protect.

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

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

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: allow-rmw policy property and mount option
Zygo Blaxell [Thu, 30 Jul 2026 21:52:30 +0000 (17:52 -0400)]
btrfs: stripe_alloc: allow-rmw policy property and mount option

Replace the provisional stripe_alloc_nocow flag with the settled
interface: a word-list policy naming the cases in which stripe_alloc
may permit the legacy unsafe RMW, each independently:

  nodatacow  in-place writes for nodatacow files' extents
  prealloc   in-place writes into preallocated extents
  fsync      waive the close-at-log-commit guarantee: no settling, no
             per-inode LOG steering, no carry-forward; logged stripes
             may be extended and RMWed as before those patches

It is "allow_rmw", not "allow_overwrite": the fsync case overwrites
nothing, but all three permit read-modify-write of stripes that a
degraded crash can then tear.  The nodatacow and prealloc cases still
require per-extent stripe isolation (the blast radius stays confined to
the writing file); fsync restores the 3a-era exposure where a degraded
crash may cost just-fsynced data, detectably, in exchange for none of
the log-commit costs.

The policy is persistent as the btrfs.stripe_alloc_allow_rmw property
on the top-level root directory, following stripe_alloc's precedent
(applied when the root inode loads during mount, before any user IO),
with a mount option of the same name as a non-persistent override; the
effective policy is their union.  Words are separated by comma, space
or colon -- the mount option form must use colon, since mount splits
options at commas.  Everything defaults off: plain stripe_alloc keeps
forcing COW and keeps the full fsync guarantee.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: write-in-place for stripe-isolated nocow extents
Zygo Blaxell [Thu, 30 Jul 2026 21:40:29 +0000 (17:40 -0400)]
btrfs: stripe_alloc: write-in-place for stripe-isolated nocow extents

Re-enable write-in-place for nodatacow files and preallocated extents
under stripe-exclusive allocation, with the understood caveat that the
write hole cannot be prevented for data that opts out of COW: an
in-place write RMWs its stripe's parity, so a degraded crash can tear
the stripe.  What CAN be guaranteed is the blast radius: in-place is
permitted only for extents whose full stripes are isolated to the
writing inode, so such a crash can tear only the writing file's own
data -- the nodatacow contract, no worse.

The gate is per extent, decided where nocow eligibility is already
checked: fast path, the stripe belongs to one of the inode's own
NOCOW-class runs (which only ever held its extents); slow path, the
committed extent tree proves sole ownership (single plain data ref,
count 1, matching root and objectid; anything shared, foreign or
metadata fails).  The fully-free claim rule keeps uncommitted foreign
extents out of partially used stripes, so the committed tree is
authoritative.  Extents that fail -- anything allocated before stripe
isolation existed, extents shared through reflink or snapshots,
relocated extents -- simply stay force-COWed, and because their rewrite
is steered into the inode's private NOCOW run, the next overwrite of
the same data passes: legacy nocow files migrate themselves to
isolation in one COW generation, with no tool and no flag day.

Log-commit settling skips NOCOW-class runs: nodatacow data gets no
fsync survival guarantee (its own later in-place writes can always
tear it), so closing the run would trap its tail for nothing.  The
write-hole debug checker skips groups that hosted NOCOW-class runs,
like relocation-used groups, since isolated in-place writes land in
stripes whose runs have drained.

The policy is enabled by a stripe_alloc_nocow mount option (requires
stripe_alloc), provisional until the persistent-property interface for
it is settled.  Off by default: stripe_alloc alone keeps forcing COW
exactly as before.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: isolate nodatacow and preallocated extents by stripe
Zygo Blaxell [Thu, 30 Jul 2026 21:27:24 +0000 (17:27 -0400)]
btrfs: stripe_alloc: isolate nodatacow and preallocated extents by stripe

Preallocated extents and nodatacow files' extents are candidates for
write-in-place, which reintroduces the raid56 write hole for every
stripe such a write touches: the RMW recomputes parity that also covers
whatever else shares the stripe.  Before write-in-place can be
re-enabled for them (a later change; stripe_alloc still forces COW
today), their placement must guarantee the blast radius: such an extent
must never share a stripe with any other file's data.

Steer them into private per-inode stripe runs of a new NOCOW class,
reusing the log-active inode machinery: runs owned by one inode, never
in the shared band slots, found by owner-and-class lookup.  Successive
allocations of the same file pack sequentially into the file's own
stripes; different files, and the datacow/relocation/log classes, never
share a stripe with them.  A preallocation signals itself through a new
btrfs_reserve_extent() parameter; nodatacow files are recognized by the
inode flag.  Placement remains best effort: when no fully-free stripes
are left for a private run the allocation falls back to the shared
runs, which is safe -- an extent that lands in a shared stripe simply
stays force-COWed when write-in-place arrives.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: raid56: pad sub-stripe writes to full stripes in open runs
Zygo Blaxell [Thu, 30 Jul 2026 19:49:41 +0000 (15:49 -0400)]
btrfs: raid56: pad sub-stripe writes to full stripes in open runs

A sub-stripe write does a full RMW: read every untouched data sector of
the stripe, recompute parity, write.  Under stripe-exclusive allocation
the read phase is usually pointless: a stripe covered by a live stripe
run has never been written at or past the run's allocation frontier, so
the sectors being read contain nothing.

When every data sector the rbio does not cover lies at or past the
frontier, zero-fill those sectors instead of reading them and write
them out with the stripe -- the zeros must reach the disk, or the
parity (computed over them) would not match what scrub reads back.  The
partial write becomes one full-stripe write: no read phase, one parity
pass.  A frontier that grows during the attempt is safe: the newer
allocation's write serializes behind this rbio's stripe lock and lands
over the zeros.  If any uncovered sector is below the frontier (already
allocated to someone else), fall back to the normal RMW.

Together with kicking parked rbios before the fast fsync's writeback
wait, this removes both stalls the raid56 layer added to fsync under
stripe_alloc: the park deadline and the RMW read round trip.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: kick parked rbios before the fast fsync's writeback wait
Zygo Blaxell [Thu, 30 Jul 2026 18:16:55 +0000 (14:16 -0400)]
btrfs: stripe_alloc: kick parked rbios before the fast fsync's writeback wait

The fast fsync path waits for page writeback, which completes only when
the raid56 layer writes the data -- but a partial-stripe rbio parks to
collect merges until its sync deadline, and on this path nothing unparks
it before the wait: the stripes are settled only later, in the logging
itself.  The full-sync path does not have this problem because the
ordered extent wait already flushes parked rbios before sleeping.

All of the fsync's writes are submitted before the wait, so nothing more
can merge into its stripes; flush the parked rbios covering the attached
ordered extents instead of sleeping out their deadline.  Removes the
sync park timeout from the fast fsync critical path.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: carry an inode's log tail forward at fsync
Zygo Blaxell [Thu, 30 Jul 2026 07:28:14 +0000 (03:28 -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.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: private per-inode stripe runs for log-active inodes
Zygo Blaxell [Thu, 30 Jul 2026 01:43:12 +0000 (21:43 -0400)]
btrfs: stripe_alloc: private per-inode stripe runs for log-active inodes

Closing the open stripe run covering every logged extent at each log
commit made completed fsyncs crash-safe, but at a placement cost: an
fsync-heavy inode shares the open band runs with every other writer, so
each of its log commits closes a shared run, fragmenting concurrent
write streams and trapping the shared run's tail.

Give log-active inodes their own runs instead.  The first fsync of an
inode sets a sticky runtime flag (at btrfs_sync_file entry, before the
fsync flushes its own delalloc, so even that first fsync's allocations
are steered).  Datacow allocations for a flagged inode come from a
private LOG-class run: claimed like any run but never placed in the
shared band slots, owned by the inode, and found by owner lookup under
the block group's stripe_run_lock.  A per-inode hint seeds the
allocator's search with the run's location; the hint is advisory (a
stale hint costs a lookup miss, never a wrong run, since the owner
match is authoritative).  When no fully-free stripes remain for a
private run the allocation falls back to the shared runs, restoring
the previous placement with unchanged safety.

One inode's log commit now settles only its own stripes: other
writers' runs stay open and their streams stay contiguous, and the
only trapped tails are the fsyncing inode's own.  Private runs also
give each log-active inode exclusive stripes, which a later change
uses to copy live tails forward and reclaim them without touching
foreign extents.

The commit-time retirement closed runs by walking the band slots,
which private runs never occupy; walk the block group's run list
instead so every open run, slotted or private, is closed and drained
under invariant I2 (no open run survives a transaction commit).

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: settle a logged extent's stripes at log commit
Zygo Blaxell [Thu, 30 Jul 2026 00:51:24 +0000 (20:51 -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 bounded and join-free: run inflight is counted from
allocation, which happens during writeback with submission following in
the same pass, so the wait is bio flight time plus the parked-write
deadline that the flush short-circuits; write_done reporting needs no
transaction join, so waiting under the inode log mutex and a running
transaction handle is safe.

The cost is spatial: every fsync that logs an extent in a partial stripe
retires that stripe early, trapping its unwritten tail like any other
partially filled stripe until it frees or balance reclaims it.
Fsync-heavy workloads therefore burn a stripe tail per touched stripe
per fsync; the follow-up per-inode log runs and copy-forward relocation
exist to reclaim exactly that cost, and are optimizations on top of the
guarantee this patch completes.

Assisted-by: Claude:claude-fable-5
(cherry picked from commit 53c44fdbca58bd1fa267a5648e236ed4238d99ed)

3 months agobtrfs: stripe_alloc: control the policy with a filesystem property
Zygo Blaxell [Wed, 29 Jul 2026 16:59:27 +0000 (12:59 -0400)]
btrfs: stripe_alloc: control the policy with a filesystem property

A mount option is an awkward fit for write-hole protection: it occupies
a mount-option bit, and protection silently lapses whenever the option
is forgotten -- an fstab edit, a rescue mount, a recovery boot -- which
is exactly when a degraded raid56 is most likely to be written.

Control the policy with a "stripe_alloc" filesystem property instead,
following the property system's compression precedent: a btrfs.
namespace xattr, user-visible and admin-controlled, on the top-level
subvolume's root directory.  Set it once (setfattr -n btrfs.stripe_alloc
-v 1, or btrfs property once btrfs-progs learns the name) and it is
persistent: the kernel applies it when the root directory inode loads
its properties during mount, before any user IO.  Deleting the xattr
disables the policy; open runs drain at the next commit's retirement,
which runs unconditionally.  Stray copies of the xattr -- a received or
cloned subvolume -- are ignored: only the top-level root carries the
policy, so receiving a stream from a stripe_alloc filesystem cannot
flip the policy on the destination.

The support checks (free space tree, not zoned, no remap-tree) are
shared with the mount option path and enforced both when the property
is set and when it is applied at mount.

This stays within the series' no-on-disk-format-change constraint, and
that is the compatibility story: an older kernel mounts the filesystem
read-write and simply uses the legacy allocator, which is fully
compatible because the on-disk layout is unchanged.  New kernels honor
the property during the feature's long-tail testing period; if no use
case surfaces where stripe-exclusive allocation is worse than the write
hole it protects against, it can eventually become the only allocation
mode and the property a no-op.

Known old-kernel interactions with the btrfs. namespace: existing
kernels list and read the xattr (the btrfs. get path is a plain xattr
read) but refuse to set or remove unknown property names, so the flag
can only be managed from a kernel that knows it.  btrfs-progs
interaction (check, property list) with an unrecognized property is a
userspace compatibility item to verify and, if needed, patch.

The mount option is kept for now as a non-persistent override.  Later
protection stages with different risk profiles (the log-tree
full-stripe relocation) should be gated by their own property rather
than widening this one, so their testing exposure can be controlled
independently.

Assisted-by: Claude:claude-fable-5
(cherry picked from commit ecd4d3de8a0493f7c406d919d533f88e8b45390c)

3 months agobtrfs: stripe_alloc: never claim stripes covered by a live run
Zygo Blaxell [Wed, 29 Jul 2026 14:35:41 +0000 (10:35 -0400)]
btrfs: stripe_alloc: never claim stripes covered by a live run

The range-to-run lookups -- attaching an ordered extent to its stripe run
and reporting completed data IO by bytenr -- assume that at most one run
on a block group's list covers any given address.  Nothing enforced that.

A reservation that is discarded before anything references it (the
cow_file_range error path under ENOSPC, the find_free_extent backout
paths) returns its bytes to the free space cache immediately, with no
pinning: there is no committed state to protect.  When an ENOSPC failure
storm discards every allocation in a stripe, the stripe is fully free
again and the claim rule -- correctly, by its own lights -- hands it out
as part of a new run while the old run object is still on the list
draining its other stripes' IO.  Full-stripe write batching widened a
run's post-close drain from microseconds to the parked-write timeout, and
the soak test hit the overlap within minutes: new allocations' ordered
extents attached to the old run (first match by range), their completions
drained the old run's inflight accounting into an assertion failure, and
the new run's accounting never drained, wedging the commit's retire wait.
The overlap is harmless to data -- a stripe can only be re-claimed if
every byte of it is free, and discarded reservations never issued bios --
but the accounting corruption is fatal.

Freed committed extents cannot reproduce this: they return to the free
cache only in the unpin phase at the tail of a commit, and the same
commit's retirement already drained -- and freed -- every run opened
before it.  Only the unpinned immediate-free paths race with a draining
run.

Rather than enumerate those paths, enforce the lookups' assumption at the
claim site: btrfs_claim_free_stripe_run() now trims a candidate to end
before the first live run overlapping it, or rejects it if its head
overlaps.  Re-claiming such stripes just waits until the old run drains
off the list, which only comes up inside ENOSPC failure storms.

Reproduced with concurrent fill-to-ENOSPC/delete cycles, balance, and
fsstress on a 4-device raid5: the assertion fired within ~15 minutes
unpatched, and ~10 hours of the same load ran clean with this fix.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: raid56: batch stripe_alloc partial writes into full-stripe writes
Zygo Blaxell [Tue, 28 Jul 2026 15:19:50 +0000 (11:19 -0400)]
btrfs: raid56: batch stripe_alloc partial writes into full-stripe writes

A raid56 sub-stripe write pays a read-modify-write: read the rest of the
stripe, recompute parity, write.  The plug callback merges rbios submitted
within one plug window and the stripe cache saves re-reads for
back-to-back writes, but measurement shows what survives them: on a
4-device raid5, small-file writeback produces 100% sub-stripe rbios (zero
full-stripe writes) and a mixed 4K-512K workload ~55%, so parity is
recomputed and rewritten once per file that lands in a stripe.

Stripe-exclusive allocation gives raid56 something the allocator never
guaranteed before: the rest of an open run's stripe is either written
before the run closes -- within the current transaction -- or not at all.
That makes holding a partial write a sound bet, so park it: a partial
write rbio whose stripe belongs to an open stripe run keeps the stripe
lock but does not start its RMW.  Later writes to the stripe merge into
it through the existing lock_stripe_add() path, and the moment its data
bitmap covers the stripe it is submitted as a single full-stripe write:
one parity computation, no reads.

Completion accounting can never trigger the flush of runts -- parked bios
have not been submitted, and preallocated or discarded allocations
produce no bios at all -- so liveness comes from explicit flushes: the
run retirement paths flush before the commit's IO drain (which waits on
the very bios parked here), ordered-extent waiters flush their range on a
short retry period, and a timer bounds everything else.  Writes with a
blocked waiter (REQ_SYNC: fsync- and sync-driven writeback) park with a
~3ms deadline instead of 100ms -- long enough for the rest of one
writeback pass over the stripe to merge in, short enough to stay
invisible in fsync latency -- and a sync bio merging into a parked rbio
pulls the deadline in.  Only the bg->open_stripe slots are consulted for
eligibility, and a parked rbio that a racing retirement closed out from
under is bounded by the timer, never by the drain.

Measured (same 4-device raid5, deterministic workloads, classifying every
write rbio at rmw_rbio):

  workload       full-stripe rbios      total write rbios
  streaming      99% -> 99%             unchanged
  mixed 4K-512K  43% -> 97%             2478 -> 1615
  small files     0% -> 86%             1537 ->  335 (stripe reads 311->23)
  fsync-per-file  0% ->  0%             unchanged (nothing co-pending)

fsync latency is 12ms vs 8ms unpatched (each fsync pays one short park).
Batching also collapses trapped free space in a mixed-size forward fill
from ~87 MiB to ~3 MiB: stripes now fill completely before the commit
closes their run, so the frontier strands almost nothing.

Validated: btrfs selftests; mixed-size + concurrency + churn + balance
workload with trapped-space accounting returning to zero after deleting
everything; scrub and full sha256 read-back over 4005 mixed random files;
and the dm-log-writes write-hole crash matrix (24/24 controls clean, 0/36
armed cases with committed data damage) -- parking does not perturb the
stripe-exclusivity guarantee it rides on.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: grow the frontier run instead of stranding its tail
Zygo Blaxell [Tue, 28 Jul 2026 06:26:50 +0000 (02:26 -0400)]
btrfs: stripe_alloc: grow the frontier run instead of stranding its tail

When an allocation is larger than every open run's remainder, the
allocator claims fresh fully-free stripes and opens a separate run,
leaving the old run's tail behind.  The banded cursors keep that tail
open for a while, but a band collision or the commit eventually closes
it, and the tail -- perfectly usable space that a misfit merely jumped
over -- is stranded in a partially filled stripe.  In a forward fill
this happens at every size upshift, and measurement shows it is where
nearly all of stripe_alloc's trapped space comes from: on a mixed-size
fill it strands ~14% of the data written, a figure that band-granularity
tuning moves by at most a tenth and commit frequency does not move at
all.

Grow the frontier run instead.  If the freshly claimed stripes directly
follow the end of an open run of the same class, extend that run to
absorb them and place the allocation at the run's old tail, spilling
contiguously into the new stripes.  Nothing is stranded, and the extent
is physically contiguous.  In a forward fill the by-size claim naturally
returns the stripes adjacent to the frontier, so the single frontier run
just keeps growing -- the allocator packs the way the stock allocator
does, while keeping stripe exclusivity: the grown stripes were claimed
fully free, the run still closes at the next commit and is never
reopened, so every stripe of the run is filled within one open-run
lifetime.  A grown run keeps its open_seq; it can only still be in a
band slot if the retire walk for its window has not yet run, which the
open_stripe_lock nesting at the claim site excludes from racing.

Measured on a 4-device raid5 with a deterministic interleaved 4K-512K
fill (trapped space via the stripe_unusable counter, byte-identical data
both sides): 111.1 MiB trapped without growing, 7.2 MiB with -- a 94%
reduction, and usable capacity at ENOSPC within 0.5% of the stock
allocator (1561 vs 1569 MiB, vs 1421 MiB without growing).  The benefit
survives churn: with age-correlated deletion the grown runs' contiguous
packing lets whole stripes free together, and steady-state usable
capacity stays at 1486-1561 MiB versus 1284-1421 MiB without growing
across correlated and adversarial small-file deletion patterns.  Data
integrity verified by scrub and full sha256 read-back over mixed
random-content files, and trapped-space accounting still returns to
zero when all files are deleted.

The open-stripe selftest is updated: the misfit allocation now grows the
run and lands at the run's old tail, spanning the stripe boundary, and
the relocation-class case doubles as a check that a claim adjacent to
another class's run never grows it.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: keep an open run per size band to trap less
Zygo Blaxell [Tue, 28 Jul 2026 00:55:59 +0000 (20:55 -0400)]
btrfs: stripe_alloc: keep an open run per size band to trap less

A single open stripe run per class forces every allocation that does not
fit the current run's remainder to close that run -- trapping its
unallocated tail in a now partially filled stripe -- and claim a fresh
fully-free stripe.  A workload that interleaves small and large extents
(the common case) therefore strands a tail on every size change, even
though a later small allocation could have filled it.

Keep one open run per power-of-two band of remaining free space instead
(band k holds a run with remaining in [2^k, 2^(k+1)) sectors), per class.
An allocation takes the run in the smallest band that still fits --
segregated best fit -- so a small write lands in an already-open, nearly
full stripe rather than opening a new one, while a large write that no
open run can hold opens a fresh stripe and leaves the smaller runs open
for the small writes that do fit them.  After each allocation the run is
re-placed into the band its new remainder falls in; when two runs collide
in a band the fuller one is kept -- it can serve larger future
allocations, and closing it would trap more -- and the other is closed,
its tail returned to the free space cache.

16 bands cover a full stripe of up to 2^16 sectors, far more than any
raid56 geometry (nr_data_stripes * stripe_len / sectorsize is 158 sectors
at 10 data stripes and a 64K stripe).  Commit-time retirement and the
read-only / removal paths now walk every band of every class; only the
bg->open_stripe[][] slots can ever hold an open run, so one pass still
suffices, and the obsolete single-slot assertions are dropped.

This does not touch the write-hole guarantee: every run is still a
contiguous fill of fully-free stripes, closed at commit and never
reopened.  It only changes which open run an allocation joins, reducing
the free space trapped in partial stripes -- and thus stripe_unusable --
for mixed-size workloads.

The open-stripe selftest is rewritten to the multi-cursor contract: a
misfit allocation now keeps the old run open (its tail is not returned to
the cache) and a later small allocation backfills it, so fewer stripes are
claimed before the free space is exhausted.

Assisted-by: Claude:claude-opus-4-8
3 months agobtrfs: account stripe_alloc trapped free space for honest statfs
Zygo Blaxell [Mon, 27 Jul 2026 16:31:14 +0000 (12:31 -0400)]
btrfs: account stripe_alloc trapped free space for honest statfs

Free space in the partially filled stripes of a stripe_alloc (raid56
write-hole-safe) block group is real free space -- it is in the free
space tree and cache -- but the stripe-exclusive allocator cannot hand it
out until the whole stripe frees.  statfs therefore over-reports available
space, promising free space that a later allocation refuses with ENOSPC.

Track this trapped space per block group as stripe_unusable, summed into
space_info->bytes_stripe_unusable.  It is derived, so there is no on-disk
format change and the free space tree and cache are left untouched
(preserving the extent-tree/free-space-tree consistency btrfs check
verifies).

stripe_unusable is defined by a scan that accumulates every free byte of
the block group into a per-stripe array and then sums the stripes that are
partially filled.  A per-stripe accumulator, rather than a streaming sweep
or a per-stripe cache search, is what makes the result correct regardless
of the order the free space cache yields its ranges -- an offset-sorted
bitmap entry can emit runs that lie past a following extent entry, so the
ranges are not globally monotonic -- and regardless of whether free space
is stored as extents or bitmaps.  A debug-build assertion checks that the
scan distributes exactly the cache's free space.  Because trapped space
only settles at commit -- when the retire path returns partially filled
stripes and deleted extents are unpinned -- the scan is recomputed at
commit for groups whose free space changed (flagged cheaply on the
allocation and free paths), which suits the timescale of the reclaim it
feeds far better than a running per-extent tally.  The space_info total is
recomputed as the sum of the armed groups after those rescans, so it
cannot drift.

statfs subtracts bytes_stripe_unusable from the data f_bavail so df
reports what can actually be allocated, and the counter is exposed at
/sys/fs/btrfs/<uuid>/allocation/data/bytes_stripe_unusable.  It is
deliberately not part of btrfs_space_info_used(), so the reservation layer
is unchanged and this carries no ENOSPC-behaviour risk.

The counter is armed once a group's free space cache is loaded, so a group
contributes zero until then and statfs starts optimistic and settles to
honest as groups cache and commit.  It is disarmed when a group turns
read-only (its free space is then accounted as read-only and already
excluded from statfs) and re-armed by a rescan on the way back to
read-write, so a balance both recovers trapped space and updates the
counter.  A CONFIG_BTRFS_DEBUG-only sysfs trigger, stripe_unusable_rescan,
forces a full recompute for auditing the accounting.

Two deliberate imprecisions, matching existing behaviour rather than
bettering it: statfs subtracts bytes_stripe_unusable but not
bytes_zone_unusable, so stripe_alloc df reports availability before reclaim
while zoned df reports it after; and superblock stripes, permanently
unusable in every profile, are left to the existing bytes_super accounting
rather than separately reported here.  Both await a maintainer decision on
a common convention.

Assisted-by: Claude:claude-opus-4-8
3 months agobtrfs: raid56: only verify recovered sectors that have a checksum
Zygo Blaxell [Sat, 1 Aug 2026 22:31:19 +0000 (18:31 -0400)]
btrfs: raid56: only verify recovered sectors that have a checksum

verify_one_sector() checks that the rbio has a csum_buf/csum_bitmap at
all, but never tests the bitmap bit for the sector it is about to
verify.  A recovered sector that has no csum -- free space, or a sector
whose ordered extent has not yet committed its csums, including the
very sector a sub-stripe write is replacing -- is then compared against
an all-zero csum_buf slot and fails with EIO.

The visible symptom: sub-stripe writes to a degraded raid5/6 fail with
EIO whenever the missing device's column in the target stripe is only
partially covered by csums.  The RMW read phase marks every sector of
the missing device as an error, recover_sectors() rebuilds the column
and verifies each rebuilt sector, and the first csum-less sector kills
the write:

  BTRFS error (device loop3): dropping unwritten extent at root 5
    ino 1061 offset [0,4095] disk bytenr 638771200 length 4096

with no underlying device error and no corruption counted anywhere.
Writing new data into partially filled stripes is exactly what a
degraded array must do to keep operating, so this makes a degraded
raid56 filesystem effectively read-only for small writes, and each
failure drops the unwritten extent (detectable data loss).

fill_data_csums() only covers sectors that have csum items, and its
sibling loop verify_bio_data_sectors() already skips sectors whose
bitmap bit is clear.  Do the same here.

Fixes: 7a3150723061 ("btrfs: raid56: do data csum verification during RMW cycle")
CC: stable@vger.kernel.org # 6.2+
Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
Assisted-by: Claude:claude-fable-5
3 months agobtrfs: propagate a split bio's error when the failing split completes last
Zygo Blaxell [Sat, 1 Aug 2026 05:31:24 +0000 (01:31 -0400)]
btrfs: propagate a split bio's error when the failing split completes last

btrfs_bio_end_io() saves the first error of any split bio in the original
btrfs_bio's ->status, then loads it into ->bio.bi_status when the last
split completes -- but only if that last completion itself succeeded:

if (atomic_dec_and_test(&bbio->pending_ios)) {
/* Load split bio's error which might be set above. */
if (status == BLK_STS_OK)
bbio->bio.bi_status = READ_ONCE(bbio->status);

The condition assumes that a failing final completion has already stored
its error in the original bio at the top of the function.  That holds only
when the bio was never split.  For a split, "bbio->bio.bi_status = status"
is applied to the clone, which is then freed and bbio switched to the
original; the original's bi_status keeps whatever an earlier, successful
split left in it, and the error never reaches the caller.

The ordering that loses the error is not rare.  A read that fails checksum
verification completes only after read repair has tried every mirror,
which takes far longer than the healthy splits of the same bio, so the
failing split completes last essentially every time.

On a degraded raid56 array the result is silent corruption.  Reads are
split per stripe, so for any read of BTRFS_STRIPE_LEN or more, a sector
whose reconstruction from a torn stripe fails its checksum is returned to
userspace as zeros with no error -- while btrfs logs the checksum failure
and increments the device corruption counter.  A 4 KiB read of the same
sector is not split and correctly returns EIO.  Profiles that do not split
at 64 KiB (single, dup, raid1) are unaffected, which is how this has gone
unnoticed.

Reproducer: on a raid5 filesystem, tear one stripe row's parity (leaving
the data intact), withhold one data member of that row and mount degraded.
Reconstructing the missing column then yields wrong bytes for that column
while every other column still verifies.  Reads of 64 KiB or more over the
affected range return zeros and succeed; 4 KiB reads return EIO.

Load the saved status unconditionally.  It is the first error seen by any
split, including this one, which is the value the caller wants in either
case.

Fixes: d48e1dea3931 ("btrfs: fix error propagation of split bios")
CC: stable@vger.kernel.org # 6.6+
Assisted-by: Claude:claude-opus-5
Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
3 months agobtrfs: allow changing system dev_extent size via sysfs topics/dev-extent-defrag
Zygo Blaxell [Sat, 30 Sep 2023 06:47:08 +0000 (02:47 -0400)]
btrfs: allow changing system dev_extent size via sysfs

When a filesystem using striped profiles such as raid0, raid10, raid5,
or raid6 is repeatedly resized and balanced, severe and disruptive
dev_extent fragmentation can occur when dev_extents are allowed to have
different sizes.

On filesystems over 50 GiB in size, data and metadata dev_extents are both
1 GiB each, but the system dev_extents are always 32 MiB regardless of
filesystem size.  This can leave some devices with odd-sized dev_extent
holes on filesystems with more devices than the metadata's stripe count.

Striped profile allocators will try to allocate the widest block
groups possible, so as the devices fill up, eventually block groups
are allocated that have dev_extents shorter than 1 GiB, and these will
be allocated on all devices because that's what striping profiles do.

As storage is expanded, these block groups are balanced and removed,
leaving behind small free space holes.  These holes limit the size of
future block group allocations, causing small dev_extents to multiply.
This repeats until the filesystem has hundreds of thousands of dev_extents
at the minimum 1 MiB size, instead of hundreds of extents at the normal
1 GiB size.

Block groups made from these small dev_extents cannot hold the largest
btrfs extents (128 MiB), making their space effectively unusable.
The btrfs allocator has several functions that are O(n) in the number of
block groups, which start to slow down significantly as the dev_extents
fragment.

This fragmentation is avoidable by:

1.  round down the device sizes to an exact multiple of 1 GiB +
1 MiB. (The 1 MiB is reserved by btrfs at the beginning of each
device, so this means 1 GiB dev_extents will always fit exactly
on the device with no fragmentation.)

2.  set all block group dev_extent sizes to 1 GiB, so that all
dev_extents and all free space holes are exactly 1 GiB in length.

3.  balance existing block groups so that they are all aligned
to 1 GiB boundaries (offset by the reserved 1 MiB at the start).

Of these, only #2 requires a kernel change.

Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
3 months agobtrfs: use BTRFS_MAX_EXTENT_SIZE in prealloc topics/prealloc-size
Zygo Blaxell [Sat, 21 Dec 2024 15:48:03 +0000 (10:48 -0500)]
btrfs: use BTRFS_MAX_EXTENT_SIZE in prealloc

The prealloc size limit of 256M was set in
commit 24542bf7ea5e ("btrfs: limit fallocate extent reservation to 256MB")
while the 128M extent size limit used everywhere else was set in
commit b888db2bd7b6 ("Btrfs: Add delayed allocation to the extent based
page tree code"), i.e. since the beginning of btrfs.

Excessively large extents cause problems for relocations already, and
there is no need for prealloc to create any more.  Bring the prealloc size
down to the same size used by normal write allocations.

Zoned devices can't use prealloc, so we don't need to do anything special
for them like we do for normal writes.

Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
3 months agobtrfs: claim stripe runs via the by-size free space index
Zygo Blaxell [Mon, 27 Jul 2026 06:38:33 +0000 (02:38 -0400)]
btrfs: claim stripe runs via the by-size free space index

btrfs_claim_free_stripe_run() walked the by-offset free space tree,
skipping every entry smaller than a full stripe.  When the free space
degenerates into many sub-stripe holes -- the steady state of a nearly
full stripe_alloc filesystem -- this scans the entire free space tree on
every allocation, which is the dominant cost of the known raid56
near-full allocation slowdown.

Walk the by-size index instead.  It is ordered by largest contiguous
free run first, so once an entry's largest run is smaller than a full
stripe no later entry can hold a fully-free stripe and the search stops
immediately: an O(1) fast fail when no stripe is claimable, instead of a
full-tree scan.  Correctness is unchanged -- an entry whose largest
contiguous run is at least a full stripe is still checked for a
stripe-aligned fully-free run exactly as before.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: refuse space_cache=v1
Zygo Blaxell [Wed, 5 Aug 2026 03:33:32 +0000 (23:33 -0400)]
btrfs: stripe_alloc: refuse space_cache=v1

The v1 free space cache inode is nodatacow, preallocated and nodatasum,
so the cache is overwritten in place during commit: a sub-stripe write
into a data block group, landing in whatever committed stripes the cache
occupies, with no csum that could reveal the damage afterwards.  That is
precisely the write this series exists to prevent.

The free space tree is not what stripe_alloc needs -- nothing in it reads
the tree, and the by-size index it allocates from is the in-memory free
space, which exists whatever the on-disk format is.  Having no cache at
all is fine too.  Only v1 has to be kept away, so say that instead of
demanding v2.

Three places, because the cache format can only be converted at mount and
never at remount, so the option alone is not the whole story:

 - btrfs_check_mountopts() rejects space_cache=v1 with stripe_alloc.

 - btrfs_reconfigure() rewrites the cache options after that validation,
   to restore what is on disk.  It has to, given the above.  Re-check
   afterwards rather than assume the options still mean what they did.

 - block group read time refuses to mount when v1 cache inodes are
   present on disk at all.  cache_generation only records whether the
   last mount wrote the cache; the inodes are the durable evidence, so
   btrfs_free_space_cache_v1_present() looks for one under
   BTRFS_FREE_SPACE_OBJECTID in the tree root.  Clearing them is one
   mount away, and the error message says so.

cache_save_setup() also declines to set the cache up while stripe_alloc
is on.  The checks above should make that unreachable, but it is the
point where the in-place write would actually be issued.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: refuse to enable on mixed block groups
Zygo Blaxell [Tue, 4 Aug 2026 20:43:03 +0000 (16:43 -0400)]
btrfs: stripe_alloc: refuse to enable on mixed block groups

Making stripe_alloc work on a mixed data+metadata filesystem means making
raid56 metadata work, and upstream does not attempt that: fill_data_csums()
skips csum lookup entirely for mixed block groups, so their sectors are not
verifiable in the raid56 read path, and verify_one_sector() consequently
returns success without checking anything.  Everything this series builds on
top -- reconstruction it can trust, a stripe cache whose contents can be
re-verified, scrub that can tell a good column from a bad one -- assumes
csum coverage that a mixed group does not have.

So do not carry a half-supported mode.  Refuse the mount option there, the
way it is already refused on zoned filesystems and with the remap tree.
Mixed block groups are a mkfs-time property of small filesystems, and the
option cannot become applicable later.

This also removes the reachable path to the commit deadlock fixed in "btrfs:
stripe_alloc: do not claim stripes in mixed block groups"; the DATA-without-
METADATA test added there stays as belt and braces, and the mount-time
warning loses its mixed case, which can no longer happen.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: stripe_alloc: do not claim stripes in mixed block groups
Zygo Blaxell [Tue, 4 Aug 2026 06:43:20 +0000 (02:43 -0400)]
btrfs: stripe_alloc: do not claim stripes in mixed block groups

btrfs_is_stripe_alloc_bg() tests only the DATA flag, so a mixed
data+metadata block group with a raid56 profile passes it and metadata
allocations go through the stripe claim rule as well.  The next commit
then deadlocks:

  sync              btrfs_retire_open_stripes+0x37c   D
                    btrfs_commit_transaction+0x2f5
  btrfs-transaction wait_current_trans+0x199          D

A run is drained when it is closed and its inflight_bytes reach zero.
Every allocation from a run adds to inflight_bytes, and the only things
that subtract are ordered extent completion, an allocation the finder
discards, and a reservation being freed.  Metadata has no ordered extent:
btrfs_alloc_tree_block() allocates nodesize with is_data false, and
end_bbio_meta_write() only clears the extent buffer's writeback state --
it reports nothing to the run.  So a metadata allocation raises
inflight_bytes and nothing ever lowers it again, open_stripe_run_drained()
never becomes true, and btrfs_retire_open_stripes() waits for a completion
that has no code path to arrive from.

Note this is an accounting gap, not a question of when tree blocks are
written: the wait would not end even if writeback had already finished.
The hung task detector stays quiet too, because wait_var_event() sleeps in
a state it exempts -- the filesystem just stops.

Reproduced deterministically on a mixed raid5 filesystem
(mkfs.btrfs -M -d raid5 -m raid5) mounted -o stripe_alloc: the first sync
after writing a few hundred small files never returns.

Two more reasons not to claim there, with the deadlock out of the way:

 - a claim that cannot find a free full stripe returns ENOSPC to the
   caller.  For data that fails a write; for metadata it aborts the
   transaction and the filesystem goes read-only.  Nothing in the
   allocator adds the pessimistic reservation margin that would make
   claiming safe against a metadata reservation already granted.

 - raid56 deliberately skips csum lookup for mixed block groups, to
   avoid recursing into a metadata read while holding the full stripe
   lock (see the comment above the map_type test in fill_data_csums()).
   Sectors in a mixed group therefore are not verifiable, which the
   recovery paths here assume they are.

Exclude them: the claim rule now requires DATA without METADATA.  Mixed
raid56 groups keep the legacy read-modify-write behaviour, write hole
included, which is what the series documents as out of scope.  (Metadata
and system block groups never carried the DATA flag, so they were already
excluded.)

While here, route the two open-coded copies of the same test through
btrfs_is_stripe_alloc_bg() so the rule lives in one place.  Both already
tested the mount option first, so this is equivalent apart from the new
exclusion.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: add a write-hole invariant checker to the raid56 write path
Zygo Blaxell [Sat, 25 Jul 2026 15:11:02 +0000 (11:11 -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.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: retire stripe runs at commit and gate stripe_alloc
Zygo Blaxell [Sat, 25 Jul 2026 05:35:20 +0000 (01:35 -0400)]
btrfs: retire stripe runs at commit and gate stripe_alloc

Hook stripe run retirement into the transaction commit, right after
TRANS_STATE_COMMIT_DOING stops accepting joins with a single writer
left.  At that point every data extent the transaction references was
inserted by an ordered extent completion that joined earlier, implying
its own data IO is done; the retirement drain waits out in-flight
neighbour writes in the same stripes (a pure data-IO wait, never an
ordered extent wait, which would deadlock on the blocked join).  After
the drain, no stripe this transaction references can ever be written
again, so a crash after the superblock write cannot tear it -- closing
the raid56 write hole for stripe-allocated block groups without
requiring flushoncommit.  A defensive retirement in
btrfs_free_block_groups() covers the transaction abort path.

Force COW for in-place writes that would land in raid56 data block
groups while stripe_alloc is enabled (nodatacow files and writes into
preallocated extents): a single in-place write could tear a stripe
containing other files' committed extents, making the guarantee
conditional on the whole filesystem's usage.  The check sits in
can_nocow_file_extent(), covering buffered and direct IO with one
choke point, and applies per extent so nocow to non-raid56 profiles
keeps working.  The data relocation inode is exempt: its extents live
in relocation-class stripe runs that never share stripes with other
data, and relocation depends on in-place writes.

Validate the option at mount: it requires the free space tree (the v1
space cache overwrites its data in place during commit), and is
refused with the remap-tree feature (whose relocation writes bypass
the ordered extent accounting) and on zoned filesystems (which have
their own allocator and no write hole).

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: report stripe run data IO through the ordered extent lifecycle
Zygo Blaxell [Sat, 25 Jul 2026 05:32:11 +0000 (01:32 -0400)]
btrfs: report stripe run data IO through the ordered extent lifecycle

Pair every byte reserved from an open stripe run with exactly one
"write done" report, so commit-time retirement can wait for all data IO
into a window's stripes:

- Ordered extents get a stripe_run pointer, attached at creation by a
  range lookup (cheap: gated on the fs having any stripe runs at all,
  and a run's block group membership is established before its
  allocation returns, so the gate cannot miss).  NOCOW and PREALLOC
  ordered extents write into previously allocated extents, which can
  never lie inside a run claimed from fully-free stripes, and are
  skipped.  The report fires once at IO completion (the IO_DONE moment
  in can_finish_ordered_extent(), before any transaction join, so the
  commit-time drain can never deadlock on a blocked join), with a
  catch-all when an ordered extent is freed without completing IO.

- Reservations freed without an ordered extent ever owning them (error
  paths) report through btrfs_free_reserved_extent(); the one caller
  that frees a range an ordered extent did own (the finish-error path)
  uses btrfs_free_reserved_extent_ordered() to avoid double reporting.

- Preallocated extents never issue data IO and report at insertion;
  this also covers relocation's data inode preallocations.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: add the stripe_alloc allocation policy for raid56 data
Zygo Blaxell [Sat, 25 Jul 2026 05:24:37 +0000 (01:24 -0400)]
btrfs: add the stripe_alloc allocation policy for raid56 data

Wire the open stripe run allocator into find_free_extent() as a per-
block-group policy: with the new stripe_alloc mount option, allocations
from raid56 data block groups go through btrfs_alloc_from_open_stripe()
instead of the clustered allocator, and only ever land in fully-free,
stripe-aligned runs.  Since the loop's terminal LOOP_NO_EMPTY_SIZE
degradation only applies to the clustered path and stripe block groups
ignore empty_size/empty_cluster, the natural terminal behaviour is:
no fully-free stripe in any block group -> allocate a chunk -> ENOSPC.
The availability hint feeds max_extent_size so callers retry with
smaller allocations instead of failing early.

Stripe runs get an allocation class: relocation overwrites its
preallocated extents in place, so its allocations must never share a
stripe with ordinary cow data.  Classes never share a run, and one
block group at a time is softly dedicated to relocation by reusing
fs_info->data_reloc_bg (btrfs_clear_data_reloc_bg() moves from zoned
code to generic code for this; the class tag, not the dedication, is
what carries correctness).  The dedication is dropped when relocation
finishes or the dedicated group runs out of stripes.

Setting a block group read-only now retires its stripe runs (in
btrfs_inc_block_group_ro(), covering scrub, relocation and unused
block group deletion), pairing with the allocator's ->ro check under
the stripe_run_lock so no run can survive into or be created in a
read-only group.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: add open stripe run tracking for stripe-exclusive allocation
Zygo Blaxell [Sat, 25 Jul 2026 04:01:17 +0000 (00:01 -0400)]
btrfs: add open stripe run tracking for stripe-exclusive allocation

Add the in-memory state and lifecycle for "open stripe runs", the
allocation windows of the raid56 stripe-exclusive allocation policy.  A
run is a contiguous stripe-aligned region claimed whole from the free
space cache via btrfs_claim_free_stripe_run() and filled strictly
sequentially by btrfs_alloc_from_open_stripe().  A run closes when it is
exhausted, when an allocation does not fit its remainder, or when the
transaction commit retires it; closed runs are never reopened and their
unallocated tails return to the free space cache, where the fully-free
claim rule makes them unallocatable until the whole stripe frees.  This
is what will guarantee that a full stripe only receives writes within
one commit window, closing the raid56 write hole for these block groups.

Each run counts reserved bytes whose data IO has not completed yet,
maintained under the block group lock and reported back through
btrfs_open_stripe_write_done().  btrfs_retire_open_stripes() implements
commit-time retirement: bump the retire sequence, close every run opened
before it, and wait for their inflight bytes to drain.  It is a pure
data-IO wait, deliberately not an ordered extent wait: it is designed to
run after the committing transaction stops accepting joins
(TRANS_STATE_COMMIT_DOING with a single writer), where waiting for
ordered extent completion would deadlock on the blocked transaction
join, and where every extent the transaction references already has its
own data on disk.  Allocations racing with the commit open runs stamped
with a newer sequence and are neither retired nor waited for; their
extents can only be referenced by the next transaction.  Block groups
with runs are tracked on an fs_info list whose membership is
established before an allocation returns, which is what lets the retire
walk rely on the sequence stamp.

Exercised by a new sanity self-test; the raid56 stripe allocation
policy and the commit hook will be the first non-test users.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: add btrfs_claim_free_stripe_run() for stripe-exclusive allocation
Zygo Blaxell [Sat, 25 Jul 2026 03:58:30 +0000 (23:58 -0400)]
btrfs: add btrfs_claim_free_stripe_run() for stripe-exclusive allocation

Add a free space cache primitive that finds and removes a contiguous,
fully-free, stripe-aligned run of full stripes from a block group.  This
is the building block for a raid56 allocation policy that never issues
sub-stripe writes into stripes containing committed data, closing the
raid56 write hole for datacow writes: because a partially-filled stripe
can never satisfy the fully-free requirement, stripes retired at commit
time become unallocatable without any persistent allocator state.

Full stripe geometry is relative to the block group start and supports
non-power-of-two stripe widths.  Unaligned head and tail remainders are
returned to the free space cache with their trim state preserved.  Runs
are found within a single free space entry; a fully-free stripe split
across an extent entry and a bitmap neighbour is deliberately not found,
which errs toward missing a claimable stripe, never toward claiming a
non-free byte.

The function is exercised by new sanity self-tests covering aligned and
capped claims, partial-stripe exclusion, head/tail carving, block-group-
relative geometry, bitmap entries, and non-power-of-two stripe widths.
The raid56 stripe allocation policy will be its first non-test user.

Assisted-by: Claude:claude-fable-5
3 months agobtrfs: raid56: fix use-after-free of rbio in bio end_io wakeups
Zygo Blaxell [Sat, 25 Jul 2026 20:06:34 +0000 (16:06 -0400)]
btrfs: raid56: fix use-after-free of rbio in bio end_io wakeups

The read/write submission rounds in raid56 count in-flight bios in
rbio->stripes_pending and wait with a bare
wait_event(rbio->io_wait, atomic_read(&rbio->stripes_pending) == 0),
while each bio's end_io does
"if (atomic_dec_and_test(&stripes_pending)) wake_up(&rbio->io_wait)".

Once the final decrement makes the counter visible as zero, the waiter
can pass its condition check without consuming the wakeup -- via
wait_event()'s fast path when all bios complete before the waiter
arrives, or a condition recheck after an earlier wakeup -- and proceed
to free the rbio through rbio_orig_end_io().  The end_io context is
then still inside wake_up() operating on the freed rbio's embedded
waitqueue lock.

This shows up under sustained raid56 RMW load in KVM guests as
recurring "pvqspinlock: lock ... has corrupted value 0x0!" warnings
from __pv_queued_spin_unlock_slowpath with a
__wake_up <- raid_wait_write_end_io <- bio_endio call trace: paravirt
spinlocks detect the unlock of the recycled lock word.  On bare metal
the use-after-free is silent and almost always harmless, which is how
it has survived; it is a plausible match for long-standing sporadic
crash reports on busy raid5 filesystems that never reproduce under
sanitizer kernels (the instrumentation widens the dec-to-wake window
so the race is always lost).

Convert the pair to a completion.  wait_for_completion()'s fast path
takes the completion's own lock, so it cannot return before complete()
has released it: the completing context is provably finished with the
rbio before the waiter can free it.  A submitter-held bias count keeps
one completion per submission round even when a round submits zero
bios or every bio finishes before the submitter starts waiting; the
scrub path only waits when finish_parity_scrub() actually began a
round.

Assisted-by: Claude:claude-fable-5
Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
3 months agobtrfs: don't abort raid56 data scrub on first uncorrectable sector
Zygo Blaxell [Thu, 4 Jul 2024 01:00:18 +0000 (21:00 -0400)]
btrfs: don't abort raid56 data scrub on first uncorrectable sector

In commit 1009254bf22a ("btrfs: scrub: use scrub_stripe to implement
RAID56 P/Q scrub") a new function scrub_raid56_parity_stripe() was
introduced to recalculate the parity stripe after correcting any
correctable errors.  When it detected unrepaired sectors in a data
stripe, it returned -EIO, which propagated up the stack through
scrub_stripe, scrub_chunk, and scrub_enumerate_chunks, where an error
makes the scrub break out of its loop early and return the error to
userspace.

That was a regression:  uncorrectable data blocks are one of the
expected possible events that occur during a scrub, so scrub should
continue until it has counted and reported all of the uncorrectable
stripes in the filesystem.  Perhaps more importantly, scrub should fix
up any correctable errors that might exist in other stripes beyond the
first uncorrectable stripe.  Errors from this function are only
appropriate when scrub cannot do its job at all:  unable to read csums,
unable to map an extent's data blocks, or out of memory.

On current kernels the bug has changed shape:  at the point where
unrepaired sectors are detected, ret no longer holds -EIO.  It holds
the leftover return value of the last scrub_find_fill_first_stripe()
call from the loop that populates the data stripes, which is 0, or 1
when the last data stripe of the full stripe contains no extents.
When the stale 1 leaks out, the caller treats any nonzero value as an
error ("if (ret) goto out;" in scrub_stripe()) and aborts the whole
scrub with a meaningless positive return value; when it is 0, the
scrub continues only by accident.

scrub_raid56_parity_stripe() has successfully completed its task as
soon as it has performed its data correction and verification steps.
Return 0 explicitly at that point, regardless of the outcome of the
verification.  The P/Q update step is still skipped for the affected
full stripe, so no garbage is written back to the devices.  Detected
errors are reported to the user via device stats and dmesg messages,
not via the return code of the scrub ioctl.

Fixes: 1009254bf22a ("btrfs: scrub: use scrub_stripe to implement RAID56 P/Q scrub")
Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
3 months agobtrfs: log a message when dropping an extent due to IO error
Zygo Blaxell [Sat, 6 Jul 2024 03:08:46 +0000 (23:08 -0400)]
btrfs: log a message when dropping an extent due to IO error

When an IO error occurs while writing a datacow file, btrfs will drop the
extent containing the unwritten blocks.  This prevents potential leaks
of information stored in the unwritten data blocks back to userspace, but
it is also a data loss event that is not easily visible from userspace.

The existing code does notify userspace of the error via the inode,
and the notification can be received through fsync (for the inode) or
syncfs (for any dirty inode on the filesystem) return values; however,
for the common case of a process that writes to a file and exits with
its data still in dirty cache pages, there is no process left to notify
when the ordered writes eventually fail.

In most cases the extent drop is preceded by error messages from the
write operation, but the IOERR bit can be set for less visible or obvious
reasons, like running out of memory, bad metadata, or as a result of
bugs that appear in other parts of btrfs from time to time.

Some of the existing error messages for writes contain only logical
addresses, while other messages contain only disk bytenrs.  For read
errors, only one address is necessary, as the user can look up the other
with `btrfs ins log -o` or `btrfs ins sub/ino`, but for write errors, the
mapping between these addresses is removed when the error is detected in
btrfs_finish_one_ordered, so we can't derive one address from the other.
We need both addresses for separate purposes:  the logical address to
identify which files have missing data, and the disk bytenr to identify
which part of the filesystem address space is failing to accept writes
(resolvable to device sectors through the chunk tree).

For now, inform the sysadmin that the data has been dropped by logging a
message when it happens, including both the logical subvol/inode/offset
triple and the disk bytenr, and the corresponding sizes.

In the future we might want to add some stats counters for this event,
similar to the dev stats counters, but not tied to any specific device.
The first step is to detect and report the events at all.

Other notes:

Because the extent is dropped, the lost data cannot be detected by a csum
mismatch or read failure, i.e. everything will look OK if the file is read
or the filesystem scrubbed, but an application will notice a truncated
file or a file with data replaced by zeros.  For datasum files, we could
simply keep the extent as-is, allow future reads or csum verification
to fail, and report EIO errors that way.  That is a larger and riskier
change to btrfs behavior than simply adding some passive monitoring of
the status quo.  This approach also has problems with csum collisions,
it doesn't work for nodatasum+datacow files, and it takes much longer
for the errors to be detected and reported to a sysadmin.

nodatacow files don't have their extents dropped; instead, they will
simply have garbage in the blocks where the writes failed.  In most
use cases for nodatacow files (e.g. VM disk images or databases), the
user will be running all writes through fsync(), O_DIRECT, or similar
mechanisms that can observe the existing EIO return value notification
path, so there's less need for diagnostic coverage in the kernel log
for nodatacow files.

Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
3 months 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>
3 months 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>
3 months agobtrfs: preserve btrfs.compression when setting inode flags
Zygo Blaxell [Sun, 17 Aug 2025 02:50:20 +0000 (22:50 -0400)]
btrfs: preserve btrfs.compression when setting inode flags

Any call to FS_IOC_SETFLAGS (e.g. via chattr), even when no flag bits
change, and even for flags unrelated to compression, overwrites the
btrfs.compression property with the mount default compression type.

Example:

# mount ... -o compress=zstd ...
$ touch zero
$ setfattr -n btrfs.compression -v zlib zero
$ getfattr -n btrfs.compression zero | grep =
btrfs.compression="zlib"
$ lsattr zero
--------c------------- zero
$ chattr +A zero
$ lsattr zero
-------Ac------------- zero
$ getfattr -n btrfs.compression zero | grep =
btrfs.compression="zstd"

Here, `+A` modifies only the atime flag, but the compression property was
silently replaced.  The same happens even if the ioctl writes back the
same flags value that was already set.

The problem is that btrfs_fileattr_set unconditionally regenerates the
compression string from fs_info->compress_type (or falls back to "zlib")
and overwrites any existing property.

Fix this by first checking for an existing per-inode compression property
and using it if present.  Only fall back to fs_info->compress_type or zlib
when no property has been set.  This ensures that inode-flag updates no
longer clobber user-configured compression settings.

Fixes: 63541927c8d1 ("Btrfs: add support for inode properties")
Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
3 months agobtrfs: backref: detect tree mod log rewind cycles in add_all_parents() topics/backref-hang
Zygo Blaxell [Sat, 18 Jul 2026 03:13:26 +0000 (23:13 -0400)]
btrfs: backref: detect tree mod log rewind cycles in add_all_parents()

The tree mod log records internal node operations (pointer add/remove/
move and boundary key replaces) but never leaf item changes. A leaf that
was COWed in the current transaction before a tree mod log user took its
sequence number is modified in place afterwards, with no record kept of
its old contents.

As a result, the "old" view of a subvolume tree presented by
btrfs_search_old_slot() and btrfs_next_old_leaf() is only structurally
consistent: rewound internal nodes carry boundary keys as of time_seq,
while the leaves they point at may have newer contents. When items are
redistributed between sibling leaves (push_leaf_left()/push_leaf_right()),
only the resulting boundary key change in the parent is logged (via
fixup_low_keys()) and therefore rewound - the item moves themselves are
invisible to the log.

When the rewound boundary keys disagree with the actual leaf contents,
btrfs_next_old_leaf() - which advances by re-searching the last key of
the current leaf from the top of the tree - can be routed backwards to a
leaf it already visited. Two leaves in that state form a closed cycle:
walking off the end of leaf L lands on leaf M, and searching for M's
last (too-small) key routes back through L to M again. If this happens
while the walked range contains no items matching the backref being
resolved, the item count never reaches ref->count and the loop in
add_all_parents() spins forever. This is easily reproduced by running
LOGICAL_INO_V2 concurrently with heavy clone activity on the same
files: the ioctl's attached transaction handle then blocks the
transaction commit, which drains all writers, freezing the tree in the
inconsistent state and turning the transient loop into a permanent hang
with the fs wedged behind the blocked commit. If a matching item does
fall inside the cycled range instead, the loop exits after counting it
multiple times, silently returning duplicated parents.

In a consistent view of the tree, item keys must strictly increase as
the walk advances. Remember the previously visited key and bail out
with -EAGAIN if the walk ever observes a key that did not increase,
turning both the hang and the silent duplication into an error.

No attempt is made to retry inside the kernel: a retry could only reuse
the same tree mod log sequence number, and when the trees are no longer
being modified (in particular when a transaction commit is draining
writers and waiting for the walker to release its own transaction
handle - exactly the scenario that makes the cycle permanent) an
identical re-walk fails the same way every time. Returning the error
instead releases the caller's transaction handle, which unblocks the
pending commit, and a retry of the ioctl from user space then attaches
a fresh tree mod log sequence number with a consistent baseline. EAGAIN
tells user space precisely that: try again, nothing is corrupted.

The check cannot fire on commit root walks (commit roots are immutable
for the duration of the walk) or on BTRFS_SEQ_LAST walks (run from the
transaction commit critical section, after all other writers have
drained and with delayed refs fully run, so the trees are quiescent): a
consistent tree view can never present non-increasing item keys,
regardless of the size of the walk. So the qgroup accounting done at
transaction commit can never see this error and abort the transaction.
Only walks with a real time_seq can reach it: the LOGICAL_INO ioctls,
which return it to user space, and the sharedness checks done for
fiemap and swap file activation. If the check ever did fire on an
immutable or quiescent tree, it would mean the tree really has out of
order keys, in which case an error is preferable to the alternative of
btrfs_next_leaf() cycling on the damaged keys forever.

btrfs_is_data_extent_shared() cannot retry with a fresh tree mod log
sequence number from that deep in the call chain, and its callers'
interfaces do not expect transient errors, so the error is handled at
the call sites. Nothing is stored in the sharedness caches for a
failed check.

fiemap conservatively reports the extent as shared: the SHARED flag is
best effort by design, and while the extent's trees are being
concurrently modified, any sharedness answer may be stale by the time
user space sees it anyway.

Swap file activation also fails, with the error converted to the same
-EINVAL that a really shared extent produces: swap_activate is a
cross-filesystem interface and is not expected to start returning
transient error codes, so the EAGAIN is not passed through. A swap file
should be fully written and committed with stable extent sharing before
swapon() is called, so a transient failure here means the file's extent
sharing was still being changed in the same transaction, which is reason
enough to reject it. A distinct warning message replaces "swapfile must
not be copy-on-write" - which would assert a property of the file that
the walk never established - and tells the admin to just retry swapon(),
which attaches a fresh tree mod log sequence number with a consistent
baseline.

Link: https://lore.kernel.org/linux-btrfs/Y28XvZmK0bAS4Ht/@hungrycats.org/
Assisted-by: Claude:claude-fable-5
Signed-off-by: Zygo Blaxell <ce3g8jdj@umail.furryterror.org>
3 months agoMerge tag 'platform-drivers-x86-v7.2-4' of git://git.kernel.org/pub/scm/linux/kernel...
Linus Torvalds [Tue, 28 Jul 2026 20:45:01 +0000 (13:45 -0700)]
Merge tag 'platform-drivers-x86-v7.2-4' of git://git.kernel.org/pub/scm/linux/kernel/git/pdx86/platform-drivers-x86

Pull x86 platform driver fix from Ilpo Järvinen:

 - Fix ACPI _DSM function index and bitmask usage for Dell DW5826e

* tag 'platform-drivers-x86-v7.2-4' of git://git.kernel.org/pub/scm/linux/kernel/git/pdx86/platform-drivers-x86:
  platform/x86: dell-dw5826e: fix ACPI _DSM function index and bitmask usage

3 months agoMerge tag 'hardening-v7.2-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/kees...
Linus Torvalds [Tue, 28 Jul 2026 20:36:01 +0000 (13:36 -0700)]
Merge tag 'hardening-v7.2-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/kees/linux

Pull hardening fixes from Kees Cook:

 - lkdtm: fix missed rename of STACKLEAK_ERASING to KSTACK_ERASE
   (Haofeng Li)

 - selftests/seccomp: Fix pointer type mismatch build error
   (Kuan-Ying Lee)

 - tests/fortify: Disable -Wstringop-overread (Nathan Chancellor)

* tag 'hardening-v7.2-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/kees/linux:
  selftests/seccomp: Fix pointer type mismatch build error
  selftests/lkdtm: rename STACKLEAK_ERASING to KSTACK_ERASE
  fortify: Disable -Wstringop-overread in tests

3 months agoMerge tag 'for-7.2-rc5-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave...
Linus Torvalds [Tue, 28 Jul 2026 15:13:45 +0000 (08:13 -0700)]
Merge tag 'for-7.2-rc5-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave/linux

Pull btrfs fixes from David Sterba:
 "Zoned mode:
   - fix assertion and handle case of finished zone and truncated extent
   - fix zone metadata write pointer on actual zone reset
   - fix deadlock caused metadata writeback and transaction commit
   - fix return value reuse leading to confusion about chunk
     reservations

  raid56 scrub:
   - fix tracking of sector checksums when there are not checksums found
   - fix inverted logic when submitting parity read bio

  mount/remount fixes:
   - fix leaking 'remount in progress' state which can break other
     operations to work (qgroup rescan, autodefrag, reclaim)
   - adjust using global block reserve after read-only mount when using
     rescue= option
   - handle missing raid stripe tree when mounted with 'ignorebadroots'

  Misc:
   - fix -Wmaybe-uninitialized warning in GET_CSUMS ioctl"

* tag 'for-7.2-rc5-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave/linux:
  btrfs: raid56: fix scrub read assembly submitting no reads
  btrfs: zoned: skip fully truncated ordered extents at zone finish
  btrfs: initialize 'args' to avoid compiler warning in btrfs_ioctl_get_csums()
  btrfs: zoned: fix missing chunk metadata reservation
  btrfs: raid56: fix an incorrect csum skip during scrub
  btrfs: report missing raid stripe tree root during lookup
  btrfs: skip global block reserve accounting for rescue mounts
  btrfs: zoned: reset meta_write_pointer on zone reset
  btrfs: zoned: fix deadlock between metadata writeback and transaction commit
  btrfs: fix leaking BTRFS_FS_STATE_REMOUNTING flag

3 months agoMerge tag 'mm-hotfixes-stable-2026-07-27-14-18' of git://git.kernel.org/pub/scm/linux...
Linus Torvalds [Mon, 27 Jul 2026 21:36:26 +0000 (14:36 -0700)]
Merge tag 'mm-hotfixes-stable-2026-07-27-14-18' of git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Pull misc fixes from Andrew Morton:
 "13 hotfixes. All are cc:stable. 11 are for MM. All are singletons -
  please see the changelogs for details"

* tag 'mm-hotfixes-stable-2026-07-27-14-18' of git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm:
  fs/proc/task_mmu: fix PAGEMAP_SCAN written state for PMD holes
  mm/hugetlb: fix list corruption in allocate_file_region_entries()
  mm: mglru: fix stale batch updates after memcg reparenting
  selftest: fix headers in fclog.c
  ocfs2: fix boundary check in ocfs2_check_dir_entry() to use buffer offset
  mm/percpu-km: fix bitmap overflow and accounting in pcpu_create_chunk()
  mm/util: don't read __page_2 for order-1 folios in snapshot_page()
  mm/hugetlb: fix swap entry corruption when clearing uffd-wp at fork()
  mm: migrate_device: fix pte_pfn/pte_dirty called on non-present PTE
  fs/proc/task_mmu: fix PAGEMAP_SCAN written state for unpopulated ptes
  userfaultfd: wait on source PMD during UFFDIO_MOVE
  lib: test_hmm: use device devt for coherent device range selection
  mm/vmstat: fold stranded per-cpu node stats when a node comes online

3 months agoMerge tag 'for-next-keys-7.2-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Mon, 27 Jul 2026 21:14:11 +0000 (14:14 -0700)]
Merge tag 'for-next-keys-7.2-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd

Pull keys fixes from Jarkko Sakkinen:

 - An unprivileged keyring whose keys collide through the
   description-chunk path can drive assoc_array node splitting
   into an out-of-bounds slot write. Fix it.

 - Fix the DCP trusted keys backend

* tag 'for-next-keys-7.2-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/jarkko/linux-tpmdd:
  assoc_array: trim the final shortcut word using the current chunk end
  keys: make keyring key-chunk byte order agree with keyring_diff_objects()
  keys: fix out-of-bounds read in keyring_get_key_chunk()
  KEYS: trusted: dcp: fix key_len validation and calc_blob_len() return type

3 months agoMerge tag 'erofs-for-7.2-rc6-fixes' of git://git.kernel.org/pub/scm/linux/kernel...
Linus Torvalds [Mon, 27 Jul 2026 16:31:44 +0000 (09:31 -0700)]
Merge tag 'erofs-for-7.2-rc6-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs

Pull erofs fixes from Gao Xiang:
 "Fix a regression in page cache sharing which can cause a NULL pointer
  dereference, and limit LZMA stream memory usage on systems with many
  CPUs.

   - Keep a valid f_path for page cache sharing to fix a recent
     mincore() NULL pointer dereference

   - Limit LZMA stream pool size when too many processors are available

   - Sync up with Hongbo Li's latest email address"

* tag 'erofs-for-7.2-rc6-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/xiang/erofs:
  erofs: cap LZMA stream pool size
  erofs: ensure valid f_path for page cache sharing
  MAINTAINERS: update Hongbo Li's email address

3 months agoMerge tag 'pinctrl-v7.2-2' of git://git.kernel.org/pub/scm/linux/kernel/git/linusw...
Linus Torvalds [Mon, 27 Jul 2026 15:48:48 +0000 (08:48 -0700)]
Merge tag 'pinctrl-v7.2-2' of git://git.kernel.org/pub/scm/linux/kernel/git/linusw/linux-pinctrl

Pull pin control fixes from Linus Walleij:
 "The most interesting commit is the S4 fix for AMD, which probably is
  helpful to a whole bunch of important machines.

   - Wakeup nits on the Qualcomm SC8280XP

   - Double-free issues on the device tree parsing error path

   - Fixup of the S4 sleep state handling on AMD pin control

   - Missing Kconfig select REGMAP_MMIO for the Microchip driver leading
     to compile stalls

   - Missing Kconfig select GENERIC_PINCONF for the Bitmain BM1880
     leading to compile stalls"

* tag 'pinctrl-v7.2-2' of git://git.kernel.org/pub/scm/linux/kernel/git/linusw/linux-pinctrl:
  pinctrl: bm1880: add missing select GENERIC_PINCONF
  pinctrl-amd: Don't clear S4 wake bits at probe
  pinctrl: microchip-sgpio: add missing select REGMAP_MMIO
  pinctrl: devicetree: don't free uninitialized dev_name on error path
  pinctrl: qcom: sc8280xp: Add missing wakeup entries for GPIO143/151
  pinctrl: qcom: Unconditionally mark gpio as wakeup enable

3 months agoerofs: cap LZMA stream pool size
Michael Bommarito [Tue, 14 Jul 2026 11:47:29 +0000 (07:47 -0400)]
erofs: cap LZMA stream pool size

fs/erofs/decompressor_lzma.c sizes the module-global MicroLZMA stream
pool from num_possible_cpus() when the lzma_streams module parameter is
unset, then z_erofs_load_lzma_config() preallocates one image-supplied
dictionary per stream, accepting dictionaries up to 8 MiB.  On high-CPU
systems, a small EROFS image can pin hundreds of MiB of vmalloc-backed
decoder state until the erofs module is unloaded.

Impact: An EROFS image mounted by the system can pin up to 8 MiB of
vmalloc memory per LZMA stream, either as intended or unexpectedly.

Bound the default stream count by a new
CONFIG_EROFS_FS_ZIP_LZMA_DEFAULT_MAX_STREAMS option, default 16, so the
worst-case default preallocation is 128 MiB if the number of CPUs is no
less than 16 while preserving the existing per-image dictionary limit.
An explicit lzma_streams module parameter is still honoured as-is, so
administrators who deliberately size the pool are not affected.

Fixes: 622ceaddb764 ("erofs: lzma compression support")
Cc: stable@vger.kernel.org
Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Michael Bommarito <michael.bommarito@gmail.com>
Reviewed-by: Gao Xiang <hsiangkao@linux.alibaba.com>
Signed-off-by: Gao Xiang <hsiangkao@linux.alibaba.com>
3 months agoerofs: ensure valid f_path for page cache sharing
Gao Xiang [Mon, 27 Jul 2026 04:27:39 +0000 (12:27 +0800)]
erofs: ensure valid f_path for page cache sharing

Previously, backing files for page cache sharing were set up with
f_path left as NULL (only f_inode was valid).  It worked, but a recent
mincore fix relies on f_path.mnt and crashes (found by "erofs/028" on
7.2-rc4):

 BUG: kernel NULL pointer dereference, address: 0000000000000018
 #PF: supervisor read access in kernel mode
 #PF: error_code(0x0000) - not-present page
 PGD 0 P4D 0
 Oops: Oops: 0000 [#1] SMP PTI
 CPU: 3 UID: 0 PID: 675528 Comm: fincore Not tainted 7.2.0-rc4-00002-g[]-dirty #1 PREEMPT(lazy)
 Hardware name: Red Hat KVM, BIOS 1.16.0-4.al8 04/01/2014
 RIP: 0010:__do_sys_mincore+0xc0/0x2c0
 ...

Specify valid paths using valid disconnected dentries together with
erofs_ishare_mnt instead of leaving f_path empty, so they are more
like real backing files in a pseudo filesystem and standard
backing_file_open() can be used directly.

Fixes: e187bc02f8fa ("mm: do file ownership checks with the proper mount idmap")
Acked-by: Hongbo Li <hongbohbli@tencent.com>
Signed-off-by: Gao Xiang <xiang@kernel.org>
3 months agoLinux 7.2-rc5 v7.2-rc5
Linus Torvalds [Sun, 26 Jul 2026 21:45:48 +0000 (14:45 -0700)]
Linux 7.2-rc5

3 months agoMerge tag 'vfs-7.2-rc5.fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs
Linus Torvalds [Sun, 26 Jul 2026 19:22:57 +0000 (12:22 -0700)]
Merge tag 'vfs-7.2-rc5.fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs

Pull vfs fixes from Christian Brauner:

 - vfs: Preserve the ACL_DONT_CACHE state in forget_cached_acl().

   ACL_DONT_CACHE is meant to be a permanent opt-out from ACL caching
   which FUSE relies on for servers that don't negotiate FUSE_POSIX_ACL.
   The helper replaced it with ACL_NOT_CACHED, silently re-enabling the
   cache, and as fuse doesn't invalidate the cache for such servers a
   properly timed get_acl() returned stale ACLs. Comes with a fuse
   selftest reproducing this.

 - pidfs:

     - Preserve PIDFD_THREAD when a thread pidfd is reopened via
       open_by_handle_at(). PIDFD_THREAD shares the O_EXCL bit which
       do_dentry_open() strips after the flags have been validated, so
       the reopened pidfd silently became a process pidfd. Comes with a
       selftest.

     - Add a pidfs_dentry_open() helper so the regular pidfd allocation
       path and the file handle path share the code that forces O_RDWR
       and reapplies the pidfd flags that do_dentry_open() strips.

     - Handle FS_IOC32_GETVERSION in the compat ioctl path.

     - Make pidfs_ino_lock static.

 - iomap:

     - Fix the block range calculation in ifs_clear_range_dirty() so a
       partial clear doesn't drop the dirty state of blocks the range
       only partially covers.

     - Support invalidating partial folios so a partial truncate or hole
       punch with blocksize < foliosize doesn't leave stale dirty bits
       behind.

     - Only set did_zero when iomap_zero_iter() actually zeroed
       something.

     - Guard ifs_set_range_dirty() and ifs_set_range_uptodate() against
       zero-length ranges where the unsigned last-block calculation
       underflows and bitmap_set() writes far beyond the ifs->state
       allocation.

     - Don't merge ioends with different io_private values as the merge
       could leak or corrupt the private data of the individual ioends.

 - exec:

     - Raise bprm->have_execfd only once the binfmt_misc interpreter has
       actually been opened. The flag was set as soon as a matching 'O'
       or 'C' entry was found. If the interpreter open failed with
       ENOEXEC the exec fell through to the next binary format with
       have_execfd raised but no executable staged and begin_new_exec()
       NULL derefed past the point of no return.

     - Fix an unsigned loop counter wrap in transfer_args_to_stack() on
       nommu. An overlong argument or environment string pushes bprm->p
       below PAGE_SIZE, the stop index becomes zero, and the loop never
       terminates, wrapping its counter and copying garbage from in
       front of the page array into the new process stack.

     - Make binfmt_elf_fdpic only honour the first PT_INTERP like
       binfmt_elf does. Each additional PT_INTERP overwrote the previous
       interpreter, leaking the name allocation and the interpreter file
       reference together with the write denial open_exec() took,
       leaving the file unwritable for as long as the system runs.

 - overlayfs:

     - Compare the full escaped xattr prefix including the trailing dot.
       An xattr like "trusted.overlay.overlayfoo" was misclassified as
       an escaped overlay xattr.

     - Check read access to the copy_file_range() source with the
       source's mounter credentials.

 - super: Thawing a filesystem whose block device was frozen with
   bdev_freeze() deadlocked. Dropping the last block layer freeze
   reference from under s_umount ends up in fs_bdev_thaw() which
   reacquires s_umount on the same task. Pin the superblock with an
   active reference instead and call bdev_thaw() without holding
   s_umount.

 - procfs: Return EACCES instead of success when the ptrace access check
   for namespace links fails.

 - afs: Use afs_dir_get_block() rather than afs_dir_find_block() for
   block 0 in afs_edit_dir_remove(), matching afs_edit_dir_add().

 - Push the memcg gating of ->nr_cached_objects() down into the btrfs
   and shmem callbacks instead of skipping every callback during
   non-root memcg reclaim. The blanket check short-circuited XFS whose
   inode reclaim hook is intentionally driven from per-memcg contexts to
   free memcg-charged slab.

 - eventpoll: Pin files while checking reverse paths.

   Since struct file became SLAB_TYPESAFE_BY_RCU a concurrent close
   could free and recycle the file under the check which then took and
   dropped the f_lock of whatever live file now occupies that slot.

* tag 'vfs-7.2-rc5.fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs: (24 commits)
  super: fix emergency thaw deadlock on frozen block devices
  pidfs: make pidfs_ino_lock static
  eventpoll: pin files while checking reverse paths
  fs: push nr_cached_objects memcg gating into individual filesystems
  afs: Fix afs_edit_dir_remove() to get, not find, block 0
  iomap: prevent ioend merge when io_private differs
  iomap: add comments for ifs_clear/set_range_dirty()
  iomap: fix out-of-bounds bitmap_set() with zero-length range
  iomap: fix incorrect did_zero setting in iomap_zero_iter()
  iomap: support invalidating partial folios
  iomap: correct the range of a partial dirty clear
  fs/super: fix emergency thaw double-unlock of s_umount
  pidfs: handle FS_IOC32_GETVERSION in compat ioctl
  ovl: check access to copy_file_range source with src mounter creds
  proc: Fix broken error paths for namespace links
  pidfs: add pidfs_dentry_open() helper
  selftests/pidfd: check PIDFD_THREAD survives open_by_handle_at()
  pidfs: preserve thread pidfds reopened by file handle
  ovl: fix trusted xattr escape prefix matching
  selftests/fuse: add ACL_DONT_CACHE regression test
  ...

3 months agoMerge tag 'spi-fix-v7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/spi
Linus Torvalds [Sun, 26 Jul 2026 19:13:42 +0000 (12:13 -0700)]
Merge tag 'spi-fix-v7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/spi

Pull spi fixes from Mark Brown:
 "Just a couple of small bits for the SpacemiT driver - one small fix,
  and a new compatible in the DT binding"

* tag 'spi-fix-v7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/spi:
  spi: dt-bindings: spacemit: add K3 SPI compatible
  spi: spacemit: Correct TX FIFO slot calculation

3 months agoMerge tag 'regulator-fix-v7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Sun, 26 Jul 2026 18:52:30 +0000 (11:52 -0700)]
Merge tag 'regulator-fix-v7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/regulator

Pull regulator fixes from Mark Brown:
 "One driver specific fix where one of the MediaTek drivers duplicated
  some core code buggily, and a core fix for an ordering issue on
  startup where we could end up configuring a voltage outside of
  constraints due to the order in which we applied constraints"

* tag 'regulator-fix-v7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/regulator:
  regulator: core: clamp voltage constraints before applying apply_uV
  regulator: mt6358: use regmap helper to read fixed LDO calibration

3 months agoMerge tag 'char-misc-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh...
Linus Torvalds [Sun, 26 Jul 2026 17:47:58 +0000 (10:47 -0700)]
Merge tag 'char-misc-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/char-misc

Pull char/misc driver fixes from Greg KH:
 "Here are a number of small char/misc/etc driver fixes for 7.2-rc5 that
  resolve a bunch of different reported issues. Included in here are:

   - rust_binder error message reporting fix

   - stratix10-svc firmware driver fixes

   - mei driver fix

   - intel_th hardware tracing driver fix

   - comedi driver fix

   - uio_hv_generic driver fix

   - ntsync selftest fix

   - nsm misc driver fix

   - some MAINTAINER file updates

  All of these have been in linux-next for over a week with no reported
  issues"

* tag 'char-misc-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/char-misc:
  MAINTAINERS: Update wine-devel list address
  rust_binder: only print failure if error has source
  intel_th: fix MSC output device reference leak
  misc: nsm: pin the module while the device is open
  mei: bus: access mei_device under device_lock on cleanup
  misc: nsm: only unlock nsm_dev on post-lock error paths
  selftests: ntsync: correct CONFIG_NTSYNC name
  comedi: comedi_parport: deal with premature interrupt
  uio_hv_generic: Bind to FCopy device by default
  MAINTAINERS: Add Greg Kroah-Hartman to GPIB
  firmware: stratix10-svc: fix teardown order in remove to prevent race
  firmware: stratix10-svc: handle NO_RESPONSE in async poll
  firmware: stratix10-svc: fix FCS SMC call kernel-doc
  firmware: stratix10-svc: fix memory leaks and list corruption bugs

3 months agoMerge tag 'staging-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh...
Linus Torvalds [Sun, 26 Jul 2026 17:30:37 +0000 (10:30 -0700)]
Merge tag 'staging-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/staging

Pull staging driver fixes from Greg KH:
 "Here are two small staging driver fixes for 7.2-rc5. They both resolve
  some reported bugs in the rtl8723bs staging driver and have been in
  linux-next for over a week with no reported issues"

* tag 'staging-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/staging:
  staging: rtl8723bs: fix OOB reads in rtw_get_wps_ie()
  staging: rtl8723bs: fix inverted HT40 secondary channel offset

3 months agoMerge tag 'tty-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/tty
Linus Torvalds [Sun, 26 Jul 2026 17:25:14 +0000 (10:25 -0700)]
Merge tag 'tty-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/tty

Pull serial driver fixes from Greg KH:
 "Here are two small serial driver fixes for 7.2-rc5.  They are:

   - sc16is7xx get_direction() callback fix, which resolves a
     user-triggerable warning in the driver

   - NULL pointer dereference on some platforms using the 8250_mid
     serial driver

  Both have been in linux-next for over a week with no reported issues"

* tag 'tty-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/tty:
  serial: sc16is7xx: implement gpio get_direction() callback
  serial: 8250_mid: Fix NULL function pointer dereference on DNV/ICX-D/SNR platforms

3 months agoMerge tag 'usb-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/usb
Linus Torvalds [Sun, 26 Jul 2026 16:25:57 +0000 (09:25 -0700)]
Merge tag 'usb-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/usb

Pull USB fixes from Greg KH:
 "Here are some small USB fixes and new device quirks and ids:

   - usb storage quirk added

   - new usb serial device ids added

   - usb-serial device name leak and other bug fixes

   - small xhci driver fixes

   - normal batch of typec driver fixes for reported issues

   - usb-atm much-reported-by-syzbot fix for firmware download races

   - sysfs BOS device removal race fix

   - lots of usb gadget driver fixes for reported issues

   - other small USB driver fixes for other reported problems

  All of these have been in linux-next this past week, many of them much
  longer"

* tag 'usb-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/usb: (30 commits)
  usb: typec: ucsi: Correct teardown ordering in ucsi_init() error path
  USB: serial: io_edgeport: cap received transmit credits
  USB: serial: option: add TDTECH MT5710-CN
  USB: serial: io_ti: reject oversized boot-mode firmware
  USB: serial: mxuport: validate firmware header size
  usb: atm: ueagle-atm: reject descriptors that confuse probe and disconnect
  usb: typec: ucsi: yoga_c630: Remove redundant duplicate altmode handling
  usb: typec: ucsi: Add duplicate detection to nvidia registration path
  usb: typec: ucsi: Detect and skip duplicate altmodes from buggy firmware
  usb: gadget: dummy_hcd: prevent fifo_req reuse during giveback
  usb: chipidea: fix usage_count leak when autosuspend_delay is negative
  usb: core: sysfs: add lock to bos_descriptors_read()
  usb: musb: omap2430: Do not put borrowed of_node in probe
  usb: core: port: Deattach Type-C connector on component unbind
  USB: storage: add NO_ATA_1X quirk for Longmai USB Key
  USB: serial: ftdi_sio: add support for E+H FXA291
  USB: serial: keyspan_pda: fix data loss on receive throttling
  usb: gadget: printer: fix infinite loop in printer_read()
  usb: gadget: f_midi: cancel pending IN work before freeing the midi object
  usb: gadget: udc: bdc: free IRQ and drain func_wake_notify before teardown
  ...

3 months agoMerge tag 'trace-v7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/trace...
Linus Torvalds [Sun, 26 Jul 2026 16:15:59 +0000 (09:15 -0700)]
Merge tag 'trace-v7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/trace/linux-trace

Pull tracing fixes from Steven Rostedt:

 - Move rb_desc->nr_page_va before updating dynamic array

   The rb_descr->page_va is a dynamic array counted by nr_page_va. But
   the updating of the page_va[] is done before the nr_page_va is
   incremented causing a build with CONFIG_UBSAN_BOUNDS to flag it as an
   overflow.

   Move the increment of the counted by value before the array element
   is updated.

 - Propagate errors from remote event bulk updates

   The return value of trace_remote_enable_event() was not being checked
   by remote_events_dir_enable_write() where it would silently fail.
   Have it check the return value and propagate that back up to user
   space.

 - Fix resource leak on mmiotrace trace_pipe close

   The mmiotrace tracer was created in 2008 before the trace_pipe had a
   close callback to allow tracers to do clean up from trace_pipe open.
   The trace_pipe close cleanup callback was added in 2009 but the
   mmiotrace tracer was not updated. It had a hack to do the cleanup in
   the read call, where it may leak if user space did not read the
   entire buffer.

   Add a callback to mmiotrace trace_pipe close do to the cleanup
   properly.

 - Fix a possible NULL pointer dereference in the mmiotrace tracer

   If the mmio_pipe_open() fails to find a PCI device, it will set the
   hiter->dev pointer to NULL. The read function will blindly
   dereference that pointer. Fix the read call to check to see if that
   pointer is populated before dereferencing it.

 - Fix union collision of module and refcnt for dynamic events

   In 'struct trace_event_call', the 'module' pointer and the 'refcnt'
   atomic variable share the same memory space in a union. The filter on
   module logic only checked if the 'module' was set to determine if the
   event belonged to the module. As dynamic events are always builtin,
   it doesn't need the 'module' field of the structure and used a
   refcount. But the module filtering logic would then mistaken these
   dynamic events as a module and call module_name(event->module) on it.

   Add a check to see if the event is a dynamic event and if so, do not
   check it for being part of the given module.

 - Reset the top level buffer in selftests before running instances

   The ftracetest selftest initializes each instance before executing
   the tests. But it does not reset the top level buffer. Dynamic events
   are only added and removed by the top level so any left over dynamic
   events will not be removed by the reset in the instances.

   Left over dynamic events can cause the tests to incorrectly fail.
   Reset the top level buffer before running the instances.

 - Make the context_switch counter 64 bit

   The code to read user space for a system call trace event or for a
   trace_marker will disable migration, enable preemption, read user
   space into a per CPU buffer, disable preemption and enable migration
   again. It checks if the per CPU context switch counter to see if it
   changed, and if it did not, it would know that the per CPU buffer was
   not touched by another task.

   But the save counter was 32 bit and it would compare it to the 64 bit
   context_switch variable. A long running system could have the
   context_switch variable greater that 1<<32 in which case the compare
   will always fail. The compare will promote the 32 bit int saved value
   to 64 bit and compare it to the full 64 bit counter. Since the top 32
   bits of the saved value was zero, it would never match.

 - Fix a use-after-free of the event_enable trigger

   The event_enable trigger allows for enabling one event when another
   event is triggered. When the trigger is removed, it must go through a
   synchronization phase to make sure it is not triggered again. The
   trigger itself is delayed by the "bulk delay" logic that was recently
   added. But the code that frees the event_enable data used to rely on
   the trigger code to do the synchronization. Now that the code uses
   the call RCU functions (and a workqueue), that delay no longer is
   there.

   Add a callback private_data_free() function that allows triggers to
   clean up data after the synchronization phase has completed.

 - Move the module_ref counter into the delay callback

   Since an event of the event_enable trigger can enable an event for a
   module, it ups the module ref count for that event's module. This
   prevents the event from trying to enable an event that no longer
   exists and cause a use-after-free bug.

   The ref counter was set back down when the trigger was removed but
   not after thy synchronization phase. This could lead to the module
   data being accessed after module was unloaded.

   Move the module ref decrement into the private_data_free() callback
   of the event_enable trigger.

 - Add mutex to protect parser in ftrace filtering

   The set_ftrace_filter file uses a parsing descriptor that is
   allocated at open and modified by writes. If multiple threads were to
   write to the descriptor at the same time, it can corrupt the parser.

   Add a mutex around the modifications of the parser descriptor.

 - Fix possible corruption in perf syscall tracing

   The perf system call trace events can now read user space. To do so,
   the reads of user space enable preemption and disables it again.
   During this time that preemption is enabled, the task can migrate.
   The perf event list head is assigned via a per CPU pointer. It is
   done before the user space part is called. If the user space reading
   migrates the task to another CPU, then the head pointer is no longer
   valid.

   Re-assign the head pointer after the reading of user space to keep it
   using the correct data.

* tag 'trace-v7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/trace/linux-trace:
  tracing: perf: Fix stale head for perf syscall tracing
  ftrace: Add global mutex to serialize trace_parser access
  tracing: Delay module ref count for "enable_event" trigger
  tracing: Fix use-after-free freeing trigger private data
  tracing: Fix context switch counter truncation
  selftests/ftrace: Reset triggers at top level before instance loop
  tracing: Fix union collision of module and refcnt for dynamic events
  tracing: Fix mmiotrace possible NULL dereferencing of hiter->dev
  tracing: Fix resource leak on mmiotrace trace_pipe close
  tracing: Propagate errors from remote event bulk updates
  tracing/remotes: Fix page_va[] access before counter update in trace_remote_alloc_buffer()

3 months agoMerge tag 'm68knommu-fixes-on-top-off-7.2-rc4' of git://git.kernel.org/pub/scm/linux...
Linus Torvalds [Sun, 26 Jul 2026 15:59:55 +0000 (08:59 -0700)]
Merge tag 'm68knommu-fixes-on-top-off-7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/gerg/m68knommu

Pull m68knommu fix from Greg Ungerer:

 - fix broken local SoC IO accesses for ColdFire

* tag 'm68knommu-fixes-on-top-off-7.2-rc4' of git://git.kernel.org/pub/scm/linux/kernel/git/gerg/m68knommu:
  m68k: coldfire: fix breakage of missed IO access update

3 months agoMerge tag 'x86-urgent-2026-07-26' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Sun, 26 Jul 2026 15:52:38 +0000 (08:52 -0700)]
Merge tag 'x86-urgent-2026-07-26' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip

Pull x86 fix from Ingo Molnar:

 - Disable jump/lookup tables in the x86 boot decompressor code
   a bit more widely, because newer versions of LLVM started
   optimizing it a bit better and introduced run-time relocations
   in PIE code (Nathan Chancellor)

* tag 'x86-urgent-2026-07-26' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip:
  x86/boot/compressed: Disable jump tables

3 months agoMerge tag 'smp-urgent-2026-07-26' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Sun, 26 Jul 2026 15:47:01 +0000 (08:47 -0700)]
Merge tag 'smp-urgent-2026-07-26' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip

Pull SMP debug fixes from Ingo Molnar:

 - SMP-call fixes when CSD lock debugging is enabled (Chuyi Zhou)

* tag 'smp-urgent-2026-07-26' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip:
  smp: Make CSD lock acquisition atomic for debug mode
  smp: Avoid invalid per-CPU CSD lookup with CSD lock debug

3 months agosuper: fix emergency thaw deadlock on frozen block devices
Christian Brauner [Thu, 23 Jul 2026 09:37:05 +0000 (11:37 +0200)]
super: fix emergency thaw deadlock on frozen block devices

do_thaw_all_callback() calls bdev_thaw() while holding sb->s_umount
exclusively. If the block device was frozen via bdev_freeze() dropping
the last block layer freeze reference calls fs_bdev_thaw() which
reacquires s_umount:

  do_thaw_all_callback(sb)
    super_lock_excl(sb)                     # holds sb->s_umount
    bdev_thaw(sb->s_bdev)
      mutex_lock(&bdev->bd_fsfreeze_mutex)
      # bd_fsfreeze_count drops 1 -> 0
      bd_holder_ops->thaw == fs_bdev_thaw
        get_bdev_super(bdev)
          bdev_super_lock(bdev, true)
            super_lock(sb, true)
              down_write(&sb->s_umount)     # same task: deadlock

The emergency thaw worker deadlocks against itself holding both
s_umount and bd_fsfreeze_mutex. That fscks any subsequent unmount,
freeze, or thaw of that filesystem and block device.

  [   81.878470] sysrq: Show Blocked State
  [   81.880140] task:kworker/0:1     state:D stack:0     pid:11    tgid:11    ppid:2      task_flags:0x4208060 flags:0x00080000
  [   81.884876] Workqueue: events do_thaw_all
  [   81.886656] Call Trace:
  [   81.887759]  <TASK>
  [   81.888763]  __schedule+0x579/0x1420
  [   81.890372]  schedule+0x3a/0x100
  [   81.891794]  schedule_preempt_disabled+0x15/0x30
  [   81.893848]  rwsem_down_write_slowpath+0x1ea/0x900
  [   81.895191]  ? __pfx_do_thaw_all_callback+0x10/0x10
  [   81.896528]  down_write+0xbd/0xc0
  [   81.897505]  super_lock+0x91/0x180
  [   81.898457]  ? __mutex_lock+0xa99/0x1140
  [   81.900748]  ? __mutex_unlock_slowpath+0x1f/0x400
  [   81.902069]  bdev_super_lock+0x5b/0x150
  [   81.903132]  get_bdev_super+0x10/0x60
  [   81.904042]  fs_bdev_thaw+0x23/0xf0
  [   81.904755]  bdev_thaw+0x82/0x100
  [   81.905484]  do_thaw_all_callback+0x2c/0x50
  [   81.906298]  __iterate_supers+0x5d/0x130
  [   81.907067]  do_thaw_all+0x20/0x40
  [   81.907739]  process_one_work+0x206/0x5e0
  [   81.908545]  worker_thread+0x1e2/0x3c0
  [   81.909339]  ? __pfx_worker_thread+0x10/0x10
  [   81.910171]  kthread+0xf4/0x130
  [   81.910799]  ? __pfx_kthread+0x10/0x10
  [   81.911528]  ret_from_fork+0x2e2/0x3b0
  [   81.912259]  ? __pfx_kthread+0x10/0x10
  [   81.913010]  ret_from_fork_asm+0x1a/0x30
  [   81.913806]  </TASK>

bdev_super_lock() even documents the violated requirement with
lockdep_assert_not_held(&sb->s_umount).

Acquiring bd_fsfreeze_mutex under s_umount also inverts the
bd_fsfreeze_mutex vs. s_umount ordering established by
bdev_{freeze,thaw}() and can thus ABBA against a concurrent block-layer
freeze even when the recursive path isn't hit.

Fix this by not holding s_umount around the bdev_thaw() loop at all. Pin
the superblock with an active reference instead as
filesystems_freeze_callback() does. The active reference keeps the
superblock from being shut down and so ->s_bdev stays valid without
holding s_umount. The block-layer-held freeze is dropped by
fs_bdev_thaw() with FREEZE_MAY_NEST | FREEZE_HOLDER_USERSPACE exactly as
a regular unfreeze would and thaw_super_locked() handles
filesystem-level freezes as before.

The emergency thaw path has deadlocked like this in one form or
another for a long long time but the current exclusively-held
shape dates back to commit [1] where thaw_bdev() already ended in
thaw_super() with s_umount held by do_thaw_all_callback().

Fixes: 08fdc8a0138a ("buffer.c: call thaw_super during emergency thaw") [1]
Cc: stable@vger.kernel.org
Link: https://patch.msgid.link/20260723-work-super-emergency_thaw-v1-1-7c315c600245@kernel.org
Signed-off-by: Christian Brauner (Amutable) <brauner@kernel.org>
3 months agoMerge tag 'rust-fixes-7.2-2' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda...
Linus Torvalds [Sat, 25 Jul 2026 17:15:23 +0000 (10:15 -0700)]
Merge tag 'rust-fixes-7.2-2' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux

Pull rust fixes from Miguel Ojeda:
 "Toolchain and infrastructure:

   - 'zerocopy' crates: update to v0.8.54 to fix a modpost error under
     'CONFIG_CC_OPTIMIZE_FOR_SIZE=y'.

     There are actually two updates in the PR: the one to v0.8.52 is
     fairly large and was originally not intended for a fixes PR, but the
     actual fix landed in the v0.8.54 one. Thus I included both here.

     The v0.8.52 update includes two things upstream added for us:
     '--cfg no_fp_fmt_parse' to avoid a local workaround, and the new
     'most_traits' feature.

     The good news is that, after these updates, the delta with upstream
     is now trivial: only an identifier prefix change and the SPDX
     parentheses.

   - Fix an objtool warning by adding one more 'noreturn' function for
     Rust 1.99.0 (expected 2026-10-01).

   - Clean up new 'semicolon_in_expressions_from_macros' lint errors for
     Rust 1.99.0 (expected 2026-10-01). The lint can be allowed, but it
     will be a hard error at some point in the future anyway, so clean it
     up now.

   - Locally allow new 'suspicious_runtime_symbol_definitions' lint for
     Rust 1.98.0 (expected 2026-08-20).

   - Globally allow 'clippy::unwrap_or_default' lint since it relies on
     optimizations -- under 'CONFIG_CC_OPTIMIZE_FOR_SIZE=y' it does not
     work well.

  'kernel' crate:

   - 'time' module: fix 'Delta::as_micros_ceil()' to round negative values
     correctly"

* tag 'rust-fixes-7.2-2' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux:
  rust: time: fix as_micros_ceil() to round correctly for negative Delta
  rust: device: avoid trailing ; in printing macros
  objtool/rust: add one more `noreturn` Rust function for Rust 1.99.0
  rust: zerocopy: update to v0.8.54
  rust: zerocopy: update to v0.8.52
  rust: allow `clippy::unwrap_or_default` globally
  rust: allow `suspicious_runtime_symbol_definitions` lint for Rust >= 1.98

3 months agoMerge tag 'perf-tools-fixes-for-v7.2-1-2026-07-25' of git://git.kernel.org/pub/scm...
Linus Torvalds [Sat, 25 Jul 2026 16:05:02 +0000 (09:05 -0700)]
Merge tag 'perf-tools-fixes-for-v7.2-1-2026-07-25' of git://git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools

Pull perf tools fixes from Arnaldo Carvalho de Melo:

 - Update header copies of kernel headers, including const.h, fs.h,
   perf_event.h, gfp_types.h, kvm.h, cpufeatures.h, rtnetlink.hp,
   msr-index.h, drm.h and socket.h

 - Add some build files related to BPF skels to .gitignore

* tag 'perf-tools-fixes-for-v7.2-1-2026-07-25' of git://git.kernel.org/pub/scm/linux/kernel/git/perf/perf-tools:
  tools headers: Sync KVM headers with the kernel sources
  tools headers: Sync UAPI linux/fs.h with the kernel sources
  perf beauty: Update copy of linux/socket.h with the kernel sources
  tools headers: Sync UAPI drm/drm.h with kernel sources
  tools arch x86: Sync the msr-index.h copy with the kernel sources
  tools headers x86 cpufeatures: Sync with the kernel sources
  tools headers: Sync linux/gfp_types.h with the kernel sources
  tools headers UAPI: Sync linux/rtnetlink.h with the kernel sources
  tools headers UAPI: Sync linux/const.h with the kernel sources
  perf bench bpf: Add missing .gitignore file

3 months agoMerge tag 'firewire-fixes-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Sat, 25 Jul 2026 15:14:13 +0000 (08:14 -0700)]
Merge tag 'firewire-fixes-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/ieee1394/linux1394

Pull firewire fix from Takashi Sakamoto:
 "Fix a bug in unit driver for RFC 2734 IPv4 over IEEE 1394.

  The driver failed to reassemble a complete datagram when it was stored
  across multiple buffer ranges in the list. Ruoyu Wang reported and
  fixed it"

* tag 'firewire-fixes-7.2-rc5' of git://git.kernel.org/pub/scm/linux/kernel/git/ieee1394/linux1394:
  firewire: net: Fix fragmented datagram reassembly

3 months agoMerge tag 'loongarch-fixes-7.2-1' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Sat, 25 Jul 2026 15:10:13 +0000 (08:10 -0700)]
Merge tag 'loongarch-fixes-7.2-1' of git://git.kernel.org/pub/scm/linux/kernel/git/chenhuacai/linux-loongson

Pull LoongArch fixes from Huacai Chen:

 - fix build warnings and errors

 - move jump_label_init() before parse_early_param()

 - retrieve CPU package ID from PPTT when available

 - fix some bugs kgdb, BPF JIT and laptop platform driver bugs

* tag 'loongarch-fixes-7.2-1' of git://git.kernel.org/pub/scm/linux/kernel/git/chenhuacai/linux-loongson:
  platform/loongarch: laptop: Explicitly reset bl_powered state when suspend
  platform/loongarch: laptop: Stop setting acpi_device_class()
  LoongArch: BPF: Fix memory leak in bpf_jit_free()
  LoongArch: BPF: Zero-extend signed ALU32 div/mod results
  LoongArch: Fix oops during single-step debugging
  LoongArch: Fix address space mismatch in kexec command line lookup
  LoongArch: Retrieve CPU package ID from PPTT when available
  LoongArch: Move jump_label_init() before parse_early_param()
  LoongArch: Fix build errors due to wrong instructions for 32BIT
  LoongArch: Increase TASK_STRUCT_OFFSET up to 2040 for 32BIT

3 months agopinctrl: bm1880: add missing select GENERIC_PINCONF
Benjamin Boortz [Mon, 20 Jul 2026 17:51:04 +0000 (19:51 +0200)]
pinctrl: bm1880: add missing select GENERIC_PINCONF

drivers/pinctrl/pinctrl-bm1880.c initialises its pinconf_ops with
.is_generic = true, but that field is only present when
CONFIG_GENERIC_PINCONF is enabled (guarded by #ifdef in pinconf.h).
The Kconfig entry for PINCTRL_BM1880 never selects GENERIC_PINCONF,
so any config that enables CONFIG_PINCTRL_BM1880=y without
CONFIG_GENERIC_PINCONF=y fails to compile:

  drivers/pinctrl/pinctrl-bm1880.c:1288:10: error: 'const struct pinconf_ops' has no member named 'is_generic'

Found by randconfig testing on arm64; tinyconfig reproducer below.
Add the missing select to fix the build.

Fixes: 49bd61ebce5f ("pinctrl: Add pinconf support for BM1880 SoC")
Cc: stable@vger.kernel.org
Signed-off-by: Benjamin Boortz <bennib@mailbox.org>
Signed-off-by: Linus Walleij <linusw@kernel.org>
3 months agopinctrl-amd: Don't clear S4 wake bits at probe
Mario Limonciello [Mon, 20 Jul 2026 16:28:44 +0000 (11:28 -0500)]
pinctrl-amd: Don't clear S4 wake bits at probe

commit 6bc3462a0f5e ("pinctrl: amd: Mask wake bits on probe again")
introduced a regression where Wake-on-LAN no longer works after suspend
or shutdown on some AMD platforms.

Firmware-programmed S4 wake bits for devices like PCIe NICs using PCI
PME are cleared at probe, but nothing restores them. Unlike S0i3/S3 wake
sources that use enable_irq_wake() -> amd_gpio_irq_set_wake(), PCIe PME
does not use GPIO IRQ infrastructure and relies on firmware configuration.

The original intent of commit 6bc3462a0f5e ("pinctrl: amd: Mask wake
bits on probe again") was to clear spurious wake bits left by firmware
to prevent unwanted wakeups. However, S4 wake bits are used for
hardware-level wake sources like WoL that bypass the kernel's IRQ wake
API.

Fix by preserving S4 wake bits at probe and only clearing S0i3/S3 bits:
- Firmware-configured S4 wake sources (WoL) continue working
- Kernel maintains control of S3/S0i3 wake policy via set_wake()
- S3-only wake sources work correctly per commit f31f33dbb3ba ("pinctrl:
  amd: Take suspend type into consideration which pins are non-wake")

The trade-off is that firmware-programmed spurious S4 wake bits remain
set, but this is less problematic than breaking WoL.

Fixes: 6bc3462a0f5e ("pinctrl: amd: Mask wake bits on probe again")
Signed-off-by: Mario Limonciello <mario.limonciello@amd.com>
Signed-off-by: Linus Walleij <linusw@kernel.org>
3 months agopinctrl: microchip-sgpio: add missing select REGMAP_MMIO
Benjamin Boortz [Sun, 19 Jul 2026 09:41:46 +0000 (11:41 +0200)]
pinctrl: microchip-sgpio: add missing select REGMAP_MMIO

The driver calls ocelot_regmap_from_resource() via <linux/mfd/ocelot.h>,
which internally uses devm_regmap_init_mmio() and requires REGMAP_MMIO.
The Kconfig entry does not select REGMAP_MMIO, causing a build failure
when no other driver in the config happens to pull in REGMAP_MMIO:

  include/linux/mfd/ocelot.h:34:24: error: implicit declaration of function 'devm_regmap_init_mmio'

Found by randconfig testing on arm64; tinyconfig reproducer below.

Fixes: 2afbbab45c26 ("pinctrl: microchip-sgpio: update to support regmap")
Cc: stable@vger.kernel.org
Signed-off-by: Benjamin Boortz <bennib@mailbox.org>
Reviewed-by: Andy Shevchenko <andy@kernel.org>
Signed-off-by: Linus Walleij <linusw@kernel.org>
3 months agopinctrl: devicetree: don't free uninitialized dev_name on error path
Karl Mehltretter [Sun, 19 Jul 2026 12:11:40 +0000 (14:11 +0200)]
pinctrl: devicetree: don't free uninitialized dev_name on error path

dt_remember_or_free_map() duplicates dev_name for each map entry. If
kstrdup_const() fails, dt_free_map() frees dev_name in all num_maps
entries, including entries that have not been initialized.

Some pinctrl drivers, including pinctrl-imx, allocate the map with
kmalloc() and leave dev_name for the core to initialize. The untouched
entries therefore contain uninitialized data which is passed to
kfree_const().

Reproduced on qemu's mcimx6ul-evk (pinctrl-imx) with failslab injection
while binding the pinctrl-consuming device, under KASAN:

  BUG: KASAN: double-free in dt_free_map+0x34/0xa4
  Free of addr c425a900 by task init/1
   kfree from dt_free_map+0x34/0xa4
   dt_free_map from dt_remember_or_free_map+0x184/0x198
   dt_remember_or_free_map from pinctrl_dt_to_map+0x33c/0x4c8
   pinctrl_dt_to_map from create_pinctrl+0x9c/0x5c0

Initialize all dev_name fields to NULL before duplicating the device
name, making the full-map cleanup safe after a partial failure.

Fixes: be4c60b563ed ("pinctrl: devicetree: Avoid taking direct reference to device name string")
Cc: stable@vger.kernel.org
Assisted-by: Claude:claude-fable-5
Signed-off-by: Karl Mehltretter <kmehltretter@gmail.com>
Signed-off-by: Linus Walleij <linusw@kernel.org>
3 months agoMerge tag 'block-7.2-20260724' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe...
Linus Torvalds [Sat, 25 Jul 2026 03:02:58 +0000 (20:02 -0700)]
Merge tag 'block-7.2-20260724' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux

Pull block fixes from Jens Axboe:

 - Fix a ublk recovery hang, where END_USER_RECOVERY without a
   successful START_USER_RECOVERY could be satisfied by a stale
   completion latch

 - Fix a stack out-of-bounds read in the CDROMVOLCTRL ioctl

 - MAINTAINERS email address update for Roger Pau Monne

* tag 'block-7.2-20260724' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux:
  MAINTAINERS: update my email address
  cdrom: fix stack out-of-bounds read in CDROMVOLCTRL
  ublk: wait on ublk_dev_ready() instead of ub->completion

3 months agoMerge tag 'io_uring-7.2-20260724' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Sat, 25 Jul 2026 02:58:03 +0000 (19:58 -0700)]
Merge tag 'io_uring-7.2-20260724' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux

Pull io_uring fixes from Jens Axboe:

 - Fix a missing ERESTARTSYS conversion in the read paths, which got
   messed up back when some code consolidation was done for read
   multishot support

 - zcrx UAPI rename, dropping the abbreviated "notif" naming in favor of
   "event" for consistency and to be less ambiguous for users. This was
   added for 7.2, so let's rename it while we still can. No functional
   or code changes, just a strict rename

* tag 'io_uring-7.2-20260724' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux:
  io_uring/zcrx: rename notif to event
  io_uring/zcrx: rename ZCRX_NOTIF_NO_BUFFERS
  io_uring/zcrx: drop "notif" from stats struct names
  io_uring/rw: fix missing ERESTARTSYS conversion in read paths

3 months agotracing: perf: Fix stale head for perf syscall tracing
Steven Rostedt [Fri, 24 Jul 2026 23:32:10 +0000 (19:32 -0400)]
tracing: perf: Fix stale head for perf syscall tracing

The code that can read the user space parameters of a system call may
enable preemption and migrate. The head of the per CPU perf events list
may be pointing to the wrong CPU event if the code migrates the task.

Reassign the head pointer if the system call event called the code that
may have caused a migration.

Cc: stable@vger.kernel.org
Link: https://patch.msgid.link/20260724193210.03fae1d6@gandalf.local.home
Reported-by: Sashiko <>
Link: https://sashiko.dev/#/patchset/20260717173252.3431565-1-usama.arif%40linux.dev
Fixes: edca33a56297d ("tracing: Fix failure to read user space from system call trace events")
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
3 months agoftrace: Add global mutex to serialize trace_parser access
Tengda Wu [Sat, 25 Jul 2026 02:47:21 +0000 (02:47 +0000)]
ftrace: Add global mutex to serialize trace_parser access

In ftrace, the trace_parser structure is allocated and initialized when
a trace file is opened, and is subsequently used across write and release
handlers to parse user input.

The affected handler paths and their specific functions are:
  - Open paths: ftrace_regex_open(), ftrace_graph_open()
  - Write paths: ftrace_regex_write(), ftrace_graph_write()
  - Release paths: ftrace_regex_release(), ftrace_graph_release()

If userspace opens a trace file descriptor and shares it across multiple
threads, concurrent write calls will race on the parser's internal state,
specifically the 'idx', 'cont', and 'buffer' fields, leading to corrupted
input or undefined behavior.

Fix this by adding a global mutex, parser_lock, to serialize all access
to trace_parser across write and release paths, preventing concurrent
corruption of parser state.

Fixes: e704eff3ff51 ("ftrace: Have set_graph_function handle multiple functions in one write")
Fixes: 689fd8b65d66 ("tracing: trace parser support for function and graph")
Cc: stable@vger.kernel.org
Link: https://patch.msgid.link/20260725024721.1983675-1-wutengda@huaweicloud.com
Signed-off-by: Tengda Wu <wutengda@huaweicloud.com>
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
3 months agoMerge tag 'v7.2-rc4-smb3-server-fixes' of git://git.samba.org/ksmbd
Linus Torvalds [Sat, 25 Jul 2026 02:50:05 +0000 (19:50 -0700)]
Merge tag 'v7.2-rc4-smb3-server-fixes' of git://git.samba.org/ksmbd

Pull smb server fixes from Steve French:
 "This contains eight ksmbd fixes covering POSIX ACL handling, SMB
  signing enforcement, DACL parsing and construction hardening, session
  lifetime handling, and validation of malformed transform and
  compressed SMB2 requests:

   - preserve inherited POSIX ACL mask when creating objects.

   - enforce the session signing requirement for plaintext SMB requests.

   - harden DACL/ACE processing against size overflows, incomplete ACE
     copies, and undersized SIDs.

   - defer teardown of a previous session until NTLM authentication
     succeeds.

   - reject undersized encryption-transform and decompressed SMB2
     requests before they can reach normal SMB2 request processing"

* tag 'v7.2-rc4-smb3-server-fixes' of git://git.samba.org/ksmbd:
  ksmbd: reject undersized decompressed SMB2 requests
  ksmbd: validate minimum PDU size for transform requests
  ksmbd: defer destroy_previous_session() until after NTLM authentication
  ksmbd: validate ACE size against SID sub-authorities
  ksmbd: restore DACL size on check_add_overflow() to avoid malformed ACL
  ksmbd: bound DACL dedup walk to copied ACEs
  ksmbd: enforce signing required by the session
  ksmbd: preserve VFS inherited POSIX ACL mask

3 months agoMerge tag 'bpf-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf
Linus Torvalds [Sat, 25 Jul 2026 02:31:12 +0000 (19:31 -0700)]
Merge tag 'bpf-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf

Pull bpf fixes from Eduard Zingerman:

 - Fix tcp_bpf_sendmsg() error path mistaking a concurrently-freed
   sk_psock->cork for the local temporary message and freeing it again
   (Chengfeng Ye)

 - Reject passing scalar NULL to nonnull arg of a global subprog.

   Previously the verifier did not account for the cases directly
   passing scalars to a global subprog, e.g.: 'global_func(0);' would
   pass even if 'global_func' argument was marked nonnull (Amery Hung)

* tag 'bpf-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf:
  bpf, sockmap: Fix cork use-after-free in tcp_bpf_sendmsg()
  selftests/bpf: Test passing scalar NULL to nonnull global subprog
  bpf: Reject passing scalar NULL to nonnull arg of a global subprog

3 months agotracing: Delay module ref count for "enable_event" trigger
Steven Rostedt [Fri, 24 Jul 2026 17:24:15 +0000 (13:24 -0400)]
tracing: Delay module ref count for "enable_event" trigger

Triggers are now delayed from freeing, but can still be triggered until
after the RCU grace period has ended. The freeing of the enable_event data
is put into the private_data_free() callback, but the put of the module
refcount is done immediately.

It is possible that if a module is removed that has an event that would
enable (or disable) it is still active, it can read the data of the module
after it is removed causing a use-after-free bug.

Move the trace_event_put_ref() that releases the module into the delayed
callback so that the module can not be removed until any reference to its
events are finished.

Cc: stable@vger.kernel.org
Link: https://patch.msgid.link/20260724132415.1b5005db@gandalf.local.home
Reported-by: Sashiko <sashiko-bot@kernel.org>
Link: https://sashiko.dev/#/patchset/20260724030523.19081-1-devnexen%40gmail.com
Fixes: 61d445af0a7c ("tracing: Add bulk garbage collection of freeing event_trigger_data")
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>
3 months agotracing: Fix use-after-free freeing trigger private data
David Carlier [Fri, 24 Jul 2026 03:05:17 +0000 (04:05 +0100)]
tracing: Fix use-after-free freeing trigger private data

Commit 61d445af0a7c ("tracing: Add bulk garbage collection of freeing
event_trigger_data") moved the kfree() of event_trigger_data to a kthread
that runs tracepoint_synchronize_unregister() before freeing. That removed
the synchronization the trigger .free callbacks used to get implicitly and
inline from trigger_data_free().

event_hist_trigger_free(), event_hist_trigger_named_free() and
event_enable_trigger_free() free their satellite data (hist_data, cmd_ops,
enable_data) right after trigger_data_free() returns. With the
synchronization now deferred to the kthread, a concurrent tracepoint
handler can still reach that data through the list_del_rcu()'d trigger,
causing a use-after-free.

The histogram teardown must stay synchronous: remove_hist_vars() and
unregister_field_var_hists() have to detach a synthetic event from the
histogram before the trigger-removal write returns, otherwise a following
command races in and the synthetic-event removal fails with -EBUSY, as the
trigger-synthetic-eprobe.tc selftest catches. Make those callbacks wait
with the correct barrier - tracepoint_synchronize_unregister(), matching
the free kthread - before freeing.

The enable trigger has no such synchronous requirement, and a blocking
synchronize there would re-serialize the path that commit deliberately
deferred. Give it an optional private_data_free() callback that the free
kthread runs after its grace period, and free enable_data from there.

Link: https://patch.msgid.link/20260724030523.19081-1-devnexen@gmail.com
Suggested-by: Masami Hiramatsu (Google) <mhiramat@kernel.org>
Suggested-by: Steven Rostedt <rostedt@goodmis.org>
Fixes: 61d445af0a7c ("tracing: Add bulk garbage collection of freeing event_trigger_data")
Signed-off-by: David Carlier <devnexen@gmail.com>
Signed-off-by: Steven Rostedt <rostedt@goodmis.org>