Commit Graph

108332 Commits

Author SHA1 Message Date
Linus Torvalds
1fc5a74b10 kmalloc_obj conversions for v7.3-rc2
- Run scripts/coccinelle/api/kmalloc_objs.cocci for v7.3
 -----BEGIN PGP SIGNATURE-----
 
 iHUEABYKAB0WIQRSPkdeREjth1dHnSE2KwveOeQkuwUCapuwVwAKCRA2KwveOeQk
 u5EeAP9TS7K4iVlw3KlZHuLIK2q+CQfALPepcu+ME2lO5dta4gEAxCTi0ZXmU7OT
 XbmWUd+DTkKNYCBW8E6Lvn72Er13uQs=
 =ZtN4
 -----END PGP SIGNATURE-----

Merge tag 'kmalloc_obj-v7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/kees/linux

Pull kmalloc_obj conversions from Kees Cook:
 "Another run of the Coccinelle script for converting kmalloc()
  family of allocations to kmalloc_obj() via the existing rules
  in scripts/coccinelle/api/kmalloc_objs.cocci"

* tag 'kmalloc_obj-v7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/kees/linux:
  treewide: refresh kmalloc_obj() conversions
  drm/amd/display: Fix harmless type mismatch in allocation
2026-09-05 20:45:18 -07:00
Linus Torvalds
9f0346dcbe Driver core fixes for 7.3-rc2
- Fix kernfs listxattr() not returning security xattr names (e.g.
   SELinux labels) when the kernfs node has no allocated kernfs_iattrs
 
 - Fix silent truncation of IRQ vector indices in the Rust PCI
   abstractions
 
 - Don't select OF from DRIVER_PE_KUNIT_TEST; skip the test when OF is
   disabled instead of silently enabling extra kernel functionality
 
 - Russ Weight is retiring from kernel development; update the Firmware
   Loader sysfs contact to the driver-core mailing list, add a CREDITS
   entry for Firmware Upload, and update MAINTAINERS accordingly
 -----BEGIN PGP SIGNATURE-----
 
 iHQEABYKAB0WIQS2q/xV6QjXAdC7k+1FlHeO1qrKLgUCapxQTQAKCRBFlHeO1qrK
 Lr1NAQD09hhWzsAkRvdDgf/rd3iUW4Fxro/KOIf+OThNRgWpRQD4+hMNQqxzk3OB
 QT3xFMqLPFtLf+voWTcWniC6UsLfCA==
 =k/Gx
 -----END PGP SIGNATURE-----

Merge tag 'driver-core-7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core

Pull driver core fixes from Danilo Krummrich:

 - Fix kernfs listxattr() not returning security xattr names (e.g.
   SELinux labels) when the kernfs node has no allocated kernfs_iattrs

 - Fix silent truncation of IRQ vector indices in the Rust PCI
   abstractions

 - Don't select OF from DRIVER_PE_KUNIT_TEST; skip the test when OF is
   disabled instead of silently enabling extra kernel functionality

 - Russ Weight is retiring from kernel development; update the Firmware
   Loader sysfs contact to the driver-core mailing list, add a CREDITS
   entry for Firmware Upload, and update MAINTAINERS accordingly

* tag 'driver-core-7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/driver-core/driver-core:
  MAINTAINERS: Remove Russ Weight from Firmware Loader
  CREDITS: Add CREDITS entry for Firmware Upload
  firmware_loader: Change contact for sysfs nodes
  rust: pci: reject IRQ vector indices that do not fit in u32
  kernfs: preserve security xattrs without allocating iattrs
  drivers: base: test: DRIVER_PE_KUNIT_TEST should not select OF
2026-09-05 11:59:05 -07:00
Linus Torvalds
d9d80a859b for-7.3-rc1-tag
-----BEGIN PGP SIGNATURE-----
 
 iQJPBAABCgA5FiEE8rQSAMVO+zA4DBdWxWXV+ddtWDsFAmqcOFUbFIAAAAAABAAO
 bWFudTIsMi41KzEuMTIsMiwyAAoJEMVl1fnXbVg7DwAP/i5lmUS85n22uWD7wkmU
 5ocMbdl9cKprtcpi8axR9kbtBIC5bq0j3sUwmiFgR6KI774v7FnxJ3AIrey3GwtF
 okiaWLffKOYROCDvmLg36ciSbFGEqjS8lwOPl1geBX7tZhhnGgcV+XRXcMv4ehj8
 HiOtjN8a+8kXrYTMB73JhBkzku7Hojb/vA9ZHXeCLjP4nfzlXneqltSQw/+3uVvf
 jrLfOX3a1lgLkz0Q7AlfAO7ppXv5msrZYu7E1aILYtLA5K6J6Gh1jyK+Y8OZlvdg
 hukhU3mAw2pCV5dg6rAurYWzVhE/tNmKmlg2s1LiW3K1Q2NNSPGvR0ArmAnd9bPY
 6ZwoK47m98xuZgIAO7v+ej9LYI3XANGwdupTmrKhQ7shLYtzvSsob7kWRYfjCMWu
 UaTGshMsrfMXZNznXm2Ydy1Gmr3TBI2J1HpUFiibRL4XgsQ7u9hLUFwiFUiMEi9V
 g9oqTN/1VUMsImADlnrdAf30pLtOe8PHV1naFLdmdl+iCPc9o0cX9X5m2fHWtkpt
 Cjz/au8Z0zMVJMIDUZuBgCX4mWNSx7pWYKQYvlGOLQEehXNLRVcY5SnIqRman8WF
 gnUPaaTb6KDS+SJjRDPkRH9ihGlNEd2c/tzrxek4/42CF842PGeMvGK06PtPyzxW
 LWtmCtBWRArSHUq09NZbboim
 =z6qW
 -----END PGP SIGNATURE-----

Merge tag 'for-7.3-rc1-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave/linux

Pull btrfs fixes from David Sterba:

 - preserve inode compression level when changing attributes

 - fix lost wakeup when waiting for a zstd workspace

 - fix bio context leaks after ordered extent processing errors

 - in send, handle unexpected extents for non-regular inodes

 - handle edge case in creation of reloc tree with enabled quotas

 - in scrub report the exact failing offset, not the stripe base

 - error handling fixes
     - error code propagation in send, zoned mode and raid-stripe-tree
     - restore active device pointer after seeding device addition error
     - transaction abort fixups

 - update Chris' email address

* tag 'for-7.3-rc1-tag' of git://git.kernel.org/pub/scm/linux/kernel/git/kdave/linux:
  MAINTAINERS: update Chris Mason's email address
  btrfs: tests: do not touch page cache if root/inode allocation failed
  btrfs: zstd: fix lost wakeup when waiting for a workspace
  btrfs: do not force reloc root creation during qgroup_account_snapshot()
  btrfs: send: fix lost error return value in will_overwrite_ref()
  btrfs: abort transaction before releasing tree_log_mutex on commit failure
  btrfs: zoned: propagate do_zone_finish() error in btrfs_zone_finish_endio()
  btrfs: zoned: finish active block group cleanup if call_zone_finish() fails
  btrfs: send: reject extents for non-regular inodes
  btrfs: return proper negative error code for update_raid_extent_item()
  btrfs: fix the possible bioc_list memory leak during error
  btrfs: fix transaction use-after-free in raid stripe insertion
  btrfs: scrub: report the failing sector's address, not the stripe base
  btrfs: preserve the compression property when other inode flags change
  btrfs: restore active device pointers after failed sprout
  btrfs: detach failed sprout device from transaction update list
  btrfs: clean up target device if block group marking fails
2026-09-05 10:18:21 -07:00
Kees Cook
3a2c4d55e3 treewide: refresh kmalloc_obj() conversions
This is another run of the Coccinelle script for converting kmalloc()
family of allocations to kmalloc_obj() via the existing rules in
scripts/coccinelle/api/kmalloc_objs.cocci

This catches both the set of kmalloc() uses added since the first
kmalloc_obj() conversions in v7.0 and adds a large group missed in the
first pass due to Coccinelle not interacting well with the cleanup.h
scoped_...() family of macros[1]. I worked around this with spatch's
"--macro-file" argument to a file with all the scoped_...() macros mapped
to Coccinelle's YACFE_ITERATOR[2] as that was the closest viable control
flow indicator I could find.

Build tested allmodconfig on x86, arm64, arm, loongarch, mips, powerpc,
riscv, and s390 with no new warnings.

Link: https://lore.kernel.org/lkml/202609021314.8A9C0B8@keescook/ [1]
Link: https://github.com/coccinelle/coccinelle/blob/master/standard.h [2]
Signed-off-by: Kees Cook <kees+treewide@kernel.org>
2026-09-04 21:37:00 -07:00
Linus Torvalds
4d7d9486c0 integrity-v7.3-rc2
-----BEGIN PGP SIGNATURE-----
 
 iIoEABYKADIWIQQdXVVFGN5XqKr1Hj7LwZzRsCrn5QUCapsP/BQcem9oYXJAbGlu
 dXguaWJtLmNvbQAKCRDLwZzRsCrn5b2gAQC3ms2HRoZolscMWqnUNoi5SmPpwcV2
 v/ojwDc1TnS9HAEA/604QYihEvRQzKQwEyF6W6b83w22tyWKhDW1a0d7KQ4=
 =/Hd6
 -----END PGP SIGNATURE-----

Merge tag 'integrity-v7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/zohar/linux-integrity

Pull IMA fixes from Mimi Zohar:

 - Instantiating the ima_file_truncate and ima_path_truncate LSM hooks
   resulted in configfs locking issues.

   configfs files should not be measured, appraised, or audited in the
   first place, so the builtin policies are updated to exclude them.

 - IMA audit messages include the filename, which could result in a page
   fault when the filename doesn't exist

 - Un-hide the IMA_MEASURE_PCR_IDX Kconfig prompt

* tag 'integrity-v7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/zohar/linux-integrity:
  ima: allow users to specify the pcr index with IMA_MEASURE_PCR_IDX
  ima: Check for ERR_PTR from dentry_path() in validate_hash_algo()
  ima: don't measure/appraise files on configfs
  configfs: move CONFIGFS_MAGIC definition to magic.h
