Zygo Blaxell [Wed, 21 Oct 2026 02:15:16 +0000 (22:15 -0400)]
btrfs: scrub: count the raid56 data repairs made by a parity scrub
The scrub of a RAID56 P/Q device reads every data stripe of each full
stripe it checks, verifies and repairs them, and writes the repairs back,
but counts nothing (SCRUB_STRIPE_FLAG_NO_REPORT): neither the scrub
progress nor the device stats. When the P/Q device's scrub reaches a
full stripe before the data device's own scrub does, the data device's
scrub finds the sector already repaired, and the error is counted
nowhere. With all devices scrubbed at once that is a large share of the
errors (one failing raid5 member: 25831 of 42371 damaged data sectors
counted; raid6: 7894 of 34146), and when the damaged device is scrubbed
last, none of them.
Count the sectors that the parity scrub repaired and wrote back, as the
data device's scrub would have: read, checksum and verify errors in the
device stats of the data stripe's own device, and in the parity scrub's
progress with corrected_errors. To count each bad sector once:
- errors left unrepaired are not counted: they stay on disk for the data
device's own scrub;
- a read-only scrub counts nothing here: nothing is written back, and the
data device's own scrub will see the same errors;
- when the data device is being scrubbed at the same time (its
scrub_ctx is set), that scrub repairs and counts its errors itself, so
the parity scrub neither writes back nor counts them. It still uses
the repaired data for its parity check. Crediting the data device's
scrub from here instead would count a sector twice whenever both scrubs
read it before either wrote the repair back, which is common when all
devices are scrubbed at once, since they move through the full stripes
together.
A missing data device is not counted against.
Test (raid56-wh-harness scrub-blame-test.sh): 8 damaged data sectors (or
whole damaged strips: 288 raid5, 224 raid6) on one member, all devices
scrubbed at once, the damaged one first, or last: every damaged sector
counted once in every order, the device stats charged to that member
only; read-only scrubs too. Before: 7 of 8 (raid6 2 of 8) at once, 0
with the damaged member last. failing-member-scrub-test.sh, one member
failing under load: raid5 36128 of 36128, raid6 30231 of 30231 damaged
sectors counted; before, 26519 of 40556 and 11049 of 30723.
After a transaction abort or another filesystem error nothing is written
back (btrfs_can_submit_repair_write()), so the parity scrub's repairs are
neither reported nor counted then, and the read repair worker's write-back
keeps that check next to the own-scrub test.
Fixes: 1009254bf22a ("btrfs: scrub: use scrub_stripe to implement RAID56 P/Q scrub") Assisted-by: Claude:claude-opus-5-5
Zygo Blaxell [Wed, 21 Oct 2026 02:15:15 +0000 (22:15 -0400)]
btrfs: scrub: name the device a raid56 data sector was read from
scrub_stripe_report_errors() finds the device and physical address for
its messages by mapping the stripe's logical address with
BTRFS_MAP_GET_READ_MIRRORS and taking stripes[mirror_num - 1]. On RAID56
that mapping is the full stripe's write mapping, and stripes[0] is the
device of the full stripe's first data stripe, not the device the sector
was read from. So "checksum error at logical ... on dev ...", "fixed up
error ... on dev ..." and "unable to fixup (regular) error ... on dev ..."
name a device that rotates over the members with the full stripes, and a
physical address on it that holds something else. The device stats were
always charged to the right device (stripe->dev).
The scrub stripe already records where it was read from: use
stripe->dev and stripe->physical. For the mirrored and striped profiles
that is the same device and address as before.
Test (raid56-wh-harness scrub-blame-test.sh): with damaged data sectors
on one raid5/raid6 member, every per-sector line names that member, in
every scrub order. Before: 1 to 8 of up to 10 lines named another
member, always the predicted stripes[0].
Zygo Blaxell [Tue, 20 Oct 2026 20:15:58 +0000 (16:15 -0400)]
btrfs: scrub: count raid56 parity mismatches as corruption errors
When scrub finds raid56 parity that does not match the data, it rewrites
the parity (or, on RAID6, rebuilds the data stripe that P and Q locate),
but counts nothing: the device stats do not change, and the scrub
progress, and so `btrfs scrub status`, says "no errors found". A
corrupted parity strip, a stale data strip, or a write hole is repaired
or papered over without a trace.
Count every sector that did not match as a corruption error
(BTRFS_DEV_STAT_CORRUPTION_ERRS) of the device that held the bad copy,
and add it to the scrub's corrected_errors:
- a data stripe that P and Q located and that was rebuilt: its device;
- otherwise the parity being scrubbed: its device.
The second case is not always right. Without a checksum on the data and
without a second parity to locate the error (RAID5, or a RAID6 row that
the decode cannot place), a mismatch may as well be a corrupt or stale
data sector that nothing can detect; scrub rewrites the parity from that
data, and the parity device is charged. Rows whose stripes had a read
error are not counted again: the read error was.
The device is the one in the scrub rbio's io context at the stripe that
held the bad copy. During dev-replace the scrubbed parity is the
source's (the target is only written), so the source is charged.
Test (raid56-wh-harness raid56-devstats-test.sh, arm P): 4 sectors of a
P strip (on raid6 also 4 of a Q strip, other rows) overwritten, then
scrub. Before: no counter moved and scrub said "no errors found".
After: corruption_errs +4 on exactly the corrupted member(s), Corrected
4 (raid6 8), and a second scrub finds nothing.
nodatasum-scrub-repair-test.sh, raid6 with one stale member per row:
every stale sector is charged once, to the member that held it.
A row whose only read error is in the other parity is counted: the check
of this parity does not use it. A read-only scrub adds nothing to
corrected_errors, and neither does a scrub after a transaction abort or
another filesystem error, which writes nothing back
(btrfs_can_submit_repair_write()).
[zygo: 7.3 port: 7.3 has no per-chunk stripe length (map->stripe_len,
two-argument btrfs_stripe_nr_to_offset()); context adjusted]
Zygo Blaxell [Tue, 20 Oct 2026 17:43:04 +0000 (13:43 -0400)]
btrfs: scrub: rebuild a raid6 data stripe that both P and Q disagree with
Scrub checks raid56 parity against the data stripes as they read. Data
without checksums (nodatasum and nodatacow files) cannot be verified, so
it is taken as it reads, and when the parity being scrubbed differs,
finish_parity_scrub() rewrites it from that data.
That is wrong when the data is what is stale. A write that fails on one
device but succeeds within the profile's tolerance is acked and leaves
that device's strip with its old contents, while P and Q were written
from the new data. With the device missing, the new data still rebuilds
from parity. Scrub then rewrites P and Q from the stale strip, and from
then on the acked data is gone: with that device missing it rebuilds to
the old contents.
On RAID6, P and Q together locate one bad stripe without a checksum: if
data stripe z is off by e, P is off by e and Q by g^z * e, in every
byte. When both differ from the data in that pattern, rebuild data
stripe z and write it back instead of rewriting the parity. Two parity
strips that are stale independently do not fit that pattern by chance
over a whole sector. Any other difference (P or Q alone, or no single
z) keeps the parity rewrite. The P and Q devices are scrubbed in
parallel, each from its own read of the data, so only the scrub of P
rebuilds; the scrub of Q leaves such a row alone (Q is right). A torn
write that reached one data stripe but neither P nor Q fits the pattern
too; the rebuild returns that stripe to its old contents, as valid for
an unacked write as the new ones. Rows with a read error were rebuilt
by recover_scrub_rbio() from the parity that is not being scrubbed, and
are left alone. In a read-only scrub nothing is written (previous
patch).
RAID5 has a single parity, so it cannot tell a stale data strip from
stale parity, and is unchanged.
Test (raid56-wh-harness nodatasum-scrub-repair-test.sh): nodatasum files
on a 5-device raid6, each file written with one member failing writes
during its writeback (each member in turn; within tolerance, so acked),
then scrub, then every file read with no member, each member and each
pair missing. Before: scrub kept the 6 stale data strips and rewrote P
and Q from them; 64 of 80 reads were wrong afterwards, 20 of them correct
before the scrub. After: the stale strips are rebuilt, P and Q match the
data, and 80 of 80 reads are correct, with and without stripe_alloc. Two
stale strips per row (two members failing) cannot be located and still
get their parity rewritten, as before.
A data sector that scrub verified, by its csum or as a tree block, is
never rebuilt: it is right as read. When P and Q both point at it, they
are what is stale (both can miss the same write, e.g. a sub-stripe write
made while the P and Q devices were missing), so the scrub of P and the
scrub of Q each rewrite theirs.
After a transaction abort or another filesystem error, the rebuilt data
is not written either: the btrfs_can_submit_repair_write() check that
"btrfs: scrub: do not write back repairs after a transaction abort" put
before the parity write moves ahead of the rebuilt-data writes, and a
running dev-replace still gets the parity copy.
[zygo: 7.3 port: context only: the comment typo "caclulated" is still in
7.3 (fixed upstream later by 49c313970a5e); 7.3 has no per-chunk stripe
shift (map->stripe_shift); context adjusted to BTRFS_STRIPE_LEN_SHIFT;
7.3 has no per-chunk stripe length (map->stripe_len, bioc->stripe_len,
the two-argument btrfs_stripe_nr_to_offset()): BTRFS_STRIPE_LEN is used
instead]
Fixes: 5a6ac9eacb49 ("Btrfs, raid56: support parity scrub on raid56") Assisted-by: Claude:claude-opus-5-5
Zygo Blaxell [Wed, 21 Oct 2026 07:59:11 +0000 (03:59 -0400)]
btrfs: scrub: do not write raid56 parity in a read-only scrub
A read-only scrub (btrfs scrub start -r) must not write to the devices.
The data stripes honour that: their repairs are only written back when
the scrub is not read-only. The raid56 parity scrub never looks at it:
finish_parity_scrub() rewrites every P or Q sector that does not match
the data, whatever the scrub's mode. So a read-only scrub of a raid56
filesystem with stale or damaged parity rewrites it.
Tell the parity scrub rbio whether the scrub is read-only, and in that
case stop after the check, before any write is built.
Test (raid56-wh-harness scrub-blame-test.sh SB_RO=1: read-only mount,
scrub -r): with 8 damaged data sectors (every order) or 8 damaged parity
sectors on one raid5/raid6 member, every member image is byte-identical
after the scrub, and the damage is still counted. Before: with damaged
parity, the scrub rewrote it, and a member image changed.
[zygo: 7.3 port: 7.3 has no per-chunk stripe length (map->stripe_len);
context adjusted to BTRFS_STRIPE_LEN]
Fixes: 5a6ac9eacb49 ("Btrfs, raid56: support parity scrub on raid56") Assisted-by: Claude:claude-opus-5-5
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 of that device break out of its loop early and return
the error to userspace. Every device holding P or Q for an affected
full stripe stops there, and parity rotates, so a few bad full stripes
stop the scrub of most of the array.
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. No other profile does this: their scrubs
count uncorrectable sectors, report them and carry on, returning 0.
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.
Since commit fab0c0f03cfd ("btrfs: introduce BTRFS_PATH_AUTO_RELEASE()
helper") the bug had changed shape: ret no longer held -EIO at that
point but the leftover return value of the last
scrub_find_fill_first_stripe() call, 0 or 1. 1 made scrub_stripe()
silently stop scrubbing the rest of the block group on that device, and
0 let the scrub continue only by accident, until "btrfs: scrub: fix lost
error return value when scrubbing raid56 parity stripe" restored the
-EIO.
scrub_raid56_parity_stripe() has successfully completed its task once it
has performed its data correction and verification steps and checked P/Q
of the rows without unrepaired sectors. Return 0 at that point,
regardless of the outcome of the verification. P/Q of the rows with
unrepaired sectors is still not regenerated, so no garbage is written
back to the devices, and during dev-replace their original P/Q is copied
to the target ("btrfs: scrub: copy raid56 parity of unrepairable rows to
the replace target"), so a replace that now carries on past them does
not lose their redundancy. The unrepaired sectors are logged, and
counted in the scrub statistics (and, since v6.16, the device stats)
when their own data device is scrubbed; they are not reported through
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>
Zygo Blaxell [Sat, 17 Oct 2026 01:06:45 +0000 (21:06 -0400)]
btrfs: scrub: read raid56 sectors without an extent from the replace source
With -r (cont_reading_from_srcdev_mode AVOID), dev-replace reads the
data stripes of the source device through the next mirror, which for
RAID56 is a rebuild from the other stripes of the row. Where the stripe
has an extent, the rebuilt bytes are checked against the csum, and if
they are wrong the repair reads the source after all. "btrfs: scrub:
copy every sector of raid56 data stripes to the replace target" also
copies the sectors without an extent, and nothing checks their rebuild:
if another stripe of the row is bad at that sector, the rebuild carries
the damage, the target's sector no longer matches what P/Q was computed
over, and the other device's bad sector, recoverable before the replace,
is lost.
Read those sectors from the source when it is present, which keeps every
row exactly as recoverable as it was on the source, and keep the rebuilt
bytes only where that read fails or the source is missing. This reads
the source for sectors that hold no data although the user asked to
avoid it, but -r is documented as reading the source only when no other
zero-defect mirror exists, and the rebuild of a sector without a csum
cannot be shown to be one.
It is a separate change so it can be dropped if reading the source here
is not wanted; without it, a replace with -r can lose blocks that were
recoverable before it.
In the test described in "btrfs: scrub: copy every sector of raid56 data
stripes to the replace target", replaces with -r lost 682-878
blocks that were recoverable before the replace, and left 1000-1150
target sectors holding rebuilt bytes that carried another device's
damage. With this change they lose none, like replaces without -r.
Zygo Blaxell [Sat, 17 Oct 2026 00:33:38 +0000 (20:33 -0400)]
btrfs: scrub: only avoid the replace source device for its own stripes
With cont_reading_from_srcdev_mode AVOID (btrfs replace start -r),
scrub_submit_initial_read() reads a stripe through the next mirror
instead of directly. In the data path that is right: the stripes there
are on the source device. But the RAID56 parity scrub
(scrub_raid56_parity_stripe(), which runs when the source holds P or Q
of a full stripe) reads the data stripes of all the other devices
through the same function, and for RAID56 the next mirror of a data
stripe is a rebuild of it from P/Q and the other data stripes, which
reads the source's P, the device the user asked to avoid.
The rebuilt bytes are verified only where the stripe has an extent with
a csum. Everywhere else the scrub buffer keeps them, and
scrub_raid56_cached_parity() hands them to the parity rbio as the data,
so finish_parity_scrub() does not check P/Q against the data on disk:
- where a sector without an extent was rebuilt from P, the recomputed
P equals the on-disk P by construction, so bad P passes the check and
is duplicated to the replace target as it is;
- where another data stripe's sector is bad, the rebuilt sectors carry
that damage, the recomputed P (P ^ bad ^ good) differs from the
on-disk P and is written to the source and the target, baking the bad
data into parity: the bad sector, recoverable before the replace, is
lost.
Apply the AVOID mode only to the stripes on the source device. A
missing device is still read through the next mirror, whichever device
it is.
The parity scrub has read the other devices' data stripes this way since 1009254bf22a ("btrfs: scrub: use scrub_stripe to implement RAID56 P/Q
scrub"), and has used the scrub buffers as the parity rbio's data since 94ead93e6375 ("btrfs: scrub: use recovered data stripes as cache to
avoid unnecessary read").
In the test described in "btrfs: scrub: copy every sector of raid56 data
stripes to the replace target", replaces with -r recomputed 184-362
parity sectors over another device's bad data and copied about twice as
many bad parity sectors verbatim to the target as replaces without -r
(1453-1600 instead of 623-712). With this change -r recomputes none
over bad data and copies exactly as much bad parity as a replace
without -r.
Zygo Blaxell [Sat, 17 Oct 2026 00:33:38 +0000 (20:33 -0400)]
btrfs: scrub: copy every sector of raid56 data stripes to the replace target
Dev-replace copies a data stripe of the source device by writing the
sectors that hold an extent (flush_scrub_stripes()), and it only visits
the data stripes that hold at least one extent: queue_scrub_stripe()
skips the others. For mirrored profiles that is all that matters.
For RAID56 it is not. P/Q of a row is computed over every data strip of
the row, whether or not the strip's sector holds an extent (deleted data,
never written space, zeroed padding), and every later rebuild of another
data strip in the row reads the replaced device's sector as an input.
If the target never got that sector, it holds whatever was there before
the replace, the rebuild produces wrong bytes, the csum check fails and
the read returns -EIO. So replacing any raid56 device, healthy or not,
silently turns recoverable damage on another device into lost data, and
leaves the affected rows without redundancy until a full scrub rewrites
their parity.
For RAID56 block groups, also write the sectors of the data stripe that
hold no extent and were read without error, and queue the data stripes
without any extent when another data stripe of their full stripe holds
one. The bytes written are the ones the scrub read: the source's
on-disk bytes, which keep the row as consistent with its P/Q as it was
on the source even if other strips of the row are bad; or, when the
source is missing or the user asked to avoid reading it (-r), the
stripe rebuilt from the other strips. A rebuilt sector is consistent
with P/Q by construction, but if another strip of the row is bad at the
time, the rebuild carries that damage and the bad sector can no longer
be recovered; that is the price of not reading the source. Full
stripes without any extent are still skipped: a later write to one
computes P/Q from what is on disk at that time.
Measured with a test that fills a 5-device raid5 (raid1 metadata) with
partially filled full stripes, corrupts two devices in different rows
and then replaces one of them, or a healthy device, without reading
anything first: each replace left 5400-6700 of these sectors unwritten
on the target, and 1028-1237 blocks that were recoverable before the
replace returned -EIO after it (667-1302 when some rows were also
damaged on both devices), on both a misc-next and a 6.18 based tree,
with and without stripe_alloc. With this change all of those sectors
are written and only the blocks that were unrecoverable before the
replace return -EIO.
[zygo: 7.3 port: 7.3 has no per-chunk stripe length (map->stripe_len,
bioc->stripe_len, the two-argument btrfs_stripe_nr_to_offset()):
BTRFS_STRIPE_LEN is used instead; the change itself is unchanged]
Zygo Blaxell [Fri, 16 Oct 2026 06:32:17 +0000 (02:32 -0400)]
btrfs: scrub: copy unrepaired raid56 data sectors to the replace target
When dev-replace copies a data stripe, it writes only the sectors that
were read or repaired successfully (flush_scrub_stripes()); sectors that
could not be repaired are left unwritten on the target. For mirrored
profiles that loses nothing: the sector was bad on every copy anyway,
and the csum keeps reporting it.
RAID56 is different. The replaced device's data strip is an input to
every later rebuild of the other strips in its rows: when another device
of the row fails, its sector is reconstructed from P/Q and the remaining
data strips, including this one. An unwritten target sector turns those
rebuilds into garbage, where the source's sector, even with a bad csum,
kept the row as consistent as it was. And as with the parity rows, the
failure may have been a transient read error, in which case the
source's bytes are the right data.
For RAID56 block groups only, write the unrepaired data sectors to the
target verbatim, as they are on the source. The scrub buffer holds the
last failed reconstruction attempt for them, not the source's bytes, so
they are read again from the source. The copy is best effort: on a read
or write error it is logged and the replace carries on. This
deliberately differs from the good-sectors-only rule of the other
profiles, for the reason above.
This is an optional improvement: it does not depend on "btrfs: scrub:
copy raid56 parity of unrepairable rows to the replace target", and
"btrfs: scrub: check raid56 parity of the rows without unrepaired data"
does not depend on it.
Zygo Blaxell [Fri, 16 Oct 2026 06:32:16 +0000 (02:32 -0400)]
btrfs: scrub: copy raid56 parity of unrepairable rows to the replace target
"btrfs: scrub: check raid56 parity of the rows without unrepaired data"
leaves the rows of a full stripe that contain unrepaired data out of the
parity scrub, so during dev-replace the target gets nothing for those
rows of the replaced device's P/Q strip.
A row is unrepairable when more of its strips failed than P/Q can
rebuild, but the failure is not always permanent: a read error during
the replace can be transient. On the source, such a row is still
covered by its original P/Q, so if the data turns out to be readable
later the row can be recovered. On the target, with nothing written for
those P/Q sectors, that hope is gone.
When replacing, copy the original P/Q sectors of those rows from the
source device to the target, so the target's P/Q for those rows matches
the source's and the rows stay as recoverable from the new device as
they were from the old one. The copy is best effort: if the source
sectors cannot be read or the target write fails, log it and carry on,
leaving those rows unwritten as before.
The commit above does not depend on this one, but a scrub that does not
fail on unrepaired data does: a replace that carries on past such a row
would otherwise leave its P/Q unwritten on the target.
[zygo: 7.3 port: 7.3 has no per-chunk stripe length (map->stripe_len,
bioc->stripe_len, the two-argument btrfs_stripe_nr_to_offset()):
BTRFS_STRIPE_LEN is used instead; the change itself is unchanged]
Zygo Blaxell [Fri, 16 Oct 2026 06:32:16 +0000 (02:32 -0400)]
btrfs: scrub: check raid56 parity of the rows without unrepaired data
When a data stripe of a full stripe has unrepaired sectors,
scrub_raid56_parity_stripe() skips the P/Q check for the whole full
stripe. Parity is per row (the same sector of every strip), so only the
rows that contain an unrepaired data sector need to be left alone.
Skipping the whole full stripe has two costs:
- on scrub, P/Q of the other rows is never verified or repaired;
- on dev-replace, the parity scrub is the only path that writes the
replaced device's P/Q strip to the target (finish_parity_scrub()
duplicates its writes when the strip being scrubbed is on the replace
source). Skipping it leaves that strip unwritten on the target, so
the good data strips of the full stripe can no longer be rebuilt from
the new device.
Collect the rows with unrepaired data sectors from all data stripes,
leave them out of the bitmap passed to the parity scrub, and check and
regenerate P/Q for the remaining rows. The bad rows keep their existing
P/Q on scrub, and on dev-replace nothing is written to the target for
them. That is the rule the other profiles already follow when they copy
a data stripe with uncorrectable sectors to the replace target
(flush_scrub_stripes() writes only the good sectors).
A full stripe with unrepaired data sectors still fails the scrub of the
device with -EIO, now after its good rows have been checked. Whether
the scrub should fail at all is left to a later change.
A sector without an extent that could be neither read nor rebuilt makes
its row bad as well: there is nothing to compute the row's parity from.
[zygo: 7.3 port: 7.3 lacks upstream 0bade584e95b (return -EIO, not ret,
for unrepaired data sectors); the statement is replaced here either way;
7.3 has no per-chunk stripe length (map->stripe_len, bioc->stripe_len,
the two-argument btrfs_stripe_nr_to_offset()): BTRFS_STRIPE_LEN is used
instead]
Zygo Blaxell [Thu, 22 Oct 2026 18:31:49 +0000 (14:31 -0400)]
btrfs: scrub: do not write back repairs after a transaction abort
A scrub that is running when a transaction aborts outside the commit
path keeps going. (An abort in the commit path cancels it in
cleanup_transaction(), unless relocation is running.) Once the abort
has forced the filesystem read-only, btrfs_inc_block_group_ro() takes
its path for a read-only mount, which needs no transaction, so the
scrub goes on through every remaining block group. For every bad
sector it finds, scrub_stripe_read_repair_worker() reads a good copy
and writes it back with scrub_write_sectors(). It does not look at the
filesystem state (sctx->readonly is fixed when the scrub starts), so
these writes go out after the abort, to a filesystem that was forced
read-only.
Skip the write-back when btrfs_can_submit_repair_write() says no. The
scrub still reads, verifies and reports. A running dev-replace still
copies to its target, which __btrfs_handle_fs_error() leaves running on
purpose.
read-repair-submit-fail-test.sh RR_ARM=scrubabort (raid56-wh-harness)
corrupts a sector of a raid1 data block group on one mirror, starts a
speed-limited scrub, and aborts a transaction (a log commit whose
superblock writes fail) while the scrub is in that block group but
before it reaches the sector. Without this patch the scrub writes the
sector back after the abort; with it nothing is written to either
device after the abort and the bad copy stays as it was.
The parity scrub of raid56 checks the same: its parity write-back is
skipped too, and its copy to a dev-replace target still goes out.
Fixes: 54765392a1b9 ("btrfs: scrub: introduce helper to queue a stripe for scrub") Assisted-by: Claude:claude-opus-5-5
Zygo Blaxell [Thu, 22 Oct 2026 18:31:48 +0000 (14:31 -0400)]
btrfs: do not write back a read repair after a transaction abort
btrfs_repair_bbio_failure() writes a repaired data sector or tree block
back to the bad copy unless the filesystem is read-only. SB_RDONLY is
not the only state that must stop that write:
- A transaction abort sets BTRFS_FS_STATE_TRANS_ABORTED, reports the
abort (with a stack dump for most errors), and then
__btrfs_handle_fs_error() sets fs_info->fs_error and only after that
SB_RDONLY. A repair that runs in between still writes after the
abort.
- An emergency shutdown (btrfs_force_shutdown()) sets fs_error but
deliberately leaves SB_RDONLY clear. A read that still reaches the
filesystem after the shutdown, such as a page fault on a mapping made
before it or a tree block read, repairs a bad copy and writes it
back.
- An error during mount, before SB_BORN, sets fs_error without
SB_RDONLY.
Nothing should be written after an abort or a shutdown. Add
btrfs_can_submit_repair_write(), which also checks the error and the
abort bit, and use it in btrfs_repair_bbio_failure(). That covers data
read repair and tree block repair (btrfs_repair_eb_io_failure()). The
read still gets the good copy's data.
read-repair-submit-fail-test.sh RR_ARM=shutdown (raid56-wh-harness)
maps a raid1 file whose tail is corrupt on one mirror, shuts the
filesystem down, drops the tail from the page cache and touches it
through the mapping. Without this patch the read repair writes the
tail back to the corrupt mirror after the shutdown; with it the read
returns the file's data, nothing is written to either device and the
corrupt copy stays as it was.
Fixes: 8ceaad6cd6e7 ("btrfs: do not ASSERT() when the fs flips RO inside btrfs_repair_io_failure()") Fixes: 9b2839451dfc ("btrfs: introduce a new shutdown state") Assisted-by: Claude:claude-opus-5-5
Zygo Blaxell [Thu, 22 Oct 2026 18:31:46 +0000 (14:31 -0400)]
btrfs: look up a repair read's csums in the same root as the failed read
A buffered read of an extent from a past transaction looks its checksums
up in the csum commit root: submit_one_bio() sets
bbio->csum_search_commit_root, and split bios and compressed reads
inherit it. repair_one_sector() leaves the flag clear on the repair
bbio, so the repair read looks the same checksums up in the running
transaction's csum tree.
Normally both lookups find the same checksums. After a transaction
abort they need not: the abort cleanup frees the running transaction's
dirty tree blocks without writing them, and a lookup that reaches one of
them once its folio is gone reads a location that was never written:
The original read finds its checksums in the commit root and detects
the bad copy, but every repair read then fails its csum lookup at
submission, so the read fails with -EIO although another copy is good.
Let the repair bbio inherit csum_search_commit_root from the failed
bbio, as btrfs_split_bio() does for split bios. The repair then finds
the checksums the failed read used, and after an abort read repair
returns the good copy's data again. It still does not write the
repaired sector back: the filesystem is read-only by then. The flag
survives the resubmission to the next mirror, because bio_reset() in
btrfs_end_repair_bio() does not touch the btrfs_bio fields.
Reproduced with read-repair-submit-fail-test.sh RR_ARM=abortgood
(raid56-wh-harness) on raid1: commit a file, make the running
transaction COW the csum leaf that holds the file's tail, corrupt the
tail on one mirror, abort the transaction by failing a log commit's
superblock write, drop the page cache and read the tail from the
corrupt mirror. Without this patch the read fails with -EIO; with it,
the read returns the file's data.
Fixes: f07b855c56b1 ("btrfs: try to search for data csums in commit root") Cc: stable@vger.kernel.org # 6.18+ Assisted-by: Claude:claude-opus-5-5
Zygo Blaxell [Thu, 22 Oct 2026 06:16:13 +0000 (02:16 -0400)]
btrfs: give the read repair bio an end_io for submit failures
repair_one_sector() initializes the repair bbio with a NULL end_io. A
repair bio normally completes through btrfs_check_read_bio(), which hands
it to btrfs_end_repair_bio() and never calls end_io. But
btrfs_submit_chunk() can fail a bio before it reaches a device: when
btrfs_map_block() fails, when btrfs_split_bio() fails, or when
btrfs_lookup_bio_sums() fails for a data read. It then ends the bio with
btrfs_bio_end_io(), which calls bbio->end_io. For a repair bio that is a
jump to address 0 in a btrfs-endio worker. The original read never
completes, and an unmount hangs on it later:
The repair bio's checksum lookup can fail where the original read's
lookup succeeded, because the two search different trees. A buffered
read of an extent from a past transaction searches the commit root
(csum_search_commit_root). The repair bbio leaves that flag clear and
searches the running transaction's csum tree. When that transaction
aborts, the cleanup frees its dirty tree blocks. A later lookup reads
such a block from disk, where it was never written, and fails with -EIO:
This was first seen right after a relocation forced the filesystem
read-only: six btrfs-endio workers oopsed within 1.5 seconds. It
reproduces with a raid1 filesystem:
- Commit a file, write more data so that the csum leaf holding the file's
tail is COWed in the running transaction, and corrupt the tail on both
mirrors.
- Abort the transaction by failing a log commit's superblock write, and
drop the page cache.
- A buffered read of the tail now oopses.
Give the repair bbio an end_io for this case. A failed submission does
not depend on the mirror: the mapping and the checksum lookup fail the
same way for every copy. So give up on the sector the way an exhausted
repair does: mark the original bio failed, drop the repair's count on
the failed_bio, and free the repair bio. The read then fails with -EIO.
Fixes: 7609afac6775 ("btrfs: handle checksum validation and repair at the storage layer") Cc: stable@vger.kernel.org # 6.6+ Assisted-by: Claude:claude-opus-5-5
Filipe Manana [Fri, 16 Oct 2026 17:02:23 +0000 (18:02 +0100)]
btrfs: scrub: fix race between scrub and scrub progress ioctl
The scrub progress ioctl is copying the scrub progress stats without
acquiring the spinlock that protects it and a concurrent scrub can be
updating the stats at the same time which can lead to load tearing
issues. So take the spinlock when copying the progress stats.
Reviewed-by: Qu Wenruo <wqu@suse.com> Reviewed-by: Daniel Vacek <neelx@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
(cherry picked from btrfs for-next commit 9065b20db1369c882b790f1fb94faad7ef871028)
Filipe Manana [Fri, 16 Oct 2026 16:53:00 +0000 (17:53 +0100)]
btrfs: scrub: fix race leading to use-after-free in the scrub progress ioctl
If the scrub progress ioctl is called when replace is about to finish, we
have a race that can result in a use-after-free of the scrub context:
1) A scrub is finishing and is at btrfs_scrub_dev();
2) A concurrent task called the scrub progress ioctl and is in
btrfs_scrub_progress(), where it takes the device_list_mutex and grabs
the device. Then it starts using the device's scrub context (for a
memcpy operation);
3) While the scrub progress ioctl task is running, the scrub task sets
the device's scrub_ctx to NULL (acquiring fs_info->scrub_lock) and
then calls scrub_put_ctx() against the scrub context, dropping the
last reference and freeing the memory - while the scrub progress ioctl
task is still using it, resulting in a use-after-free.
Fix this by changing btrfs_scrub_progress() to take fs_info->scrub_lock
before using the scrub context.
Reviewed-by: Qu Wenruo <wqu@suse.com> Reviewed-by: Daniel Vacek <neelx@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
(cherry picked from btrfs for-next commit 9f618b59ff51ccefadc45c66ab4e88beffacf2be)
Filipe Manana [Fri, 16 Oct 2026 16:14:49 +0000 (17:14 +0100)]
btrfs: scrub: fix lost wakeup and hang when cancelling a scrub that is finishing
When scrub finishes, it does a wakeup on the fs_info->scrub_pause_wait
wait queue and then sets dev->scrub_sctx to NULL. On the other hand the
scrub cancel code (btrfs_scrub_cancel_dev()) waits on that wait queue
for dev->scrub_sctx to be NULL. So this means if btrfs_scrub_cancel_dev()
is called right when scrub is finishing and sees the wakeup before the
NULL is assigned to dev->scrub_sctx by btrfs_scrub_dev(), it hangs.
Fix this by doing the wakeup in btrfs_scrub_dev() after setting
dev->scrub_sctx to NULL.
Fixes: a2de733c78fa ("btrfs: scrub") Reviewed-by: Qu Wenruo <wqu@suse.com> Signed-off-by: Filipe Manana <fdmanana@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
(cherry picked from btrfs for-next commit bca2507eda60cf43e09b98aae2914d96744881d7)
Qu Wenruo [Wed, 19 Aug 2026 01:06:16 +0000 (10:36 +0930)]
btrfs: replace btrfs_repair_io_failure() to use bio for page iteration
Currently btrfs_repair_io_failure() uses a @paddrs[] array to iterate
pages.
Such a parameter is required for bs > ps cases, as one fs block crosses
several pages.
However there is a much simpler and existing way to iterate pages: bio
and bvec_iter.
This changes btrfs_repair_io_failure() by:
- Use a const @bvec_iter pointer to locate where the pages are
- Extract file offset/logical from the @bbio
- Require no @step parameter
Above features allow us to shorten the parameter list.
- Rename the function to btrfs_repair_bbio_failure()
- Change the caller in btrfs_repair_eb_io_failure() to allocate a bbio
Unlike the data read path, we do not have a handy bbio in that case.
So we need to allocate one just for btrfs_repair_bbio_failure().
- Change the error reporting in btrfs_repair_bbio_failure() to include
root id and use inode number directly
Now for btree inode we will report a proper inode number (1).
Reviewed-by: Boris Burkov <boris@bur.io> Signed-off-by: Qu Wenruo <wqu@suse.com> Signed-off-by: David Sterba <dsterba@suse.com>
(cherry picked from commit 15ed4a938b30fcb72e96187f36e2c4ff0e6e2227)
Reading I/O statistics via sysfs concurrently with tearing down a
frontend device might result in UAF or a NULL dereference, as the
reading of the statistics data is not synchronized with freeing the
data.
Use a rwlock for synchronizing.
This is XSA-528 / CVE-2026-100082
Fixes: db6fbc106786 ("xen/blkback: make st_ statistics per ring") Reported-by: Yehyeong Lee <yhlee@isslab.korea.ac.kr> Signed-off-by: Juergen Gross <jgross@suse.com> Acked-by: Roger Pau Monné <roger@xenproject.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
In order for the function to legitimately avoid locking/RCU, it needs to
run after all TX/RX processing has finished/stopped: Lookups happen from
xenvif_start_xmit(), while adds/removes happen from xenvif_tx_action()
(called out of xenvif_poll()).
Move the call out of xenvif_disconnect_data() (the call to the function
from connect()'s error path doesn't require any cleaning up there), and
put it past the synchronization point in backend_disconnect().
The network statistic data in the driver is protected by RCU.
Unfortunately when tearing down the queues after an error during
connecting to the frontend (e.g. due to illegal Xenstore data filled
in by the guest), the statistic data is being freed without
synchronizing the RCU state. In case the data is being read via sysfs
in this phase, access to already freed memory or memory being in new
use is possible.
Fix that by calling synchronize_net() before freeing the queue data.
Twenty years ago I made creating a tuntap device require CAP_NET_ADMIN
in commit ca6bb5d7ab22 ("[NET]: Require CAP_NET_ADMIN to create tuntap
devices.")
The idea was to allow the permissions on /dev/net/tun to be relaxed to
0666 and thus allow owners of tun devices assigned with TUNSETOWNER to
actually open it and get at their devices.
What we missed at the time was that persistent devices with *no* owner
were already essentially world-consumable, and anyone who could open
the device node could also attach to those.
Even then, using persistent devices with no explicitly set owner — on
the (false) presumption that CAP_NET_ADMIN would be required to open
them — wasn't an egregious userspace bug. There are cases where it does
make sense to separate the creation/configuration of the netdevice, from
the process which shovels packets into it.
Since then, TUNSETGROUP was added a year later in commit 8c644623fe7e
("[NET]: Allow group ownership of TUN/TAP devices."). Its commit message
noted that if both uid and gid are set, both have to match (in itself a
bizarre choice) — but still not that with *neither* set, no permission
at all was required.
Then in 2012 commit c8d68e6be1c3 ("tuntap: multiqueue support") allowed
new queues to be attached to a device from the moment of its creation,
with no way for userspace to close the race between creation and a
subsequent TUNSET{OWNER,GROUP}.
In 2024, commit 3ca459eaba1bf ("tun: fix group permission check") tried
to fix things to be saner: only require the user *or* the group to
match, in line with standard POSIX permissions, and require
CAP_NET_ADMIN if neither the user nor group authorised the access
(although it put the CAP_NET_ADMIN check first, and would wrongly have
reported the capability as having been used even when it was not).
That fix was reverted in commit a70c7b3cbc06 ("tun: revert fix group
permission check") due to allegedly causing a regression in an selinux
test suite which *expected* the attachment to succeed when authorised
by none of user, group, nor CAP_NET_ADMIN:
https://lore.kernel.org/netdev/CAFqZXNtkCBT4f+PwyVRmQGoT3p1eVa01fCG_aNtpt6dakXncUg@mail.gmail.com/
We should not break UAPI. But we don't have to consider an selinux test
case which deliberately exercises a security flaw to be UAPI worth
preserving either. To which end, I have fixed it in selinux-testsuite
commit b2f894f0016b ("tests/tun_tap: set an owner on the device for the
relabel tests").
So: fix the lack of CAP_NET_ADMIN check on devices which *haven't* been
assigned an owner or group, while leaving the weird tun ownership model
as it was (user *and* group have to match, if both are set). If someone
still wants to fix the latter (which wasn't actually the reason the
previous attempt was reverted), they can do it under separate cover.
Permit attaching to an existing device only if an owner and/or group was
set and the caller matches all that were set, or if the caller has
CAP_NET_ADMIN. The only behavioural change is that a device with no
owner or group now requires CAP_NET_ADMIN to attach — precisely the
loophole we want to close.
And put the CAP_NET_ADMIN check in the right place this time.
Fixes: ca6bb5d7ab22 ("[NET]: Require CAP_NET_ADMIN to create tuntap devices.") Reported-by: Andrew Lutomirski <luto@kernel.org> Signed-off-by: David Woodhouse <dwmw@amazon.co.uk> Cc: stable@vger.kernel.org Reviewed-by: Willem de Bruijn <willemb@google.com> Link: https://patch.msgid.link/3c77f88acff5b3c2617b22d64faad15f6212619c.camel@infradead.org Signed-off-by: Jakub Kicinski <kuba@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
With CONFIG_HZ=1024, msecs_to_jiffies(1200) includes an overflow check
that calls jiffies_to_msecs(MAX_JIFFY_OFFSET). Its saturation branch
returns MAX_JIFFY_OFFSET, which exceeds the six-second upper bound.
GCC 10.5 carries that branch into clamp_t()'s bounds check and fails to
build ksmbd_tcp_writev() on MIPS.
Compute the 1200 ms lower bound with DIV_ROUND_UP() instead, so both
bounds are compile-time constants. The lower bound still rounds up to
the next jiffy, and the retry interval remains between 1.2 and 6 seconds.
When a thread pushes work to its own todo list, InnerThread::push_work()
returns PushWorkRes::OkNotifyPoll if the thread uses epoll, but four
call sites in thread.rs discard this return value. As a result, a
non-blocking BC_* write that enqueues work onto the calling thread's
todo list without also reading will not wake epoll. Check the return
value and call self.process.notify_poll(false) when
PushWorkRes::OkNotifyPoll is returned.
This is similar to commit 97830f3c3088 ("binder: signal epoll threads of
self-work"), but in C Binder pending thread work also prevented
subsequent process work from waking epoll, causing a permanent hang,
which is not the case in Rust Binder. This means that in practice, it
merely delays notifications rather than completely failing to send them.
Cc: stable@kernel.org Fixes: dbb17c9ea756 ("rust_binder: move (e)poll wait queue to Process") Reported-by: Poil Zero <poilandgginchi@gmail.com> Signed-off-by: Alice Ryhl <aliceryhl@google.com> Link: https://patch.msgid.link/20261016-binder-poll-self-work-v1-1-c29c87d99abb@google.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
[ sashal: adapted reply_inner() to unconditional immediate completion because TransactionFlag::DeferComplete is absent ] Signed-off-by: Sasha Levin <sashal@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
ksmbd_reopen_durable_fd() republishes a detached durable handle in the
reconnecting session's file table and takes no reference for that entry.
If smb2_open() then fails, cleanup relies on the final ksmbd_fd_put() to
remove the volatile id.
Two reconnects of the same handle can both take a lookup reference before
either attaches it. If the one that reopens first then fails and drops
its references first, the other request makes the final put through
ksmbd_put_durable_fd(). That frees the handle without removing the first
session's table entry, so tearing that session down writes to freed
memory.
Commit 3515503322f4 ("ksmbd: fix durable reconnect error path file
lifetime") handles a final put made by the reconnecting request, but not
one made by another holder.
Remove the volatile id under the file-table lock on this error path,
before the references are dropped, as ksmbd_close_fd() does on the
request_open path just above. Removal then no longer depends on which
holder makes the final put. The stale comment in the reconnect cleanup
is updated to match. A successful reconnect is unchanged.
Fixes: c8efcc786146 ("ksmbd: add support for durable handles v1/v2") Cc: stable@vger.kernel.org Signed-off-by: Ian Bridges <icb@fastmail.org> Signed-off-by: Namjae Jeon <linkinjeon@kernel.org> Signed-off-by: Sasha Levin <sashal@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
A completed DurableHandleReqV2 CREATE can be replayed through another
channel while its original channel is exiting. The existing replay path
returns the open but leaves its connection and oplock references pointing
at the old channel. Its open count also stays on that channel, and a
later CLOSE through the surviving channel decrements the wrong counter.
After checking the owner, lease key and persistent flag, verify that an
active open is still published in the requesting session's file table.
Do this even when no oplock was granted, and before processing a consumed
replay. Do not read a borrowed opinfo session pointer for this check.
Keep a healthy original binding. If the original channel is exiting or
releasing, move the open and its own oplock references to the requesting
channel. Serialize this with CLOSE using the session file-table lock,
and with detach, reconnect and notification snapshots using m_lock.
The earlier lock index and lease-table changes make their lifetimes
independent of this connection change. No old-channel r_count wait is
needed, including when an unrelated request remains active there.
Account final close against fp->conn in one place, balance durable detach
and reconnect, and transfer the count with a replay binding change. A
final global lookup put may run after CLOSE has removed the volatile id;
unlink the open from the inode list on that final close as well.
A live completed CREATE replay may follow a break that lowered the
durable open's batch oplock. Apply the batch eligibility check only to
detached reconnects, while retaining the owner, lease key and persistent
flag checks for active replays.
Fixes: bb8bf7eb13b5 ("ksmbd: add SMB3 request replay support") Reported-by: Pan Guihua <pan.guihua@datatom.com> Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
Retain the file lifetime and connection accounting groundwork needed by
failed durable reconnect cleanup. Always unlink the open from the inode
list on final close, including when a global lookup owns the last put.
Charge that close to the bound connection and balance the count across
durable detach, reconnect and reconnect failure.
Serialize detach and reconnect with the inode lock, reject reopening a
closed handle, and detach only the oplock belonging to that open. Preserve
the existing byte-range lock connection lists and their reference transfers.
Active CREATE replay rebinding is omitted because the independent lock
indexing it requires is absent; no new helper is introduced.
Prepare CREATE error cleanup to distinguish an open retained by the request
from one that has not acquired that reference. Close and complete a retained
request open explicitly, while preserving the existing put for the other
case. This supplies the cleanup branch required by the durable reconnect
unpublication fix without the unrelated tree-disconnect changes.
Assisted-by: LLM
Stable-dep-of: 248b5819591c ("ksmbd: fix use-after-free after a failed durable reconnect") Signed-off-by: Sasha Levin <sashal@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
An SMB WRITE to an existing named stream can silently discard data after
its written range. ksmbd stores streams as xattr values, but the write
path passes offset + count as the length of the replacement xattr even
when the old stream is longer. Writing 26 bytes at offset 0 to a 60-byte
stream reports 26 bytes written while discarding the remaining 34 bytes.
Keep the existing xattr length when an in-place write ends before EOF.
Reject writes that cross XATTR_SIZE_MAX rather than storing only the
portion that fits while reporting the full requested count.
Commit 4ea0bb8aaedf ("ksmbd: handle set/get info file for streamed file")
intentionally skipped ordinary inode truncation for stream handles: an
EOF SetInfo on an ADS had truncated the base file. That fixed the base
file corruption but left stream EOF changes reporting success without
resizing the stream. Handle these requests by resizing only the stream
xattr; the base file size remains untouched. Zero-fill stream extensions.
This is needed alongside the write fix: a short write's accidental
truncation previously masked an ignored explicit EOF change. The stream
resize helper returns xattr errors directly rather than using the
base-file truncate path's EBADF conversion.
Fixes: f44158485826 ("cifsd: add file operations") Fixes: 4ea0bb8aaedf ("ksmbd: handle set/get info file for streamed file") Cc: stable@vger.kernel.org Signed-off-by: DaeMyung Kang <charsyam@gmail.com> Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ sashal: Used non-const mnt_idmap pointers in stream write and truncate helpers to match existing xattr APIs. ] Signed-off-by: Sasha Levin <sashal@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
SMB stream names are case-insensitive, but ksmbd stores each named
stream in an xattr whose name is case-sensitive. Opening an existing
stream finds its xattr with a case-insensitive match, yet the handle
keeps the name as the client spelled it, and every later operation that
needs an exact name uses that spelling:
- a WRITE or an end-of-file change creates a second xattr, so a stream
created as "Foo" and written through "foo" ends up stored twice, and
which value a later lookup returns depends on xattr list order;
- delete-on-close and delete-pending removal can fail with -ENODATA,
or remove only a case-variant copy and leave the original;
- the share mode check compares stream names with strcmp(), so two
opens of the same stream that differ only in case do not conflict.
Have ksmbd_vfs_casexattr_len() copy the matching xattr's name into the
handle when the stream is opened, so later operations use the name
already on disk. The match must have the same length as the name it
replaces; the stream lookup passes a length that includes the
terminating NUL, which already guarantees that, and the check makes the
copy safe for any caller. A stream that does not exist yet keeps the
client's spelling, as before.
smb2_rename() compares and looks up fp->stream.name case-insensitively,
so it behaves the same with either spelling.
Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3") Cc: stable@vger.kernel.org Signed-off-by: DaeMyung Kang <charsyam@gmail.com> Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ sashal: retained non-const mnt_idmap pointers and passed NULL for the new argument in the additional get_file_stream_info() caller ] Signed-off-by: Sasha Levin <sashal@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
When get_inode_acl() fails, it returns an ERR_PTR(), but
ksmbd_acls_fattr() stored that pointer in smb_fattr without
checking for errors. Later callers then passed the error pointer
to security descriptor helpers or posix_acl_release(), resulting
in an invalid pointer dereference.
This was reproduced on an XFS-backed share when xfs_get_acl()
returned ERR_PTR(-ENOMEM). Querying the SMB ACL from a CIFS client
triggered the crash:
BUG: unable to handle page fault for address: fffffffffffffff8
RIP: smb_acl_sec_desc_scratch_len+0x58/0x90 [ksmbd]
Call Trace:
smb2_query_info+0x40d/0x17c0 [ksmbd]
handle_ksmbd_work+0x1ca/0x770 [ksmbd]
Fix this by checking the return values from get_inode_acl() in
ksmbd_acls_fattr(). Treat -EOPNOTSUPP as indicating that no ACL is
available, and propagate all other errors to the callers. Update
smb2_open() and smb2_get_info_sec() to handle these errors.
Cc: stable@vger.kernel.org Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3") Assisted-by: Codex:gpt-5.6-sol Reviewed-by: ChenXiaoSong <chenxiaosong@kylinos.cn> Signed-off-by: Henry Hu <huhai@kylinos.cn> Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ sashal: Retained the non-const struct mnt_idmap * parameter in ksmbd_acls_fattr() to match the existing UID/GID mapping helpers. ] Signed-off-by: Sasha Levin <sashal@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
ksmbd_close_fd_app_instance_id() supersedes a prior open that has the
same AppInstanceId. It reaches that open's session through opinfo->sess.
This pointer is not refcounted.
Session teardown detaches durable handles before it frees the session.
It does not detach a non-durable open. That open still points at the
session through opinfo->sess after the session is freed. Another session
can supersede the open at the same time. The supersede then takes a
write lock through the stale pointer, in the freed session's file table.
BUG: KASAN: slab-use-after-free in _raw_write_lock+0x71/0xd0
Call Trace:
_raw_write_lock+0x71/0xd0
ksmbd_close_fd_app_instance_id+0xd9/0x670 [ksmbd]
smb2_open+0x3e10/0xd910 [ksmbd]
Freed by task 212:
ksmbd_session_destroy+0x38d/0x480 [ksmbd]
Fix this by looking the session up by opinfo->session_id. The lookup
returns a reference, as smb2_break_collect_channels() does. Recheck that
opinfo->sess still points at it before using it.
Do the lookup without m_lock held. destroy_previous_session() takes
m_lock under the session table lock, and taking them in the other order
here would deadlock.
An oplock or lease break belongs to an open that can outlive its original
channel. A draining channel or stalled TCP writer can otherwise leave the
break pending until timeout or invalidate a durable open.
Snapshot the owner's live channels and try eligible connections with the
same notification. Track TCP delivery separately from the SMB ACK, retry
when a channel stops progressing, and share one break deadline. Run
ordinary break waits on a dedicated workqueue so blocked request
responses do not stall breaks.
Publish NONE before sending a level II break, which requires no ACK, so
an unsolicited ACK observes the completed level while TCP delivery is
pending.
Keep the first rename lease notification in the request context and
enqueue the interim writer only after the notification is accepted. Join
that work before returning so a blocked interim response does not stop
notification retries or release the request early.
A nonblocking break send must distinguish a PDU accepted by TCP from one
still queued in ksmbd. Retrying an accepted PDU can send duplicates, while
abandoning a partial send can corrupt the stream.
Queue owned PDU bytes when TCP cannot accept the full message. Track the
stream position through socket delivery and TCP ACK, and expose it to break
retries. Bound retained data and stop queued writes during teardown.
clear_and_wake_up_bit() was introduced by commit 8236b0ae31c8 ("bdi:
wake up concurrent wb_shutdown() callers.") to replace the open-coded
clear_bit_unlock() + smp_mb__after_atomic() + wake_up_bit() sequence.
Replace the sequence and drop the now-trivial wake_up_oplock_break()
wrapper, calling the helper directly at each call site.
Compound response handling pads the last response of a compound to an
8-byte boundary by growing the final iov and the RFC1002 length.
smb2_allocate_rsp_buf() allocates exactly response_sz. A command can
fill the response buffer to within 7 bytes of its end, for example a
QUERY_INFO whose output is bounded only by the space left. The padding
can then run past the allocation, and ksmbd_tcp_writev() reads those
bytes when it sends the response.
Allocate room for the padding when the request is a compound, as
smb2_read() and smb2_read_pipe() do for their payloads. response_sz is
unchanged, so commands still fill only up to it, and kvzalloc() zeroes
the padding.
smb2_allocate_rsp_buf() uses the MAX_CIFS_SMALL_BUFFER_SIZE
(448-byte) buffer for a single SMB2_CREATE response. That buffer also
holds a 4-byte length field, which only leaves 444 bytes for the SMB2
body.
The AAPL response made this buffer too small. After 8f1b796ff113, a
request with AAPL response contexts may need at least 456 bytes. In
the 456-byte case, create_aapl_rsp_buf() is appended last, clears 128
bytes, and writes 12 bytes past the allocation.
KASAN reports:
BUG: KASAN: slab-out-of-bounds in create_aapl_rsp_buf+0x31/0x6e0
Write of size 128 at addr ffff88800370954c by task kworker/0:0/9
...
create_aapl_rsp_buf+0x31/0x6e0
smb2_open+0x58f9/0xef10
...
smb2_allocate_rsp_buf+0x19d/0x370
...
The buggy address is located 332 bytes inside of
allocated 448-byte region [ffff888003709400, ffff8880037095c0)
Reserve enough space for any fixed CREATE response KSMBD can build.
Store the required allocation size in the per-dialect values table.
This keeps the small buffer for other commands and avoids using the max
transaction buffer for every CREATE.
Fixes: 8f1b796ff113 ("ksmbd: add AAPL kAAPL_SERVER_QUERY create context support") Assisted-by: Codex:gpt-5 Signed-off-by: Jérémy Jean <Jeremy.Jean@oss.cyber.gouv.fr> Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
Stable-dep-of: 714f27729121 ("ksmbd: fix out-of-bounds read when padding the final compound response") Signed-off-by: Sasha Levin <sashal@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
io_recv_finish() debits sr->mshot_total_len with min_t(int, sel->val,
sr->mshot_total_len). sel->val is the cumulative byte count of the
request: on a bundle retry the receive path adds sr->done_io back to the
return value, and the bundle branch in io_recv_finish() recovers the new
bytes with this_ret = sel->val - sr->done_io. The debit therefore uses
the wrong value after a bundle retry, and the int cast truncates a limit
above INT_MAX.
For an IORING_OP_RECV multishot request with optlen above INT_MAX, the
limit becomes negative when cast to int, so the first completion debits
the entire limit and ends the multishot with IORING_RECV_MSHOT_DONE
while the socket still holds data that covers the limit. With 120 bytes
queued, a 64-byte buffer and optlen 0x80000000, the first 64-byte CQE
lacks IORING_CQE_F_MORE and 56 bytes remain unread; the same setup with
optlen 0x7fffffff posts 64 and 56 bytes with F_MORE.
After a bundle retry, the bytes already debited for the previous
attempts are debited again, so the limit is exhausted early. With 1400
bytes queued, optlen 1000 and buffers of 600, 100, 100, 50, 50 and 200
bytes, the first attempt delivers 700 bytes and retries; the second
delivers 200 more, but the debit accounts for 900 and finishes the
request with a terminal 900-byte CQE while 500 bytes remain unread. The
limit could have been reached.
Debit only the bytes received by this invocation, sel->val -
sr->done_io, and compare as unsigned so a limit above INT_MAX is
accounted correctly. Non-bundle multishot requests keep sr->done_io at
zero, so their accounting is unchanged.
Fixes: 0ebc9a7ecf6a ("io_uring/net: Support multishot receive len cap") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Cheng Yongkang <teel4res@gmail.com> Link: https://patch.msgid.link/179328314078.648427.10086632105828535293@gmail.com
[axboe: fix-up near-by incorrect comment while in there] Signed-off-by: Jens Axboe <axboe@kernel.dk> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
io_timeout_cancel() posts the cancelled timeout's -ECANCELED CQE without
advancing ctx->cq_timeouts. io_timeout_fn() and io_kill_timeout()
advance it for every timeout CQE they post, and io_flush_timeouts()
computes the number of non-timeout completions as
seq = cached_cq_tail - cq_timeouts
to compare against each off timeout's target_seq. The cancelled
timeout's CQE is therefore counted as a regular completion, so every
cancellation makes an already armed off timeout fire one completion
early.
A ring with a keep-alive timeout of off=4 completes it after two NOPs
when one off=100 victim is cancelled through IORING_OP_ASYNC_CANCEL, and
before any NOP when two victims are cancelled. The cancel CQE should
count, but the cancelled timeouts' -ECANCELED CQEs must not: the
expected counts are three and two NOPs respectively.
Advance cq_timeouts when io_timeout_extract() succeeds, under
timeout_lock and before the -ECANCELED completion is queued, matching
io_timeout_fn() and io_kill_timeout(). The -ENOENT and -EALREADY paths
post no new timeout CQE and keep their accounting. Both the
ASYNC_CANCEL and the TIMEOUT_REMOVE path go through io_timeout_cancel().
Fixes: bfe68a221905 ("io_uring: off timeouts based only on completions") Cc: stable@vger.kernel.org Assisted-by: LLM Signed-off-by: Cheng Yongkang <teel4res@gmail.com> Link: https://patch.msgid.link/179328314078.648427.13761781546953594668@gmail.com Signed-off-by: Jens Axboe <axboe@kernel.dk> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
An IOPOLL ring without DEFER_TASKRUN can be reaped by a task other than
the one that submitted the I/O. If a polled request is marked
REQ_F_REISSUE, io_free_batch_list() calls io_queue_iowq() with the
original tctx. Ordinary task exit can tear down tctx->io_wq after
draining only the tracked requests. The live request pins the task, but
not its io-wq, so the foreign task can race io_wq_put_and_exit() and
enqueue through a freed or NULL queue.
Forward foreign userspace enqueues to the owning task before accessing
tctx->io_wq. Use a dedicated task_work callback so reissues still go
straight to io-wq, and fail them if task_work is running in cancellation
mode. Preserve the existing PF_KTHREAD cancellation path. This also
covers the other callers of io_queue_iowq() without changing the
worker-owned enqueue path.
io_sq_thread_stop() wakes the SQPOLL thread and waits for it to exit.
The thread belongs to the thread group that created the ring, so a
SIGSTOP or the cgroup freezer holds it in get_signal(), and the wake up
doesn't change that. io_ring_exit_work() then sleeps in that wait until
someone continues or kills the process. iou_exit has 64 slots, so 64
closed SQPOLL rings of a stopped process keep every other ring from
being freed, for everyone.
Don't wait. Set the stop bit, wake the thread, and let it exit when it
gets to run again. The sqd can now outlive its last ring, so give it a
second refcount with one reference for the rings and one for the thread,
and free it with the last one. The thread can't reach a freed ring,
rings leave ctx_list before dropping their reference, and the io-wq hash
is refcounted.
Fixes: 16efa4fce3b7 ("io_uring: allow IO worker threads to be frozen") Signed-off-by: Chris Mason <mason@kernel.org> Signed-off-by: Jens Axboe <axboe@kernel.dk> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
A task other than the owner can free a request, io_ring_exit_work()
running the local task_work of a DEFER_TASKRUN ring for example, or
io_do_iopoll() reaping completions. io_put_task() then takes the else
branch:
percpu_counter_sub(&tctx->inflight, 1);
if (unlikely(atomic_read(&tctx->in_cancel)))
wake_up(&tctx->wait);
put_task_struct(tctx->task);
The first line is what lets the owner leave io_uring_cancel_generic(),
and on exec it frees the tctx right after. Nothing holds that off for
the remaining three lines, the task reference only covers a tctx freed
along with the task_struct. It used to work out because
io_uring_del_tctx_node() took the uring_lock that the freeing side holds
across io_put_task(), until that moved to tctx_lock.
Free the tctx with kfree_rcu(), and enter an RCU read section in
io_put_task() before the count is dropped.
Fixes: 5623eb1ed035 ("io_uring/tctx: add separate lock for list of tctx's in ctx") Signed-off-by: Chris Mason <mason@kernel.org> Signed-off-by: Jens Axboe <axboe@kernel.dk> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
bpf_io_uring_submit_sqes() calls io_submit_sqes() from inside the loop
program, with current->bpf_ctx set, and requests issued inline run with
it set too. The socket code uses has_current_bpf_ctx() to recognize
calls from bpf_setsockopt() and friends, where the caller holds the
socket lock and has already been vetted, and skips both.
So a SOCKET_URING_OP_SETSOCKOPT from the SQ passes sockopt_capable()
without the capability, and runs without lock_sock(). A task with no
capability can set SO_MARK, IP_TRANSPARENT or TCP_REPAIR, and two
threads changing IP_OPTIONS on one socket, one through the ring, double
free in no time. SOCK_DESTROY via IORING_OP_SENDMSG ends up in
tcp_abort() without the lock the same way.
Clear the run context around io_submit_sqes(). The SQEs come from
userspace and must be issued like those of any other ring. They still
run inside the program's RCU tasks trace read section, so a request
that sleeps there holds up that grace period, but other request types
do that already.
A failed xa_store() can leave nodes without entries in the tree, and
erasing every entry doesn't free those. An XArray needs xa_destroy()
before it goes away, even an empty one. That was dropped for tctx->xa in
commit ca6484cd308a ("io_uring: no need to call xa_destroy() on empty
xarray") over a lockdep report from freeing the tctx in softirq context,
and ctx->personalities never had it.
Now that the nodes are charged, a store can fail at memory.max and the
leaked nodes stay charged. Call xa_destroy() in io_uring_clean_tctx(),
which the task runs itself in process context before the tctx is freed,
in the error path of __io_uring_add_tctx_node(), and for
ctx->personalities in io_ring_ctx_free().
Fixes: ca6484cd308a ("io_uring: no need to call xa_destroy() on empty xarray") Signed-off-by: Chris Mason <mason@kernel.org> Signed-off-by: Jens Axboe <axboe@kernel.dk> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The io_tctx_node allocated the first time a task touches a ring, and
the XArray nodes behind tctx->xa and ctx->personalities, are plain
GFP_KERNEL. tctx->xa is indexed by the ring pointer, so nearly every
entry needs nodes of its own, and a task gets one entry per ring it has
used. 642 threads on 4000 rings held 2.3GB with 59MB charged against a
64MB memory.max.
Allocate the node with GFP_KERNEL_ACCOUNT and set XA_FLAGS_ACCOUNT on
both XArrays.
The io_mapped_ubuf of a registered buffer has one bio_vec per page,
unless the pages coalesce into huge pages. Huge pages only count against
RLIMIT_MEMLOCK once per ring, so a buffer that maps the same 2MB folio
over and over in a way that defeats coalescing gets a full bvec array
per registration while only the one folio counts as locked. 1GB of that
registered in 100 slots took several times a 64MB memory.max, with 2.6MB
charged.
Allocate the io_mapped_ubuf and the io_rsrc_node with
GFP_KERNEL_ACCOUNT. An object reused from the ring caches stays charged
to whoever allocated it first, same as the io_kiocb cache.
io_wq_exit_start() sets IO_WQ_BIT_EXIT, but worker creation task_work
queued before that stays queued until io_wq_exit_workers() cancels it.
In between the task runs its task_work while canceling requests, and a
worker can still get created.
That's a problem for exec. begin_new_exec() calls io_uring_task_cancel()
after de_thread(), when it's supposedly the only thread left, and
io_wq_exit_workers() only waits for ->worker_done, which a worker
completes before do_exit(). So the exiting worker is still in the thread
group, using the mm, files and sighand, while exec replaces them. Easy
to hit with a signal pending when create_io_thread() fails and the retry
gets queued right before execve().
Cancel the queued creation task_work as soon as the exit bit is set.
Pending work that isn't otherwise canceled now ends with -ECANCELED when
the io-wq is destroyed, rather than depending on whether the task
happened to run its task_work first.
Fixes: 685fe7feedb9 ("io-wq: eliminate the need for a manager thread") Signed-off-by: Josef Bacik <josef@toxicpanda.com>
[axboe: the barrier is already upstream, see 0e5663856b69, only the
cancel is new] Signed-off-by: Jens Axboe <axboe@kernel.dk> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
ecb6817b769f ends the drain when the dispatched drain request has posted
its CQE and nothing else is deferred. But the deferred list is processed
in between, and if the request it starts is itself a drain request, the
drain is over before that one has even run. A request submitted after
that point then runs ahead of it:
1. P0 in flight, D1 and D2 (both IOSQE_IO_DRAIN) deferred behind it
2. P0 completes, D1 is started
3. D1 completes, drain_done is set, D2 is started, the list is empty
4. IO_RING_F_DRAIN_ACTIVE is cleared with D2 still in flight
Anything submitted now bypasses the drain. The same happens with D2 as
the head of a link, as those aren't tracked in ->drain_req at all.
Have io_queue_deferred() report whether it started a drain request, and
don't end the drain if it did. Starting non-drain requests and ending it
is still fine, they were only waiting on the drain request that just
completed.
Fixes: ecb6817b769f ("io_uring: end the drain when the drain request completes") Reported-by: Karl Mehltretter <kmehltretter@gmail.com> Link: https://lore.kernel.org/io-uring/20261027043323.98916-1-kmehltretter@gmail.com/ Cc: stable@vger.kernel.org Signed-off-by: Jens Axboe <axboe@kernel.dk> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
IORING_OP_CONNECT on an O_NONBLOCK AF_UNIX stream socket retries a
connect that fails with -EAGAIN because the listener's backlog is full.
Polling the client socket doesn't help: an unconnected stream socket
reports EPOLLOUT and EPOLLHUP right away, before the backlog drains. So
io_uring retries the connect until the apoll retry limit is hit, then
punts the request to io-wq. With a full backlog, io_connect() runs 128
times in the submitting task and once more in a new io-wq worker. That
worker stays in the task's thread group, so a later
unshare(CLONE_NEWUSER) fails with -EINVAL.
None of this changes the result. __sys_connect_file() adds the socket's
own O_NONBLOCK to every attempt, so the attempt from io-wq fails with
-EAGAIN as well. That -EAGAIN becomes the CQE result, and connect(2)
returns the same -EAGAIN.
Let's complete the request with -EAGAIN right away when the socket has
O_NONBLOCK set, like connect(2) does. io_accept() already completes
-EAGAIN this way for IORING_ACCEPT_DONTWAIT. -EINPROGRESS still waits
for the connection to complete. A blocking socket still ends up in
io-wq, where the connect sleeps until the listener accepts.
When io_uring_register(2) is invoked with fd == -1, it dispatches
directly to io_uring_register_blind() without checking
current->io_uring_restrict.
As a result, a task with per-task register restrictions installed via
IORING_REGISTER_RESTRICTIONS can still invoke blind registration opcodes
such as IORING_REGISTER_SEND_MSG_RING even when those opcodes are not in
the task's allowed register_op bitmap.
Check current->io_uring_restrict->register_op in
io_uring_register_blind() before dispatching blind registration opcodes.
When an IORING_OP_SOCKET request is prepared in io_socket_prep(),
sock->type retains creation flags such as SOCK_CLOEXEC and SOCK_NONBLOCK
until __sys_socket_file() masks them off with SOCK_TYPE_MASK during
execution.
However, io_socket_bpf_populate() copies sock->type into
bctx->socket.type without masking off ~SOCK_TYPE_MASK. As a result, a
cBPF filter inspecting bctx->socket.type against socket types such as
SOCK_DGRAM or SOCK_STREAM can be bypassed by ORing SOCK_CLOEXEC or
SOCK_NONBLOCK into the socket type.
Mask sock->type with SOCK_TYPE_MASK when populating bctx->socket.type.
io_recvmsg() takes the transfer length from the ring provided buffer when
sqe->len is 0, and such a buffer can be up to 4G. min_ret is an int, so 2G
or more makes it negative and the (ret < min_ret) block is skipped, and the
oversized length reaches the socket layer unchanged: an empty socket then
completes with 0 instead of arming poll, and a short read is reported as
complete. Clamp the length to MAX_RW_COUNT, as io_recv() does.
Fixes: c7fb19428d67 ("io_uring: add support for ring mapped supplied buffers") Signed-off-by: Yichong Chen <chenyichong@uniontech.com> Link: https://patch.msgid.link/20261023112209.87979-1-chenyichong@uniontech.com Signed-off-by: Jens Axboe <axboe@kernel.dk> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
io_ring_buffers_peek() flags the request with REQ_F_BL_EMPTY if the
buffers it picked were the last ones available, comparing head to tail.
When the loop breaks because max_len was exhausted the buffer was picked,
but head is left pointing at it, so the flag isn't set if it was the last
buffer. A bundle receive then retries, finds no buffer, and the request,
which has received data, is marked as failed on account of the -ENOBUFS.
That severs a link, and ends a multishot.
In the next patch I will switch drvdata from static global to a
devm_kzalloc struct. In preparation for that, move the led_classdev_mc
to be a member of the gos_cfg_drvdata struct. As part of that effort,
provide a constant name when accessing it and access the led_classdev
through the led_classdev_mc.
Fixes: be6d7dbb368ba840d7 ("HID: hid-lenovo-go-s: Add RGB LED control interface") Cc: stable@vger.kernel.org Signed-off-by: Derek J. Clark <derekjohn.clark@gmail.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Currently this driver registers attributes before the MCU is ready to
accept commands. This can lead to attribute access that blocks the MCU
in some rare cases.
Move attribute construction to gos_cfg_setup, after the device has been
queried. Gate creation to drvdata.gp_registered and
drvdata.rgb_registered so a resume before setup has run doesn't prevent
attribute creation or attempt to re-register the same attributes.
Fixes: a23f3497bf208c59ad ("HID: hid-lenovo-go-s: Add Lenovo Legion Go S Series HID Driver") Cc: stable@vger.kernel.org Signed-off-by: Derek J. Clark <derekjohn.clark@gmail.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
mcu_property_out() reinits send_cmd_complete immediately after a
timeout is detected, before the next command that reuses it is sent.
If the MCU's reply to the timed-out command arrives after this reinit
but before the next command's wait begins, it silently satisfies the
next, unrelated command's wait instead of the one it actually answers,
handing that caller stale data with no way to detect the mismatch.
Track when a command has timed out via cmd_orphaned. Before the next
command reuses the completion, wait a bounded 25ms for a stale reply
to arrive and be consumed, then unconditionally clear the flag and
reinit the completion. This does not fully eliminate the window in
which an unrelated reply could still be received, but bounds it to
a short interval right before a new command is sent. Behavior matches
the solution to the same problem in hid-msi.
Fixes: a23f3497bf208c59ad ("HID: hid-lenovo-go-s: Add Lenovo Legion Go S Series HID Driver") Cc: stable@vger.kernel.org Signed-off-by: Derek J. Clark <derekjohn.clark@gmail.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Currently a device can suspend while delayed work is pending or
executing. Cancel delayed work if it was pending and restart it if it
hasn't run yet. Gate access to show/store functions behind a bool to
prevent access prior to cfg_setup() being completed.
Fixes: a23f3497bf208c59ad ("HID: hid-lenovo-go-s: Add Lenovo Legion Go S Series HID Driver") Cc: stable@vger.kernel.org Signed-off-by: Derek J. Clark <derekjohn.clark@gmail.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Currently mcu_property_out() blanket returns 0, discarding the ret
value and any errors with it. Wait completion returns a positive value
when it is not timed out, which would error on all successes, so if it
is positive return the ret value from the raw event handler. Only if
it is 0 set it to -EBUSY, otherwise pass the actual error.
Fixes: a23f3497bf208c59ad ("HID: hid-lenovo-go-s: Add Lenovo Legion Go S Series HID Driver") Cc: stable@vger.kernel.org Signed-off-by: Derek J. Clark <derekjohn.clark@gmail.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
hid_gos_cfg_remove() calls a mutex before canceling delayed work. That
delayed work function calls mcu_property_out(), which holds the same mutex.
Prevent deadlock my removing the mutex prior to stopping the work.
Additionally, since cancel_delayed_work has the potential to re-arm,
switch to disable_delayed_work.
Fixes: a23f3497bf208c59ad ("HID: hid-lenovo-go-s: Add Lenovo Legion Go S Series HID Driver") Cc: stable@vger.kernel.org Signed-off-by: Derek J. Clark <derekjohn.clark@gmail.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The raw event callback runs before HID core validates and zero-pads the
report. It passes the buffer to a helper which inspects data[0] and, for a
special report, reads the complete struct savu_mouse_report_special. A
truncated report can therefore cause an out-of-bounds read.
Require enough data for the special report before calling the helper.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw-event length validation to hid-asus.
Fixes: 6a2a6390cf09 ("HID: roccat: add support for Roccat Savu") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Benjamin Tissoires <bentiss@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The raw event callback runs before HID core validates and zero-pads the
report. It reads the report number without checking the received length
and passes matching data to roccat_report_event(), which copies a complete
struct ryos_report_special. A truncated report can therefore cause an
out-of-bounds read and expose adjacent data through the Roccat character
device.
Require a complete special report before inspecting or forwarding it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw-event length validation to hid-asus.
Fixes: 6f3a19360545 ("HID: roccat: add support for Ryos MK keyboards") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Benjamin Tissoires <bentiss@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The raw event callback runs before HID core validates and zero-pads the
report. It passes the buffer to helpers which inspect data[0] and read a
complete struct pyra_mouse_event_button for button reports. A truncated
report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw-event length validation to hid-asus.
Fixes: cb7cf3da0daa ("HID: roccat: add driver for Roccat Pyra mouse") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Benjamin Tissoires <bentiss@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The raw event callback runs before HID core validates and zero-pads the
report. It passes the buffer to helpers which inspect data[0] and read a
complete struct kovaplus_mouse_report_button for button reports. A
truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw-event length validation to hid-asus.
Fixes: 0e70f97f257e ("HID: roccat: Add support for Kova[+] mouse") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Benjamin Tissoires <bentiss@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The raw event callback runs before HID core validates and zero-pads the
report. It reads the report number without checking the received length
and passes matching data to roccat_report_event(), which copies a complete
struct konepure_mouse_report_button. A truncated report can therefore
cause an out-of-bounds read and expose adjacent data through the Roccat
character device.
Require a complete button report before inspecting or forwarding it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw-event length validation to hid-asus.
Fixes: 8936aa31cd5f ("HID: roccat: add support for Roccat Kone Pure gaming mouse") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Benjamin Tissoires <bentiss@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The raw event callback runs before HID core validates and zero-pads the
report. It passes the buffer to helpers which inspect data[0] and, for a
button report, read the complete struct koneplus_mouse_report_button. A
truncated report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw-event length validation to hid-asus.
Fixes: 47dbdbffe15b ("HID: roccat: Add support for Roccat Kone[+] v2") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Benjamin Tissoires <bentiss@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The raw event callback runs before HID core validates and zero-pads the
report. It passes the buffer to helpers which inspect data[0] and, for a
button report, read the complete struct isku_report_button. A truncated
report can therefore cause an out-of-bounds read.
Require enough data for the button report before calling either helper.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw-event length validation to hid-asus.
Fixes: d41c2a7011df ("HID: roccat: Add support for Isku keyboard") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Benjamin Tissoires <bentiss@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The wired Anne Pro 2 identifying as 04d9:a292 stops delivering keyboard
input after a period of inactivity. Unplugging and reconnecting the
keyboard restores input.
Keeping ObinsKit running prevents the problem. A read-only userspace
reader that keeps USB HID interface 1 open also prevents it, as does
usbhid.quirks=0x04d9:0xa292:0x00000400 without either application running.
Commit ca28aff0e1dc ("HID: quirks: Always poll Obins Anne Pro 2
keyboard") added HID_QUIRK_ALWAYS_POLL for product ID a293.
The variant identifying as 04d9:a292 exhibits the same symptom.
Apply the quirk to this product ID as well.
The HID core invokes raw_event callbacks before validating the report
length. pxrc_raw_event() reads byte seven and writes bytes one and seven
without checking that the report contains those bytes.
A one-byte input report reproduced the first invalid access under KASAN:
BUG: KASAN: slab-out-of-bounds in pxrc_raw_event+0x161/0x260
Read of size 1 by task hidtrigger/90
Call Trace:
pxrc_raw_event+0x161/0x260
kasan_report+0x139/0x170
Require all eight bytes before reading or rewriting the report.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw_event length validation to hid-asus.
The HID core invokes raw_event callbacks before validating the report
length. Prodikeys reports 0x01 and 0x04 are passed to handlers that always
read bytes one through three, regardless of the supplied size. A truncated
report can therefore cause an out-of-bounds read.
Require four bytes for the two fixed-format reports. Keep report 0x03 on
its existing variable-length path, which derives the number of note pairs
from size and only accesses complete pairs.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw_event length validation to hid-asus.
MCP2221 responses are 64-byte reports, but mcp2221_raw_event() currently
accepts any report of at least four bytes. Several response handlers read
far beyond that minimum. In particular, the I2C status response reads
offset 20 and copies ADC samples starting at offset 50. Other GPIO, SRAM,
and flash response handlers also access fixed offsets beyond byte three.
The HID core invokes raw_event callbacks before validating the report
length, so a truncated response can cause an out-of-bounds read. Require a
complete protocol report before dispatching any response handler.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw_event length validation to hid-asus.
Fixes: 67a95c21463d ("HID: mcp2221: add usb to i2c-smbus host bridge") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The writable gpio_mode_enforce parameter can change between probe and
remove.
If it changes from false to true after probe, remove skips cancellation
of init_work. Pending or running work can then access devm-managed
driver state after teardown. Changing it from true to false can make
remove cancel an uninitialized delayed work item.
Initialize init_work whenever IIO is reachable and cancel it
unconditionally on remove. Keep the parameter check only for scheduling
the initialization.
The false-to-true cancellation gap was previously reported by Sashiko.
We also encountered this issue during our static-analysis research.
The HID core invokes raw_event callbacks before validating the report
length. mcp2200_raw_event() casts a READ_ALL response to struct
mcp_read_all_resp and reads fields through offset ten without checking that
the response contains the structure.
A one-byte READ_ALL response reproduced the issue under KASAN:
BUG: KASAN: slab-out-of-bounds in mcp2200_raw_event+0x24b/0x3a0
Read of size 1 by task hidtrigger/89
Call Trace:
mcp2200_raw_event+0x24b/0x3a0
kasan_report+0x139/0x170
Reject an incomplete READ_ALL response with a protocol error before reading
its fields. The common completion path then wakes the command waiter with
the error instead of leaving it to time out.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw_event length validation to hid-asus.
Fixes: 740329d7120f ("HID: mcp2200: added driver for GPIOs of MCP2200") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The HID core invokes raw_event callbacks before validating the report
length. For an unnumbered keyboard report, logi_dj_raw_event() uses the
second byte as temporary storage while prepending a report ID. A one-byte
report therefore makes both the initial write and the later restoration
access data beyond the received report.
Reject unnumbered keyboard reports that do not provide the temporary byte.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw_event length validation to hid-asus.
Fixes: 74808f9115ce ("HID: logitech-dj: add support for non unifying receivers") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The HID core invokes raw_event callbacks before validating the report
length. elo_raw_event() only checks the first-byte packet marker before
elo_process_data() reads coordinates, flags, and pressure through offset
seven. A truncated packet beginning with the expected marker can therefore
cause an out-of-bounds read.
Require the complete eight-byte SmartSet packet before parsing it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw_event length validation to hid-asus.
Fixes: d23efc19478a ("HID: add driver for ELO 4000/4500") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The HID core invokes raw_event callbacks before validating the report
length. cp2112_raw_event() reads every field of a transfer status response
without checking size. For a data response, it reads the length at offset
two and copies that many bytes from offset three, again without ensuring
that the input report contains them.
Require a complete transfer status structure. For data responses, first
require the header and then ensure the clamped payload length fits in the
received report before copying it.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw_event length validation to hid-asus.
The HID core invokes raw_event callbacks before validating the report
length. cougar_raw_event() reads the key code and action from offsets one
and two without checking that those bytes are present. A short report on
the special interface can therefore cause an out-of-bounds read.
Consume reports that do not contain the action field before accessing the
fixed offsets, consistent with the callback's handling of other reports on
the special interface.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw_event length validation to hid-asus.
Fixes: b8e759b8f6da ("HID: cougar: Add support for the Cougar 500k Gaming Keyboard") Cc: stable@vger.kernel.org Signed-off-by: Jiale Yao <yaojiale02@163.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Syzbot reported an out-of-bounds shift (32-bit integer shifted left by
32) in the s32ton() routine in the HID core. This routine converts a
signed 32-bit integer to a signed n-bit integer, and it caps the value
of n at 32. But when n == 32 there's no need to do anything; it can
simply return the input value. This will avoid calculating (1 << n)
when n is 32, which was the cause of the invalid shift.
Signed-off-by: Alan Stern <stern@rowland.harvard.edu> Fixes: 69c02ffde6ed ("HID: core: clamp report_size in s32ton() to avoid undefined shift") Reported-by: syzbot+25a1d2907885b2182275@syzkaller.appspotmail.com Closes: https://lore.kernel.org/linux-usb/6ac9cbd8.a150a118.27e199.0025.GAE@google.com/ Tested-by: syzbot+25a1d2907885b2182275@syzkaller.appspotmail.com Cc: stable@vger.kernel.org Link: https://patch.msgid.link/dfa0aa1c-e55e-4316-8307-f72a07383634@rowland.harvard.edu Signed-off-by: Benjamin Tissoires <bentiss@kernel.org> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Commit 0919db9f3583 ("HID: asus: always fully initialize devices") added a
loop during asus_probe() to send keyboard feature report initializations
(asus_kbd_init) to all ASUS HID devices.
On ASUS laptops with I2C/HID touchpads (such as the ASUS E200HA), sending
keyboard feature reports (FEATURE_KBD_REPORT_ID) to touchpad endpoints
sends invalid feature requests to touchpad hardware, corrupting probe
state and causing the touchpad to become unresponsive.
Wrap the asus_report_id_init loop in an `if (!drvdata->tp)` check so
keyboard feature initialization only runs for actual keyboards.
Tested on ASUS E200HA (where touchpad functionality is fully restored)
and ASUS VivoBook Flip 14 TP401MA (confirming zero regressions).
Use report type from request node while sending feature and input reports
to HID core. The cli_data report type array is never assigned and
feature reports are sent as input reports.
The accelerometer HID report descriptor declares a trailing motion-state
field (usage 0x0451), but the Sensor Fusion Hub never reports this data,
so each accelerometer input report is one byte shorter than the descriptor
advertises.
This was previously harmless because hid-core zero-padded short reports.
Since commit 0a3fe972a7cb ("HID: core: Mitigate potential OOB by removing
bogus memset()") such reports are rejected instead:
hid-sensor-hub 0020:1022:0001.0003: Event data for report 1 was too short (15 vs 14)
As a result the accelerometer input events are dropped and screen
auto-rotation stops working on AMD SFH systems.
Remove the motion-state field from the accelerometer report descriptor and
drop the unused in_accel_shake_detection member, so the descriptor matches
the report actually provided by the hardware.
Fixes: 1434f9fc0e47 ("SFH: Create HID report to Enable support of AMD sensor fusion Hub (SFH)") Reported-by: Andrej Scek <scek.andrej@gmail.com> Closes: https://lore.kernel.org/linux-input/CADrS85612m-Hh-G4BJmOhy-y6r3Ni3kD8_GM-2QRBeWWEEZWuA@mail.gmail.com/ Cc: stable@vger.kernel.org Signed-off-by: Basavaraj Natikar <Basavaraj.Natikar@amd.com> Signed-off-by: Jiri Kosina <jkosina@suse.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
The HID core invokes raw_event callbacks before validating the report
length. zc_raw_event() verifies the report ID in byte zero and then reads
the key code from byte one for report IDs 0x02 and 0x03 without checking
that the second byte is present.
A one-byte report reproduced the issue under KASAN:
BUG: KASAN: slab-out-of-bounds in zc_raw_event+0x54c/0x580
Read of size 1 by task hidtrigger/93
Call Trace:
zc_raw_event+0x54c/0x580
__hid_input_report+0x2ef/0x3a0
inject_store+0x479/0x490 [faketrans]
Require both the report ID and key code before processing the report.
Commit 47669bec44fe ("HID: asus: refactor the two workqueues and init
sequence") added the same kind of raw_event length validation to hid-asus.
usbhid starts polling a device's interrupt IN endpoint on open
(usbhid_open() -> hid_start_in()). If the report descriptor declares no
input reports there is nothing to read there, so the poll is useless,
and on some composite devices it is also harmful.
The ASUS ROG N-Key keyboards expose a second, input-less interface used
only for RGB control via feature reports. Opening its hidraw node (any
hidraw reader does, including SDL/Steam Input or a plain cat) starts the
pointless IN poll and keypress reports on the keyboard interface get
dropped for as long as the node stays open: a lost key-down drops a
letter, a lost key-up leaves the key stuck. usbmon shows the dropped
reports never reach the URB layer.
The useless poll itself is long-standing; commit 4ac74ea68f64 ("HID:
asus: early return for ROG devices") is what exposes it on these
devices by keeping the input-less interface alive instead of ejecting
it, so its hidraw node can be opened and the poll started.
Skip the poll in usbhid_open() when the device has no input reports.
Feature reports and hidraw output keep working over the control and OUT
endpoints, so the interface is otherwise unaffected.
get_d_signext() has two compounding bugs since its introduction in 2010:
1. The extraction mask 0x8FF silently drops bits 8-10 of the 12-bit D
field (PPC ISA bits 21-23), corrupting any displacement that has any
of those bits set.
2. The sign-magnitude idiom "-(d & 0x7ff)" is wrong for two's-complement:
for D=0xFFC (encoding of -4) it returns -252 instead of -4.
Together these errors produce a wrong effective address for psq_l, psq_lu,
psq_st, and psq_stu whenever the displacement is negative or is a positive
value >= 0x100 with bits 8-10 set — essentially any real-world paired-
single stack-relative access.
The D field occupies the bottom 12 bits of the instruction word (confirmed
by the adjacent W and I extractions via inst_get_field(inst,16,16) and
inst_get_field(inst,17,19)). Replace the open-coded logic with the standard
sign_extend32(inst & 0xfff, 11), which correctly performs two's-complement
sign extension from 12 bits to 32 bits.
kvmppc_hv_find_lock_hpte() requires virtual-mode callers to run with
preemption disabled, because it can return with HPTE_V_HVLOCK still held
until the caller later unlocks the HPTE. Existing virtual-mode callers
in book3s_64_mmu_hv.c already follow that rule.
Two virtual-mode call paths do not:
1. kvmppc_handle_exit_hv() calls kvmppc_hpte_hv_fault() for hash-mode
data-side and instruction-side faults after guest exit, with
preemption already enabled. kvmppc_hpte_hv_fault() calls
kvmppc_hv_find_lock_hpte() directly.
2. kvmppc_pseries_do_hcall() executes virtual-mode handlers for HPT
hcalls via kvmppc_pseries_do_hpt_hcall() with preemption enabled.
The handlers for H_ENTER, H_REMOVE, H_READ, H_CLEAR_MOD, H_CLEAR_REF,
H_PROTECT, and H_BULK_REMOVE spin on try_lock_hpte() or lock_rmap(),
and H_ENTER also reaches kvmppc_do_h_enter(), which uses
arch_spin_lock() on kvm->mmu_lock. That raw lock choice is
intentional because kvmppc_do_h_enter() is also used by real-mode
callers, so the correct fix is to establish the proper preemption
context at the virtual-mode caller boundary.
If a vCPU thread is preempted while holding HPTE_V_HVLOCK, any other
thread on the same CPU trying to acquire the same bit-lock can spin
indefinitely. The same applies to lock_rmap() users and to the H_ENTER
path while holding the raw mmu_lock.
Fix this by adding preempt_disable()/preempt_enable() pairs around the
two kvmppc_hpte_hv_fault() call sites in kvmppc_handle_exit_hv(), and
around the kvmppc_pseries_do_hpt_hcall() invocation in
kvmppc_pseries_do_hcall(). Targeting only the HPT hcall helper avoids
wrapping non-HPT hcalls (such as H_RTAS, H_CONFER, H_REGISTER_VPA) that
perform page faults, blocking memory allocations, or context switches.
Wait to bind a memslot to a guest_memfd instance until *after* the memslot
is fully prepared, as creating the binding in guest_memfd will effectively
expose the memslot to readers. As pointed out by Sashiko, binding the
memslot before it's ready to be exposed to the rest of the world can break
various memslot assumption and rules. E.g. x86 could observe a NULL rmap
pointer if a PUNCH_HOLE hit the guest_memfd after the binding was created,
but before KVM made it through kvm_prepare_memory_region().
kvm_gmem_unbind() takes mapping->invalidate_lock only if the
get_file_active() succeeds. When the guest_memfd file is dying, its
reference count is already zero so get_file_active fails and the binding
is removed without holding the invalidate lock.
kvm_gmem_invalidate_{start,end}() checks f->bindings independently to
decide whether to begin or end KVM MMU invalidation. So, the bindings
must therefore remain stable between the two calls. Otherwise, unbind
can remove a binding after start increments mmu_invalidate_in_progress,
but before end finds the binding and decrements it.
Example, unbind race with memory failure:
CPU 0: memory failure CPU 1: memslot delete
---------------------------------- ---------------------------
(guest_memfd file is dying)
kvm_gmem_error_folio()
kvm_gmem_invalidate_start()
finds binding
mmu_invalidate_in_progress++
kvm_gmem_unbind()
get_file_active() fails
removes binding
kvm_gmem_invalidate_end()
no binding found
counter stays elevated
mmu_invalidate_retry() then returns 1 forever, so guest page faults
retry without ever installing a mapping and the guest hangs.
Remove the distinction between live and dying files in the unbind path.
Always use slot->gmem.file and take the invalidate lock when it's non-NULL.
Normal unbind callers hold slots_lock, which prevents release from clearing
the pointer or freeing the file state until unbind completes. Final VM
teardown can only see a NULL pointer because guest_memfd pins the KVM until
release has cleared all bindings.
Fixes: ae431059e75d ("KVM: guest_memfd: Remove bindings on memslot deletion when gmem is dying") Cc: stable@vger.kernel.org Reported-by: Sashiko <sashiko-bot@kernel.org> Closes: https://lore.kernel.org/all/20260728092027.225CF1F000E9@smtp.kernel.org Suggested-by: Sean Christopherson <seanjc@google.com> Signed-off-by: Shivank Garg <shivankg@amd.com> Reviewed-by: David Hildenbrand (Arm) <david@kernel.org> Link: https://patch.msgid.link/20260901-gmem-unbind-fix-v2-1-12febe1d2216@amd.com Signed-off-by: Sean Christopherson <seanjc@google.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Split binding a memslot to a guest_memfd instance into prepare() and
commit() phases so that KVM can separate preparing the memslot from binding
the memslot to the gmem instance, i.e. from committing the memslot. This
will allow waiting to commit the memslot+gmem binding until the memslot is
fully prepared, which is necessary as the memslot becomes reachable when
the binding is created.
As a bonus, drop the unwind-on-failure from the commit phase (other than
nullifying the bindings), as the only reason bind() did the full unwind is
because it technically didn't own the memslot, i.e. "needed" to leave
memslot in the same state it started in.
No functional change intended (the unwinding down on bind() failure was
effectively dead code since KVM simply deletes the memslot on failure,
i.e. there was nothing that could actually observe the unwind).
Cc: stable@vger.kernel.org Reviewed-by: David Hildenbrand (Arm) <david@kernel.org> Link: https://patch.msgid.link/20260922001332.1121266-5-seanjc@google.com Signed-off-by: Sean Christopherson <seanjc@google.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Enable Bus Lock VM exit functionality for TDX guests.
Bus Lock VM exit is an existing feature supported by KVM. Userspace can
enable Bus Lock VM exit through KVM_BUS_LOCK_DETECTION_EXIT when it's
reported as supported. However, KVM reports the support of this CAP
just based on the hardware capability but doesn't differentiate between
VMX and TDX. This leads to the issue that userspace can enable this cap
for TDX guests without getting an error, but the feature is not actually
enabled because KVM doesn't call the TDX module API to program the
relevant TD VMCS fields.
Enable Bus Lock VM exit for TDX guests by programming the
BUS_LOCK_DETECTION control in the TD VMCS and by adding the exit handler.
Note, there is no enumeration bit for this feature by TDX module because
all TDX modules support it and allow to set the TD VMCS as long as the
hardware supports the feature.
Fixes: 161d34609f9b ("KVM: TDX: Make TDX VM type supported") Cc: stable@vger.kernel.org Originally-by: Chenyi Qiang <chenyi.qiang@intel.com> Signed-off-by: Xiaoyao Li <xiaoyao.li@intel.com> Reviewed-by: Nikolay Borisov <nik.borisov@suse.com> Link: https://patch.msgid.link/20260819094903.3060020-9-xiaoyao.li@intel.com Signed-off-by: Sean Christopherson <seanjc@google.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
When handling the real Exit Reason, don't assume the upper 16 bits as
all-0 in tdx_to_vmx_exit_reason(), in preparation for enabling Bus Lock
VM exit.
When Bus Lock VM exit is enabled, the bit 26 of Exit Reason becomes
valid and it can be 1 with various exit reasons. Change the logic in
tdx_to_vmx_exit_reason() to check the 'basic' Exit Reason for correctness.
Also preserve bit[31:16] when changing the (basic) Exit Reason, to not
lose the information in bit[31:16].
Change the return type of tdx_to_vmx_exit_reason() to
"union vmx_exit_reason" for the convenience of manipulating the basic
field.
Fixes: c42856af8f70 ("KVM: TDX: Add a place holder for handler of TDX hypercalls (TDG.VP.VMCALL)") Cc: stable@vger.kernel.org Signed-off-by: Xiaoyao Li <xiaoyao.li@intel.com> Link: https://patch.msgid.link/20260819094903.3060020-5-xiaoyao.li@intel.com Signed-off-by: Sean Christopherson <seanjc@google.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Forcefully update the exit_reason to KVM's "standard" EXIT_REASON_UNDEFINED
if tdx_vcpu_run() bails without trying to run the vCPU because KVM needs to
wait for an in-progress S-EPT zap to complete. This avoids handling the
previous exit multiple times due to a stale exit_reason.
Fixes: 4b2abc49712b ("KVM: TDX: Kick off vCPUs when SEAMCALL is busy during TD page removal") Cc: stable@vger.kernel.org Signed-off-by: Xiaoyao Li <xiaoyao.li@intel.com> Link: https://patch.msgid.link/20260819094903.3060020-6-xiaoyao.li@intel.com
[sean: use EXIT_REASON_UNDEFINED, drop comment about bits 31:16] Signed-off-by: Sean Christopherson <seanjc@google.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Set bits 31:16 to 0 instead of all-1s when synthesizing an exit reason,
e.g. if the TDX Module never attempted VM-Enter, or when stuffing the exit
reason due to an unexpected "real" EPT Misconfig. Opportunistically use
VMX's KVM-defined EXIT_REASON_UNDEFINED (0xdead) instead of -1u.
KVM is going to support Bus Lock VM exit for TDX, after which bit 26 of
the Exit Reason becomes meaningful and indicates that a bus lock happened.
The existing synthesized Exit Reason, -1u, will cause a false positive in
that case. Change the synthesized Exit Reason from -1u to U16_MAX, so that
bits 31:16 are set to 0. This also avoids the potential issues when other
bits in 31:16 become valid in the future.
As a bonus, the check for synthesized Exit Reason in tdx_failed_vmentry()
becomes unnecessary. Just drop it.
Cc: stable@vger.kernel.org Signed-off-by: Xiaoyao Li <xiaoyao.li@intel.com> Reviewed-by: Rick Edgecombe <rick.p.edgecombe@intel.com> Reviewed-by: Binbin Wu <binbin.wu@linux.intel.com> Link: https://patch.msgid.link/20260819094903.3060020-4-xiaoyao.li@intel.com
[sean: use EXIT_REASON_UNDEFINED instead of another magic value] Signed-off-by: Sean Christopherson <seanjc@google.com> Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>