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

2026-09-21: 6.18/topics/logical-ino-costs combines the former backref-hang,
delayed-ref-fixes and logical-ino topics into one three-patch series
(reducing LOGICAL_INO costs): the add_all_parents() rewind-cycle hang, the
quadratic delayed-ref merge walk, and BTRFS_LOGICAL_INO_ARGS_COMMIT_ROOT.
Tree unchanged by the restructure.

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

Integration of topics/low-space with topics/stripe-alloc, in block-group.c
and space-info.c (octopus only from 2026-09-29; since 2026-10-29 it lives in
topics/low-space, which is restacked on topics/stripe-alloc: "btrfs: hold
block groups free for relocation" carries it; Zygo: "they all have to be
submitted in some order as patches, not merges"):
 - a group held for relocation counts only its claimable whole stripes
   as reserve (resynced at each commit-time stripe rescan); its trapped
   space is in bytes_stripe_unusable already, and counting it twice made
   the metadata space_info read over-full on a full raid6 filesystem;
 - ordinary data writers' whole-stripe admission excludes the held
   groups' stripes; relocation still sees them.
stripe_meta's bytes_stripe_reserve is NOT reduced by the held groups: it
is an admission margin that keeps tree blocks off the reserve's emergency
fallback, and without it a metadata fill consumed the reserve before any
relocation (dhive sresmn raid5/raid5, 2026-09-29).

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

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

Also merges '6.18/topics/allocator-hints' (topics/allocator-hints: Kai
Krakow's allocator hint series from kakra/rebase-6.18/btrfs-patches,
replacing the four hint patches formerly carried on zygo-6.18.x-zb64, plus
the UAPI-header fix and the device-replace fix).

Also merges '6.18/topics/read-policies' (topics/read-policies: Kai Krakow's
read policies and per-device read stats: CONFIG_BTRFS_READ_POLICIES,
queue and queue-adaptive policies, CONFIG_BTRFS_PER_DEVICE_IO_STATS).
Kconfig and sysfs.c conflicts with allocator-hints resolved as the union,
in kakra's order.

6.18/topics/logical-ino-costs gains kakra's "btrfs: avoid RCU stall during
backref list construction" (cond_resched in add_inline_refs/add_keyed_refs).

2026-10-10 (Zygo): topics/raid6-fixes replaced by 6.18/topics/raid56-disguise, the
6.18 backport of upstream 49ba3a3c0d67 ("btrfs: disguise single-data-RAID56 as
RAID1/RAID1C3"): btrfs maps 2-device RAID5 and 3-device RAID6 chunks as
RAID1/RAID1C3 and never calls lib/raid6 with three disks, so the x1
gen_syndrome fix and the raid6_pq.algo= test knob are no longer needed.

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

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

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

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

2026-10-17: 6.18/topics/raid56-scrub-replace commit messages aligned with misc-next
(misc-next starts the topic with Filipe Manana's -EIO fix; 6.18 already returns
-EIO there).  Tree unchanged.

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

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

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

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

2026-10-27 (Zygo: on 6.18, backports go at the head of the topic that uses
them): 6.18/topics/raid56-disguise is folded into the head of
6.18/topics/stripe-alloc and is no longer a separate parent; the upstream
backports in logical-ino-costs, raid56-fixes and read-repair-fixes move to
the head of their topics.  Candidate: + wbkick v5 (stripe-alloc).

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

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

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

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

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

The merge conflicts in fs/btrfs/scrub.c, with two neighbours: the new
scrub_pause_point() goes in front of scrub_raid56_parity_stripe(), where
topics/raid56-scrub-replace adds scrub_raid56_copy_parity_rows() (both
kept, the copy helper first), and in scrub_simple_mirror() the pause
point follows topics/replace-fixes' BTRFS_FS_ERROR() stop (kept, then
the new pause point in place of the old pause check).

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

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

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

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

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

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

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

PREFERRED_NONE devices still count: the allocator uses them as the last
tier.  Without CONFIG_BTRFS_ALLOCATOR_HINTS the data and metadata
estimates are identical and only one is computed.

The estimates have been hint-blind since "btrfs: add allocator_hint
mode", earlier in this series, taught the allocator the hints.

The fallback to fs_info->free_chunk_space (zoned filesystems, or a
failed estimate) and the reclaim thresholds that read it stay hint-blind.

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

6.18 port: needs the per-profile available space estimate backported
first (upstream 52fead5eb8a7, c84053d9f7f7, 2672a26a7551, v7.1); before
it, calc_available_free_space() divided fs_info->free_chunk_space, the
unallocated space of every device, by the profile's copy count, which is
hint-blind and also wrong for unequal devices without hints.

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

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

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

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

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

Taking chunk_mutex in the store also closes the race at the end of a
device replace: the finish moves the hint and the dirty bit to the
target under the same mutex, so a hint change on the source either
reaches the target or, once the source has the replace devid, returns
-EBUSY.  The replace target (devid 0, no dev item) still returns -EBUSY.
Also check sb_rdonly() before BTRFS_FS_OPEN, so a read-only mount
reports -EROFS rather than -EBUSY, and refuse seed devices, which are
read-only and not written by the commit-time update.

The store orders the new type before the dirty bit
(smp_mb__before_atomic(); the commit's test_and_clear_bit() is the other
half), and btrfs_update_device() reads the type with READ_ONCE(), so the
commit cannot write the old type and clear the bit on a weakly ordered
machine.

Assisted-by: Claude:claude-opus-5-5
7 days agobtrfs: allocator hints: keep the hint across device replace
Zygo Blaxell [Sun, 4 Oct 2026 04:44:58 +0000 (00:44 -0400)]
btrfs: allocator hints: keep the hint across device replace

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Before a pause, finish the queued stripes and release both paths, so that
a commit can only pass with nothing of the scrub's still referring to the
old commit root, and the next search starts from the new one.

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

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

[zygo: 6.18 backport: 6.18 has no pause point in scrub_raid56_parity_stripe(),
 so only the scrub_simple_mirror() one changes]

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

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

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

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

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

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

[zygo: 6.18 backport: clean pick on top of the previous patch.]

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

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

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

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

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

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

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

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

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

[zygo: 6.18 backport: on 6.18/topics/read-repair-fixes, whose head backports
 Qu Wenruo's 15ed4a938b30 (btrfs_repair_bbio_failure()); fs.h and disk-io.c
 differ in context only (compressed_write_workers, endio_freespace_worker).]

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Assisted-by: Codex:gpt-5
Assisted-by: Claude:claude-opus-5-5
9 days agobtrfs: apply the balance limit_min filter only to a limit range
Zygo Blaxell [Tue, 10 Nov 2026 04:34:16 +0000 (23:34 -0500)]
btrfs: apply the balance limit_min filter only to a limit range

The balance limit filter takes a single count (BTRFS_BALANCE_ARGS_LIMIT)
or a min..max range (BTRFS_BALANCE_ARGS_LIMIT_RANGE), and limit shares
its bytes with limit_min and limit_max in struct btrfs_balance_args.
__btrfs_balance() applies the limit_min check to every chunk, on the
assumption that limit_min is 0 unless a range was given.  With a single
limit it is not: on little-endian machines limit_min is the low 32 bits
of limit.

The check runs after should_balance_chunk() has decremented limit for
the chunk.  With limit=L and M chunks passing the other filters, L > M,
the counting pass counts M, and the i-th of those chunks (from 1) sees
limit_min = L - i, so it is skipped while M < L - i.  The first L - M - 1
chunks are skipped, and each of them still uses up one count of the
limit.  The balance relocates 2M + 1 - L chunks instead of M, and none
when L >= 2M + 1.  For example, limit=9 with 7 matching data chunks
relocates 6.  A limit no larger than the number of matching chunks is
not affected.

Apply the check only to a limit range: LIMIT_RANGE set and LIMIT not
set.  should_balance_chunk() applies the single limit when both flags
are set, so the minimum of the range does not apply then either.

Fixes: 12907fc79818 ("btrfs: extend balance filter limit to take minimum and maximum")
Assisted-by: Claude:claude-opus-5-5
11 days agobtrfs: honor FMODE_NOCMTIME when cloning 6.18/topics/nocmtime
Jeff Layton [Thu, 5 Nov 2026 20:07:45 +0000 (15:07 -0500)]
btrfs: honor FMODE_NOCMTIME when cloning

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

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

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

[zygo: 6.18 backport: 6.18's btrfs_clone_files() locks up to destoff +
len - 1 and passes 0 as no_time_update; context adjusted, the change
itself is unchanged]

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

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

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

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

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

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

[zygo: 6.18 backport: 6.18 still has the __btrfs_prealloc_file_range()
wrapper and btrfs_prealloc_file_range_trans() for the v1 space cache.
update_times goes through insert_prealloc_file_extent() and
__btrfs_prealloc_file_range(); btrfs_prealloc_file_range_trans() passes
true, so the v1 cache inode keeps updating its times as before.
btrfs_fallocate() context lacks the btrfs_is_shutdown() check]

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

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

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

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

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

[zygo: 6.18 backport: 6.18's btrfs_clone() takes struct inode * and
passes BTRFS_I(inode) to btrfs_replace_file_extents(); context adjusted,
the change itself is unchanged]

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

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

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

Skip the update for FMODE_NOCMTIME files too.

Fixes: e5e9b24ab8fa ("nfsd: freeze c/mtime updates with outstanding WRITE_ATTRS delegation")
Signed-off-by: Jeff Layton <jlayton@kernel.org>
Link: https://lore.kernel.org/r/20261105-delegts-btrfs-v1-1-a42a2b93cdc2@kernel.org
13 days agoLinux 6.18.62 v6.18.62
Greg Kroah-Hartman [Fri, 6 Nov 2026 18:17:37 +0000 (13:17 -0500)]
Linux 6.18.62

Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoxen-blkback: Avoid UAF when reading I/O statistics
Juergen Gross [Thu, 5 Nov 2026 07:27:38 +0000 (08:27 +0100)]
xen-blkback: Avoid UAF when reading I/O statistics

commit a02926f7c89bfc798ee9514e09694ff4279928a1 upstream.

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

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>
13 days agoxen-netback: defer xenvif_mcast_addr_list_free()
Jan Beulich [Fri, 6 Nov 2026 16:07:01 +0000 (17:07 +0100)]
xen-netback: defer xenvif_mcast_addr_list_free()

commit bfddc420afe827d9f06458cdf8087cd602f8c9cb upstream.

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

This is XSA-527 / CVE-2026-100081.

Fixes: b17075d5c198 ("xen-netback: fix race condition on XenBus disconnect")
Reported-by: kerhunt <kerhunt@proton.me>
Signed-off-by: Jan Beulich <jbeulich@suse.com>
Reviewed-by: Juergen Gross <jgross@suse.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoxen-netback: Fix UAF when reading statistics data
Juergen Gross [Fri, 6 Nov 2026 12:07:52 +0000 (13:07 +0100)]
xen-netback: Fix UAF when reading statistics data

commit 5fb756f1bbec7a3862dda5d79028bf656271804c upstream.

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.

This is XSA-526 / CVE-2026-100080

Reported-by: Yehyeong Lee <yhlee@isslab.korea.ac.kr>
Signed-off-by: Juergen Gross <jgross@suse.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoLinux 6.18.61 v6.18.61
Greg Kroah-Hartman [Fri, 6 Nov 2026 17:06:15 +0000 (12:06 -0500)]
Linux 6.18.61

Link: https://lore.kernel.org/r/20261104211043.516122098@linuxfoundation.org
Tested-by: SJ Park <sj@kernel.org>
Tested-by: Peter Schneider <pschneider1968@googlemail.com>
Tested-by: Wentao Guan <guanwentao@uniontech.com>
Tested-by: Ron Economos <re@w6rz.net>
Tested-by: Pavel Machek (CIP) <pavel@nabladev.com>
Tested-by: Brett A C Sheffield <bacs@librecast.net>
Tested-by: Florian Fainelli <florian.fainelli@broadcom.com>
Tested-by: Shuah Khan <skhan@linuxfoundation.org>
Tested-by: Miguel Ojeda <ojeda@kernel.org>
Tested-by: Barry K. Nathan <barryn@pobox.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agorust: bitmap: add MAX_LEN and MAX_INLINE_LEN constants
Alice Ryhl [Tue, 25 Nov 2025 13:59:37 +0000 (13:59 +0000)]
rust: bitmap: add MAX_LEN and MAX_INLINE_LEN constants

commit f5535d78e12600deb30a9fb3c628c425f0caec21 upstream.

To avoid hard-coding these values in drivers, define constants for them
that drivers can reference. Also, update all instances in bitmap.rs and
id_pool.rs that use these values to use the new constants.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Burak Emir <bqe@google.com>
Signed-off-by: Yury Norov (NVIDIA) <yury.norov@gmail.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agotun: Require CAP_NET_ADMIN to attach to an ownerless device
David Woodhouse [Tue, 20 Oct 2026 09:48:10 +0000 (10:48 +0100)]
tun: Require CAP_NET_ADMIN to attach to an ownerless device

commit ffdf678dd16610e3f006dac904bd37c09684673c upstream.

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>
13 days agoALSA: hda/realtek: Fix audio after Windows reboot on ASUS Q423SA
Scott Gauche [Mon, 5 Oct 2026 15:40:17 +0000 (11:40 -0400)]
ALSA: hda/realtek: Fix audio after Windows reboot on ASUS Q423SA

commit 8acd6469f42784f38872ad83b14c41152d986b63 upstream.

The ASUS Vivobook S 14 Q423SA-U5512 (DMI family S5406SA) with the
ALC294 codec has working analog audio when booted directly after a full
shutdown. After a warm reboot from Windows 11, audio works briefly during
Linux startup, then both the internal speakers and headphones become
silent. PCM playback continues without errors.

Coefficient 0x1b is 0x4e4b on a direct cold boot, but 0x4a4b after the
Windows warm reboot. Restoring bit 10 changes it back to 0x4e4b and
immediately enables both analog outputs. Speaker playback, headphone
playback, jack switching, cold boot, and suspend/resume were tested
successfully. The same 0x4a4b state and immediate recovery with 0x4e4b
were independently confirmed on another S5406SA with subsystem 1043:10c4.

The same coefficient write is already used by
ALC294_FIXUP_ASUS_COEF_1B for the ASUS UX431DA. That fixup cannot be
reused here because it chains to ALC289_FIXUP_ASUS_GA401 and applies
unrelated DAC routing and microphone pin configuration.

Add a model-specific fixup for subsystem 1043:10c4 and chain it to the
existing ALC2XX_FIXUP_HEADSET_MIC fixup instead.

Link: https://github.com/thesofproject/sof/issues/11051
Fixes: f2d08f3651fb ("ALSA: hda/realtek: Fix headset mic on ASUS Vivobook S14 S5406SA")
Signed-off-by: Scott Gauche <scott-dev@scottgauche.com>
Link: https://patch.msgid.link/20261005154017.1164657-1-scott-dev@scottgauche.com
Signed-off-by: Takashi Iwai <tiwai@suse.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoopp: fix use after free in _update_opp_table_clk()
Peter Griffin [Tue, 8 Sep 2026 12:37:27 +0000 (12:37 +0000)]
opp: fix use after free in _update_opp_table_clk()

commit 1f6de65e3314519ce462bfd3a1d29e918f97e4e5 upstream.

dev_pm_opp_put_opp_table() frees the opp_table which is subsquently used
by dev_err_probe(). This causes an Oops during boot on gs101-oriole.

cpu cpu0: error 000000006b6b6b6b: Couldn't find clock
Unable to handle kernel paging request at virtual address 006b6b6b6b6b6cd3
...
Hardware name: Oriole (DT)
pstate: 00400005 (nzcv daif +PAN -UAO -TCO -DIT -SSBS BTYPE=--)
pc : _of_add_table_indexed+0x80/0xbb0
lr : _of_add_table_indexed+0x6c/0xbb0
...
Call trace:
 _of_add_table_indexed+0x80/0xbb0 (P)
 dev_pm_opp_of_cpumask_add_table+0x70/0x120
 dt_cpufreq_probe+0x23c/0x480
 platform_probe+0x64/0xb8

Fixes: 84f05af0975c9 ("opp: Use clk_get_optional() to avoid leaving opp_table->clk as an error pointer")
Signed-off-by: Peter Griffin <peter.griffin@linaro.org>
Reviewed-by: Tudor Ambarus <tudor.ambarus@linaro.org>
[ Viresh: use return value of dev_err_probe() ]
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agonetfilter: conntrack: always lower timeout for non-closing RST packets
Pablo Neira Ayuso [Mon, 10 Aug 2026 08:18:22 +0000 (10:18 +0200)]
netfilter: conntrack: always lower timeout for non-closing RST packets

commit 73df81b38cb7f70a347a97370386378a86e53019 upstream.

The existing check might extend the timeout if the ESTABLISHED timeout
has been tuned to be lower than UNACK via sysctl. Reported by sashiko.

Fixes: bf80e6802273 ("netfilter: conntrack: tcp: use UNACK timeout for non-closing RST packets")
Signed-off-by: Pablo Neira Ayuso <pablo@netfilter.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agodrm/amdgpu/powerplay: Align get_tonga_state_array() header with prototype
Srinivasan Shanmugam [Thu, 25 Jun 2026 04:55:24 +0000 (10:25 +0530)]
drm/amdgpu/powerplay: Align get_tonga_state_array() header with prototype

commit 4986757d3207383c052689532e505edccc6df7c8 upstream.

The function header above get_tonga_state_array() still refers to
check_powerplay_tables() and does not describe all of the function
parameters.

Update it to match the current function prototype and include the
missing parameter description.

Fixes: 1ac24df78c56 ("drm/amd/pm: Validate Tonga PowerPlay state array bounds")
Cc: Yang Wang <kevinyang.wang@amd.com>
Cc: Hawking Zhang <Hawking.Zhang@amd.com>
Signed-off-by: Srinivasan Shanmugam <srinivasan.shanmugam@amd.com>
Reviewed-by: Yang Wang <lkevinyang.wang@amd.com>
Signed-off-by: Alex Deucher <alexander.deucher@amd.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoselftests: ublk: add missing gitignore for metadata_size binary
Alexander Atanasov [Sun, 25 Jan 2026 08:57:46 +0000 (08:57 +0000)]
selftests: ublk: add missing gitignore for metadata_size binary

commit 8e5bcc3a955a2cc4460b391f55d3b49905eb248e upstream.

A new utility metadata_size was added in
commit 261b67f4e347 ("selftests: ublk: add utility to get block device metadata size")
but it was not added to .gitignore. Fix that by adding it there.

While at it sort all entries alphabetically and add a SPDX license header.

Reviewed-by: Caleb Sander Mateos <csander@purestorage.com>
Fixes: 261b67f4e347 ("selftests: ublk: add utility to get block device metadata size")
Signed-off-by: Alexander Atanasov <alex@zazolabs.com>
Reviewed-by: Ming Lei <ming.lei@redhat.com>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agomedia: rc: Fix build failure with CONFIG_LIRC disabled
Sean Young [Wed, 23 Sep 2026 08:32:02 +0000 (09:32 +0100)]
media: rc: Fix build failure with CONFIG_LIRC disabled

commit 0c795849fd70d6bdb99aea5dd08d9b43128612f6 upstream.

commit 37efd09ba2c6 ("media: rc: Ensure registered is cleared in error
path") broke the build if CONFIG_LIRC was not enabled.

Fixes: 37efd09ba2c6 ("media: rc: Ensure registered is cleared in error path")
Reported-by: kernel test robot <lkp@intel.com>
Link: https://lore.kernel.org/oe-kbuild-all/202609230511.Em5Osw74-lkp@intel.com
Signed-off-by: Sean Young <sean@mess.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agomm/rmap: don't discard lazyfree THPs at PMD level
Zi Yan [Tue, 13 Oct 2026 02:20:16 +0000 (22:20 -0400)]
mm/rmap: don't discard lazyfree THPs at PMD level

commit 984c0700854e35779a2bcce6b02783e709b6efa2 upstream.

__discard_anon_folio_pmd_locked() clears a lazyfree THP's PMD before it
determines whether the folio can be discarded, and restores it if the
folio is dirty or has extra references.  It is done under only the PMD
lock and the anon_vma read lock inside try_to_unmap_one() and no mmap lock
is held.  The temporarily none PMD causes UAF.

A parallel munmap() or mremap() is supposed to serialize with it on the
PMD lock, but zap_pmd_range() (called by munmap()) and move_page_tables()
(called by mremap()) do not take the lock when they see the temporarily
none PMD and skip the PMD.  There is no more page table walk after the
none PMD is restored:

- munmap(): free_pgtables() waits in unlink_anon_vmas() for the anon_vma
  lock, then free_pmd_range() drops the restored PMD as bad without
  removing the rmap, so the folio keeps a stale mapcount.

- whole-VMA MREMAP_DONTUNMAP: dontunmap_complete() unlinks the source VMA
  from its anon_vma while the restored PMD still maps the folio.

- plain mremap(): the THP is not moved but unmapped, so the THP's data is
  lost.

In the first two cases, the folio stays mapped, but no VMA that maps it is
linked to its anon_vma.  When the anon_vma is freed, it is still reachable
when one rmap walks the folio.  Racing lazyfree reclaim against
MREMAP_DONTUNMAP as an unprivileged user reproduces a KASAN use-after-free
in folio_lock_anon_vma_read() as reported in the Closes link.

One solution is to use an invalidated PMD instead of a cleared one until
the discard is committed, but it needs arch fixes first.
1. GUP-fast still follows an invalidated PMD on riscv, LoongArch and s390.
2. sparc64 miscounts thp_pte_count when an invalidated PMD is set again or
   cleared.

To keep the fix simple for backport, stop discarding lazyfree THPs at PMD
level instead. try_to_unmap_one() splits the PMD and discards the folio at
PTE level.

unmap_huge_pmd_locked() and __discard_anon_folio_pmd_locked() are left in
place, unused, to minimize this fix for backport and the invalidated PMD
approach is planned as a follow-up series to use them again.

Link: https://lore.kernel.org/20261012-lazyfree-stable-fix-v2-1-6387d6e30063@nvidia.com
Fixes: 735ecdfaf4e8 ("mm/vmscan: avoid split lazyfree THP during shrink_folio_list()")
Signed-off-by: Zi Yan <ziy@nvidia.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Reported-by: Kyle Zeng <kylebot@openai.com>
Closes: https://lore.kernel.org/r/20261009165214.40212-2-kylebot@openai.com
Reviewed-by: Kyle Zeng <kylebot@openai.com>
Reviewed-by: Lance Yang <lance.yang@linux.dev>
Acked-by: David Hildenbrand (Arm) <david@kernel.org>
Reviewed-by: Lorenzo Stoakes (ARM) <ljs@kernel.org>
Tested-by: JongHyuk Kim(MalHyuk) <malhyuk97@gmail.com>
Link: https://lore.kernel.org/CADQRuqvXQ=YE=7T3oR66vTxE33pi=ygEeZKPTOU=cALZL0Figw@mail.gmail.com
Assisted-by: LLM
Cc: Rik van Riel <riel@surriel.com>
Cc: Liam R. Howlett <liam@infradead.org>
Cc: Vlastimil Babka <vbabka@kernel.org>
Cc: Harry Yoo <harry@kernel.org>
Cc: Jann Horn <jannh@google.com>
Cc: <stable@vger.kernel.org>
Signed-off-by: Zi Yan <ziy@nvidia.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agopps: generators: fix use-after-free when closing a removed device
Danish Khateeb [Wed, 4 Nov 2026 15:58:23 +0000 (10:58 -0500)]
pps: generators: fix use-after-free when closing a removed device

[ Upstream commit d19552611cb2eb6329826871565e5309bec2f288 ]

The cdev of a PPS generator is embedded in struct pps_gen_device, but
nothing ties the lifetime of that structure to the cdev: pps_gen is
freed by the release function of its device, and an open file holds a
device reference only until pps_gen_cdev_release() drops it.

When the generator is unregistered while /dev/pps-genN is open, that
put_device() drops the last reference and frees pps_gen, and __fput()
then calls cdev_put() on the freed cdev:

  BUG: KASAN: slab-use-after-free in cdev_put+0x53/0x60
  Read of size 8 at addr ffff88801383e138 by task ppsgen64/149
  Call Trace:
   cdev_put+0x53/0x60
   __fput+0x745/0xad0
   fput_close_sync+0xd9/0x1b0
   __x64_sys_close+0x86/0xf0
  ...
  Freed by task 149:
   kfree+0x25a/0x6d0
   device_release+0xca/0x3c0
   kobject_put+0x169/0x320
   pps_gen_cdev_release+0x51/0x80
   __fput+0x36a/0xad0

pps.c had the same bug, fixed in commit c79a39dc8d06 ("pps: Fix a
use-after-free").

Fix it the usual way: embed the struct device in pps_gen_device and
register both with cdev_device_add(). This makes the device the parent
of the cdev, so the cdev holds a device reference until the last file
is closed.

Fixes: 86b525bed275 ("drivers pps: add PPS generators support")
Cc: stable@vger.kernel.org
Assisted-by: LLM
Signed-off-by: Danish Khateeb <danishkhateeb03@gmail.com>
Acked-by: Rodolfo Giometti <giometti@enneenne.com>
Link: https://patch.msgid.link/20260929124937.51114-2-danishkhateeb03@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agopps: change pps_gen_class to a const struct
Jori Koolstra [Wed, 4 Nov 2026 15:58:22 +0000 (10:58 -0500)]
pps: change pps_gen_class to a const struct

[ Upstream commit 4dc0c899b14c3ea2c9b5f42b523301040d1c8100 ]

The class_create() call has been deprecated in favor of class_register()
as the driver core now allows for a struct class to be in read-only
memory. Change pps_gen_class to be a const struct class and drop the
class_create() call.

Signed-off-by: Jori Koolstra <jkoolstra@xs4all.nl>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Acked-by: Rodolfo Giometti <giometti@enneenne.com>
Link: https://patch.msgid.link/20260302142436.3292766-1-jkoolstra@xs4all.nl
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Stable-dep-of: d19552611cb2 ("pps: generators: fix use-after-free when closing a removed device")
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agomedia: ipu-bridge: Fix use-after-free in IVSC error path
Yibo Tan [Wed, 4 Nov 2026 15:58:03 +0000 (10:58 -0500)]
media: ipu-bridge: Fix use-after-free in IVSC error path

[ Upstream commit 3d42d1c82717f0853379b516a7fab54b636e09cc ]

ipu_bridge_get_ivsc_acpi_dev() returns an ACPI device with a reference
held. If no matching CSI device is found, ipu_bridge_check_ivsc_dev()
drops that reference before passing the device to dev_err(). Concurrent
CSI device and ACPI namespace removal can drop the other references,
making this the final put. dev_err() then reads the freed struct
acpi_device and its kobject name.

This was reproduced without kprobes by racing normal CSI platform-device
unregistration and ACPI configfs table removal against the production
ipu_bridge_init() entry. KASAN reported the final free through
device_release(), followed by invalid reads through _dev_err().

Emit the error message while the lookup reference is still held, then
drop the reference as before.

Source reproducers and vulnerable/fixed serial logs, with only the build
hostname redacted, are available at:
https://github.com/kimaiden1984-boop/linux-ipu-bridge-acpi-uaf-reproducer

The fixed target builds with W=1 on x86-64. This was not tested on
physical IPU hardware. The tests establish runtime reachability but do
not measure occurrence frequency on shipping systems or establish
exploitability.

Fixes: c66821f381ae ("media: pci: intel: Add IVSC support for IPU bridge driver")
Cc: stable@vger.kernel.org
Assisted-by: Codex:GPT-5
Signed-off-by: Yibo Tan <lhfff@tju.edu.cn>
Signed-off-by: Sakari Ailus <sakari.ailus@linux.intel.com>
[ sashal: Retained the existing "MEI CSI dev" diagnostic because CVS support is absent. ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: fix use-after-free after a failed durable reconnect
Ian Bridges [Tue, 3 Nov 2026 22:40:00 +0000 (17:40 -0500)]
ksmbd: fix use-after-free after a failed durable reconnect

[ Upstream commit 248b5819591c577727930e4e255a455235fab50a ]

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.

  BUG: KASAN: slab-use-after-free in __close_file_table_ids+0x14d/0x740 [ksmbd]
  Call Trace:
   __close_file_table_ids+0x14d/0x740 [ksmbd]
   ksmbd_destroy_file_table+0x76/0x100 [ksmbd]
   ksmbd_session_destroy+0xf8/0x480 [ksmbd]
   ksmbd_dispose_sessions+0x13e/0x200 [ksmbd]
   ksmbd_conn_sessions_cleanup+0x4c3/0x6d0 [ksmbd]
  Freed by task 1030:
   __ksmbd_close_fd+0x97d/0x1000 [ksmbd]
   smb2_open+0x14eb/0xd9f0 [ksmbd]

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>
[ sashal: Adapted the cleanup call to a braced if (fp) block because the replay and request-open cleanup branches are absent. ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: verify transform SessionId matches the decrypted header
Dairui Zhang [Tue, 3 Nov 2026 21:38:12 +0000 (16:38 -0500)]
ksmbd: verify transform SessionId matches the decrypted header

[ Upstream commit 798214e6fafcdcc29f5ba2661a473232b5e70cfb ]

When an encrypted request comes in, the decryption key is picked by
the SessionId in the transform header, but the request is then
authorized under whatever session the decrypted inner header names.
Nothing ever compares the two, so on a connection with more than
one session a client can get a request decrypted with one session's
key and run it as another session. Encrypted requests are exempt
from signing too, so a valid AEAD tag is the only proof of session
identity, and it is checked against the wrong session.

MS-SMB2 says the server must check that the transform SessionId
matches the one in the decrypted SMB2 header and treat a mismatch
as a protocol error. Add that check in __handle_ksmbd_work() after
decryption, before dispatching: the message has to be at least one
fixed SMB2 header, the first operation must not set
SMB2_FLAGS_RELATED_OPERATIONS and its SessionId must match the
transform SessionId, and every following non-related operation in
a compound chain must carry the same SessionId. NextCommand
offsets must be 8-byte aligned and stay inside the message; the
bounds check is done by subtraction so it cannot wrap.

When the decrypted payload is a compression transform, the
existing decompression step runs first and the decompressed SMB2
message is checked instead, since a compression transform header
carries no SessionId.

Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Reported-by: Dairui Zhang <zhangdairui@gmail.com>
Assisted-by: LLM
Cc: stable@vger.kernel.org
Signed-off-by: Dairui Zhang <zhangdairui@gmail.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ sashal: Placed session validation directly after decryption because the intervening decompression code is absent. ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: fix named stream write and EOF handling
DaeMyung Kang [Tue, 3 Nov 2026 21:37:54 +0000 (16:37 -0500)]
ksmbd: fix named stream write and EOF handling

[ Upstream commit 02165c8d402392278a5cd2cf97645ed73a7ad4a1 ]

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: changed const struct mnt_idmap pointers to non-const pointers ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: fix out-of-bounds read when padding the final compound response
Ian Bridges [Tue, 3 Nov 2026 19:48:59 +0000 (14:48 -0500)]
ksmbd: fix out-of-bounds read when padding the final compound response

[ Upstream commit 714f27729121d59f103ca4dad7b0c2d1c125cd71 ]

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.

  BUG: KASAN: slab-out-of-bounds in _copy_from_iter+0x744/0x10e0
  Call Trace:
   _copy_from_iter+0x744/0x10e0
   tcp_sendmsg_locked+0x2290/0x3f80
   ksmbd_tcp_writev+0x10c7/0x1ab0 [ksmbd]

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.

Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Cc: stable@vger.kernel.org
Signed-off-by: Ian Bridges <icb@fastmail.org>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ sashal: Adjusted context to retain work->conn->vals->max_trans_size instead of vals->max_trans_size. ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: use the existing xattr name for a named stream
DaeMyung Kang [Tue, 3 Nov 2026 19:48:46 +0000 (14:48 -0500)]
ksmbd: use the existing xattr name for a named stream

[ Upstream commit a7d1d52748e0fe4d06fdb871fc9899904fbba93f ]

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: adapted stream lookup signature changes to the existing callers and non-const mnt_idmap interface ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: fix invalid pointer dereference when get_inode_acl() fails
Henry Hu [Tue, 3 Nov 2026 19:48:15 +0000 (14:48 -0500)]
ksmbd: fix invalid pointer dereference when get_inode_acl() fails

[ Upstream commit 19d180c7baab7126af5848ed87d5f7b5add0cef2 ]

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 mnt_idmap parameter in ksmbd_acls_fattr() ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: prevent stale data from being written by SMB2 WRITE requests
Namjae Jeon [Tue, 3 Nov 2026 15:47:24 +0000 (10:47 -0500)]
ksmbd: prevent stale data from being written by SMB2 WRITE requests

[ Upstream commit bc0e0f5ac1d7b044d403f859406b4b66d4b1ce9b ]

Initialize the compatibility byte in request buffers without zeroing
the entire allocation. Keep the one-byte compatibility exception for
SMB2 messages so valid zero-length WRITE requests remain compatible,
and validate the data range in the WRITE handlers against the current
compound request before accessing it.

This prevents stale request-buffer data from being written to files or
sent to IPC pipes.

Fixes: 443d61d1fa9f ("ksmbd: allocate one more byte for implied bcc[0]")
Cc: stable@vger.kernel.org
Reported-by: zdi-disclosures@trendmicro.com # ZDI-CAN-32436
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ sashal: Inlined the unavailable smb2_current_req_len() helper and omitted the decompression change because compression support is absent. ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: prevent share root removal through empty paths
Namjae Jeon [Tue, 3 Nov 2026 15:34:00 +0000 (10:34 -0500)]
ksmbd: prevent share root removal through empty paths

[ Upstream commit 9fd1fcbbf84986a7bcf601a2b90540899069d263 ]

A FileLinkInformation request can supply "/" as the new link name.
smb2_get_name() strips the trailing slash and passes an empty string to
ksmbd_vfs_kern_path_start_removing().

ksmbd_vfs_path_lookup() resolves an empty pathname as the configured share
path, without LOOKUP_BENEATH. With ReplaceIfExists set, smb2_create_link()
can therefore remove the share root from its parent before link creation
fails. An authenticated client with a writable share and DELETE access to
a file can trigger this if the share root is empty and the mapped user
has write and search permission on its parent directory.

Return -EINVAL for empty pathnames when for_remove is set, before
resolving the share path or acquiring removal resources. Ordinary lookups
continue to accept empty pathnames for opening the share root.

Fixes: 74d7970febf7 ("ksmbd: fix racy issue from using ->d_parent and ->d_name")
Cc: stable@vger.kernel.org
Reported-by: Zachariah Mithani (AploSec) <zachariah@aplosai.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ sashal: Replaced for_remove with the existing do_lock parameter. ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: fix session reference leak on compounded SESSION_SETUP
Ian Bridges [Tue, 3 Nov 2026 15:29:53 +0000 (10:29 -0500)]
ksmbd: fix session reference leak on compounded SESSION_SETUP

[ Upstream commit 03bd8f5279e490e15e0c0f0fa388ffbd2fbacd65 ]

A compound request can place SESSION_SETUP after another command. That
earlier command leaves a reference to its session in work->sess.
smb2_sess_setup() then overwrites work->sess with the session it looks up
or creates, and the dispatcher later puts work->sess only once. The
inherited reference is never dropped. That leaks the session, together
with its setup connection and socket, and every repeat of the compound
leaks another.

  unreferenced object (size 512):
    __kmalloc_cache_noprof+0x32c/0x3a0
    ksmbd_smb2_session_create+0xf6/0x9c0 [ksmbd]
    smb2_sess_setup+0xda4/0x6280 [ksmbd]
    handle_ksmbd_work+0x88c/0x1cb0 [ksmbd]

Save the inherited session on entry. After the request has been
processed, release it once, but only when smb2_sess_setup() has replaced
work->sess with its own session or cleared it. Do this after
ksmbd_conn_unlock() so the put does not run under srv_mutex. An error path
may instead leave the inherited session in work->sess. Keep it there, so
the dispatcher still puts it and the error response is still signed or
encrypted with it as before.

Fixes: 7aa8804c0b67 ("ksmbd: fix user-after-free from session log off")
Cc: stable@vger.kernel.org
Signed-off-by: Ian Bridges <icb@fastmail.org>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ sashal: Omitted the installed = true assignment for the absent rejected-binding signature-check block. ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoksmbd: deny access for an empty DACL instead of granting the request
Aamir Ahmed [Tue, 3 Nov 2026 14:59:19 +0000 (09:59 -0500)]
ksmbd: deny access for an empty DACL instead of granting the request

[ Upstream commit de0cffef897c1c232ed973f89928cd6c93d0b1e3 ]

smb_check_perm_dacl() returns the access mask it computes to the SMB2
CREATE handler, which uses it as the granted access for the open. For a
security descriptor whose DACL is present but contains no ACEs, the
function is supposed to deny access: an empty (non-NULL) DACL grants no
access to anyone except the object owner's implicit READ_CONTROL and
WRITE_DAC (MS-DTYP 2.4.5).

The empty-DACL branch only denies when both

  - the DACL has no trailing bytes (pdacl_size == sizeof(struct smb_acl)),
    and
  - the request contains bits beyond READ_CONTROL / WRITE_DAC.

In every other case it takes the shared "goto err_out" with rc still 0,
which returns success without modifying *pdaccess, so the caller grants
the full requested access. Three problems follow:

  - The READ_CONTROL / WRITE_DAC carve-out models the owner's implicit
    rights, but the check runs before is_owner is computed, so those
    rights are handed to *every* caller, not just the owner. For
    READ_CONTROL the SMB2 CREATE path does not fall back to
    inode_permission(), so any user can read the security descriptor of
    an object whose empty DACL is meant to deny them.

  - A request of exactly READ_CONTROL and/or WRITE_DAC is granted to any
    caller. WRITE_DAC lets the handle rewrite the DACL.

  - A DACL that declares zero ACEs but carries trailing bytes
    (pdacl_size > sizeof(struct smb_acl)) skips the deny entirely and is
    granted whatever was requested.

On shares where the NT ACL is the authoritative access control -- e.g.
"force user" shares, where every client maps to one POSIX identity so
POSIX cannot distinguish users -- this is an access-control bypass.

Compute is_owner before the empty-DACL branch and deny access from an
empty DACL unless the caller is the owner requesting no more than
READ_CONTROL / WRITE_DAC.

Fixes: e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Cc: stable@vger.kernel.org
Assisted-by: LLM
Signed-off-by: Aamir Ahmed <elb12345@hotmail.co.uk>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ sashal: added missing ownership declarations and initialization of is_owner using the mount’s ID mapping ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agodriver core: take parent lock in async device attach
Mario Peter [Tue, 3 Nov 2026 13:43:18 +0000 (08:43 -0500)]
driver core: take parent lock in async device attach

[ Upstream commit 187a62f99da29b1a55602b0d401a783d8dc86161 ]

For device types with need_parent_lock set (only USB interfaces),
probe() must run with the parent device locked. A synchronous attach
after device_add() gets this from the caller, e.g.
usb_set_configuration() holds the udev lock while adding interfaces.
__device_attach_async_helper() runs the probe from an async worker
instead, where that lock isn't held, and only takes device_lock(dev).

With async probing enabled for the hub driver (e.g. driver_async_probe=*
or driver_async_probe=hub), this races when a multi-TT hub is
configured. For multi-TT hubs, hub_probe() calls
usb_set_interface(hdev, 0, 1) to select the TT-per-port altsetting, and
usb_set_interface() creates the endpoint devices of the interface a
second time:

  usb_set_configuration()           async worker
    [udev locked]
    device_add(intf)
      queues the probe  ----------> __device_attach_async_helper()
                                      [intf locked, udev not locked]
                                      hub_probe()
                                        usb_set_interface(hdev, 0, 1)
    create_intf_ep_devs(intf)             create_intf_ep_devs(intf)

create_intf_ep_devs() checks and sets intf->ep_devs_created without a
lock of its own. If usb_set_configuration() has created ep_81 but not
yet set the flag, usb_set_interface() skips removing the endpoint
devices of the old altsetting and creates ep_81 again. With a
synchronous probe, hub_probe() runs inside device_add() with the udev
lock held, and usb_set_configuration() then finds ep_devs_created
already set.

Single-TT hubs don't call usb_set_interface() from hub_probe() and
don't show this warning, but their probe runs without the udev lock as
well.

On an i.MX8MM board with an onboard USB2514 hub this hit 11 of 100
boots:

  sysfs: cannot create duplicate filename '.../1-1/1-1:1.0/ep_81'
  Call trace:
   sysfs_warn_dup
   usb_create_ep_devs
   create_intf_ep_devs
   usb_set_interface
   hub_probe
   usb_probe_interface
   really_probe
   __device_attach_async_helper
   async_run_entry_fn

It also shows on v7.3-rc6 in QEMU, with dummy_hcd and a raw-gadget
program emulating a multi-TT hub: re-authorizing the hub in a loop,
while a SCHED_FIFO task preempts the writing task at random points for
3 ms, hit the warning in 29 of 6000 iterations.

Take the parent lock in __device_attach_async_helper() as well, like
__driver_attach_async_helper() does, and move
__device_driver_lock/unlock() up for that. With this the warning was
gone in 300 boots on the board and in 6000 iterations in QEMU.

Fixes: 765230b5f084 ("driver-core: add asynchronous probing support for drivers")
Signed-off-by: Mario Peter <mario.peter@leica-geosystems.com>
Cc: stable@vger.kernel.org # 4.2
Cc: Dmitry Torokhov <dmitry.torokhov@gmail.com>
[ johan: switch to async_schedule_dev_nocall() to avoid deadlock if
         async_schedule_dev() runs synchronously when parent lock is
 held ]
Signed-off-by: Johan Hovold <johan@kernel.org>
Link: https://patch.msgid.link/20261014133109.1392265-4-johan@kernel.org
[ Fold the nested conditions into a single if statement; correct commit
  message to mention "device types" rather than "buses" for
  "need_parent_lock". - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agodriver core: Check drivers_autoprobe for all added devices
Vincent Liu [Tue, 3 Nov 2026 13:43:17 +0000 (08:43 -0500)]
driver core: Check drivers_autoprobe for all added devices

[ Upstream commit ea34511aaf755349999a1067b2984a541bee1492 ]

When a device is hot-plugged, the drivers_autoprobe sysfs attribute is
not checked (at least for PCI devices). This means that
drivers_autoprobe is not working as intended, e.g. hot-plugged PCI
devices will still be autoprobed and bound to drivers even with
drivers_autoprobe disabled.

The problem likely started when device_add() was removed from
pci_bus_add_device() in commit 4f535093cf8f ("PCI: Put pci_dev in device
tree as early as possible") which means that the check for
drivers_autoprobe which used to happen in bus_probe_device() is no
longer present (previously bus_add_device() calls bus_probe_device()).
Conveniently, in commit 91703041697c ("PCI: Allow built-in drivers to
use async initial probing") device_attach() was replaced with
device_initial_probe() which faciliates this change to push the check
for drivers_autoprobe into device_initial_probe().

Make sure all devices check drivers_autoprobe by pushing the
drivers_autoprobe check into device_initial_probe(). This will only
affect devices on the PCI bus for now as device_initial_probe() is only
called by pci_bus_add_device() and bus_probe_device(), but
bus_probe_device() already checks for autoprobe, so callers of
bus_probe_device() should not observe changes on autoprobing.
Note also that pushing this check into device_initial_probe() rather
than device_attach() makes it only affect automatic probing of
drivers (e.g. when a device is hot-plugged), userspace can still choose
to manually bind a driver by writing to drivers_probe sysfs attribute,
even with autoprobe disabled.

Any future callers of device_initial_probe() will respect the
drivers_autoprobe sysfs attribute, which is the intended purpose of
drivers_autoprobe.

Signed-off-by: Vincent Liu <vincent.liu@nutanix.com>
Link: https://patch.msgid.link/20251022120740.2476482-1-vincent.liu@nutanix.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Stable-dep-of: 187a62f99da2 ("driver core: take parent lock in async device attach")
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agosmb: client: fix early procfs exposure race
Fredric Cover [Mon, 2 Nov 2026 22:15:04 +0000 (17:15 -0500)]
smb: client: fix early procfs exposure race

[ Upstream commit 7b1afb631395c958993cda4631002258ef4151ea ]

Currently, init_cifs() calls cifs_proc_init() near the beginning of
the function, before INIT_LIST_HEAD, leading to a momentarily
uninitialized, but exposed, procfs. If a userspace process reads this
empty procfs, iterating over a zeroed list_head leads to a NULL
pointer dereference and a kernel oops/panic.

For example, if a delay is added between cifs_proc_init() and
INIT_LIST_HEAD, and a userspace process is polling
/proc/fs/cifs/DebugData, the following oops occurs:

BUG: kernel NULL pointer dereference, address: 0000000000000608
Oops: Oops: 0000 [#1] SMP PTI
CPU: 0 UID: 0 PID: 3477 Comm: cat Not tainted
7.3.0-02212-g4df4d2a577db-dirty #6 PREEMPT(lazy)
RIP: 0010:cifs_debug_data_proc_show+0x103/0xd80 [cifs]
Call Trace:
<TASK>
 ? seq_read_iter+0x86/0x400
 ? seq_read_iter+0x86/0x400
 seq_read_iter+0x183/0x400
 proc_reg_read_iter+0x62/0x90
 copy_splice_read+0x215/0x310
 splice_file_to_pipe+0xec/0x1c0
 do_splice+0x4b8/0x780
 __se_sys_splice+0x18f/0x250
 do_syscall_64+0x109/0x330
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
</TASK>

Fix this by moving cifs_proc_init() down in init_cifs(), ensuring it runs
only after all internal lists, locks, counters, and workqueues are fully
ready, but before registering the filesystem. Update the error cleanup
ladder and exit_cifs() to maintain proper LIFO order.

Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Fredric Cover <fredric.cover.lkernel@gmail.com>
Cc: stable@vger.kernel.org
Signed-off-by: Paulo Alcantara <pc@manguebit.org>
[ sashal: Adjusted init_cifs() context because smb1_init_maperror() and smb2_init_maperror() are absent. ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agosmb: client: do not pass a NULL buf to is_oplock_break()
Zikang Gao [Mon, 2 Nov 2026 22:14:57 +0000 (17:14 -0500)]
smb: client: do not pass a NULL buf to is_oplock_break()

[ Upstream commit 2225ab306575e424b3dad2ee1be2521c89249d15 ]

receive_encrypted_read() sets *num_mids = 1 and never writes the
caller's bufs[]. Offload returns -1 with *num_mids = 0, so the
demultiplex thread skips the frame. The inline decrypt path
returns 0 even when smb2_find_mid() fails.

cifs_demultiplex_thread() then treats mids[i] == NULL as an
oplock break and calls is_oplock_break(bufs[i], server) with
bufs[i] still NULL. smb2_is_valid_oplock_break() reads
hdr.Command at offset 12 and oopses.

A large encrypted READ whose MessageId does not match is enough
to panic cifsd.

    Oops: general protection fault, probably for non-canonical address
    0xdffffc0000000001: 0000 [#1] SMP KASAN PTI
    KASAN: null-ptr-deref in range
    [0x0000000000000008-0x000000000000000f]
    CPU: 0 PID: 100 Comm: cifsd
    RIP: smb2_is_valid_oplock_break+0xc8/0x2270 [cifs]
    cifs_demultiplex_thread
    Kernel panic - not syncing: Fatal exception

Return -1 when inline decrypt finds no mid, and skip
is_oplock_break() plus the unknown-frame dump when bufs[i]
is NULL. receive_encrypted_standard() already assigns
bufs[*num_mids].

Fixes: c42a6abe3012 ("CIFS: Add capability to decrypt big read responses")
Assisted-by: LLM
Signed-off-by: Zikang Gao <2715417602@qq.com>
Reviewed-by: David Howells <dhowells@redhat.com>
Signed-off-by: Paulo Alcantara <pc@manguebit.org>
Cc: stable@vger.kernel.org
[ sashal: Adjusted context to retain the existing one-argument mid_execute_callback() and release_mid() calls. ]
Signed-off-by: Sasha Levin <sashal@kernel.org>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoio_uring/net: fix multishot recv length limit accounting
Cheng Yongkang [Wed, 4 Nov 2026 18:44:12 +0000 (11:44 -0700)]
io_uring/net: fix multishot recv length limit accounting

Commit 3e3aebb7570ccdde5cc49c9bfc8fd3a436b71b0c upstream.

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>
13 days agoio_uring/timeout: count cancelled timeouts in cq_timeouts
Cheng Yongkang [Wed, 4 Nov 2026 18:44:11 +0000 (11:44 -0700)]
io_uring/timeout: count cancelled timeouts in cq_timeouts

Commit 1c8b49851543f41fc8bb18bcd1f15cc93d14b530 upstream.

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>
13 days agoio_uring: defer foreign io-wq enqueues to task_work
Kyle Zeng [Wed, 4 Nov 2026 18:44:10 +0000 (11:44 -0700)]
io_uring: defer foreign io-wq enqueues to task_work

Commit 3de16279b43dc285ed2222aba06cebdc82fdb28b upstream.

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.

Signed-off-by: Kyle Zeng <kylebot@openai.com>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
[axboe: 6.18 lacks 13b0742fd058, which removed io_req_queue_iowq(). Name
the new task_work callback io_queue_iowq_foreign_tw() so it doesn't
clash with the existing io_req_queue_iowq_tw()]
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoio_uring/sqpoll: don't wait for the thread to exit
Chris Mason [Wed, 4 Nov 2026 18:44:09 +0000 (11:44 -0700)]
io_uring/sqpoll: don't wait for the thread to exit

Commit 360395e8dbf9d23579f74b84a1af11190813b0f8 upstream.

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>
13 days agoio_uring: free XArray nodes left by a failed store
Chris Mason [Wed, 4 Nov 2026 18:44:08 +0000 (11:44 -0700)]
io_uring: free XArray nodes left by a failed store

Commit 51bab09b7ca1a9a6dd9303a3b7ee346f8128c963 upstream.

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>
[axboe: 6.18 installs the tctx before adding the node and has no error
path that frees it, drop that hunk. There's no ctx->hpage_acct either]
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoio_uring: charge tctx nodes and personalities
Chris Mason [Wed, 4 Nov 2026 18:44:07 +0000 (11:44 -0700)]
io_uring: charge tctx nodes and personalities

Commit 0b34e7b20a48710b6f53716bf7030920b69fdbdd upstream.

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.

Fixes: 0f2122045b94 ("io_uring: don't rely on weak ->files references")
Signed-off-by: Chris Mason <mason@kernel.org>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
[axboe: 6.18 has kmalloc() for the node, inline in
__io_uring_add_tctx_node()]
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoio_uring/rsrc: charge buffer arrays and nodes to memcg
Chris Mason [Wed, 4 Nov 2026 18:44:06 +0000 (11:44 -0700)]
io_uring/rsrc: charge buffer arrays and nodes to memcg

Commit 075d5837bafc317e796548f721b8fbf7add6821d upstream.

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.

Fixes: de2939388be5 ("io_uring: improve registered buffer accounting for huge pages")
Signed-off-by: Chris Mason <mason@kernel.org>
Signed-off-by: Jens Axboe <axboe@kernel.dk>
[axboe: 6.18 uses kvmalloc() + struct_size_t() rather than
kvmalloc_flex()]
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoio_uring/io-wq: no new workers once the exit has begun
Josef Bacik [Wed, 4 Nov 2026 18:44:05 +0000 (11:44 -0700)]
io_uring/io-wq: no new workers once the exit has begun

Commit 47c68f925062a6013235d06add85a59f7d91e0fb upstream.

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>
13 days agoio_uring/net: don't retry a non-blocking connect() that fails with -EAGAIN
Daan De Meyer [Wed, 4 Nov 2026 18:44:04 +0000 (11:44 -0700)]
io_uring/net: don't retry a non-blocking connect() that fails with -EAGAIN

Commit 71537ed811107c514c0342e98902d489d6d2b7cd upstream.

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.

Fixes: f8e85cf255ad ("io_uring: add support for IORING_OP_CONNECT")
Signed-off-by: Daan De Meyer <daan@amutable.com>
Link: https://patch.msgid.link/20261027-b4-io-uring-connect-eagain-v1-1-f4e3aaaa49ee@amutable.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoio_uring/net: keep recvmsg buffer select length within MAX_RW_COUNT
Yichong Chen [Wed, 4 Nov 2026 18:44:03 +0000 (11:44 -0700)]
io_uring/net: keep recvmsg buffer select length within MAX_RW_COUNT

Commit 18d3f56eb6e6500a65d81cf265f0fe74fd9ecab6 upstream.

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>
13 days agoio_uring/kbuf: advance head when a pickup empties the buffer ring
Yichong Chen [Wed, 4 Nov 2026 18:44:02 +0000 (11:44 -0700)]
io_uring/kbuf: advance head when a pickup empties the buffer ring

Commit 8742f4b5a472c347fe568a73468a2d9e4d630b33 upstream.

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.

Fixes: 35c8711c8fc4 ("io_uring/kbuf: add helpers for getting/peeking multiple buffers")
Signed-off-by: Yichong Chen <chenyichong@uniontech.com>
Link: https://patch.msgid.link/20261023091711.83481-1-chenyichong@uniontech.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agosmb: smbdirect: fix buffer length underflow in RDMA transfers
Stefan Metzmacher [Fri, 23 Oct 2026 10:26:09 +0000 (19:26 +0900)]
smb: smbdirect: fix buffer length underflow in RDMA transfers

commit 7193241a49c958782ba4b8df06da3734d1e317d2 upstream.

When a remote buffer descriptor is larger than the remaining local
buffer, smbdirect_connection_rdma_xmit() clamps its length and sets
buf_len to zero. The common accounting code then subtracts the clamped
length from buf_len, causing it to underflow. If another descriptor
follows, the loop processes it with a wrapped remaining length and
includes memory beyond the local buffer in the RDMA transfer.

A client can trigger an out-of-bounds kernel write with an SMB WRITE
request, or an out-of-bounds kernel read with an SMB READ request, by
supplying multiple RDMA buffer descriptors with an oversized descriptor
before the last one.

Remove the premature assignment to buf_len. Subtracting the clamped length
already consumes the remaining buffer, so the next iteration stops and
only descriptors within the local buffer are used to build work requests.

Fixes: e628bf939aaf ("ksmbd: reduce descriptor size if remaining bytes is less than request size")
Cc: stable@vger.kernel.org
Reported-by: zdi-disclosures@trendmicro.com # ZDI-CAN-33549
Signed-off-by: Stefan Metzmacher <metze@samba.org>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
[ metze: in 6.18 the code is smb_direct_rdma_xmit() in
  fs/smb/server/transport_rdma.c ]
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoovl: fix mount setup failing when override_creds drops CAP_SYS_ADMIN
Amir Goldstein [Sat, 17 Oct 2026 16:43:30 +0000 (18:43 +0200)]
ovl: fix mount setup failing when override_creds drops CAP_SYS_ADMIN

commit 333ad304d4794d6384087ea7fc16e58ab642809b upstream.

When a process drops CAP_SYS_ADMIN and calls fsconfig(FSCONFIG_SET_FLAG,
"override_creds"), overlayfs saves those restricted credentials in
ofs->creator_cred. ovl_fill_super() then wraps the entire mount setup in
with_ovl_creds(), switching to those restricted credentials for the
duration.

Mount setup calls clone_private_mount(), which checks CAP_SYS_ADMIN
against current credentials. With restricted credentials active, this
check fails with -EPERM even though the task issuing
FSCONFIG_CMD_CREATE is fully privileged.

Use the mounter's real credentials only for cloning the private layer
mounts. Keep all other backing filesystem operations during mount setup
under the stashed credentials.

Reported-by: Disha Goel <disgoel@linux.ibm.com>
Closes: https://lore.kernel.org/linux-unionfs/20260924112858.51392-1-disgoel@linux.ibm.com
Fixes: c28f922c9dcee ("clone_private_mnt(): make sure that caller has CAP_SYS_ADMIN in the right userns")
Cc: stable@vger.kernel.org
Reviewed-by: Christian Brauner (Amutable) <brauner@kernel.org>
Signed-off-by: Amir Goldstein <amir73il@gmail.com>
[backport: 6.18 has no scoped_with_creds(), use scoped_class(override_creds)]
Signed-off-by: Amir Goldstein <amir73il@gmail.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoovl: do not copy up a dentry that was removed
Chris Mason [Wed, 4 Nov 2026 18:45:16 +0000 (19:45 +0100)]
ovl: do not copy up a dentry that was removed

commit f635192ad223d2009ee640b63adf5ce3198aa338 upstream.

A change to a removed file through an open descriptor replaces whatever
has its old name in the upper layer.

Copy up must only create a name in the upper directory, never replace
one. After an unlink, an rmdir or a rename over a lower dentry, a
dentry that an open file keeps alive still has its old parent and name,
but in the upper directory that name is now a whiteout or a new object.
ovl_copy_up_workdir() renames the copy over it, which brings back the
removed object and destroys whatever took its name.

An unprivileged user opened a lower FIFO and unlinked it, root created
a file at that name, and fchmod on the old descriptor replaced the file
of root with the FIFO.

Fix this by looking up the target name of the rename in
ovl_copy_up_workdir() with LOOKUP_EXCL, so that copy up fails with
-EEXIST if the name is taken, as copy up with O_TMPFILE already does
when it links the copy to the name.

Fixes: e9be9d5e76e3 ("overlay filesystem")
Cc: stable@vger.kernel.org
Signed-off-by: Chris Mason <mason@kernel.org>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
[amir: use LOOKUP_EXCL instead of relying on d_unhashed()]
Signed-off-by: Amir Goldstein <amir73il@gmail.com>
[backport: no start_renaming_dentry() and LOOKUP_EXCL, fail with -EEXIST if
 the target of ovl_lookup_upper() is positive]
Signed-off-by: Amir Goldstein <amir73il@gmail.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoovl: hold a reference on the parent in readdir
Chris Mason [Wed, 4 Nov 2026 18:45:15 +0000 (19:45 +0100)]
ovl: hold a reference on the parent in readdir

commit 16d319e12328acafeafd3eecdf09c46d7fb43452 upstream.

Listing a directory on an overlay uses a freed dentry and crashes the
kernel when a lookup moves the directory at the same time.

Code that can sleep may only use d_parent without a reference while
something stops a move of the dentry. ovl_iterate_real(),
ovl_need_adjust_d_ino() and ovl_cache_update() use the d_parent of the
listed directory and hold only the lock of that directory. When a
lookup finds the directory under another parent after a change to a
layer, d_splice_alias() moves it without that lock and drops its
reference on the old parent.

With a delay in ovl_iterate_real(), getdents64 on an overlay directory
raced a rename in the lower layer and a lookup that moved its dentry,
and after an rmdir of the old parent KASAN reported a use-after-free in
security_inode_getattr().

Fix this by using dget_parent() in the three functions.

Fixes: b5efccbe0a12 ("ovl: constant d_ino across copy up")
Cc: stable@vger.kernel.org
Signed-off-by: Chris Mason <mason@kernel.org>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
[amir: fix comments in ovl_need_adjust_d_ino()]
Signed-off-by: Amir Goldstein <amir73il@gmail.com>
[backport: no ovl_need_adjust_d_ino(), take the parent with dget_parent()
 in ovl_iterate() and test a local flag]
Signed-off-by: Amir Goldstein <amir73il@gmail.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoovl: check that the parents of volatile/dirty are dirs
Chris Mason [Wed, 4 Nov 2026 18:45:14 +0000 (19:45 +0100)]
ovl: check that the parents of volatile/dirty are dirs

commit e34d2ef818e4c7676d8d8e1bf43e6a1ed39efb2a upstream.

An unprivileged user crashes the kernel by mounting overlayfs with the
volatile option.

A dentry that serves as the parent of a lookup must be a directory.
ovl_create_volatile_dirty() walks work/incompat/volatile/dirty by name,
and ovl_lookup_or_create() returns an existing entry whatever its type.
A file or a symlink that another task creates during the mount becomes
the parent of the next lookup, which calls a NULL ->lookup.

An unprivileged user mounted overlayfs with "volatile" in a user
namespace while a second process created a symlink named work/incompat,
and the mount task oopsed on a NULL ->lookup call.

Fix this by returning -ENOTDIR from ovl_lookup_or_create() when the
caller asked for a directory and the existing entry is a non-dir.

Fixes: c86243b090bc ("ovl: provide a mount option "volatile"")
Cc: stable@vger.kernel.org
Signed-off-by: Chris Mason <mason@kernel.org>
Signed-off-by: Josef Bacik <josef@toxicpanda.com>
Signed-off-by: Amir Goldstein <amir73il@gmail.com>
[backport: no ovl_start_creating_upper(), check the child of
 ovl_lookup_upper() in ovl_lookup_or_create() instead]
Signed-off-by: Amir Goldstein <amir73il@gmail.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoHID: roccat: savu: reject short special reports
Jiale Yao [Thu, 24 Sep 2026 14:29:17 +0000 (22:29 +0800)]
HID: roccat: savu: reject short special reports

commit 76c51fdc825a0486f8d88ff896d39acec8f377b4 upstream.

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>
13 days agoHID: roccat: ryos: reject short special reports
Jiale Yao [Thu, 24 Sep 2026 14:29:16 +0000 (22:29 +0800)]
HID: roccat: ryos: reject short special reports

commit 02f3607d0beb82e76481568bf631235e6a319b47 upstream.

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>
13 days agoHID: roccat: pyra: reject short button reports
Jiale Yao [Thu, 24 Sep 2026 14:29:15 +0000 (22:29 +0800)]
HID: roccat: pyra: reject short button reports

commit 493268f459bb6aeeecbc77f2204c11ad74d05213 upstream.

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>
13 days agoHID: roccat: kovaplus: reject short button reports
Jiale Yao [Thu, 24 Sep 2026 14:29:14 +0000 (22:29 +0800)]
HID: roccat: kovaplus: reject short button reports

commit e95917a606f486e46f5136fc1b72190742a091d6 upstream.

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>
13 days agoHID: roccat: konepure: reject short button reports
Jiale Yao [Thu, 24 Sep 2026 14:29:13 +0000 (22:29 +0800)]
HID: roccat: konepure: reject short button reports

commit 1590b7c9bea0abe7a5d25dbfe06287c48c238a6f upstream.

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>
13 days agoHID: roccat: koneplus: reject short button reports
Jiale Yao [Thu, 24 Sep 2026 14:29:12 +0000 (22:29 +0800)]
HID: roccat: koneplus: reject short button reports

commit d879e17a8b4c572c0b53b4e42a36849484e8f00c upstream.

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>
13 days agoHID: roccat: isku: reject short button reports
Jiale Yao [Thu, 24 Sep 2026 14:29:11 +0000 (22:29 +0800)]
HID: roccat: isku: reject short button reports

commit 93e5f7f6189af76a2b2e2dfe647838a7b9f99d21 upstream.

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>
13 days agoHID: quirks: Always poll the Anne Pro 2 with product ID a292
Gabor Tanz [Mon, 12 Oct 2026 15:03:57 +0000 (17:03 +0200)]
HID: quirks: Always poll the Anne Pro 2 with product ID a292

commit cbc13a78a89d087252947d0a51048e576cfcb3ef upstream.

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.

Cc: stable@vger.kernel.org
Assisted-by: LLM
Signed-off-by: Gabor Tanz <gabor.tanz@gmail.com>
Signed-off-by: Jiri Kosina <jkosina@suse.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoHID: pxrc: reject short input reports
Jiale Yao [Thu, 24 Sep 2026 14:44:12 +0000 (22:44 +0800)]
HID: pxrc: reject short input reports

commit 0deb22da5a8c6663c3e071f55fd7d7e3189f5517 upstream.

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.

Fixes: acc3e34613da ("HID: Add driver for PhoenixRC Flight Controller")
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>
13 days agoHID: prodikeys: validate fixed-format MIDI reports
Jiale Yao [Thu, 24 Sep 2026 14:44:11 +0000 (22:44 +0800)]
HID: prodikeys: validate fixed-format MIDI reports

commit 0ff37294c41bd925258893310398bc2b45fcd4a7 upstream.

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.

Fixes: 3a370ca1dcf8 ("HID: Prodikeys PC-MIDI HID Driver")
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>
13 days agoHID: picoLCD: check for fb_deferred_io_init() error
Lorenzo Stoakes (ARM) [Sat, 26 Sep 2026 13:17:01 +0000 (14:17 +0100)]
HID: picoLCD: check for fb_deferred_io_init() error

commit feade898fc958ff355101adf12d5632272e64220 upstream.

fb_deferred_io_init() allocates deferred I/O state, populating
info->fbdefio_state, or leaving it NULL if an error occurs.

Currently picolcd_init_framebuffer() ignores its return value.

Therefore if an error arises in fb_deferred_io_init() (for instance, due
to an allocation failure) info->fbdefio_state is left NULL.

When the file is subsequently opened, fb_open() will dereference a NULL
pointer (calling fb_deferred_io_open()).

Fix this by checking for the error.

Also correct cleanup ordering - defio is initialised after the sysfs file,
so cleanup defio first.

Fixes: 56c134f7f1b5 ("fbdev: Track deferred-I/O pages in pageref struct")
Cc: stable@vger.kernel.org
Signed-off-by: Lorenzo Stoakes (ARM) <ljs@kernel.org>
Signed-off-by: Helge Deller <deller@gmx.de>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoHID: mcp2221: validate response report length
Jiale Yao [Thu, 24 Sep 2026 14:44:10 +0000 (22:44 +0800)]
HID: mcp2221: validate response report length

commit 1ae40774d386b7a51e4799200106429a7e14e8ec upstream.

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>
13 days agoHID: mcp2200: validate READ_ALL response length
Jiale Yao [Thu, 24 Sep 2026 14:44:09 +0000 (22:44 +0800)]
HID: mcp2200: validate READ_ALL response length

commit 26ce0e6bf0b27fc6a2f490f38555dfd0a27c9605 upstream.

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>
13 days agoHID: logitech-dj: validate unnumbered keyboard reports
Jiale Yao [Thu, 24 Sep 2026 14:44:08 +0000 (22:44 +0800)]
HID: logitech-dj: validate unnumbered keyboard reports

commit c2deafcb4c8227771f768d77ed3c0a489250e9b2 upstream.

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>
13 days agoHID: elo: reject short touchscreen reports
Jiale Yao [Thu, 24 Sep 2026 14:44:07 +0000 (22:44 +0800)]
HID: elo: reject short touchscreen reports

commit 1cb92fcb2ac344d78737e3c5cb7b061dfb2850b1 upstream.

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>
13 days agoHID: cp2112: validate response report lengths
Jiale Yao [Thu, 24 Sep 2026 14:44:06 +0000 (22:44 +0800)]
HID: cp2112: validate response report lengths

commit fc54e71a063c0dcc4bceba6d0f71805a9b84082d upstream.

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.

Fixes: e932d8178667 ("HID: add hid-cp2112 driver")
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>
13 days agoHID: cougar: reject short special-key reports
Jiale Yao [Thu, 24 Sep 2026 14:44:05 +0000 (22:44 +0800)]
HID: cougar: reject short special-key reports

commit c6c0df8a4b73a0d563c5e64de640ef5ff525fc82 upstream.

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>
13 days agoHID: core: Fix out-of-bounds left shift by 32 in s32ton()
Alan Stern [Sat, 10 Oct 2026 17:44:15 +0000 (13:44 -0400)]
HID: core: Fix out-of-bounds left shift by 32 in s32ton()

commit 5fe63b415c636c7f4f6848a8e53bdd4bbf0c300d upstream.

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>
13 days agoHID: amd_sfh: Use report type from request node
Basavaraj Natikar [Tue, 6 Oct 2026 10:37:54 +0000 (16:07 +0530)]
HID: amd_sfh: Use report type from request node

commit 85f1bea97f1909f81577cfcf3e4db9017e7f5337 upstream.

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.

Fixes: 1434f9fc0e47 ("SFH: Create HID report to Enable support of AMD sensor fusion Hub (SFH)")
Closes: https://github.com/ublue-os/bazzite/issues/5796
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>
13 days agoHID: amd_sfh: Remove unsupported motion-state field from accelerometer report
Basavaraj Natikar [Tue, 6 Oct 2026 10:37:53 +0000 (16:07 +0530)]
HID: amd_sfh: Remove unsupported motion-state field from accelerometer report

commit 6ff86122906357687735dd379c6279e3b2fa26af upstream.

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>
13 days agoHID: zydacron: validate key report length
Jiale Yao [Thu, 24 Sep 2026 14:44:13 +0000 (22:44 +0800)]
HID: zydacron: validate key report length

commit 9932c9af185f8586e883d44ca562c12f4487c762 upstream.

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.

Fixes: d0742abaa1c3 ("HID: add omitted hid-zydacron.c file")
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>
13 days agoKVM: PPC: Fix get_d_signext() 12-bit displacement for paired-single D-form
Amit Machhiwal [Mon, 28 Sep 2026 12:28:37 +0000 (17:58 +0530)]
KVM: PPC: Fix get_d_signext() 12-bit displacement for paired-single D-form

commit 31895b0ff96778b524c74b43a108090581271603 upstream.

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.

Fixes: 831317b605e7 ("KVM: PPC: Implement Paired Single emulation")
Cc: stable@vger.kernel.org
Signed-off-by: Amit Machhiwal <amachhiw@linux.ibm.com>
Signed-off-by: Madhavan Srinivasan <maddy@linux.ibm.com>
Link: https://patch.msgid.link/20260928122837.8782-4-amachhiw@linux.ibm.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: PPC: Book3S HV: Add preempt_disable() around virtual-mode HPTE bit-lock users
Amit Machhiwal [Mon, 28 Sep 2026 12:28:36 +0000 (17:58 +0530)]
KVM: PPC: Book3S HV: Add preempt_disable() around virtual-mode HPTE bit-lock users

commit abbbe5ff83e7c9ed3a4d61b73011f1df7bf87907 upstream.

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.

Fixes: 6165d5dd99db ("KVM: PPC: Book3S HV: add virtual mode handlers for HPT hcalls and page faults")
Cc: stable@vger.kernel.org # v5.14+
Signed-off-by: Amit Machhiwal <amachhiw@linux.ibm.com>
Reviewed-by: Ritesh Harjani (IBM) <ritesh.list@gmail.com>
Signed-off-by: Madhavan Srinivasan <maddy@linux.ibm.com>
Link: https://patch.msgid.link/20260928122837.8782-3-amachhiw@linux.ibm.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: TDX: Enable Notify VM exit
Xiaoyao Li [Wed, 19 Aug 2026 09:48:55 +0000 (17:48 +0800)]
KVM: TDX: Enable Notify VM exit

commit d93395058c1951bb657c8895dd1fc0f22263f1cc upstream.

Enable Notify VM exit functionality for TDX guests.

Notify VM exit is an existing feature supported by KVM.  Userspace can
enable Notify VM exit through KVM_CAP_X86_NOTIFY_VMEXIT 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 Notify VM exit for TDX guests by:

  - Invoking TDX module API calls to set NOTIFY_VM_EXITING and Notify
    Window in TD VMCS.  It's done in tdx_vcpu_init() where other TD VMCS
    bits are set.  Since TDX vCPU cannot be reset, it only needs to be
    configured once when initializing the TDX vCPU.

  - Adding corresponding exit handler for TDX Notify VM Exit.

Notify VM exit can happen when executing the IRET instruction.  If the
IRET unblocks the NMI blocking state, bit 12 of the exit qualification
is set.  In this case, the VMM needs to restore the "blocked by NMI" state
when it decides to re-enter the guest.  For TDX, KVM cannot manage the
GUEST_INTERRUPTIBILITY_INFO and it's TDX module's responsibility to
handle it.  Extract the common part without NMI blocking handling into a
helper in common.h so that it can be shared between VMX and TDX.

Note, KVM uses "pre-production" terminology for the feature formally called
Notify VM-Exit.  All public versions of the SDM refer to the feature as
Instruction Timeout.  This will be remedied in the near future, for now,
use KVM's terminology for consistency.

Note, #2, there is no enumeration bit for Notify VM exit by TDX module
because all TDX modules support it, and allow to set the corresponding
TD VMCS fields as long as the hardware supports the feature.

Fixes: 161d34609f9b ("KVM: TDX: Make TDX VM type supported")
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-2-xiaoyao.li@intel.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: TDX: Check if there is valid exit infos based on vp_enter_ret
Xiaoyao Li [Wed, 19 Aug 2026 09:48:56 +0000 (17:48 +0800)]
KVM: TDX: Check if there is valid exit infos based on vp_enter_ret

commit 0966c881ea13be5ec89820c185de4d55568e80ed upstream.

Check if there is valid exit info based on vp_enter_ret instead of relying
on the clobbered Exit Reason, in tdx_get_exit_info().

Current KVM uses "Exit Reason is not equal to the synthesized invalid
Exit Reason, -1u," as the condition to identify there is a real TD Exit
and valid exit infos.  However, there is one issue with this approach:
KVM updates the Exit Reason to the synthesized invalid Exit Reason for
real EPT MISCONFIG as well.  This is a false positive for real EPT
MISCONFIG, which has valid exit infos.

Though the issue can be addressed by changing the handling for real EPT
MISCONFIG to not update the Exit Reason to the synthesized one, relying
on the clobbered Exit Reason itself is brittle.  Instead, check
vp_enter_ret directly to identify if it is a valid Exit Reason.

Fixes: da407fe45908 ("KVM: TDX: Handle EPT violation/misconfig exit")
Cc: stable@vger.kernel.org
Suggested-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Xiaoyao Li <xiaoyao.li@intel.com>
Reviewed-by: Binbin Wu <binbin.wu@linux.intel.com>
Link: https://patch.msgid.link/20260819094903.3060020-3-xiaoyao.li@intel.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: x86: Zero reserved synic flags when delivering message to avoid stack leak
Sean Christopherson [Wed, 26 Aug 2026 18:44:49 +0000 (11:44 -0700)]
KVM: x86: Zero reserved synic flags when delivering message to avoid stack leak

commit 2616f497506a772db53e7bb1024cde50b4c165e0 upstream.

Ensure all reserved flags are zeroed when setting the msg_pending flag as
part of SynIC message delivery, as setting only msg_pending can leak seven
bits of kernel stack data to the guest.  E.g. gcc typically uses a
bitwise-OR to set the msg_pending flag, without initializing the on-stack
variable.

Precisely zero the flags, e.g. as opposed to zeroing the entire structure,
to make it somewhat more obvious that the flags *need* to be zeroed.  E.g.
it would be quite easy to misread the initial read of guest memory and
think that zeroing the entire structure is completely superfluous.

Fixes: 3a0e7731724f ("x86: kvm: hyperv: simplify SynIC message delivery")
Cc: stable@vger.kernel.org
Reported-by: Stefan Teodorescu <fane@google.com>
Reviewed-by: Vitaly Kuznetsov <vkuznets@redhat.com>
Link: https://patch.msgid.link/20260826184449.814130-1-seanjc@google.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: x86: Take SRCU in kvm_zap_gfn_range()
Chengfeng Ye [Tue, 25 Aug 2026 18:39:24 +0000 (02:39 +0800)]
KVM: x86: Take SRCU in kvm_zap_gfn_range()

commit b59a87c1ba3c347e8aec5f932eb7abf13064fd62 upstream.

kvm_zap_gfn_range() walks memslots and rmaps and may drop mmu_lock to
reschedule. Callers that do not already hold kvm->srcu (or slots_lock)
can race with memslot deletion: synchronize_srcu_expedited() does not
wait, kvm_free_memslot() frees the old slot and its rmap, and the zap
resumes on freed memory.

The VFIO noncoherent-DMA path hits this by zapping the entire GPA
space without SRCU. KASAN reported:

  BUG: KASAN: vmalloc-out-of-bounds in slot_rmap_walk_next+0x82/0x1c0
  Read of size 8 at addr ffffc900005c1008
  Call Trace:
   slot_rmap_walk_next+0x82/0x1c0
   __kvm_rmap_zap_gfn_range+0x17a/0x280
   kvm_zap_gfn_range+0x2a6/0x6a0
   kvm_vfio_set_attr+0x576/0x770
   kvm_device_ioctl+0x1ff/0x3b0

Take SRCU inside kvm_zap_gfn_range() so every caller is covered.
Nesting with an existing kvm->srcu critical section is fine; the
helper uses a local index. Drop the now-redundant SRCU pair from
__kvm_set_or_clear_apicv_inhibit().

Fixes: 362ff6dca541 ("KVM: x86/mmu: Zap KVM TDP when noncoherent DMA assignment starts/stops")
Cc: stable@vger.kernel.org
Signed-off-by: Chengfeng Ye <nicoyip.dev@gmail.com>
Reviewed-by: Kai Huang <kai.huang@intel.com>
Link: https://patch.msgid.link/20260825183924.237727-1-nicoyip.dev@gmail.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: x86: Request event processing for exception VM-Exits
Loc Nguyen [Fri, 2 Oct 2026 05:42:54 +0000 (05:42 +0000)]
KVM: x86: Request event processing for exception VM-Exits

commit 88b23a2e8286b7016c3b58dc10093cf28c22aa3d upstream.

Request event processing whenever kvm_queue_exception_vmexit() queues an
exception VM-Exit.  Most callers reach the helper through
kvm_multiple_exception(), which already sets KVM_REQ_EVENT, but nested
asynchronous page faults call it directly.

Without another event request, vcpu_enter_guest() skips
kvm_check_and_inject_events() and re-enters L2.  A subsequent VM-Exit can
clear the pending exception while reconstructing vectoring state, losing
the synthetic #PF VM-Exit.  The APF reason remains PAGE_NOT_PRESENT and a
later regular #PF can consume the stale value.

Setting KVM_REQ_EVENT in the common helper ensures that L1 receives the
queued VM-Exit before KVM re-enters L2.

Fixes: 7709aba8f716 ("KVM: x86: Morph pending exceptions to pending VM-Exits at queue time")
Cc: stable@vger.kernel.org
Signed-off-by: Loc Nguyen <loc@ryzome.com>
Link: https://patch.msgid.link/20261002053723.3275202-2-loc@ryzome.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: x86: Preserve DR6.BLD (Bus Lock Detect) when delivering #DB payload
Sean Christopherson [Wed, 30 Sep 2026 19:36:23 +0000 (12:36 -0700)]
KVM: x86: Preserve DR6.BLD (Bus Lock Detect) when delivering #DB payload

commit 719a1d58bf43edd03b271df90b67c58c1e9a7da4 upstream.

Preserve Bus Lock Detect if it isn't present in the payload.  Unlike RTM,
which is explicitly modified on every #DB,  DR6.BLD is modified if and only
if the #DB is due to a (coincident) Bus Lock Detect.

Per Intel's SDM:

  Other debug exceptions do not modify this bit.

And AMD's APM

  All other #DB exceptions leave DR6[BLD] unmodified,

Restore the explicit RTM handling that was clobbered by commit
9a3ecd5e2aa1 ("KVM: X86: Rename DR6_INIT to DR6_ACTIVE_LOW"), as the
semantics of any given bit are feature specific, i.e. are obviously not
consistent for active-high versus active-low.  In other words, while the
bug was technically introduced when support for Bus Lock Detect was added,
it's really that attempt to genericize handling of active-low bits that set
KVM up to fail.

Fixes: e8ea85fb280e ("KVM: X86: Add support for the emulation of DR6_BUS_LOCK bit")
Cc: stable@vger.kernel.org
Link: https://patch.msgid.link/20260930193634.3415089-2-seanjc@google.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: x86: Clear hardware HLT state when userspace makes a vCPU not-halted
Keqiang Duan [Thu, 20 Aug 2026 12:35:12 +0000 (20:35 +0800)]
KVM: x86: Clear hardware HLT state when userspace makes a vCPU not-halted

commit 883719f57f5d3898637b130d6db4742471cad618 upstream.

Force a vCPU out of its hardware-tracked halted state when userspace puts
the vCPU into any state other than HALTED via KVM_SET_MP_STATE, i.e. clear
VMCS.GUEST_ACTIVITY_STATE if it says the vCPU is halted.  Add an optional
kvm_x86_ops hook to do the clearing, as SVM has no equivalent VMCB field.

When HLT-exiting is disabled for a VM (KVM_CAP_X86_DISABLE_EXITS with
KVM_X86_DISABLE_EXITS_HLT, e.g. QEMU's "-overcommit cpu-pm=on"), a guest
HLT halts the physical CPU instead of exiting to KVM, and hardware saves
GUEST_ACTIVITY_STATE=HLT into the VMCS on the next VM-Exit.  That field is
sticky: it survives VM-Exit/VM-Enter and is only cleared by vmx_clear_hlt()
on event injection, or by vmx_vcpu_reset() on INIT / vCPU creation.

Nothing clears it on a userspace-driven state change.  KVM_SET_REGS only
writes the software register cache and KVM_SET_MP_STATE only writes
vcpu->arch.mp_state; kvm_vcpu_running() likewise consults software state
only.  A VMM that emulates a machine reset therefore ends up with a vCPU
that KVM happily VM-Enters while hardware refuses to fetch instructions.

Reproduce with a Linux guest by triggering a panic/kdump on a non-boot
vCPU: nmi_shootdown_cpus() parks the other vCPUs -- including vCPU0 -- in
crash_nmi_callback(), which does local_irq_disable() followed by a bare
HLT.  The capture kernel then resets the machine via port 0xCF9.  QEMU
rewrites RIP to 0xfff0 and sets mp_state to RUNNABLE, but vCPU0's
GUEST_ACTIVITY_STATE is still HLT, so the BSP never executes the reset
vector, never sends SIPIs, and the entire VM hangs at "reboot: machine
restart" forever.  Only destroying and recreating the VM recovers it.

Key off "not HALTED" rather than "is RUNNABLE" as HALTED is the only target
state for which retaining the hardware halted state is meaningful; every
other transition either can't be reached on VMX, e.g. AP_RESET_HOLD, or
goes through vmx_vcpu_reset(), which stuffs GUEST_ACTIVITY_ACTIVE anyways.
This also captures the intent more directly: KVM only ever drops the
hardware halted state, it never installs it.

Hook KVM_SET_MP_STATE rather than the VM-Enter path so that the clearing
is driven by an explicit userspace declaration, and so that no work is
added to vmx_vcpu_run().  Gate the call on kvm_hlt_in_guest() even though
vmx_clear_hlt() checks it as well, as the check is cheap and makes it
obvious in common code when the hardware state can exist at all.

Do nothing for TDX vCPUs as TDX doesn't support disabling HLT-exiting and
KVM cannot access a TD's VMCS, i.e. the VMCS used to run the vCPU can't
in HALTED state, and even if it were, KVM can't change it.

Fixes: caa057a2cad6 ("KVM: X86: Provide a capability to disable HLT intercepts")
Cc: stable@vger.kernel.org
Tested-by: Qinguang Chen <chenqinguang@kuaishou.com>
Signed-off-by: Zhiping Du <duzhiping@kuaishou.com>
Signed-off-by: Keqiang Duan <duankeqiangcym@gmail.com>
Reviewed-by: Chao Gao <chao.gao@intel.com>
Link: https://patch.msgid.link/20260820123512.87236-1-duankeqiangcym@gmail.com
[sean: drop claim that spurious wakeups are ok, massage changelog]
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: x86/xen: Take kvm->srcu in __kvm_xen_has_interrupt()
David Woodhouse [Mon, 31 Aug 2026 21:26:41 +0000 (22:26 +0100)]
KVM: x86/xen: Take kvm->srcu in __kvm_xen_has_interrupt()

commit aa8ad943f242ef14d136c5440b1178de77466c9e upstream.

kvm_gpc_check() checks the cached memslot generation against the current
one, which dereferences kvm->memslots and therefore requires kvm->srcu to
be held. __kvm_xen_has_interrupt() does not take it.

Most callers do happen to hold kvm->srcu, but not all of them:

 - kvm_emulate_halt() on the VM-Exit path, via kvm_vcpu_has_events() and
   kvm_cpu_has_extint(). vcpu_enter_guest() drops the vCPU's SRCU lock
   before entering the guest, so it is not held on the way back out.

 - kvm_vcpu_block() -> kvm_vcpu_check_block() -> kvm_arch_vcpu_runnable(),
   which is the case the existing comment in this function describes.

On a PROVE_RCU kernel the former produces:

  WARNING: suspicious RCU usage
  include/linux/kvm_host.h:1092 suspicious rcu_dereference_check() usage!
  ...
   kvm_gpc_check+0x344/0x3e0 [kvm]
   __kvm_xen_has_interrupt+0x83/0x310 [kvm]
   kvm_cpu_has_extint+0x1ff/0x370 [kvm]
   kvm_cpu_has_interrupt+0x16/0x100 [kvm]
   kvm_vcpu_has_events+0x4ce/0x690 [kvm]
   kvm_emulate_halt+0x52/0x1f0 [kvm]
   vmx_vcpu_run+0x988/0x2630 [kvm_intel]

Use guard(srcu) so that the three existing early returns don't each need
an explicit unlock. SRCU read sections nest, so this is harmless on the
paths which already hold it, and srcu_read_lock() does not sleep, so it
is also safe in the atomic case which this function already handles.

Fixes: 7caf9571563e ("KVM: x86/xen: Use gfn_to_pfn_cache for vcpu_info")
Cc: stable@vger.kernel.org
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
Assisted-by: Claude:claude-mythos-5
Reviewed-by: Paul Durrant <paul@xen.org>
Link: https://patch.msgid.link/20260831213632.81023-11-dwmw2@infradead.org
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: x86/xen: Enforce 4-byte alignment of vcpu_info registration
David Woodhouse [Mon, 31 Aug 2026 21:26:37 +0000 (22:26 +0100)]
KVM: x86/xen: Enforce 4-byte alignment of vcpu_info registration

commit eacdb76c5f04956035c5d7f7e1973028f30684a2 upstream.

Xen's map_guest_area() enforces that vcpu_info is aligned to
sizeof(xen_ulong_t). KVM has no such check, allowing a guest to
register vcpu_info at an arbitrary byte alignment.

Enforce unconditional 4-byte alignment regardless of the current
shinfo mode. This is sufficient because subsequent commits ensure
that all locked atomic operations on vcpu_info fields use at most
32-bit accesses. Return -ENXIO on failure, matching Xen's
map_guest_area() behaviour for unaligned requests.

Originally observed in review of an unrelated patch:
https://lore.kernel.org/all/20260604193554.1BA311F00893@smtp.kernel.org/

Cc: stable@vger.kernel.org
Fixes: 73e69a86347a ("KVM: x86/xen: register vcpu info")
Reported-by: sashiko-bot@kernel.org
Closes: https://lore.kernel.org/all/20260604193554.1BA311F00893@smtp.kernel.org
Assisted-by: Kiro:claude-opus-4.6-1m
Signed-off-by: David Woodhouse <dwmw@amazon.co.uk>
Reviewed-by: Paul Durrant <paul@xen.org>
Link: https://patch.msgid.link/20260831213632.81023-7-dwmw2@infradead.org
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: x86/mmu: Bug the VM if KVM calcs a CPU role with EFER.LMA=1 && CR4.PAE=0
Sean Christopherson [Wed, 2 Sep 2026 23:20:27 +0000 (16:20 -0700)]
KVM: x86/mmu: Bug the VM if KVM calcs a CPU role with EFER.LMA=1 && CR4.PAE=0

commit 34dacbe7ae93f2d3c26cd0bf3e08200b1fa2c180 upstream.

Bug the VM if KVM attempts to construct a CPU role with the should-be-
impossible combination of long mode being active without PAE paging being
enabled.  KVM's MMU construction assumes that EFER.LMA can be set if and
only CR4.PAE is set, and will create a completely invalid MMU if that
assumption fails.  FNAME(walk_addr_generic) already has sanity checks to
try and mitigate the fallout, but attempt to catch such bugs earlier, as
this is (at least) the second time KVM has had bugs that escaped into
FNAME(walk_addr_generic), and it's entirely possible the bad state could
cause problems elsewhere.

Cc: stable@vger.kernel.org
Link: https://patch.msgid.link/20260902232028.2767071-5-seanjc@google.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: x86/mmu: Bug the VM if KVM attempts to walk more levels than the MMU has
Sean Christopherson [Wed, 2 Sep 2026 23:20:26 +0000 (16:20 -0700)]
KVM: x86/mmu: Bug the VM if KVM attempts to walk more levels than the MMU has

commit 115f9405a2ed6d78ee7ad8436bdd638743f6d1d4 upstream.

Extend the "EFER.LMA && !CR4.PAE" check, which exists largely to guard
against KVM configuring a paging32 MMU with more than 2 levels of paging,
with a very explicit check for exactly that: that KVM isn't trying to walk
more levels of paging than the MMU template provides.  I.e. harden KVM
against all bugs that would cause KVM to generates accesses beyond the
bounds of guest_walker's arrays, regardless of how KVM ended up with the
misconfigured MMU.

Note, don't use w->cpu_role.base.level directly as the paging64 template
only provides two levels of page tables for PAE paging on 32-bit hosts, and
handles the third level by manually emulating the PDPTR access.

Cc: stable@vger.kernel.org
Link: https://patch.msgid.link/20260902232028.2767071-4-seanjc@google.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: VMX: Preserve negative return value in vmx_handle_exit() with bus lock detected
Xiaoyao Li [Wed, 19 Aug 2026 09:49:00 +0000 (17:49 +0800)]
KVM: VMX: Preserve negative return value in vmx_handle_exit() with bus lock detected

commit cef48693da1e964e9f192bfc16cd0ed287c48337 upstream.

Preserve the negative return value from __vmx_handle_exit() when a bus
lock is detected, instead of always overwriting it with 0.

The purpose of bus_lock_detected handling is to force a userspace exit to
inform userspace that a bus lock happened. The negative return value can
achieve this purpose, and changing the negative value to 0 fails to return
an error to userspace. So, preserve the negative return value.

Fixes: fe6b6bc802b4 ("KVM: VMX: Enable bus lock VM exit")
Cc: stable@vger.kernel.org
Reported-by: sashiko-bot@kernel.org
Closes: https://lore.kernel.org/all/20260805034602.5B2BB1F000E9@smtp.kernel.org/
Signed-off-by: Xiaoyao Li <xiaoyao.li@intel.com>
Link: https://patch.msgid.link/20260819094903.3060020-7-xiaoyao.li@intel.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: VMX: Make handle_bus_lock_vmexit() a shared helper
Xiaoyao Li [Wed, 19 Aug 2026 09:49:01 +0000 (17:49 +0800)]
KVM: VMX: Make handle_bus_lock_vmexit() a shared helper

commit 326fa2c9b4d3e6cab58c139eb55aaabd7179192e upstream.

Move handle_bus_lock_vmexit() from vmx.c to main.c to make it a shared
helper so that TDX can use it for Bus Lock VM exit handling as well.
Rename it to add vt_ prefix to reflect that it is a helper for both VMX
and TDX.

Cc: stable@vger.kernel.org
Signed-off-by: Xiaoyao Li <xiaoyao.li@intel.com>
Reviewed-by: Nikolay Borisov <nik.borisov@suse.com>
Link: https://patch.msgid.link/20260819094903.3060020-8-xiaoyao.li@intel.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
13 days agoKVM: VMX: Disallow using to_vmx() in common VT code
Sean Christopherson [Fri, 4 Sep 2026 01:03:46 +0000 (18:03 -0700)]
KVM: VMX: Disallow using to_vmx() in common VT code

commit f305fd31f52a8d3ce4d2bf0c88c45bb7a373809c upstream.

Poison to_vmx() in main.c and posted_intr.c so that attempting to interpret
the vCPU as a VMX vCPU will fail at compile time, as opposed to failing at
runtime, or worse corrupting state without outright failing.

Note, to_tdx() is buried in tdx.c, i.e. isn't broadly reachable, and so
doesn't need the same treatment as to_vmx().

Reviewed-by: Xiaoyao Li <xiaoyao.li@intel.com>
Reviewed-by: Kai Huang <kai.huang@intel.com>
Tested-by: Kai Huang <kai.huang@intel.com>
Reviewed-by: Binbin Wu <binbin.wu@linux.intel.com>
Cc: stable@vger.kernel.org
Link: https://patch.msgid.link/20260904010353.3175819-2-seanjc@google.com
Signed-off-by: Sean Christopherson <seanjc@google.com>
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>