2026-09-04 19:36:11 -07:00
Linus Torvalds
408802f1e6 A small fixup for the new nearfull_sync mount option, a potential
use-after-free fix (marked for stable) and a patch that eliminates
 the last use of PageWriteback macro in the tree.
 -----BEGIN PGP SIGNATURE-----
 
 iQFHBAABCgAxFiEEydHwtzie9C7TfviiSn/eOAIR84sFAmqa/nETHGlkcnlvbW92
 QGdtYWlsLmNvbQAKCRBKf944AhHzi7qLB/4gfbxdP5lystLHoDbwSo+ceM15Apl+
 THXVTBGspHNe5w07/fk1NfSk8KccqN66cCh9W23JMZt2PQr+n5/0Azp+ZkcL+koO
 CNNhvachvs+E3J5cRNHvvP3PCQurOO0tCO4vGGHRt6j3VTrWdwKkgVHGHu2hZ49q
 GLkm82eUKYkZdV80FV31q1ZdXHQBCAuxkBgRQNbqlc9yj3OA6UoxLsAaB3uxvmKq
 sifdvIyWFt/+SdntzoM6Dt4vo6P0/RiQJdIXKLj+fxHFiJEeX0IJaTpZvA7FOHOt
 DyRMhb3lTzQBDjZydNQO15XcjfifskuqeQxxSQmISv7lASiUkq5Tn+uj
 =p61q
 -----END PGP SIGNATURE-----

Merge tag 'ceph-for-7.3-rc2' of https://github.com/ceph/ceph-client

Pull ceph fixes from Ilya Dryomov:
 "A small fixup for the new nearfull_sync mount option, a potential
  use-after-free fix (marked for stable) and a patch that eliminates
  the last use of PageWriteback macro in the tree"

* tag 'ceph-for-7.3-rc2' of https://github.com/ceph/ceph-client:
  ceph: apply nearfull_sync option on remount
  libceph: remove pinning assertion in ceph_msg_data_iter_next()
  ceph: lock mutex in ceph_mds_check_access()
2026-09-04 13:27:58 -07:00
Linus Torvalds
58f93a4b73 - Fix a tree connection use-after-free in smb2_tree_connect() by
balancing references across concurrent connect, disconnect, and
    session logoff paths.
 
  - Validate source and target ranges in COPYCHUNK requests before range
    locking and copy operations.
 
  - Fix an oplock break notification UAF by acquiring a connection
    reference under ksmbd_inode lock and releasing it after the
    notification work completes.
 
  - Fix the sparc build by using an unsigned int for the atomic work
    state, ensuring xchg() uses a supported four-byte operation.
 -----BEGIN PGP SIGNATURE-----
 
 iQJKBAABCgA0FiEE6NzKS6Uv/XAAGHgyZwv7A1FEIQgFAmqan48WHGxpbmtpbmpl
 b25Aa2VybmVsLm9yZwAKCRBnC/sDUUQhCP41D/4gNSDDjbGg/Du5nNlNfd7x0/Ql
 ARgdajcnTT/2rUrBkXb3hfNi7BvSHz8jShb7acnwcs9VbxF7cWMk0r+tkjpsONI9
 hwUAXiqOQNkiUJZez+29WgiVuIqNjWSB9WKDGcA7J364Vnwm4M5a8y9wZHfV9ReQ
 aXmVlNlWP6zosrXv4Ex2Eb1bUaYnB822ZrsMQBdiZireUlVUyi/MeWOIrjxt7xPJ
 /nMTJcyDNIFjJJIQMZ/LjzIzvD82QO4LP3F8rlvHD2UIMQik6m0UXF3wPUZGPMbp
 X3o/sPoZHF1KrVpOG4SR5Lvy6KHLtGDSP7bVVhw4ahdtUnyeAeHx/xo9+OKbsiBO
 E4Sji35E8ZyIZ/xHMtOfSfA74W9ia0A0olWyG/mviptJ0RD8unddJP+D/L+EAD0I
 2pQyt9YfwsXm/7FoQXzfbtyi8Z2gl5Jp+xNr6DOyzkIulsBxFOBjgqrUEaTV2/Dc
 abqnVPLo4X9zqiE0HdSNS/go2STx9iox02blZ2wBmYNxEy4X22IheXbyN+wdtn8Q
 Ts8PrE1W0DO8PjWL9TG8okRYY3tRd0AcAVffi6P+QqkRsQNRCduv0mnAsSY1EuU0
 r/M2i5RpQ+JIBLQc4C53zOaAbBCyY1MSXUCgAs1BVyyUdqtjdPJbzyzNn6FDYVPA
 HrPxSl+fmtBsH0C25A==
 =2ZL4
 -----END PGP SIGNATURE-----

Merge tag 'ksmbd-for-7.3-rc2-part2' of git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/smb

Pull smb server fixes from Namjae Jeon:

 - Fix a tree connection use-after-free in smb2_tree_connect() by
   balancing references across concurrent connect, disconnect, and
   session logoff paths.

 - Validate source and target ranges in COPYCHUNK requests before range
   locking and copy operations.

 - Fix an oplock break notification UAF by acquiring a connection
   reference under ksmbd_inode lock and releasing it after the
   notification work completes.

 - Fix the sparc build by using an unsigned int for the atomic work
   state, ensuring xchg() uses a supported four-byte operation.

* tag 'ksmbd-for-7.3-rc2-part2' of git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/smb:
  ksmbd: fix tree connection use-after-free in smb2_tree_connect()
  ksmbd: validate COPYCHUNK source and target ranges
  ksmbd: fix use-after-free in oplock break notification
  ksmbd: fix sparc build with atomic work state
2026-09-04 08:42:14 -07:00
Linus Torvalds
97be98b94d - Serialize truncate, fallocate, and mmap fault paths with
invalidate_lock, avoiding mmap failures during concurrent size changes
    and exposure of uninitialized data during allocation.
 
  - Correct fallocate signal and zeroing error handling.
 
  - Fix FITRIM range alignment to prevent discard requests from extending
    into allocated clusters.
 
  - Fix free-cluster accounting when cluster-freeing rollback or bitmap
    clearing fails.
 
  - Keep volumes marked dirty when ntfs errors have been recorded.
 
  - Compute bi_sector in 512-byte units, preventing silent corruption on
    4Kn devices.
 
  - Validate sectors_per_cluster values and prevent undefined shifts when
    parsing MFT and index record sizes.
 
  - Bound $AttrDef traversal to the loaded table size.
 
  - Fix MFT record resizing, memmove overlap, and kmap_local cleanup issues.
 
  - Improve error propagation across attribute, EA, and reparse operations,
    including returning -ERANGE for undersized xattr buffers.
 
  - Avoid modifying the HasEA flag when setxattr fails and return
    DT_UNKNOWN when directory inode lookup fails.
 
  - Reduce contention in WOF decompression by performing block reads outside
    the decompression lock.
 -----BEGIN PGP SIGNATURE-----
 
 iQJKBAABCgA0FiEE6NzKS6Uv/XAAGHgyZwv7A1FEIQgFAmqZGasWHGxpbmtpbmpl
 b25Aa2VybmVsLm9yZwAKCRBnC/sDUUQhCIdnD/9OEohX3GvIqwHT90GubLIGunJr
 S2D1MSJz0AwNF0sNQhTawAc3fbjwI77B2H3mI/Xghkd4IvgtzcY/L/jYfaZ3M7sn
 Grctto0BypHI5DuBbArfjTQdW/NkPR0IpXGyBLQ8sO6aYVUPGAG0lvL9tT1Zm52N
 JQU1mtjEihE5ZpD79gx8PexuDJHIg0uuok4EANk9Vu+Ub68bDBsnl/Zyxm4spIEA
 976QAdboGDvo+71IdpPSaMuSAMytOf7LDJqxECqZXN5aUOoz9wrJnjELVg+xRE6c
 AFM9hHZ4tZ0zs5A0EpR835URaB/bxGWpbGdkCyDDBm+QMHiTGNp5nGFl/Sd/NO5B
 NcSaj0Tc2+7DbcTLU2hk1FhUsEk8eTwBZK05gxE6OajAIfAyXqxTNeB1th5smLKG
 PjKWjQh9F2okIB71D6jkdntAs/0RPyuu37bTl0EtJeuRoWYZooHkgeA+tV350BQz
 vjOwQuVUnDoNRQ0z1egrqAZalgjoNG7xLu0fI+n7eXZ5a4XZvQpYlKWKsodXYVwX
 TBwnQhst8zEx49fe5dIBGnLiZhhQMe2zxmh7lxAOu6VcVPE4Xv6jSwzcilyiPtQF
 YrdZGOEgtByOLsD+m1PRYZvukvQDDpn+NX6w4dJ+YL3MjGB7X1e2c7imqonJJYM1
 0hByGPAn3g+5XdGSig==
 =gAcy
 -----END PGP SIGNATURE-----

Merge tag 'ntfs-for-7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/ntfs

Pull ntfs fixes from Namjae Jeon:

 - Serialize truncate, fallocate, and mmap fault paths with
   invalidate_lock, avoiding mmap failures during concurrent size
   changes and exposure of uninitialized data during allocation

 - Correct fallocate signal and zeroing error handling

 - Fix FITRIM range alignment to prevent discard requests from extending
   into allocated clusters

 - Fix free-cluster accounting when cluster-freeing rollback or bitmap
   clearing fails

 - Keep volumes marked dirty when ntfs errors have been recorded

 - Compute bi_sector in 512-byte units, preventing silent corruption on
   4Kn devices

 - Validate sectors_per_cluster values and prevent undefined shifts when
   parsing MFT and index record sizes

 - Bound $AttrDef traversal to the loaded table size

 - Fix MFT record resizing, memmove overlap, and kmap_local cleanup
   issues

 - Improve error propagation across attribute, EA, and reparse
   operations, including returning -ERANGE for undersized xattr buffers

 - Avoid modifying the HasEA flag when setxattr fails and return
   DT_UNKNOWN when directory inode lookup fails

 - Reduce contention in WOF decompression by performing block reads
   outside the decompression lock

* tag 'ntfs-for-7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/ntfs: (23 commits)
  ntfs: take invalidate_lock in ntfs_filemap_page_mkwrite()
  ntfs: take invalidate_lock in ntfs_setattr_size()
  ntfs: handle signal interruption in fallocate
  ntfs: fix FITRIM range alignment
  ntfs: read WOF chunks outside the decompression lock
  ntfs: leave HasEA flag untouched on setxattr failure
  ntfs: fix race between fallocate and mmap reads
  ntfs: fix memmove overlap in ntfs_new_attr_flags
  ntfs: compute bi_sector in 512-byte units
  ntfs: reject invalid sectors_per_cluster in the boot sector
  ntfs: bound $AttrDef table walk to the loaded table size
  ntfs: fix undefined behavior in mft/index record size calculation
  ntfs: treat any nonzero dio zero-range return as an error
  ntfs: fix incorrect MFT record pointer passed to ntfs_attr_record_resize
  ntfs: do not mark the volume clean in sync_fs when errors were recorded
  ntfs: skip free cluster decrement when rollback fails
  ntfs: only count successfully cleared runs when freeing clusters
  ntfs: fix kmap_local leak in write_mft_record_nolock() error paths
  ntfs: return real error from ntfs_non_resident_attr_record_add()
  ntfs: preserve error code in ntfs_resident_attr_record_add()
  ...
2026-09-03 08:10:04 -07:00
Qu Wenruo
0c1032c8c3 btrfs: tests: do not touch page cache if root/inode allocation failed
Inside test_find_delalloc() of extent-io-tests.c, if we fail to allocate
a dummy root or the test inode, we go to out label to clean up.

But at that stage, @inode is still NULL and we will call
process_page_range() to access the page cache of the inode, this will
cause NULL pointer dereference.

This is a very minor bug, as it only affects selftests which are not
compiled in by default for most distros, and very hard to trigger.

Fix it by adding a new out_root_info label to handle root and inode
allocation failure.

This is a pre-existing bug reported by Sashiko while reviewing another
patch.

Link: https://sashiko.dev/#/patchset/cover.1786095309.git.wqu%40suse.com
Reviewed-by: Boris Burkov <boris@bur.io>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:30 +02:00
FAN YE
2acb9f3d1c btrfs: zstd: fix lost wakeup when waiting for a workspace
A writer can sleep forever in zstd_get_workspace() even though a workspace
is free.  When zstd_alloc_workspace() fails, the task is queued on
zwsm->wait and schedules unconditionally, never re-testing the pool.
zstd_put_workspace() publishes the workspace and then calls cond_wake_up(),
which only wakes when a sleeper is already visible, so a workspace returned
between the failed allocation and prepare_to_wait() wakes nobody.  The
window is wide: zstd_alloc_workspace() goes through kvmalloc() and may
enter reclaim.

Only a max level workspace triggers the wakeup and one is deliberately kept
allocated as the fallback every waiter waits for, so once its wakeup is
lost the writer stays in TASK_UNINTERRUPTIBLE until some other task happens
to return one.  Re-check the pool after prepare_to_wait() has published the
waiter, and use the workspace if one turned up.

Fixes: 3f93aef535 ("btrfs: add zstd compression level support")
Assisted-by: Claude:claude-opus-5
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: FAN YE <fy15309206903@gmail.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:30 +02:00
Qu Wenruo
cacf358322 btrfs: do not force reloc root creation during qgroup_account_snapshot()
[BUG]
When running btrfs/252 with quota enabled through MKFS_OPTIONS="-O quota",
it has a high chance to trigger the following kernel warning and flips
the fs RO:

  BTRFS info (device dm-2): relocating block group 30408704 flags metadata|dup
  ------------[ cut here ]------------
  WARNING: fs/btrfs/extent-tree.c:879 at lookup_inline_extent_backref+0x74b/0x960 [btrfs], CPU#4: btrfs/2173
  CPU: 4 UID: 0 PID: 2173 Comm: btrfs Not tainted 7.2.0-rc6-custom+ #457 PREEMPT(full)  3adc6528fb66f7a55fe1095385818e742f200aab
  Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS unknown 02/02/2022
  RIP: 0010:lookup_inline_extent_backref+0x74b/0x960 [btrfs]
  Call Trace:
   <TASK>
   insert_inline_extent_backref+0x7c/0x160 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   __btrfs_inc_extent_ref+0xa9/0x270 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   __btrfs_run_delayed_refs+0x4af/0x11c0 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   btrfs_run_delayed_refs+0x9d/0xf0 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   create_pending_snapshot+0x39d/0xf00 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   create_pending_snapshots+0x9b/0xc0 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   btrfs_commit_transaction+0x280/0xeb0 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   prepare_to_relocate+0x147/0x200 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   relocate_block_group+0x6b/0x5e0 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   btrfs_relocate_block_group+0x92c/0x2380 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   btrfs_relocate_chunk+0x3f/0x1a0 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   btrfs_balance+0xa2c/0x19c0 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   btrfs_ioctl+0x2839/0x2d30 [btrfs 32f09462c54d9c922fca74a3e4866f4aa7737b72]
   __x64_sys_ioctl+0x416/0x9a0
   do_syscall_64+0xe1/0x790
   entry_SYSCALL_64_after_hwframe+0x4b/0x53
   </TASK>
  ---[ end trace 0000000000000000 ]---
  BTRFS info (device dm-2): leaf 4593991680 gen 233 total ptrs 175 free space 5953 owner 2
  BTRFS info (device dm-2): refs 3 lock_owner 2173 current 2173
  	item 0 key (166772736 METADATA_ITEM 1) itemoff 16250 itemsize 33
  		extent refs 1 gen 222 flags 2
  		ref#0: tree block backref root 266
         [ Skip the tree dump ]
  	item 174 key (263225344 METADATA_ITEM 0) itemoff 10328 itemsize 33
  		extent refs 1 gen 162 flags 258
  		ref#0: tree block backref root 267
  BTRFS error (device dm-2): extent item not found for insert, bytenr 179847168 num_bytes 16384 parent 4594335744 root_objectid 273 owner 0 offset 0
  BTRFS error (device dm-2): failed to run delayed ref for logical 179847168 num_bytes 16384 type 182 action 1 ref_mod 1: -117

[CAUSE]
The above error is showing that there is a tree reference to a metadata
extent that is no longer there.

With "ref_verify" mount option (requires CONFIG_BTRFS_DEBUG), there is
some extra debug output:

  BTRFS error (device dm-2): dumping block entry [180961280 16384], num_refs 0, metadata 1, from disk 0
  BTRFS error (device dm-2):   root entry 256, num_refs 18446744073709551615
  BTRFS error (device dm-2):   root entry 273, num_refs 18446744073709551615
  BTRFS error (device dm-2):   Ref action 3, root 273, ref_root 273, parent 0, owner 0, offset 0, num_refs 1
     btrfs_force_cow_block+0x129/0x7d0 [btrfs]
     btrfs_cow_block+0x10a/0x250 [btrfs]
     btrfs_search_slot+0x5eb/0xf40 [btrfs]
     btrfs_insert_empty_items+0x3a/0x70 [btrfs]
     insert_with_overflow+0x53/0x130 [btrfs]
     btrfs_insert_dir_item+0x125/0x290 [btrfs]
     btrfs_add_link+0xaa/0x410 [btrfs]
     btrfs_rename+0x5ea/0xcd0 [btrfs]
     btrfs_rename2+0x28/0x60 [btrfs]
     vfs_rename+0x5b2/0xe10
     filename_renameat2+0x244/0x430
     __x64_sys_rename+0x48/0x70
     do_syscall_64+0xe1/0x790
     entry_SYSCALL_64_after_hwframe+0x4b/0x53
  BTRFS error (device dm-2):   Ref action 2, root 273, ref_root 273, parent 0, owner 0, offset 0, num_refs 18446744073709551615
     btrfs_force_cow_block+0x327/0x7d0 [btrfs]
     btrfs_cow_block+0x10a/0x250 [btrfs]
     btrfs_search_slot+0x5eb/0xf40 [btrfs]
     btrfs_lookup_file_extent+0x4d/0x70 [btrfs]
     btrfs_drop_extents+0x151/0xf00 [btrfs]
     insert_reserved_file_extent+0xfe/0x3e0 [btrfs]
     btrfs_finish_one_ordered+0x549/0xc40 [btrfs]
     btrfs_work_helper+0xde/0x350 [btrfs]
     process_one_work+0x198/0x380
     worker_thread+0x1c8/0x330
     kthread+0xee/0x120
     ret_from_fork+0x28f/0x310
     ret_from_fork_asm+0x11/0x20
  BTRFS error (device dm-2):   Ref action 1, root 273, ref_root 0, parent 4594335744, owner 0, offset 0, num_refs 1
     __btrfs_mod_ref+0x1c5/0x2d0 [btrfs]
     btrfs_copy_root+0x262/0x390 [btrfs]
     create_reloc_root+0xb9/0x370 [btrfs]
     btrfs_init_reloc_root+0xb0/0x1b0 [btrfs]
     record_root_in_trans+0xa6/0xd0 [btrfs]
     create_pending_snapshot+0x383/0xf00 [btrfs]
     create_pending_snapshots+0x9b/0xc0 [btrfs]
     btrfs_commit_transaction+0x280/0xeb0 [btrfs]
     prepare_to_relocate+0x147/0x200 [btrfs]
     relocate_block_group+0x6b/0x5e0 [btrfs]
     btrfs_relocate_block_group+0x92c/0x2380 [btrfs]
     btrfs_relocate_chunk+0x3f/0x1a0 [btrfs]
     btrfs_balance+0xa2c/0x19c0 [btrfs]
     btrfs_ioctl+0x2839/0x2d30 [btrfs]
     __x64_sys_ioctl+0x416/0x9a0
     do_syscall_64+0xe1/0x790

The above shows the direct cause, Ref action 3 is the oldest operation,
which shows the tree block is created by COW.  Then ref action 2 shows
it's COWed away, by a metadata update, meaning the tree block is already
released, should not be referred any more.

Then the final one, is trying to create a reloc tree for subvolume 273,
and that reloc root creation is referring to the already dropped tree
block.

The root cause is that, during qgroup_account_snapshot(), we are calling
record_root_in_trans() with "force = true".
So if the root has no reloc root, we will create one, but at that
timing it's already too late.

Normally reloc root should be created before the commit and current
roots diverge, to avoid the same problem we are hitting.

But during relocation initialization, we are committing the current
running transaction, with a new reloc_control attached halfway.

And if qgroup is enabled, the record_root_in_trans() with "force = true"
calls will force reloc root creation even if we do not and should not
create reloc root at that timing.

[FIX]
Do not force reloc root creation during record_root_in_trans() with
"force = true" cases, which is only called by qgroup_account_snapshot().

If we're really under relocation, the reloc root should be created way
early, before the commit and current root diverge.  If the root has no
reloc tree yet, it means we're still initializing the reloc, and do not
need a reloc root.

So skipping the reloc tree creation in qgroup_account_snapshot() should
be safe.

Link: https://bugzilla.suse.com/show_bug.cgi?id=1275740
Fixes: 4d31778aa2 ("btrfs: qgroup: Fix root item corruption when multiple same source snapshots are created with quota enabled")
Assisted-by: LLM (initial analysis, but incorrect conclusion with too many burnt tokens)
Tested-by: Disha Goel <disgoel@linux.ibm.com>
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:30 +02:00
Avi Weiss
d0285dfbc3 btrfs: send: fix lost error return value in will_overwrite_ref()
The direct-return refactoring in commit b3047a42f5 ("btrfs: send:
directly return from will_overwrite_ref() and simplify it") changed
will_overwrite_ref() to return directly instead of going through the
common out label.

That resulted in a negative return value from is_inode_existent() to
start being converted to 0, making lookup errors unable to be
distinguished from the inode not existing.

process_recorded_refs() expects negative errors from
will_overwrite_ref() and aborts processing when it receives one.

Return the value from is_inode_existent() to restore the previous error
propagation behavior as it was before the refactor.

Fixes: b3047a42f5 ("btrfs: send: directly return from will_overwrite_ref() and simplify it")
Signed-off-by: Avi Weiss <thnkslprpt@gmail.com>
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:30 +02:00
Leo Martins
529c01c3dc btrfs: abort transaction before releasing tree_log_mutex on commit failure
When transaction metadata writeout fails in btrfs_commit_transaction(),
the current code only logs the error, drops tree_log_mutex and then goes
through cleanup_transaction(), which aborts the transaction and records
the fs error.

That is too late for the tree log side. A log sync can already be
waiting on tree_log_mutex, because the committing transaction is moved
to TRANS_STATE_UNBLOCKED while that mutex is held, which lets fsyncs
join the next transaction and queue up in btrfs_sync_log(). Once the
failed commit drops tree_log_mutex, such a log sync acquires it, sees
BTRFS_FS_ERROR() still clear, and writes super_for_commit. That
superblock holds the roots prepared for the transaction that has just
failed to write out its metadata, so it can point at tree blocks that
never reached the disk, and the next mount fails with a parent transid
mismatch.

Commit 165ea85f14 ("btrfs: do not write supers if we have an fs
error") fixed this class of problem by making btrfs_sync_log() check for
an fs error right after taking tree_log_mutex. That check only works if
the commit path publishes the fs error before it releases the same
mutex, and commit 68d4ece9c3 ("btrfs: don't call
btrfs_handle_fs_error() in btrfs_commit_transaction()") removed the only
thing that did so.

Restore the ordering by aborting the transaction while tree_log_mutex is
still held. We have a transaction handle here, so this does not need to
bring back the btrfs_handle_fs_error() call: __btrfs_abort_transaction()
records the fs error itself, which is all btrfs_sync_log() looks at, and
the error message put in its place is kept.

This is what commit 3810ab40af ("btrfs: abort transaction on error in
write_all_supers()") already does for the next call in this function.

This is reproducible on an unmodified kernel by failing the first
couple of bios of a transaction commit with fail_make_request while a
concurrent fsync workload keeps log syncs queued on tree_log_mutex.

Fixes: 68d4ece9c3 ("btrfs: don't call btrfs_handle_fs_error() in btrfs_commit_transaction()")
CC: stable@vger.kernel.org # 7.0+
Reviewed-by: Boris Burkov <boris@bur.io>
Reviewed-by: jlayton@meta.com <jlayton@meta.com>
Signed-off-by: Leo Martins <loemra.dev@gmail.com>
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:30 +02:00
Johannes Thumshirn
c428b763f2 btrfs: zoned: propagate do_zone_finish() error in btrfs_zone_finish_endio()
btrfs_zone_finish_endio() ignored the return value of do_zone_finish()
and always returned 0, silently dropping a failed zone finish.

Instead propagate any error from do_zone_finish() as the caller
btrfs_finish_ordered_io() already handles it.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:29 +02:00
Johannes Thumshirn
a18a6b93a2 btrfs: zoned: finish active block group cleanup if call_zone_finish() fails
do_zone_finish() clears BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE before finishing
the zones. If call_zone_finish() then fails it returned early, leaving the
now inactive block group on fs_info->zone_active_bgs, leaking its
reference, the BTRFS_FS_NEED_ZONE_FINISH waiters are never woken, and as
its alloc_offset equals the zone capacity btrfs_zone_finish_one_bg() keeps
selecting it, spinning btrfs_zoned_activate_one_bg().

Fall through to the cleanup on failure too and return the error, but keep
the block group read-only as its zones are left inconsistent.

Fixes: d70cbdda75 ("btrfs: zoned: consolidate zone finish functions")
Link: https://sashiko.dev/#/patchset/20260818100037.1366563-1-johannes.thumshirn%40wdc.com
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:29 +02:00
ZhengYuan Huang
0853dc4f26 btrfs: send: reject extents for non-regular inodes
[BUG]
A corrupted subvolume tree can leave an EXTENT_DATA item attached to an
inode whose mode is not S_IFREG or S_IFLNK. During send, such an item can
be treated as file data and crash through a NULL address_space operation:

  BUG: kernel NULL pointer dereference, address: 0000000000000000
  #PF: supervisor instruction fetch in kernel mode
  #PF: error_code(0x0010) - not-present page
  Call Trace:
    <TASK>
    read_pages+0x80b/0xb30 mm/readahead.c:173
    page_cache_ra_unbounded+0x40d/0x890 mm/readahead.c:302
    do_page_cache_ra mm/readahead.c:332 [inline]
    page_cache_ra_order+0xa16/0xcd0 mm/readahead.c:535
    page_cache_sync_ra+0x5ce/0x9d0 mm/readahead.c:626
    page_cache_sync_readahead include/linux/pagemap.h:1379 [inline]
    put_file_data fs/btrfs/send.c:5224 [inline]
    send_write fs/btrfs/send.c:5291 [inline]
    send_extent_data+0x16b2/0x29b0 fs/btrfs/send.c:5715
    send_write_or_clone fs/btrfs/send.c:6135 [inline]
    process_extent+0x5d4/0x17b0 fs/btrfs/send.c:6504
    changed_extent fs/btrfs/send.c:7079 [inline]
    changed_cb+0x22f9/0x3cd0 fs/btrfs/send.c:7245
    full_send_tree fs/btrfs/send.c:7318 [inline]
    send_subvol fs/btrfs/send.c:7910 [inline]
    btrfs_ioctl_send+0x46a9/0x57f0 fs/btrfs/send.c:8248
    ...

[CAUSE]
process_extent() skips extent items for symlinks but assumes every other
inode with an extent item is a regular file. For a corrupted non-regular
inode, btrfs_iget() does not install the regular file address_space
operations. The readahead fallback can then call a NULL read_folio
callback before the existing validation in btrfs_get_extent() can run.

[FIX]
Reject extent items for inode types other than regular files and symlinks
at the common send extent-processing boundary. Symlink handling is left
unchanged because send emits symlink data from read_symlink(). This covers
full, incremental and new-generation sends without adding a check to the
regular I/O path.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: ZhengYuan Huang <gality369@gmail.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:29 +02:00
Qu Wenruo
a03fa65184 btrfs: return proper negative error code for update_raid_extent_item()
The function btrfs_abort_transaction() only accepts negative error code,
and have the macro VERIFY_NEGATIVE_ERROR() to verify that error code.

But inside update_raid_extent_item(), if there is such key found, we
return 1, breaking the negative error code scheme.

Furthermore if we hit some real error during the tree search, e.g. -EIO,
then the error code is always over-written to -EINVAL.

Fix both problems by following other call sites by overwriting @ret to
-ENOENT if the btrfs_search_slot() failed to locate the key.

This is very unlikely to hit, as we only enter update_raid_extent_item()
if there is a conflicting key already in the raid stripe tree.

This was reported by Sashiko when reviewing another patch.

Link: https://sashiko.dev/#/patchset/20260817021512.3010812-1-shuangpeng.kernel%40gmail.com
Fixes: 8c4cba2adb ("btrfs: update stripe extents for existing logical addresses")
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:29 +02:00
Qu Wenruo
afbe737783 btrfs: fix the possible bioc_list memory leak during error
There are two possible ways to leak bioc memory on
btrfs_ordered_extent::bioc_list:

- An error occurred for btrfs_insert_one_raid_extent()
  Then the function btrfs_insert_raid_extent() immediately return
  without freeing any bioc in the bioc_list.

- An ordered extent hit an IO error
  In that case the ordered extent will have BTRFS_ORDERED_IOERR set, and
  skip the call on btrfs_insert_raid_extent() completely.

Fix the problem by:

- Introduce a new helper, btrfs_cleanup_ordered_bioc_list()
  Which will remove all bioc from the bioc_list, and release the bioc.

- Call the above helper for btrfs_insert_raid_extent()
  So that the cleanup helper is always called no matter what.

- Call the above helper for btrfs_finish_one_ordered()
  This is called just before the final release on the ordered extent.

This was reported by Sashiko when reviewing another patch.

Link: https://sashiko.dev/#/patchset/20260817021512.3010812-1-shuangpeng.kernel%40gmail.com
Fixes: 02c372e1f0 ("btrfs: add support for inserting raid stripe extents")
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:29 +02:00
Shuangpeng Bai
a8813a923f btrfs: fix transaction use-after-free in raid stripe insertion
If allocation of a RAID stripe extent fails,
btrfs_insert_one_raid_extent() aborts and ends the transaction before
returning -ENOMEM.

btrfs_finish_one_ordered(), the production caller through
btrfs_insert_raid_extent(), still owns the transaction handle. It handles
the error by aborting the transaction and then reaches the common exit
path, which ends the transaction again.

The premature end can free the handle and drop its transaction reference.
Transaction cleanup can then free the transaction before the caller's
second abort accesses the handle and transaction, resulting in
use-after-free.

Keep the abort at the failure site, but let the caller's common exit path
end the transaction once, after it has finished using both objects.

Fixes: 02c372e1f0 ("btrfs: add support for inserting raid stripe extents")
Assisted-by: Codex:GPT-5
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Shuangpeng Bai <shuangpeng.kernel@gmail.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:29 +02:00
James C. Owens
33ce0aa4c5 btrfs: scrub: report the failing sector's address, not the stripe base
scrub_stripe_report_errors() iterates over the sectors of a stripe, but
every message it emits passes stripe->logical, the address of the first
sector of the 64KiB stripe, rather than the address of the sector being
reported. The physical address is likewise computed once, before the
loop, from stripe->logical.

This matters because scrub_print_common_warning() uses that logical
address for the backref walk which produces the "root %llu inode %llu
offset %llu ... (path: ...)" part of the message. As the address is
always the stripe base, the reported root/inode/offset/path can identify
a different file from the one whose sector actually failed.

A 64KiB stripe routinely spans several extents belonging to unrelated
files. On the machine where this was found, the stripe at logical
0x17D9380000 holds four sectors of /usr/share/plasma/emoji/bg.dict, then
a file inside a docker volume, then sectors referenced only by
snapshots. Every error anywhere in that stripe is attributed to bg.dict.

The effect is visible statistically: across ten months and four kernel
series that machine logged 81 distinct flagged logical addresses, and
every one of them is exactly 64KiB aligned. Since BTRFS_STRIPE_LEN is
64KiB and stripe->logical is stripe aligned by construction, real
failures distributed across sectors could not produce that.

Report the address of the sector actually being examined. Adding the
sector offset to the physical address is valid because BTRFS_STRIPE_LEN
is the unit contiguous on a single device for every profile, so a stripe
never crosses a device boundary.

Fixes: 0096580713 ("btrfs: scrub: introduce error reporting functionality for scrub_stripe")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: James C. Owens <jamesowens@optonline.net>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 22:19:21 +02:00
Alex Markuze
dc173b3741 ceph: apply nearfull_sync option on remount
ceph_parse_mount_param() stores nearfull_sync / nonearfull_sync on the
temporary fs_context options, but ceph_reconfigure_fc() never copied
CEPH_MOUNT_OPT_NEARFULL_SYNC onto the live mount. Remount therefore
succeeded while writes and /proc/mounts kept the original-mount flag.

Apply the flag the same way as ASYNC_DIROPS and SPARSEREAD so remount
can enable or disable NEARFULL IOCB_DSYNC promotion.

Fixes: c7a12c20bfba ("ceph: make nearfull sync writes opt-in")
Signed-off-by: Alex Markuze <amarkuze@redhat.com>
Reviewed-by: Xiubo Li <xiubo.li@clyso.com>
Signed-off-by: Ilya Dryomov <idryomov@gmail.com>
2026-09-02 12:23:05 +02:00
Max Kellermann
a61c6ae1da ceph: lock mutex in ceph_mds_check_access()
MDS session OPEN handling replaces mdsc->s_cap_auths under
mdsc->mutex, freeing the previous array and its strings.

ceph_mds_check_access() traverses this array without holding the
mutex.  A concurrent session reopen can therefore free the array while
it is being inspected, resulting in a use-after-free like this:

  Unable to handle kernel paging request at virtual address 003aaad64b2c8bb9
  [...]
  Internal error: Oops: 0000000096000004 [#1]  SMP
  Modules linked in:
  CPU: 56 UID: 2953037534 PID: 1253231 Comm: php-cgi8.4 Not tainted 6.18.45-i2-ampere #1146 NONE
  [..]
  pc : ceph_mds_check_access+0xd4/0x550
  lr : ceph_mds_check_access+0xc8/0x550
  [...]
  Call trace:
   ceph_mds_check_access+0xd4/0x550 (P)
   ceph_atomic_open+0x138/0xbe8
   path_openat+0xa24/0xfa8
   do_filp_open+0x94/0x158
   do_sys_openat2+0x88/0xf8

Cc: stable@vger.kernel.org
Fixes: 596afb0b89 ("ceph: add ceph_mds_check_access() helper")
Signed-off-by: Max Kellermann <max.kellermann@ionos.com>
Reviewed-by: Alex Markuze <amarkuze@redhat.com>
Signed-off-by: Ilya Dryomov <idryomov@gmail.com>
2026-09-02 12:22:03 +02:00
Cen Zhang (Microsoft Security FORGE Labs)
b5ec6c462a ksmbd: fix tree connection use-after-free in smb2_tree_connect()
ksmbd_tree_conn_connect() publishes a new tree connection in
sess->tree_conns with a single reference and returns its pointer to
smb2_tree_connect(). The handler continues to initialize the object and
build the response after publication. A concurrent session logoff can
erase the connection and drop that reference, freeing the object while
the handler still uses it.

BUG: KASAN: slab-use-after-free in smb2_tree_connect+0xe3d/0xf90
  smb2_tree_connect (fs/smb/server/smb2pdu.c:2872)
  handle_ksmbd_work
  process_one_work
  worker_thread
  kthread

After xa_store() succeeds, take a second reference before releasing
tree_conns_lock. The original reference belongs to the xarray entry and
the second belongs to the creating smb2_tree_connect() handler.

Keep the references balanced in every path:

- On normal exit or an error after publication, smb2_tree_connect()
  drops its creator reference. Error cleanup also calls
  ksmbd_tree_conn_disconnect(), which drops the xarray reference only if
  it removes the exact entry.
- SMB2 TREE_DISCONNECT uses the same helper to remove the entry and drop
  its xarray reference. The request's existing lookup reference remains
  owned by the request and is released by the existing cleanup.
- Session LOGOFF removes each entry and drops its xarray reference. If
  it wins the race, later cleanup sees that the entry is gone and does
  not drop that reference again.

To enforce this ownership, claim the disconnected state and erase the
exact entry atomically under tree_conns_lock. This guarantees one drop
for the xarray reference and one drop by each in-flight user, regardless
of which teardown path wins. If logoff removes the entry before
initialization completes, fail the connect instead of marking the
detached object TREE_CONNECTED.

Fixes: 33b235a6e6 ("ksmbd: fix race condition between tree conn lookup and disconnect")
Reported-by: Xiang Mei (Microsoft) <xmei5@asu.edu>
Cc: AutonomousCodeSecurity@microsoft.com
Cc: stable@vger.kernel.org
Signed-off-by: Cen Zhang (Microsoft Security FORGE Labs) <cenzhang@linux.microsoft.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-09-02 17:58:35 +09:00
Alon Shakevsky
0480cee8cc ksmbd: validate COPYCHUNK source and target ranges
ksmbd_vfs_copy_file_ranges() rejects negative source offsets in the
copy loop, but it does not validate target offsets. It also calculates
lock and overlap endpoints before ensuring that either range fits within
MAX_LFS_FILESIZE.

When the target is an alternate data stream, the buffered path passes a
negative target offset to ksmbd_vfs_stream_write(). Let n be Length and
let -d be TargetOffset, where 0 < d < n <= XATTR_SIZE_MAX. For an empty
stream, the writer allocates n - d bytes, then copies n bytes starting d
bytes before the allocation. An authenticated SMB client can control d
and the source data, overwrite kernel heap memory, and crash the host.

Validate both ranges before lock, overlap, or I/O calculations.

Fixes: 8482150a07 ("ksmbd: support copychunk for alternate data streams")
Assisted-by: Antiproof:GPT-5.6-Sol
Signed-off-by: Alon Shakevsky <shakevsky@berkeley.edu>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-09-02 17:58:15 +09:00
Abdifatah Suruur
0e75389962 ksmbd: fix use-after-free in oplock break notification
smb2_oplock_break_noti() reads opinfo->conn without any lock and
dereferences it after two allocations which may sleep.  When the
durable handle owning the oplock is disconnected, session_fd_check()
clears opinfo->conn and drops its conn reference under ci->m_lock, and
the last ksmbd_conn_put() frees the connection.  A break triggered by
another connection that races with the teardown can then resurrect the
freed connection: ksmbd_conn_get() is a plain atomic_inc, and the
queued break work later dereferences the stale conn via
ksmbd_conn_write(), a use-after-free reachable by any authenticated
client holding a durable batch oplock.

Thread the caller's inode into the notification path instead of taking
a new reference on it.  Every caller of oplock_break() already holds a
live ksmbd_file (or an explicit ksmbd_inode_lookup_lock() reference,
in the parent lease break paths) on the inode that owns the break
target's oplock list, so ci cannot be freed during the call, and its
lock can be taken without dereferencing opinfo->o_fp, which a
concurrent close may free.  Select and pin the connection under
ci->m_lock, the same lock session_fd_check() and
ksmbd_reopen_durable_fd() use to update opinfo->conn, so a concurrent
detach either loses the race to the clear or keeps the connection
alive until the notification work releases it.  Transfer the reference
to the work item and release it on allocation failures.

Fixes: b003086d76 ("ksmbd: fix NULL-deref of opinfo->conn in oplock/lease break notifiers")
Cc: stable@vger.kernel.org
Signed-off-by: Abdifatah Suruur <suruurism@gmail.com>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-09-02 17:58:11 +09:00
Namjae Jeon
636abbe7a6 ksmbd: fix sparc build with atomic work state
Use an unsigned int for the work state so xchg() uses a supported
4-byte operation on sparc.

Fixes: d12168084c ("ksmbd: safely drain sessions during logoff")
Reported-by: kernel test robot <lkp@intel.com>
Closes: https://lore.kernel.org/oe-kbuild-all/202609021157.8f7Wx34I-lkp@intel.com/
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-09-02 17:58:00 +09:00
Frederick Lawler
ab84c31441 configfs: move CONFIGFS_MAGIC definition to magic.h
IMA shouldn't measure or appraise configfs, but currently does because
it's missing from the default exclusion policies. Move CONFIGFS_MAGIC to
magic.h to expose the file system's magic to IMA, as well as other userland
applications.

Suggested-by: Mimi Zohar <zohar@linux.ibm.com>
Signed-off-by: Frederick Lawler <fred@cloudflare.com>
Acked-by: Breno Leitao <leitao@debian.org>
Signed-off-by: Mimi Zohar <zohar@linux.ibm.com>
2026-09-01 22:28:55 -04:00
Sam Ho
e8a0095c7d btrfs: preserve the compression property when other inode flags change
Setting the compression property on an inode also sets BTRFS_INODE_COMPRESS
on it, and btrfs_inode_flags_to_fsflags() reports that back as FS_COMPR_FL
to FS_IOC_GETFLAGS. chattr(1), like any other FS_IOC_SETFLAGS caller, reads
the current flags, flips only the bit the user asked for and writes the
whole set back, so a request as unrelated as "chattr +i" reaches
btrfs_fileattr_set() with FS_COMPR_FL set.

btrfs_fileattr_set() takes that as a request to enable compression and
overwrites the compression property with the algorithm from the mount
options, falling back to zlib when the filesystem was not mounted with
-o compress. The algorithm the user selected is silently replaced:

  # btrfs property set /mnt/foo compression zstd
  # btrfs property get /mnt/foo compression
  compression=zstd
  # chattr +i /mnt/foo
  # btrfs property get /mnt/foo compression
  compression=zlib

Every chattr operation triggers this, not just +i, and directories are
affected as well, so files created afterwards inherit the wrong algorithm
too. On a filesystem mounted with -o compress=lzo the property is replaced
with lzo instead. Recovering needs a chattr -i first, because the immutable
flag rejects the setxattr that "btrfs property set" issues.

Prefer the algorithm recorded in the compression property and only fall
back to the mount default when there is no property, so that unrelated
flag changes no longer overwrite the user's choice. Inodes that have the
compress flag set but no property still get the default, so they behave
as before.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Sam Ho <samho@synology.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 00:02:03 +02:00
Guanghui Yang
e0b54613aa btrfs: restore active device pointers after failed sprout
btrfs_init_new_device() switches latest_dev and possibly s_bdev from the
seed device to the new sprout device before creating the first writable
chunks.

If chunk creation or the subsequent sprout setup fails, the error path
releases the new device without switching those pointers back.
btrfs_show_devname() can then dereference the freed latest_dev and crash.

Restore the active device pointers to the latest seed device before
removing and releasing the failed sprout device.

Fixes: b7cb29e666 ("btrfs: update latest_dev when we create a sprout device")
Assisted-by: Codex:gpt-5
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Guanghui Yang <3497809730@qq.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 00:01:40 +02:00
Guanghui Yang
c93b3c43df btrfs: detach failed sprout device from transaction update list
When creating the first metadata chunk for a sprout filesystem,
create_chunk() adds the new device to the transaction dev_update_list
through device->post_commit_list.

If the subsequent system chunk creation fails, btrfs_init_new_device()
aborts the transaction and releases the device while post_commit_list is
still linked. This triggers a warning in btrfs_free_device() and leaves
the transaction list referencing freed memory.

Detach the device while holding chunk_mutex before releasing it.

Fixes: bbbf7243d6 ("btrfs: combine device update operations during transaction commit")
Assisted-by: Codex:gpt-5
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Guanghui Yang <3497809730@qq.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 00:01:38 +02:00
Guanghui Yang
40fe154ba0 btrfs: clean up target device if block group marking fails
btrfs_dev_replace_start() adds the replacement target to the device list
before marking block groups to copy. If marking fails, returning
directly leaves the target linked and keeps the device accounting
incremented.

Jump to the existing cleanup path so the target device is removed and
released on failure.

The issue was found by a failure-path metadata residual analyzer and
verified with targeted failure injection on v6.14.

Assisted-by: Codex:gpt-5
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Guanghui Yang <3497809730@qq.com>
Reviewed-by: David Sterba <dsterba@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2026-09-02 00:01:34 +02:00
Linus Torvalds
89a312991d SMB client fixes for v7.3-rc2
A batch of bug fixes for the SMB client:
 
  - Fixes for fallocate range operations (insert, collapse, zero, punch
    hole): the insert range implementation copied overlapping chunks in
    the wrong direction, corrupting file data on every server except
    Windows.  Several related issues in the same area are also
    addressed — stale page cache and FS-Cache readback, an integer
    truncation on large files, missing RLIMIT_FSIZE validation and
    missing sparse file marking.
 
  - Data corruption fixes in the O_TRUNC open path: one where i_size
    was zeroed before the server confirmed the truncate and another
    where the lack of locking allowed concurrent buffered writes to be
    silently discarded.
 
  - Heap overflow fixes in legacy SMB1 paths: one in extended attribute
    writes and one in POSIX ACL handling, both exploitable via
    unprivileged setxattr(2).
 
  - Fix for multiuser mount with krb5 failing because the username
    option was not propagated to new per-user connections.
 
  - Fix for split debug message in __release_mid() after a printk
    conversion.
 -----BEGIN PGP SIGNATURE-----
 
 iHUEABYKAB0WIQTcqRusfSdYROJQwGkpVtNKoQNdYwUCapcv6wAKCRApVtNKoQNd
 Y0dgAQDvlnpdCsg1SZZN7T/wSy08fP7GEl2lUoCb8m6LQHlDlwEA/RG+FeY8sRkb
 iJexqIGT85a48SHmpSavzBO3qkuqIQo=
 =+Qbr
 -----END PGP SIGNATURE-----

Merge tag 'cifs-fixes-7.3-rc2' of https://git.manguebit.org/linux

Pull smb client fixes from Paulo Alcantara:

 - Fixes for fallocate range operations (insert, collapse, zero, punch
   hole)

   The insert range implementation copied overlapping chunks in the
   wrong direction, corrupting file data on every server except Windows.

   Several related issues in the same area are also addressed — stale
   page cache and FS-Cache readback, an integer truncation on large
   files, missing RLIMIT_FSIZE validation and missing sparse file
   marking.

 - Data corruption fixes in the O_TRUNC open path: one where i_size was
   zeroed before the server confirmed the truncate and another where the
   lack of locking allowed concurrent buffered writes to be silently
   discarded

 - Heap overflow fixes in legacy SMB1 paths: one in extended attribute
   writes and one in POSIX ACL handling, both exploitable via
   unprivileged setxattr(2)

 - Fix for multiuser mount with krb5 failing because the username option
   was not propagated to new per-user connections

 - Fix for split debug message in __release_mid() after a printk
   conversion

* tag 'cifs-fixes-7.3-rc2' of https://git.manguebit.org/linux:
  smb: client: reject SetEA requests that do not fit the request buffer
  smb: client: fix data corruption with concurrent writes and O_TRUNC
  cifs: don't update i_size in cifs_do_truncate without a cached handle
  smb: client: fix heap overflow in cifs_do_set_acl()
  smb: client: fix multiuser mount with krb5
  smb: client: transport: Fix debug printing in __release_mid()
  smb/client: invalidate fscache for fallocate range operations
  smb/client: fix stale page cache in insert/collapse range
  smb/client: fix integer truncation in collapse range
  smb/client: fix data corruption in emulated insert range
  smb/client: mark file sparse before emulating insert range
  smb/client: validate new EOF for zero range
  smb/client: validate new EOF for insert range
  cifs: add revalidation on FSCTL failure in smb2_duplicate_extents()
2026-09-01 13:37:14 -07:00
Linus Torvalds
9a58da8005 - Prevent unintended data exposure by clearing pipe compound padding and
the response buffer.
 
  - Initialize missing fields in FS_OBJECT_ID_INFORMATION,
    FS_CONTROL_INFORMATION, and FS_POSIX_INFORMATION.
 
  - Propagate DACL parsing and allocation failures so malformed security
    descriptors are rejected.
 
  - Rate-limit errors for unmapped SIDs to prevent kernel log flooding.
 
  - Drain multichannel sessions during LOGOFF, wake deferred locks and
    cancellable requests, and ensure cancellation callbacks run only once.
 
  - Fix listener kthread reference handling and teardown ordering during
    netdevice events.
 
  - Validate normalized-name and IPC share configuration response lengths.
 
  - Update the KSMBD MAINTAINERS entry and add Paulo Alcantara as
    an SMBDIRECT co-maintainer.
 -----BEGIN PGP SIGNATURE-----
 
 iQJKBAABCgA0FiEE6NzKS6Uv/XAAGHgyZwv7A1FEIQgFAmqWnz0WHGxpbmtpbmpl
 b25Aa2VybmVsLm9yZwAKCRBnC/sDUUQhCJK8EACCE2K2p9CH6kiy9VnMjEqTbIBF
 ZRCmxrspoPAMuTbK6529dXHUVTsXlUdJ/FVzGwNLtvXwEIVjNaQDqBEFWCdPElE+
 8grKsC1S3gH3t8Z1wT6eNh5cpDoA+rWJDbNK4DsmHdoVagyjd9dd7fkMi7nq0WJS
 NO7BTHaTuTaZDul8UXc1gqkVLviZZWkrtkGVVnsJV1z5cFls6P81cVmtzP0836cU
 kVDYSI0EZnX+1P5CtOxL3r5LDBex6lRHU+rj1ypJRJDM2nR+bYIeJk+XMjylKCHT
 liPj7dwI/ptVzp+n3dbcTyhLZayDhZ0/GeJanX2/midtiNSKhao9h94BymPU91jV
 JugPlkAO8Vqwo7xojWRqudz4Kg/vgr66NexQ/3W2tuRXXFN4kEWmQG0N5+kH0K3d
 sJ5xA9uLj24+d29fjylkdSGpuRLR8XcR01he2CaqLRopXZrCxFChwzZwbads1rI/
 kXtYrORB0u99ScwTRQeW90dzeZ+1R3aHOyf8H86zyJ07l2NxG8t5L/49vuaiaiEZ
 5r4hhPVumlmDQdPoOcugOmkJL68+W4TzS7UfcOSgq43W31BE1dYsaX7u4MHNk/Nq
 UiWJJPArJ3ry8e4GLqQXx4ylZJnykGS9s676gFCO1GAI+eXoQ4R0k7RCKy/TW0ap
 t3oa0Yj+Y4QAZCD3Rw==
 =UL/J
 -----END PGP SIGNATURE-----

Merge tag 'ksmbd-for-7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/smb

Pull smb server fixes from Namjae Jeon:

 - Prevent unintended data exposure by clearing pipe compound padding
   and the response buffer

 - Initialize missing fields in FS_OBJECT_ID_INFORMATION,
   FS_CONTROL_INFORMATION, and FS_POSIX_INFORMATION

 - Propagate DACL parsing and allocation failures so malformed security
   descriptors are rejected

 - Rate-limit errors for unmapped SIDs to prevent kernel log flooding

 - Drain multichannel sessions during LOGOFF, wake deferred locks and
   cancellable requests, and ensure cancellation callbacks run only once

 - Fix listener kthread reference handling and teardown ordering during
   netdevice events

 - Validate normalized-name and IPC share configuration response lengths

 - Update the KSMBD MAINTAINERS entry and add Paulo Alcantara as an
   SMBDIRECT co-maintainer

* tag 'ksmbd-for-7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/smb:
  ksmbd: validate normalized name response length
  ksmbd: fix listener task lifetime on netdev events
  ksmbd: prevent out-of-bounds reads in share config responses
  ksmbd: rate limit unmapped SID errors
  ksmbd: propagate DACL parsing errors
  ksmbd: zero pipe read compound padding
  ksmbd: safely drain sessions during logoff
  MAINTAINERS: Update the KSMBD entry
  MAINTAINERS: Add Paulo Alcantara as an SMBDIRECT co-maintainer
  ksmbd: fill in FileSysIdentifier in FS_POSIX_INFORMATION
  ksmbd: initialize FileSystemControlFlags in FS_CONTROL_INFORMATION
  ksmbd: zero the FS_OBJECT_ID_INFORMATION buffer before filling it in
2026-09-01 08:17:01 -07:00
Hengyu Liang
7b15d6cf25 kernfs: preserve security xattrs without allocating iattrs
Commit d5e81a5650 ("kernfs: avoid iattr allocation in listxattr")
made kernfs_iop_listxattr() return an empty list when the kernfs node
has no allocated kernfs_iattrs.

However, this also skips security xattr names provided by
simple_xattr_list(). As of now, applications can retrieve the SELinux
label of a sysfs file with getxattr(), but cannot do it through
listxattr().

A similar issue happened before in commit b09e0fa4b4 ("tmpfs:
implement generic xattr support"). It was fixed by commit 8b0ba61df5
("fs/xattr.c: fix simple_xattr_list to always include security.* xattrs").
Perhaps this recent commit needs a fix as well.

The issue can be reproduced with a simple python program:

    python3 - <<'PY'
    import os

    path = "/sys/kernel/warn_count"

    print("getxattr:", os.getxattr(path, "security.selinux"))
    print("listxattr:", os.listxattr(path))
    PY

Before commit d5e81a5650 ("kernfs: avoid iattr allocation in listxattr"),
the result is:

    getxattr: b'system_u:object_r:sysfs_t:s0\x00'
    listxattr: ['security.selinux']

After that commit, the result is:

    getxattr: b'system_u:object_r:sysfs_t:s0\x00'
    listxattr: []

This patch will keep listxattr() consistent with getxattr() when security
xattrs are available.

Fixes: d5e81a5650 ("kernfs: avoid iattr allocation in listxattr")
Signed-off-by: Hengyu Liang <hengyul@cs.unc.edu>
Acked-by: Tejun Heo <tj@kernel.org>
Link: https://patch.msgid.link/20260822051705.1761850-1-hengyul@cs.unc.edu
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2026-09-01 17:11:19 +02:00
Linus Torvalds
a7f25dc23f xfs: fixes for 7.3-rc2
Signed-off-by: Carlos Maiolino <cem@kernel.org>
 -----BEGIN PGP SIGNATURE-----
 
 iJUEABMJAB0WIQSmtYVZ/MfVMGUq1GNcsMJ8RxYuYwUCapUNuQAKCRBcsMJ8RxYu
 Y/QVAX9SDXNSP3dw04wAuYgwSH5Ftm+WAnwusAsSvJkQdTvU0nEpAHyjb6WokS5a
 EbOGy5UBfRyqJFOmOw6wF5Ax0Aoxrt+lN8CuoDoh6aEhtYlh0jvd50ustYX8QSas
 W2R9B6IFIw==
 =JWP4
 -----END PGP SIGNATURE-----

Merge tag 'xfs-fixes-7.3-rc2' of gitolite.kernel.org:/pub/scm/fs/xfs/xfs-linux

Pull xfs fixes from Carlos Maiolino:
 "This contains a few fixes for the zoned storage support, a possible
  deadlock vector fix, some code refactoring patches and a quota evasion
  fix on XFS while exporting it via NFS.

  Please note that for the quota evasion fix, a couple patches for the
  capability subsystem are included in the pull request. Those have been
  ack'ed by the respective maintainer which also agreed to have them
  going through the xfs tree.

  This also includes a patch for the quota subsystem to stop issuing
  audit messages during quota enforcing. Quota maintainer also ack'ed
  and agreed with this going through xfs tree"

* tag 'xfs-fixes-7.3-rc2' of gitolite.kernel.org:/pub/scm/fs/xfs/xfs-linux:
  capability: unexport has_capability_noaudit
  xfs: replace ns_capable_noaudit
  quota: Don't issue audit messages on quota enforcing
  capability: Add new capable_noaudit
  xfs: fix capability check in xfs
  xfs: restore bi_bdev in xfs_zone_gc_write_chunk
  xfs: split ioend handling into a separate source file
  xfs: factor out a xfs_iomap_set_anon_write helper
  xfs: fix zoned write iomap flags assignments
  xfs: fix racy open zone caching
  xfs: handle NULL open_zone for merged ioends in xfs_ioend_put_open_zones
  xfs: use inode_init_always_gfp with __GFP_NOFAIL in xfs_inode_alloc
  xfs: remove kmem_to_page()
  xfs: don't flush and invalidate internal RT device twice in xfs_shutdown_devices
  xfs: split an assert in xfs_trans_log_buf
  xfs: don't hold buffer locks across sync transaction commit in xfs_sync_sb_buf
2026-08-31 10:45:40 -07:00
Yunpeng Tian
4aa2c106ae smb: client: reject SetEA requests that do not fit the request buffer
CIFSSMBSetEA() copies the caller's extended attribute value into the
SMB request buffer without checking that it fits.  The requirement is
stated in the source but was never implemented:

	/*BB add length check to see if it would fit in
	     negotiated SMB buffer size BB */
	/* if (ea_value_len > buffer_size - 512 (enough for header)) */
	if (ea_value_len)
		memcpy(parm_data->list.name + name_len + 1,
		       ea_value, ea_value_len);

The only bound applied on the way in is in cifs_xattr_set():

	#define MAX_EA_VALUE_SIZE CIFSMaxBufSize
	...
	if (size > MAX_EA_VALUE_SIZE)

CIFSMaxBufSize is the full payload capacity of the buffer, so a value
of exactly that size leaves no room for the SMB header, the TRANS2
parameter block, the fealist header and the EA name that are written
ahead of it in the same object.

SendReceive() already enforces the correct limit on this very length:

	if (in_len > CIFSMaxBufSize + MAX_CIFS_HDR_SIZE)

but it is called after the copy has taken place.  An unprivileged
setxattr(2) on an SMB1 mount with a 250-byte name and a 16384-byte
value writes 16384 bytes starting 345 bytes into a 16588-byte
cifs_request object, ending 141 bytes past it:

  BUG: KASAN: slab-out-of-bounds in CIFSSMBSetEA+0xabc/0xde0
  Write of size 16384 at addr ffff888003aa0159 by task init/68
   __asan_memcpy+0x3c/0x60
   CIFSSMBSetEA+0xabc/0xde0
   cifs_xattr_set+0xd3a/0xff0
   __vfs_setxattr+0x13e/0x1a0
  The buggy address is located 345 bytes inside of
   allocated 16588-byte region

Apply SendReceive()'s limit to the assembled request before the copy
rather than after it, and widen the byte counters so the sum cannot
wrap before it is tested.

byte_count is also tested against U16_MAX, because it is stored in the
16-bit pSMB->ByteCount.  That becomes reachable when CIFSMaxBufSize is
raised at module load, where it may be set as high as 1024*127: with a
5-byte EA name and a 65521-byte value, count is exactly U16_MAX while
byte_count is 65556, and cpu_to_le16() would truncate it to 20 and
transmit a frame whose ByteCount does not match its length.  Testing
byte_count covers count as well, since byte_count is the larger of the
two and count's only 16-bit consumer is written after this point.

check_add_overflow() is evaluated first so that total_len is assigned
before it is reported.

Fixes: 1da177e4c3 ("Linux-2.6.12-rc2")
Reported-by: Yunpeng Tian <shionthanatos@gmail.com>
Reported-by: Mingda Zhang <npczmd@qq.com>
Reported-by: Gongming Wang <gmwgg05@gmail.com>
Reported-by: Qinrun Dai <jupmouse@gmail.com>
Cc: stable@vger.kernel.org
Signed-off-by: Yunpeng Tian <shionthanatos@gmail.com>
Reviewed-by: Namjae Jeon <linkinjeon@kernel.org>
Signed-off-by: Paulo Alcantara <pc@manguebit.org>
2026-08-31 12:01:07 -03:00
Paulo Alcantara
a8603b52b3 smb: client: fix data corruption with concurrent writes and O_TRUNC
cifs_do_truncate() flushes dirty pages with filemap_write_and_wait()
and truncates the file on the server, but in the old code both
operations ran without holding i_rwsem or invalidate_lock.  A
concurrent buffered write via netfs_perform_write() -- which only
needs i_rwsem shared -- could dirty new pages after the flush but
before the local truncation, and those pages would be silently
discarded by cifs_setsize() -> truncate_pagecache().

Fix by acquiring inode_lock (exclusive i_rwsem) and
filemap_invalidate_lock at the top of cifs_do_truncate(), so the
entire flush-truncate-resize sequence is atomic with respect to:

  - buffered writes (blocked by exclusive i_rwsem, since
    netfs_start_io_write takes i_rwsem shared),
  - read page faults (blocked by exclusive invalidate_lock, since
    filemap_fault takes it shared),
  - writeback collection (blocked by netfs_wb_begin/netfs_wb_end
    around the server truncate and local resize, since
    netfs_writepages also acquires the wb lock).

Fixes: 110fee6b9b ("smb: client: fix missing timestamp updates with O_TRUNC")
Signed-off-by: Paulo Alcantara <pc@manguebit.org>
Reviewed-by: Namjae Jeon <linkinjeon@kernel.org>
Cc: Ronnie Sahlberg <ronniesahlberg@gmail.com>
Cc: Shyam Prasad N <sprasad@microsoft.com>
Cc: Tom Talpey <tom@talpey.com>
Cc: Bharath SM <bharathsm@microsoft.com>
Cc: stable@vger.kernel.org
2026-08-31 11:49:50 -03:00
Hongling Zeng
0fecc393f2 ntfs: take invalidate_lock in ntfs_filemap_page_mkwrite()
ntfs_filemap_page_mkwrite() calls iomap_page_mkwrite() without holding
mapping->invalidate_lock, so a concurrent truncate or fallocate can be
in the middle of invalidating pagecache and rewriting the runlist while
the write fault maps blocks and dirties the folio.  This races with
ntfs_attr_fallocate(), which merges clusters into the in-memory
runlist, drops the runlist lock, and only afterwards zeroes the newly
allocated clusters on disk; and with the punch-hole/insert/collapse
paths that free clusters after truncating the cache.

Per Documentation/filesystems/locking.rst, ->page_mkwrite() must ensure
there are no truncate/invalidate races, "usually mapping->invalidate_lock
is suitable for proper serialization".  xfs takes its mmaplock (= the
invalidate_lock rwsem) shared in exactly this path.

Take invalidate_lock shared around iomap_page_mkwrite().  The read-only
fault path is already covered because filemap_fault() itself grabs
invalidate_lock shared on instantiation/read paths; only page_mkwrite
was bypassing it in this driver.

Fixes: 9c87959601 ("ntfs: update file operations")
Cc: stable@vger.kernel.org
Reviewed-by: Hyunchul Lee <hyc.lee@gmail.com>
Reviewed-by: Baolin Liu <liubaolin@kylinos.cn>
Signed-off-by: Hongling Zeng <zenghongling@kylinos.cn>
Co-developed-by: Namjae Jeon <linkinjeon@kernel.org>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:47:53 +09:00
Hongling Zeng
9cc5761b8f ntfs: take invalidate_lock in ntfs_setattr_size()
ntfs_setattr_size() updates i_size and resizes the on-disk attribute
without holding mapping->invalidate_lock.  Page faults take the lock
shared, so a fault racing the resize can resolve a VCN against the
transient runlist state of ntfs_non_resident_attr_expand() and fail
with a spurious SIGBUS, and can interleave with the size-change
epilogue (truncate_pagecache(), i_size_write(),
pagecache_isize_extended()).

Take invalidate_lock exclusively around the whole resize after
inode_dio_wait(), matching the fallocate path and other filesystems
such as xfs, which wraps truncate in its mmaplock (= invalidate_lock).

Fixes: 9c87959601 ("ntfs: update file operations")
Cc: stable@vger.kernel.org
Reviewed-by: Hyunchul Lee <hyc.lee@gmail.com>
Reviewed-by: Baolin Liu <liubaolin@kylinos.cn>
Signed-off-by: Hongling Zeng <zenghongling@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:46:30 +09:00
Hongling Zeng
4dc8f4ee2d ntfs: handle signal interruption in fallocate
The ntfs_attr_fallocate() function checks for pending signals during
allocation loops and exits early via 'out' label. However, when a signal
interrupts the operation with err == 0, the function returns 0 (success)
instead of -EINTR.

The signal_pending() checks at the allocation loops jump to 'out' without
setting err = -EINTR, so the function returns success even when interrupted
by a signal.

Set err = -EINTR when jumping to the signal exit path, and only override
when no other error is pending. This ensures:

- Allocation interrupted by signal returns -EINTR
- Allocation that completed successfully before signal arrived returns 0
- Other errors are preserved and not overwritten by -EINTR

Fixes: 495e90fa33 ("ntfs: update attrib operations")
Cc: stable@vger.kernel.org
Signed-off-by: Hongling Zeng <zenghongling@kylinos.cn>
Reviewed-by: Baolin Liu <liubaolin@kylinos.cn>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:43:59 +09:00
Alon Shakevsky
ba9572bc43 ksmbd: validate normalized name response length
FILE_NORMALIZED_NAME_INFORMATION converts the open file path to UTF-16.
smb2_allocate_rsp_buf() leaves these responses in the 448-byte small
buffer, and get_file_normalized_name_info() converts the path without
checking the remaining space.

An authenticated client can query a long path and make
smbConvertToUTF16() write beyond work->response_buf.

Use the large response buffer for normalized-name queries. Before
conversion, verify that the response has room for the worst-case UTF-16
output and its terminator.

Fixes: 10aeff72ab ("ksmbd: support normalized name information")
Assisted-by: Antiproof:GPT-5.6-Sol
Signed-off-by: Alon Shakevsky <shakevsky@berkeley.edu>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:27:36 +09:00
Namjae Jeon
a506290f59 ksmbd: fix listener task lifetime on netdev events
The listener thread exits when its listening socket is shutdown. The
netdevice notifier shuts down the socket before calling kthread_stop(), so
the task_struct can be freed before kthread_stop() gets its reference.

Create the listener in a stopped state and hold an extra task_struct
reference until kthread_stop_put() completes. Also stop and release
listeners before freeing their interface records during TCP teardown.

Fixes: 3316a8fc84 ("ksmbd: server: avoid busy polling in accept loop")
Reported-by: Farhad Alemi <farhad.alemi@berkeley.edu>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:27:11 +09:00
Namjae Jeon
f25e93768f ksmbd: prevent out-of-bounds reads in share config responses
Validate IPC share configuration payload sizes before consuming
variable-length fields. Bound veto list parsing and account for
the separator byte when deriving the path length.

Fixes: a677ebd8ca ("ksmbd: validate payload size in ipc response")
Reported-by: Kanishka De Silva <kpskanna1915@gmail.com>
Reported-by: Farhad Alemi <farhad.alemi@berkeley.edu>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:27:06 +09:00
Namjae Jeon
feca5e70fc ksmbd: rate limit unmapped SID errors
A client can include many structurally valid but unmapped SIDs in a DACL.
Logging every mapping failure lets one request generate hundreds of kernel
error messages.

Rate limit the message to prevent an authenticated client from flooding
the kernel log.

Fixes: e2f34481b2 ("cifsd: add server-side procedures for SMB3")
Reported-by: Cheryl Babcock <cheryl@renat.io>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:26:45 +09:00
Namjae Jeon
c61dc7b1b4 ksmbd: propagate DACL parsing errors
parse_dacl() silently accepts truncated ACEs and allocation failures,
allowing set_info_sec() to continue with an incomplete ACL conversion.

Return parsing and allocation errors to parse_sec_desc() so malformed
security descriptors are rejected before inode attributes or ACL xattrs
are updated.

Fixes: e2f34481b2 ("cifsd: add server-side procedures for SMB3")
Reported-by: Cheryl Babcock <cheryl@renat.io>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:26:38 +09:00
Namjae Jeon
73f860489e ksmbd: zero pipe read compound padding
Compound response handling extends the last response iov to an eight-byte
boundary.

smb2_read_pipe() allocates only the payload size, so the alignment padding
can expose up to seven bytes of uninitialized kernel heap memory.

Allocate the aligned size and clear the unused tail before pinning the
response buffer.

Fixes: e2b76ab8b5 ("ksmbd: add support for read compound")
Reported-by: Cheryl Babcock <cheryl@renat.io>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:26:34 +09:00
Namjae Jeon
d12168084c ksmbd: safely drain sessions during logoff
SMB3 multichannel allows requests for one session to run on multiple
connections. Wait for all channels bound to a session before freeing
shared session objects.

A deferred byte-range lock remains counted as a running request and only
wakes when its file closes. Wake blocked locks during the drain without
unpublishing or modifying their file objects. Synchronous CANCEL requests
must invoke their cancellation callback to wake pending operations, while
CHANGE_NOTIFY completion remains specific to the asynchronous path.

Serialize session teardown with channel registration and previous-session
cleanup, and use atomic work-state transitions so LOGOFF, CANCEL, and
connection teardown invoke cancellation callbacks only once.

Fixes: 76e98a158b ("ksmbd: fix race condition between destroy_previous_session() and smb2 operations()")
Reported-by: Cheryl Babcock <cheryl@renat.io>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:26:30 +09:00
Aleksandr Khromov
db2267b27c ksmbd: fill in FileSysIdentifier in FS_POSIX_INFORMATION
smb2_get_info_filesystem() reports 56 bytes for FS_POSIX_INFORMATION,
that is the whole of FILE_SYSTEM_POSIX_INFO, but never assigns
FileSysIdentifier.  Those eight bytes go to the client as they are found
in the response buffer.

The buffer is zeroed on allocation, so a standalone request leaks
nothing.  A compound request can leak: the offset of the next response
is advanced by the length pinned for the previous one, so a reply that
was written into the buffer and then dropped in favour of the short
error response of smb2_set_err_rsp() stays there, and the next reply is
laid over it with only the header cleared.

Report the file system id statfs() returned, which is what the field is
for.  FileSysIdentifier is __le64 and f_fsid is a pair of ints, so
assemble the value first, val[0] as the low half, and convert it on the
way out.

Fixes: e2f34481b2 ("cifsd: add server-side procedures for SMB3")
Cc: stable@vger.kernel.org
Signed-off-by: Aleksandr Khromov <haa@amicon.ru>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:26:17 +09:00
Aleksandr Khromov
c0cd3fc682 ksmbd: initialize FileSystemControlFlags in FS_CONTROL_INFORMATION
smb2_get_info_filesystem() reports 48 bytes for FS_CONTROL_INFORMATION,
that is the whole of struct smb2_fs_control_info, but never assigns
FileSystemControlFlags.  Those four bytes go to the client as they are
found in the response buffer.

The buffer is zeroed on allocation, so a standalone request leaks
nothing.  A compound request can leak: the offset of the next response
is advanced by the length pinned for the previous one, so a reply that
was written into the buffer and then dropped in favour of the short
error response of smb2_set_err_rsp() stays there, and the next reply is
laid over it with only the header cleared.

ksmbd does not implement quota tracking, so report no control flags.

Fixes: e2f34481b2 ("cifsd: add server-side procedures for SMB3")
Cc: stable@vger.kernel.org
Signed-off-by: Aleksandr Khromov <haa@amicon.ru>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:26:12 +09:00
Aleksandr Khromov
399aa12450 ksmbd: zero the FS_OBJECT_ID_INFORMATION buffer before filling it in
smb2_get_info_filesystem() reports 64 bytes for FS_OBJECT_ID_INFORMATION,
that is the whole of struct object_id_info, but writes only 46 of them:

 - objid[] is 16 bytes, and when the volume UUID is not available only
   sizeof(stfs.f_fsid) (8) bytes are copied into it;
 - extended_info.version_string[] is STRING_LENGTH (28) bytes, and only
   strlen("1.1.0") (5) bytes are copied into it.

The response buffer is zeroed on allocation (kvzalloc() in
smb2_allocate_rsp_buf()), so for a standalone request the remaining 31
bytes are zero.  In a compound request they need not be.  The offset of
the next response is advanced by the length pinned for the previous one,
so if a preceding command wrote its reply into the buffer and then
failed, smb2_set_err_rsp() pins only the short error response and the
next reply lands inside the area that has already been written.  Only
the header is cleared there:

	memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);

The client then receives up to 31 bytes of a response it was not meant
to see, including one that failed with an access denied error.

Clear the structure before filling it in.  As a side effect
version_string is now NUL terminated.

Fixes: e2f34481b2 ("cifsd: add server-side procedures for SMB3")
Suggested-by: ChenXiaoSong <chenxiaosong@chenxiaosong.com>
Cc: stable@vger.kernel.org
Signed-off-by: Aleksandr Khromov <haa@amicon.ru>
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
2026-08-31 19:26:07 +09:00