]> git.hungrycats.org Git - linux/log
linux
9 days agobtrfs: scrub: do not let a transaction commit pass under queued stripes misc-next/topics/scrub-commit-pause
Zygo Blaxell [Wed, 11 Nov 2026 03:12:36 +0000 (22:12 -0500)]
btrfs: scrub: do not let a transaction commit pass under queued stripes

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

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

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

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

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

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

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

Fixes: 1dc4888e725d ("btrfs: scrub: avoid unnecessary extent tree search preparing stripes")
Assisted-by: Claude:claude-opus-5-5
2 weeks agobtrfs: === misc-next on b-for-next ===
David Sterba [Wed, 21 Feb 2024 14:50:10 +0000 (15:50 +0100)]
btrfs: === misc-next on b-for-next ===

Any commits after this one are for testing and evaluation only.

Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: handle zero num_stripes in btrfs_chunk_item_size()
Cheng Yongkang [Sun, 1 Nov 2026 07:14:44 +0000 (00:14 -0700)]
btrfs: handle zero num_stripes in btrfs_chunk_item_size()

validate_sys_chunk_array() calls btrfs_chunk_item_size() with the
on-disk num_stripes before btrfs_check_chunk_valid() has checked the
chunk. With CONFIG_BTRFS_ASSERT=y, a zero-stripe system chunk trips
ASSERT(num_stripes) instead of being rejected:

  assertion failed: num_stripes, in fs/btrfs/volumes.h:714
  kernel BUG at fs/btrfs/volumes.h:714!
  RIP: 0010:btrfs_validate_super+0x3ce7/0x4210
  Call Trace:
   open_ctree
   btrfs_get_tree
   vfs_get_tree
   do_new_mount

Drop the assertion and compute the size as the chunk header plus
num_stripes stripes. The size is unchanged for num_stripes > 0, and a
zero-stripe chunk now reaches btrfs_check_chunk_valid(), which rejects
it, so the mount fails with -EUCLEAN.

Suggested-by: Qu Wenruo <wqu@suse.com>
Link: https://lore.kernel.org/linux-btrfs/d2ee0cc1-674e-4447-88da-d346122a43a4@suse.com/
Fixes: 2a9bb78cfd36 ("btrfs: validate system chunk array at btrfs_validate_super()")
Signed-off-by: Cheng Yongkang <teel4res@gmail.com>
[ Slightly rework the commit message. ]
Signed-off-by: Qu Wenruo <wqu@suse.com>
2 weeks agobtrfs: reject refs=0 subvolume without DEAD in SUBVOL_SYNC_WAIT
Cheng Yongkang [Sun, 1 Nov 2026 06:25:39 +0000 (23:25 -0700)]
btrfs: reject refs=0 subvolume without DEAD in SUBVOL_SYNC_WAIT

btrfs_ioctl_subvol_sync() assumes that a cached root with zero
references has BTRFS_ROOT_SUBVOL_DEAD set, and asserts that before
waiting for the cleaner. Two states break the assumption:

- A corrupt ROOT_ITEM with zero references and a matching orphan item,
  on a writable filesystem.
- A failed subvolume deletion. btrfs_delete_subvolume() zeroes the
  root references, aborts the transaction, which forces the filesystem
  read-only, and then clears DEAD again. No on-disk metadata is
  corrupted in this case.

With CONFIG_BTRFS_ASSERT=y, both reach a BUG().

Change the ASSERT() into a proper rejection to avoid triggering a BUG().

Fixes: 6c83d153ed86 ("btrfs: add new ioctl to wait for cleaned subvolumes")
Cc: stable@vger.kernel.org
Suggested-by: Qu Wenruo <quwenruo.btrfs@gmx.com>
Link: https://lore.kernel.org/linux-btrfs/dd97efe9-91ec-495b-b698-acff1447421c@gmx.com/
Signed-off-by: Cheng Yongkang <teel4res@gmail.com>
[ Rework the commit message, drop the ad-hoc RW check. ]
Signed-off-by: Qu Wenruo <wqu@suse.com>
2 weeks agobtrfs: fix a livelock in wait_for_commit() on PREEMPT_RT
Daniel Vacek [Fri, 30 Oct 2026 14:28:03 +0000 (15:28 +0100)]
btrfs: fix a livelock in wait_for_commit() on PREEMPT_RT

Peter reported [1] that running multiple RR tasks doing sync()
on fully preemptible kernel may starve other/normal sync() tasks
due to fs_info::trans_lock turned into rt_mutex.

This is caused by RR tasks contending over the mutex with priority over
other tasks, which in turn lack progress and they are no longer able to
remove TRANS_STATE_COMPLETED transactions from the fs_info::trans_list.

The offenders start looping in wait_for_commit() expecting the completed
transactions to get off the trans_list but since they're bouncing the
trans_lock the tasks with other/normal priority which are about to delist
such transactions never get a chance to do so due to lower priority.

A simple reproducer can be found in the mentioned email thread [1].

The situation can be resolved by boosting the priority of the starved
tasks or dropping priority of the offenders. Thought this fix prevents
the situation from happening in the first place. We simply delist the
transactions before changing them to completed state. That breaks the
loop condition.

[1] https://lore.kernel.org/linux-btrfs/SJ0PR17MB4288C46458DCE2C015839D0FBB9E2@SJ0PR17MB4288.namprd17.prod.outlook.com/

Reported-by: Naulls, Peter <PeterNaulls@eaton.com>
Fixes: 5fd76bf31ccfe ("btrfs: fix relocation crash due to premature return from btrfs_commit_transaction()")
CC: stable@vger.kernel.org # 5.15+
Tested-by: Naulls, Peter <PeterNaulls@eaton.com>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Daniel Vacek <neelx@suse.com>
2 weeks agobtrfs: wait for a grace period before freeing a new device
Binbin Deng [Wed, 14 Oct 2026 02:37:33 +0000 (10:37 +0800)]
btrfs: wait for a grace period before freeing a new device

KASAN reports a slab-use-after-free in btrfs_statfs() walking
fs_devices->devices. btrfs_init_new_device() publishes the new device
with list_add_rcu() and can fail afterwards, for example with -ENOSPC
in init_first_rw_device() when a user with CAP_SYS_ADMIN adds a device
that is too small to a seeding filesystem mounted read-only. The error
path removes the entry with list_del_rcu() and frees the object in
btrfs_free_device() without waiting for a grace period, while
btrfs_calc_avail_data_space() and btrfs_ioctl_fs_info() keep reading
the device list under rcu_read_lock().

BUG: KASAN: slab-use-after-free in btrfs_statfs+0x11af/0x14a0
Read of size 8 at addr ffff8880096be858 by task poc/252
Call Trace:
 <TASK>
 dump_stack_lvl+0x53/0x70
 print_report+0xd0/0x630
 ? __pfx__raw_spin_lock_irqsave+0x10/0x10
 ? filename_lookup+0x1a9/0x540
 ? btrfs_statfs+0x11af/0x14a0
 kasan_report+0xce/0x100
 ? btrfs_statfs+0x11af/0x14a0
 btrfs_statfs+0x11af/0x14a0
 statfs_by_dentry+0x117/0x1e0
 user_statfs+0xac/0x130
 ? __pfx_user_statfs+0x10/0x10
 __do_sys_statfs+0x80/0xe0
 ? __pfx___do_sys_statfs+0x10/0x10
 do_syscall_64+0xf9/0x540
 entry_SYSCALL_64_after_hwframe+0x77/0x7f

Allocated by task 256:
 kasan_save_stack+0x33/0x60
 kasan_save_track+0x14/0x30
 __kasan_kmalloc+0x8f/0xa0
 __kmalloc_cache_noprof+0x158/0x370
 btrfs_alloc_device+0xad/0x3e0
 btrfs_init_new_device+0x3e8/0x36e0
 btrfs_ioctl+0x150d/0x6c20
 __x64_sys_ioctl+0x134/0x1c0
 do_syscall_64+0xf9/0x540
 entry_SYSCALL_64_after_hwframe+0x77/0x7f

Freed by task 256:
 kasan_save_stack+0x33/0x60
 kasan_save_track+0x14/0x30
 kasan_save_free_info+0x3b/0x60
 __kasan_slab_free+0x43/0x70
 kfree+0x121/0x380
 btrfs_init_new_device+0x4a0/0x36e0
 btrfs_ioctl+0x150d/0x6c20
 __x64_sys_ioctl+0x134/0x1c0
 do_syscall_64+0xf9/0x540
 entry_SYSCALL_64_after_hwframe+0x77/0x7f

Fix by waiting for an RCU grace period after the device is removed
from the list and before it is freed.Place the synchronize_rcu() after
dropping the mutexes and before the `error_trans` label.

Fixes: 1f78160ce1b1 ("Btrfs: using rcu lock in the reader side of devices list")
Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Binbin Deng <18983559317@163.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: validate but do not set bdev blocksize
Qu Wenruo [Sat, 24 Oct 2026 23:39:50 +0000 (10:09 +1030)]
btrfs: validate but do not set bdev blocksize

[BACKGROUND]
In the very early days, commit 325cd4bafeb6 ("Btrfs: properly set
blocksize when adding new device.") set the bdev blocksize as at that
time btrfs is using __bread() for super block IO, which went through
buffer heads thus requires the strict block size limit.

Then btrfs super block IO moved away from buffered heads, by commit
8f32380d3f29 ("btrfs: use the page cache for super block reading") and
commit 314b6dd0eebf ("btrfs: use bios instead of buffer_heads from super
block writeout").

So after that there is already no strict blocksize requirement for
btrfs, except the bdev's block size should not exceed 4K, which is also
the super block size of btrfs.

Btrfs data read/writes all follow sectorsize, which can be larger than
4K.
Btrfs metadata read/writes all follow nodesize, which is already 16K by
default.

Furthermore, there is already a bug report that set_blocksize() can
trigger a lockdep warning from btrfs, as set_blocksize() will acquire
inode lock, and under certain races can lead to lockdep warnings.

[ENHANCEMENT]
Remove the set_blocksize() calls, instead call bdev_validate_blocksize()
inside btrfs_open_device_deny_freeze() and btrfs_get_bdev_and_sb().

Btrfs doesn't use buffer heads, thus no strict set_blocksize()
requirement. But we still want to call bdev_validate_blocksize(), just in
case where a future block device with larger blocksize (e.g. 16K) shows
up.

For such devices btrfs super block bios will be rejected, so we want to call
bdev_validate_blocksize() early to reject such devices.

Furthermore, the bdev_validate_blocksize() itself is lockless, thus it
should resolve the lockdep report from syzbot.

Reported-by: syzbot+5c01398781fb51df783a@syzkaller.appspotmail.com
Link: https://lore.kernel.org/linux-btrfs/6adcb3be.4ce6c07b.2dfc0c.0005.GAE@google.com/
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zstd: pass fs_info to btrfs_warn() on failure to allocate workspace manager
Filipe Manana [Wed, 28 Oct 2026 15:37:59 +0000 (15:37 +0000)]
btrfs: zstd: pass fs_info to btrfs_warn() on failure to allocate workspace manager

The workspace manager is per filesystem and we have access to the fs_info
structure of the filesystem in zstd_alloc_workspace_manager(), so pass it
to the btrfs_warn() call so that we get a better log message (including
the device, state, etc).

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zstd: prevent leak of workspace below maximum level
Filipe Manana [Wed, 28 Oct 2026 16:06:27 +0000 (16:06 +0000)]
btrfs: zstd: prevent leak of workspace below maximum level

When putting a workspace we always protect the workspace for the maximum
level from reclaim, since it can be used not just for that level but as
well for any level below it. However the logic is flawed because if we do
the put for a workspace at level 10 for example (maximum is level 15) and
there is currently no idle workspace for the maximum level because all
are currently being used, we don't add the workspace to the LRU list and
that can result in leaking it if we don't get more compression or
decompression requests for level 10 or any level below 10.

Fix this by skipping the addition to the LRU list only if the level of
the workspace matches the maximum level too (besides the list of idle
workspaces for the maximum level being empty).

Fixes: 3f93aef535c8 ("btrfs: add zstd compression level support")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: don't cache rbio if an error is hit
Qu Wenruo [Wed, 28 Oct 2026 06:30:47 +0000 (17:00 +1030)]
btrfs: don't cache rbio if an error is hit

If rmw_rbio() hit an error after cache_rbio_pages() call, the rbio still
have RBIO_CACHE_READY_BIT set, thus can be utilized for future page
stealing.

But that rbio didn't really reach the disk, thus using the pages for
future steal can cause data inconsistency between in-memory cache and
on-disk data.

Fix the problem by clearing the RBIO_CACHE_READY_BIT on the error path
of rmw_rbio().

Fixes: 5eb30ee26fa4 ("btrfs: raid56: introduce the main entrance for RMW path")
Assisted-by: LLM (find the bug)
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: fix racy bio_list changes for failed RMW rbio
Qu Wenruo [Wed, 28 Oct 2026 06:30:46 +0000 (17:00 +1030)]
btrfs: fix racy bio_list changes for failed RMW rbio

If an RMW work failed early, e.g. alloc_rbio_parity_pages() failed, it
won't get RBIO_RMW_LOCKED_BIT set, and get rbio_orig_end_io() called.

In that case, there can be a race between bio_list_get() on the rbio,
and new incoming bio merging into the rbio:

 A is the rbio that rbio_orig_end_io() is running on.
 a is the higher layer bio that generated the rbio A.

 B is the new rbio that will be merged into A.
 b is the higher layer bio that generated the rbio B.

   rbio_orig_end_io(A) worker         |       lock_stripe_add(B)
--------------------------------------+---------------------------------
rbio_orig_end_io(A)                   | lock_stripe_add(B)
|- cur = bio_list_get(A)              | |- rbio_can_merge(A, B)
|  |- bio = A->bio_list.head;         | |  which returned true
|  |  which bio a is returned.        | |
|  |                                  | |
|  |- A->bio_list.tail = NULL;        | |
|  |                                  | |
|  |                                  | |- merge_rbio(A, B)
|  |                                  | |  |- bio_list_merge_init()
|  |                                  | |     |- if (A->bio_list.tail)
|  |                                  | |     |  A->bio_list.tail is
|  |                                  | |     |  still NULL
|  |                                  | |     |
|  |                                  | |     |- A->bio_list.head = b
|  |                                  | |     |- A->bio_list.tail = b
|  |- A->bio_list.head = NULL;        | |- return 1;
|  |- return bio;                     |    Caller expect rbio A to
|     which is bio a.                 |    complete bio b.
|
|- extra = bio_list_get()
|  Which is NULL
|
|- rbio_endio_bio_list(cur);
   Which only ends bio a.

In above case, the bio_list race can get bio b lost, and never ended.
Thankfully this race window is very tiny, so not practical in the real
world.

Fix it by setting RBIO_RMW_LOCKED_BIT for error path before calling
rbio_orig_end_io().
And since we're ensuring all RMW rbios have RBIO_RMW_LOCKED_BIT bit set
before calling rbio_orig_end_io(), add two ASSERT()s for that and remove
the old comment.

Fixes: 5eb30ee26fa4 ("btrfs: raid56: introduce the main entrance for RMW path")
Assisted-by: LLM (find and analyze the bug)
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zoned: fix double free of bitmaps on clone failure
Thomas Fourier [Wed, 28 Oct 2026 09:50:51 +0000 (10:50 +0100)]
btrfs: zoned: fix double free of bitmaps on clone failure

btrfs_clone_dev_zone_info() duplicates the original orig_dev->zone_info
with kmemdup(), which also copies the seq_zones, empty_zones and
active_zones pointers. The clone then replaces them one by one with
fresh bitmaps. If one of the allocations fails, the error path frees all
three pointers, including those not yet replaced, which still point to
the bitmaps owned by the original device.

Clear the three pointers right after kmemdup() so the error path only frees
what this function allocated.

Fixes: 21e61ec6d0bb ("btrfs: zoned: clone zoned device info when cloning a device")
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Thomas Fourier <fourier.thomas@gmail.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zoned: fix lockdep splat on mount
Johannes Thumshirn [Wed, 28 Oct 2026 11:57:27 +0000 (12:57 +0100)]
btrfs: zoned: fix lockdep splat on mount

When mounting a filesystem on a zoned drive passed into a VM via a
virtio-blk disk lockdep sporadically complains about a possible deadlock
between BTRFS' dev_replace::rwsem and virtio-blk's vdev_mutex:

 ======================================================
 WARNING: possible circular locking dependency detected
 7.3.0-rc6+ #317 Not tainted
 ------------------------------------------------------
 mount/7418 is trying to acquire lock:
 ffff888102c07860 (&vblk->vdev_mutex){+.+.}-{4:4}, at: virtblk_report_zones+0xda/0x440

 but task is already holding lock:
 ffff8881fd725ea8 (&fs_info->dev_replace.rwsem){++++}-{4:4}, at: btrfs_load_block_group_zone_info+0x186/0xe50

 which lock already depends on the new lock.

 the existing dependency chain (in reverse order) is:

 -> #4 (&fs_info->dev_replace.rwsem){++++}-{4:4}:
        down_read+0x42/0x170
        btrfs_map_block+0x1a6/0xe70
        btrfs_submit_bbio+0x1a3/0x910
        submit_one_bio+0x93/0xd0
        btrfs_readahead+0x1c4/0x200
        read_pages+0x56/0x200
        page_cache_ra_order+0x27c/0x410
        filemap_get_pages+0x12f/0x4a0
        filemap_read+0xed/0x400
        vfs_read+0x240/0x340
        ksys_read+0x61/0xd0
        do_syscall_64+0xa3/0x4f0
        entry_SYSCALL_64_after_hwframe+0x76/0x7e

 -> #3 (mapping.invalidate_lock#3){++++}-{4:4}:
        down_read+0x42/0x170
        filemap_fault+0xb0/0x1a40
        __do_fault+0x34/0xc0
        __handle_mm_fault+0x919/0x1db0
        handle_mm_fault+0x97/0x240
        do_user_addr_fault+0x21d/0x690
        exc_page_fault+0x8e/0x230
        asm_exc_page_fault+0x26/0x30

 -> #2 (vm_lock){++++}-{0:0}:
        __vma_start_exclude_readers+0x91/0x1b0
        __vma_start_write+0x47/0xd0
        vma_expand+0x4c/0x2a0
        relocate_vma_down+0x126/0x200
        setup_arg_pages+0x240/0x3e0
        load_elf_binary+0x1be/0x1860
        bprm_execve+0x2d2/0x7b0
        kernel_execve+0x107/0x130
        kernel_init+0xc2/0x130
        ret_from_fork+0x1ff/0x2f0
        ret_from_fork_asm+0x1a/0x30

 -> #1 (&mm->mmap_lock){++++}-{4:4}:
        __might_fault+0x68/0xa0
        _copy_to_user+0x22/0x70
        blkdev_copy_zone_to_user+0x22/0x40
        virtblk_report_zones+0x297/0x440
        blkdev_report_zones_ioctl+0xfd/0x130
        blkdev_ioctl+0x20f/0x2c0
        __x64_sys_ioctl+0x86/0xd0
        do_syscall_64+0xa3/0x4f0
        entry_SYSCALL_64_after_hwframe+0x76/0x7e

 -> #0 (&vblk->vdev_mutex){+.+.}-{4:4}:
        __lock_acquire+0x15a8/0x2850
        lock_acquire+0xea/0x2f0
        __mutex_lock+0xa7/0x10d0
        virtblk_report_zones+0xda/0x440
        blkdev_report_zones_cached+0x162/0x190
        btrfs_get_dev_zones+0xdc/0x2c0
        btrfs_load_block_group_zone_info+0x2b6/0xe50
        btrfs_read_block_groups+0x338/0xc80
        open_ctree+0x1aca/0x24b3
        btrfs_get_tree.cold+0x105/0x26c
        vfs_get_tree+0x28/0xb0
        __do_sys_fsconfig+0x324/0x690
        do_syscall_64+0xa3/0x4f0
        entry_SYSCALL_64_after_hwframe+0x76/0x7e

 other info that might help us debug this:

 Chain exists of:
   &vblk->vdev_mutex --> mapping.invalidate_lock#3 --> &fs_info->dev_replace.rwsem

  Possible unsafe locking scenario:

        CPU0                    CPU1
        ----                    ----
   rlock(&fs_info->dev_replace.rwsem);
                                lock(mapping.invalidate_lock#3);
                                lock(&fs_info->dev_replace.rwsem);
   lock(&vblk->vdev_mutex);

  *** DEADLOCK ***

 locks held by mount/7418: 3, last CPU#0:
  #0: ffff888110aa6868 (&fc->uapi_mutex){+.+.}-{4:4}, at: __do_sys_fsconfig+0x2ae/0x690
  #1: ffff888112ba20e8 (&type->s_umount_key#31/1){+.+.}-{4:4}, at: sget_fc+0x148/0x8d0
  #2: ffff8881fd725ea8 (&fs_info->dev_replace.rwsem){++++}-{4:4}, at: btrfs_load_block_group_zone_info+0x186/0xe50

Holding the rwsem was widened in 0090d6e1b210 ("btrfs: zoned: fix
use-after-free due to race with dev replace"), but it now also covers
calling into blkdev_report_zones_cached(). The device replace ioctl()
only works on a mounted filesystem and the only caller with setting
'new' to false is read_one_block_group() which is only called during
mount, so it is safe to drop the rwsem before calling into
blkdev_report_zones_cached().

Fixes: 0090d6e1b210 ("btrfs: zoned: fix use-after-free due to race with dev replace")
Reviewed-by: Naohiro Aota <naohiro.aota@wdc.com>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zoned: don't wait for ordered extents in do_zone_finish()
Johannes Thumshirn [Tue, 27 Oct 2026 14:33:05 +0000 (15:33 +0100)]
btrfs: zoned: don't wait for ordered extents in do_zone_finish()

do_zone_finish() calls btrfs_wait_ordered_roots(), which holds
fs_info->ordered_operations_mutex while waiting for writeback. It can be
reached from writeback itself:

  cow_file_range()
  `-> btrfs_reserve_extent()
    `-> find_free_extent()
      `-> btrfs_zone_finish_one_bg()
        `-> do_zone_finish()

If another task holds the mutex and waits for that writeback, this
deadlocks.

In general, we want to ensure all writes in the block group to
complete before finishing the zone, as relocation does. However, the
current callers do not need the wait (or cannot wait) in do_zone_finish():

- Relocation already waits for reservations and ordered extents itself
  before calling btrfs_zone_finish().
- btrfs_delete_unused_bgs() checks that ->reserved is zero and sets the
  block group read-only while holding groups_sem, so there can be no
  in-flight data write.
- btrfs_zone_finish_one_bg() is called from the allocation path and
  cannot wait.

Dropping the wait is still safe. Once the block group is read-only,
->reserved can only drop, and for data it only drops after the ordered
extent's I/O has completed. So if ->reserved is zero, no data write is
left in flight. If it is non-zero, do_zone_finish() returns -EAGAIN,
which all callers handle.

This makes btrfs_zone_finish_one_bg() fail with -EAGAIN when it races
with an allocation in the selected block group.

Fixes: 393f646e34c1 ("btrfs: zoned: finish least available block group on data bg allocation")
Reviewed-by: Naohiro Aota <naohiro.aota@wdc.com>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: lzo: use memcpy_to_folio() in copy_compressed_data_to_bio()
Filipe Manana [Mon, 26 Oct 2026 17:34:10 +0000 (17:34 +0000)]
btrfs: lzo: use memcpy_to_folio() in copy_compressed_data_to_bio()

We are manually mapping the folio, copying to it with memcpy() and then
unmapping, but this can all simply be done with memcpy_to_folio()  that
is provided by the MM layer. So use memcpy_to_folio() instead.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Johannes Thumshirn <johannes.thumshrin@wdc.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zlib: use memcpy_from_folio() in copy_data_into_buffer()
Filipe Manana [Mon, 26 Oct 2026 17:31:37 +0000 (17:31 +0000)]
btrfs: zlib: use memcpy_from_folio() in copy_data_into_buffer()

We are manually mapping the folio, copying from it with memcpy() and then
unmapping, but this can all simply be done with memcpy_from_folio() that
is provided by the MM layer. So use memcpy_from_folio() instead.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Johannes Thumshirn <johannes.thumshrin@wdc.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: add stripe_len < PAGE_SIZE support for alloc_rbio_*_pages()
Qu Wenruo [Thu, 22 Oct 2026 09:39:29 +0000 (20:09 +1030)]
btrfs: add stripe_len < PAGE_SIZE support for alloc_rbio_*_pages()

The functions alloc_rbio_parity_pages() and alloc_rbio_data_pages()
didn't support stripe_len < PAGE_SIZE cases, and fallback to
alloc_rbio_pages() instead.

That's mostly to avoid the case where both data and P/Q blocks can exist
in the same page.

However even in that case, it's not a big deal, the existing
infrastructures like index_stripe_sectors() can handle it correctly.

Update those functions to support stripe_len < PAGE_SIZE cases, with two
points to note:

- Extra attention needed for the round direction
  For alloc_rbio_data_pages() we need to round up, so the last data page
  gets allocated.

  For alloc_rbio_parity_pages() we need to round down, so the first
  P/Q page get allocated.

- Mixed page allocation
  We can call alloc_rbio_parity_pages() first, then
  alloc_rbio_data_pages().

  In that case, it's alloc_pages_bulk() saving us, which always skips
  allocated slot. Thus we're still safe.

Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: add stripe_len < PAGE_SIZE support for steal_rbio()
Qu Wenruo [Thu, 22 Oct 2026 09:39:28 +0000 (20:09 +1030)]
btrfs: add stripe_len < PAGE_SIZE support for steal_rbio()

The function steal_rbio() is utilized to use the pages that belongs to
uptodate data blocks, without doing a page copy.

That is done by just updating the dest->stripe_pages[] pointer to use
the point inside @src directly.

That function previously will reject stripe_len < PAGE_SIZE cases, as a
page can contain both data and P/Q blocks.

But that shouldn't be a big deal, as long as the corresponding P/Q
blocks are not marked uptodate, we can still steal the page that also
contains P/Q blocks.

So rework steal_rbio() to support stripe_len < PAGE_SIZE by:

- Calculate the last page index correctly
  Instead of iterating all pages but skip P/Q pages, calculate the last
  page index properly.

  The last page may contain both data and P/Q blocks, but we can still
  steal the page.

- Update the bitmap in one go
  Instead of updating the stripe_uptodate_bitmap for every page, we can
  do the update in just one go, out of the main loop.

  And that update should not touch the P/Q blocks.

- Remove unused helpers
  * page_nr_to_sector_nr()
  * page_nr_to_num_sectors()
  * steal_rbio_page()
  * is_data_stripe_page()

  * full_page_sectors_uptodate()
    This one is very annoying, because of its __maybe_unused
    attribution.

  They are based on the old BTRFS_STRIPE_LEN >= PAGE_SIZE assumption,
  and no longer utilized.

- Make index_stripe_sectors() update the stripe_paddrs[] without a page
  This doesn't cause any functional change for now, as there is no one
  accessing the source stripe_paddrs[] after a steal.

  But this should still make the function a little more robust.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: introduce rbio_nr_data_sectors() helper
Qu Wenruo [Thu, 22 Oct 2026 09:39:27 +0000 (20:09 +1030)]
btrfs: introduce rbio_nr_data_sectors() helper

The pattern "rbio->nr_data * rbio->stripe_nsectors" is utilized more
than 5 times inside raid56.c, it's worthy to extract it into a new
helper.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: remove fs_info argument from btrfs_add_bg_to_space_info()
Filipe Manana [Fri, 23 Oct 2026 09:26:08 +0000 (10:26 +0100)]
btrfs: remove fs_info argument from btrfs_add_bg_to_space_info()

It's not used, so remove it.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: remove redundant space_info assignment in btrfs_add_bg_to_space_info()
Filipe Manana [Fri, 23 Oct 2026 09:16:54 +0000 (10:16 +0100)]
btrfs: remove redundant space_info assignment in btrfs_add_bg_to_space_info()

There's no point in setting the block group's space_info member as the
space_info was extracted from the block group early when the variable was
declared and did not change.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: send: fix missing hole punching during incremental send
Filipe Manana [Wed, 21 Oct 2026 19:34:59 +0000 (20:34 +0100)]
btrfs: send: fix missing hole punching during incremental send

When using the no-holes feature (enabled by default since btrfs-progs
v5.15) and doing an incremental send, we can miss issuing a hole punching
command when the following conditions happen:

1) A hole is punched in a tail section of a file extent item that happens
   to be the last item in a leaf (for example the extent covers the file
   range [1M, 3M) and a hole is punched in the range [2M, 3M)). Between
   the end of this file extent item's range and the i_size, there are
   other file extent items;

2) The next leaf was not modified in the send snapshot, remaining shared
   with the parent snapshot.

In this scenario we are unable to detect a hole was punched and never
issue a hole punch command because with no-holes there we don't have an
explicit file extent item to mark a hole.

Fix this by teaching maybe_send_hole() to detect such case.
A test case for fstests will follow soon.

Reported-by: Tristan Elvers <tristanelvers@gmail.com>
Link: https://lore.kernel.org/linux-btrfs/CAFoLKK+aErV4p6ZJPnVeH5SHQ5++0f=8ZgxPWe-E-CkeKBs8PA@mail.gmail.com/
Fixes: 16e7549f045d ("Btrfs: incompatible format change to remove hole extents")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: force a transaction commit when fsyncing stripe-tree extents
Johannes Thumshirn [Thu, 22 Oct 2026 09:06:53 +0000 (11:06 +0200)]
btrfs: force a transaction commit when fsyncing stripe-tree extents

An extent in a block-group that uses the RAID stripe-tree has its logical
to physical mapping stored in that tree, which only becomes persistent
when the stripe-tree is written out at transaction commit. But the RAID
stripe-tree is not logged in the log tree.

A fsync therefore logs a file-extent item whose logical range cannot be
resolved after a crash. Replay restores the file-extent item and the
file has the correct size, but reading it fails with EIO and nothing is
reported.

Force a full commit when logging such an extent. Extents reach the log
both from log_one_extent() and from copy_items(), so check in both.
copy_items() skips extents from a past transaction, their mapping is
already committed, the same reason their checksums are not logged.

Fixes: 02c372e1f016 ("btrfs: add support for inserting raid stripe extents")
Reviewed-by: Filipe Manana <fdmanana@suse.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>
2 weeks agobtrfs: remove BUG*() from raid56.c
Qu Wenruo [Wed, 21 Oct 2026 22:48:47 +0000 (09:18 +1030)]
btrfs: remove BUG*() from raid56.c

There are several BUG()/BUG_ON() inside raid56.c, which cause
checkpatch warning if code is touching them. This is especially annoying
if using b4, with btrfs-workflow git hooks applied, which makes b4 to
wait for user input but without any output.

Address them by removing one very impossible BUG(), and using ASSERT() for
the remaining ones:

- __remove_rbio_from_cache()
- rbio_is_full()
- unlock_stripe()
  Replace the BUG_ON() with ASSERT().

- finish_parity_scrub()
  Remove the BUG(), as alloc_rbio() has already properly calculated
  real_stripes and nr_data using the number of parity.

  Furthermore, initialize @has_qstripe at the beginning of the function
  using the bioc->map_type directly.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: introduce extra limits on btrfs_chunk::stripe_len
Qu Wenruo [Wed, 21 Oct 2026 03:39:43 +0000 (14:09 +1030)]
btrfs: introduce extra limits on btrfs_chunk::stripe_len

The new limits are:

- Stripe_len must be no smaller than sectorsize
  As sectorsize is still the minimal unit.

- Stripe_len must be no larger than BTRFS_STRIPE_LEN
  We still have a lot of things requiring on BTRFS_STRIPE_LEN alignment,
  e.g. dev extent and chunk allocation.
  A stripe_len larger than BTRFS_STRIPE_LEN will cause problems for the
  existing chunk allocator.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: convert zoned.c to use map->stripe_len
Qu Wenruo [Wed, 21 Oct 2026 03:39:42 +0000 (14:09 +1030)]
btrfs: convert zoned.c to use map->stripe_len

There are still several call sites using BTRFS_STRIPE_LEN, but that's
when doing the basic zoned checks.

For other call sites with a btrfs_chunk_map, use map->stripe_len instead
of the hardcoded BTRFS_STRIPE_LEN.

And since we're here, replace the following pattern

if (val & BTRFS_STRIPE_LEN_MASK)

with
if (!IS_ALIGNED(val, stripe_len))

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: convert raid56.c to use rbio->bioc->stripe_len
Qu Wenruo [Wed, 21 Oct 2026 03:39:41 +0000 (14:09 +1030)]
btrfs: convert raid56.c to use rbio->bioc->stripe_len

So that raid56 can support stripe length other than BTRFS_STRIPE_LEN.

There are several extra things to note:

- btrfs_raid_bio::stripe_npages is removed
  With stripe_len < BTRFS_STRIPE_LEN, there is no guarantee that a page
  won't cross multiple stripes.

  E.g. with 4K stripe_len and sectorsize, 2 data stripes, with 64K page
  size, one page will cover the full stripe.

  So stripe_npages no longer makes sense, just remove it.

- alloc_rbio_data_pages()/alloc_rbio_parity_pages() fallback
  For the same above reason, a page can contain both data and parity
  blocks.
  In that case we can no longer only allocate pages for data/parity.

  Add a fallback that if stripe_len is smaller than page size, always
  allocate all the pages.

  This is not the best solution, but should be good enough for now until
  the variable stripe_len is properly tested.

- steal_rbio() fallback
  If stripe_len is smaller than PAGE_SIZE, it's hard to only steal the
  data pages.

  Again skip the stealing if stripe_len is smaller than PAGE_SIZE.

Reviewed-by: Johannes Thusmhirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: convert volumes.c and block-group.c to use map->stripe_len
Qu Wenruo [Wed, 21 Oct 2026 03:39:40 +0000 (14:09 +1030)]
btrfs: convert volumes.c and block-group.c to use map->stripe_len

There are still some BTRFS_STRIPE_LEN usage remaining, but they are all
for chunk allocation.

There is one more refactor for is_same_chunk_map(), as there are more
members to compare, the parameter list can go longer and longer.

Instead of passing a new @stripe_len member, pass extent_buffer and
btrfs_chunk pointers, and grab the needed member inside that function.

And doing "if (unlikely()) return false" for each member check.

Although this make is_same_chunk_map() more complex, considering it's
only called for system chunks, it should not bring too much overhead.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: add a new 'stripe_len' parameter to btrfs_stripe_nr_to_offset()
Qu Wenruo [Wed, 21 Oct 2026 03:39:39 +0000 (14:09 +1030)]
btrfs: add a new 'stripe_len' parameter to btrfs_stripe_nr_to_offset()

That helper is currently using a fixed BTRFS_STRIPE_LEN, change it to
accept a 'u32 stripe_len'.

Also add an ASSERT() to make sure the @stripe_len passed in is power of
2, and no larger than BTRFS_STRIPE_LEN.

There is a special case where we still pass BTRFS_STRIPE_LEN into
btrfs_stripe_nr_to_offset(), that's for chunk allocation to determine
the minimal device extent size.

In that case, since our future planned map->stripe_len is always power
of 2 and no larger than BTRFS_STRIPE_LEN, we are totally fine to use the
old BTRFS_STRIPE_LEN.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: change scrub to use stripe_len
Qu Wenruo [Wed, 21 Oct 2026 03:39:38 +0000 (14:09 +1030)]
btrfs: change scrub to use stripe_len

Several points to note:

- scrub_ctx::stripes[] stripe_len updates
  We always pre-initialize scrub_ctx::stripes[] at the very beginning of
  scrub, without holding any btrfs_chunk_map.

  So init_scrub_stripe() still uses BTRFS_STRIPE_LEN, and all allocated
  memory are based on that stripe length.

  But before scrubbing each chunk, update_scrub_stripe_len() will be
  called to update the scrub_stripe::stripe_len.

- Stripe_len should not exceed BTRFS_STRIPE_LEN
  Since scrub_stripe's heap memory are all based on BTRFS_STRIPE_LEN,
  any stripe_len larger than BTRFS_STRIPE_LEN will cause
  access-beyond-boundary.

  Thankfully there is no plan to support such stripe_len >
  BTRFS_STRIPE_LEN any time soon.

- alloc_scrub_bbio() changes
  Previously we ensure BTRFS_STRIPE_LEN >= PAGE_SIZE, so
  BTRFS_STRIPE_LEN >> PAGE_SHIFT can never be zero.

  But now stripe_len can be smaller than PAGE_SIZE. E.g. stripe_len 4K,
  page size 64K.

  So we have to use "round_up(stripe_len, PAGE_SIZE) >> PAGE_SHIFT"
  instead.

  Finally alloc_scrub_bbio() is always called with a scrub_stripe
  pointer as the @private parameter, change the type from (void *) to
  (struct scrub_stripe *), so that we can grab the stripe_len without
  a new parameter.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: add btrfs_io_context::stripe_len and load it
Qu Wenruo [Wed, 21 Oct 2026 03:39:37 +0000 (14:09 +1030)]
btrfs: add btrfs_io_context::stripe_len and load it

The new member will be utilized by various path that no direct
btrfs_chunk_map is available, but a stripe length is still required.

The new member is located inside a hole between @refs and @fs_info, so
no size increase for btrfs_io_context.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: load the on-disk btrfs_chunk::stripe_len
Qu Wenruo [Wed, 21 Oct 2026 03:39:36 +0000 (14:09 +1030)]
btrfs: load the on-disk btrfs_chunk::stripe_len

Currently btrfs doesn't load btrfs_chunk::stripe_len into
btrfs_chunk_map, as tree-checker will reject any chunk whose stripe_len
is not 64K.

But for the future we will want stripe length other than 64K.

As a preparation for the variable stripe length in the future, load
btrfs_chunk::stripe_len into btrfs_chunk_map::stripe_len and
stripe_shift.

For now stripe_len is still 64K, no matter if it's loaded from the
on-disk metadata or newly allocated chunk.
As tree-checker still rejects any chunk whose stripe_len is not 64K.

The two new members fit into the existing hole of btrfs_chunk_map, so
the size of btrfs_chunk_map stay the same.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: reduce the width of num_stripes and sub_stripes
Qu Wenruo [Wed, 21 Oct 2026 03:39:35 +0000 (14:09 +1030)]
btrfs: reduce the width of num_stripes and sub_stripes

The on-disk btrfs_chunk structure uses u16 for both num_stripes and
sub_stripes, so there is no need to use "int" to represent them in
btrfs_chunk_map.

Follow the on-disk format to use u16 for those members, including
verified_stripes too.

And since verified_stripes is u16, it no longer completely fill the
hole between @refs and @start.
Instead use @num_stripes and @sub_stripes to fill the hole, and leave a 6
bytes hole between @verified_stripes and @stripes.

This doesn't save any space for btrfs_chunk_map, but leaves enough space
for future expansion.

Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zoned: avoid underflow of space info bytes_zone_unusable
Johannes Thumshirn [Fri, 11 Sep 2026 11:41:12 +0000 (13:41 +0200)]
btrfs: zoned: avoid underflow of space info bytes_zone_unusable

The two functions btrfs_free_reserved_bytes() and
btrfs_reset_unused_block_groups() both manipulate
space_info->bytes_zone_unusable without using the accessor function
btrfs_space_info_update_bytes_zone_unusable() potentially risking an
underflow (in case of btrfs_reset_unused_block_groups()).

Use btrfs_space_info_update_bytes_zone_unusable() in both function, in
the case of btrfs_free_reserved_bytes() it is mostly for documenting
purposes.

Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zoned: requeue block group if zone reset bails out
Johannes Thumshirn [Thu, 10 Sep 2026 12:19:39 +0000 (14:19 +0200)]
btrfs: zoned: requeue block group if zone reset bails out

btrfs_reset_unused_block_groups() drops the block-group from
fs_info->unused_bgs before performing the work that can actually fail,
the actual submission of a REQ_OP_ZONE_RESET.

Every failed operation after this leaves the block-group dangling,
physically reset, but the in-memory structures aren't and it is not
requeued to be reset on fs_info->unused_bgs.

Instead of bailing out, re-add this block-group to fs_info->unused_bgs
list.

Fixes: 453a73c3069a ("btrfs: zoned: reclaim unused zone by zone resetting")
Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zoned: fix possible UAF in wait_eb_writebacks()
Johannes Thumshirn [Wed, 9 Sep 2026 09:45:34 +0000 (11:45 +0200)]
btrfs: zoned: fix possible UAF in wait_eb_writebacks()

wait_eb_writebacks() iterates the fs_info->buffer_tree xarray and waits
for the writeback of these extent-buffers. Waiting for writeback needs
to be done without the rcu_read_lock() held (because it can sleep) and
thus the loop drops the rcu_read_lock() before calling into
wait_on_extent_buffer_writeback(). But extent_buffers are freed through
RCU, so if btrfs_release_extent_buffer_rcu() is scheduled while we're
still waiting on the writeback, the extent_buffer will be freed causing
a use-after-free.

Similar to what is done in find_extent_buffer_nolock(), get a reference
to the extent_buffer before calling into
wait_on_extent_buffer_writeback() so a successful writeback does not
free the extent_buffer while we still have a reference to it.

Fixes: 2dd7e7bc0282 ("btrfs: zoned: wait for extent buffer IOs before finishing a zone")
Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: zoned: only change active zone counter on successful (de)activation
Johannes Thumshirn [Wed, 9 Sep 2026 06:47:25 +0000 (08:47 +0200)]
btrfs: zoned: only change active zone counter on successful (de)activation

btrfs_zone_activate() unconditionally decrements the reserved_active_zones
counter regardless if btrfs_dev_set_active_zone() fails to set the zone
active, i.e. because it raced with another call that already set the bit
in the bitmask, or not.

This can lead to a double decrement of the counter in case the bit has
already been set.

Only decrement the counter *iff* btrfs_dev_set_active_zone() successfully
marked the zone in the bitmap.

Mirror this behaviour when clearing the bit again.

Fixes: a7e1ac7bdc5a ("btrfs: zoned: reserve zones for an active metadata/system block group")
Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: allow idmapped DEFRAG ioctls
Tao Cui [Fri, 9 Oct 2026 07:53:25 +0000 (15:53 +0800)]
btrfs: allow idmapped DEFRAG ioctls

btrfs_ioctl_defrag() checks MAY_WRITE against nop_mnt_idmap, so on an
idmapped mount the owner comparison uses the caller's fsuid against the
raw on-disk uid and the ioctl fails with -EPERM even for the file's
owner.  Pass the mount idmap down so defrag works on idmapped mounts.

The check, added in 616d374efa23 ("btrfs: allow defrag on a file opened
read-only that has rw permissions"), is not a privilege gate.  It only
tests whether the file could have been opened for writing, and a user
who owns the file on the idmapped mount can already open it O_RDWR,
write() to it or fallocate() it.  Defragmenting a regular file only
rearranges the caller's own extents; there is nothing it can rewrite
that the caller could not rewrite anyway.  Whole-subvolume defrag on a
directory keeps its capable(CAP_SYS_ADMIN) requirement, and the
!capable() guard around this check is left as is.

FIDEDUPERANGE already works this way for unprivileged callers:
may_dedupe_file() in fs/remap_range.c compares the inode owner through
file_mnt_idmap(file) and falls back to inode_permission() with the same
idmap, and dedupe can rewrite one file's extents from another file's
contents, which is a stronger operation than defrag.

On regular mounts file_mnt_idmap() is nop_mnt_idmap and nothing
changes.

Reviewed-by: Seth Forshee <sforshee@kernel.org>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Christian Brauner (Amutable) <brauner@kernel.org>
Signed-off-by: Tao Cui <cuitao@kylinos.cn>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: prevent deleting the wrong subvolume by ID
guolingxing [Sun, 18 Oct 2026 15:38:10 +0000 (15:38 +0000)]
btrfs: prevent deleting the wrong subvolume by ID

When deleting a subvolume by ID, btrfs_ioctl_snap_destroy() first
resolves the requested ID to a name, then looks up that name again
under the parent directory lock.

A concurrent rename can change which subvolume is associated with
the name between these operations. Since the deletion path does not
verify the ID of the resolved subvolume, it can delete a different
subvolume while leaving the requested one intact.

This was reproduced by repeatedly exchanging the names of two
subvolumes using renameat2(RENAME_EXCHANGE) while deleting one of
them by ID. The wrong subvolume was deleted in 9 out of 14 independent
tests.

Fix this by checking that the resolved subvolume ID matches the
requested ID while holding the parent directory lock. Return -EAGAIN
on a mismatch so that userspace can retry the operation instead of
being told that the requested subvolume does not exist.

Fixes: 949964c92843 ("btrfs: add new BTRFS_IOC_SNAP_DESTROY_V2 ioctl")
CC: stable@vger.kernel.org
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: guolingxing <guolingxing@tju.edu.cn>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: make chunk size validation to be simpler
Qu Wenruo [Sun, 18 Oct 2026 04:17:02 +0000 (14:47 +1030)]
btrfs: make chunk size validation to be simpler

Commit 6ded22c1bfe6 ("btrfs: reduce div64 calls by limiting the number
of stripes of a chunk to u32") introduced a chunk size limit check, but
it is using a wrong result in the comment:

  U32_MAX << BTRFS_STRIPE_LEN_SHIFT results 256T, not 256G.

Instead of calculating the size limit, using an immediate number
(SZ_256G).

This has the following benefit:

- Still large enough for future expansion
  Although the check is 1024 times more strict, I don't think we will
  allow 256G chunk anytime soon.

  And we have higher chance (10 more bits) to catch a bitflip in the
  high bits.

- Much harder to diverge from the comment
  We don't need to calculate the number anymore.

Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: scrub: fix race between scrub and scrub progress ioctl
Filipe Manana [Fri, 16 Oct 2026 17:02:23 +0000 (18:02 +0100)]
btrfs: scrub: fix race between scrub and scrub progress ioctl

The scrub progress ioctl is copying the scrub progress stats without
acquiring the spinlock that protects it and a concurrent scrub can be
updating the stats at the same time which can lead to load tearing
issues. So take the spinlock when copying the progress stats.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: scrub: fix race leading to use-after-free in the scrub progress ioctl
Filipe Manana [Fri, 16 Oct 2026 16:53:00 +0000 (17:53 +0100)]
btrfs: scrub: fix race leading to use-after-free in the scrub progress ioctl

If the scrub progress ioctl is called when replace is about to finish, we
have a race that can result in a use-after-free of the scrub context:

1) A scrub is finishing and is at btrfs_scrub_dev();

2) A concurrent task called the scrub progress ioctl and is in
   btrfs_scrub_progress(), where it takes the device_list_mutex and grabs
   the device. Then it starts using the device's scrub context (for a
   memcpy operation);

3) While the scrub progress ioctl task is running, the scrub task sets
   the device's scrub_ctx to NULL (acquiring fs_info->scrub_lock) and
   then calls scrub_put_ctx() against the scrub context, dropping the
   last reference and freeing the memory - while the scrub progress ioctl
   task is still using it, resulting in a use-after-free.

Fix this by changing btrfs_scrub_progress() to take fs_info->scrub_lock
before using the scrub context.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: scrub: remove unused first_free member from struct scrub_ctx
Filipe Manana [Fri, 16 Oct 2026 16:29:52 +0000 (17:29 +0100)]
btrfs: scrub: remove unused first_free member from struct scrub_ctx

It's not used since commit 001e3fc263ce ("btrfs: scrub: remove
scrub_block and scrub_sector structures"), so remove it.

Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: scrub: fix lost wakeup and hang when cancelling a scrub that is finishing
Filipe Manana [Fri, 16 Oct 2026 16:14:49 +0000 (17:14 +0100)]
btrfs: scrub: fix lost wakeup and hang when cancelling a scrub that is finishing

When scrub finishes, it does a wakeup on the fs_info->scrub_pause_wait
wait queue and then sets dev->scrub_sctx to NULL. On the other hand the
scrub cancel code (btrfs_scrub_cancel_dev()) waits on that wait queue
for dev->scrub_sctx to be NULL. So this means if btrfs_scrub_cancel_dev()
is called right when scrub is finishing and sees the wakeup before the
NULL is assigned to dev->scrub_sctx by btrfs_scrub_dev(), it hangs.

Fix this by doing the wakeup in btrfs_scrub_dev() after setting
dev->scrub_sctx to NULL.

Fixes: a2de733c78fa ("btrfs: scrub")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: scrub: allocate stripe buffer with GFP_KERNEL
Filipe Manana [Fri, 16 Oct 2026 11:55:55 +0000 (12:55 +0100)]
btrfs: scrub: allocate stripe buffer with GFP_KERNEL

In init_scrub_stripe() we are allocating a stripe's buffer with GFP_NOFS
but we can use GFP_KERNEL instead since we are not holding a transaction
handle or any locks that could cause a deadlock if GFP_KERNEL triggers a
transaction commit.

So switch to GFP_KERNEL. We are also doing GFP_KERNEL for the allocation
of stripe->csums just a few lines below.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: lzo: remove the special handling inside one fs block
Qu Wenruo [Thu, 15 Oct 2026 08:59:50 +0000 (19:29 +1030)]
btrfs: lzo: remove the special handling inside one fs block

Since commit 3eaf5f082c4c ("btrfs: extract inlined creation into a
dedicated delalloc helper"), even for inlined compressed extents the cb
range will be exact one block, aka [0, sector).

And several attempts to bring back the old compression range [0, i_size]
all failed with extra races against i_size.

So I think the behavior will stay. With that said, we can further
simplify the lzo compression path.
Since the range is always aligned to block size, and lzo compression is
already done block by block, there is no reason to handle sub-block
sized range.

We can safely remove the @sectorsize_mask, @sector_off and @in_len
variables, and always use @sectorsize as input length for each
compression iteration.

Finally add two ASSERT()s to make sure the range passed into
btrfs_compress_bio() is always block aligned.

Reviewed-by: Daniel Vacek <neelx@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: reject existing chunks that don't match
Qu Wenruo [Fri, 16 Oct 2026 00:48:19 +0000 (11:18 +1030)]
btrfs: reject existing chunks that don't match

During read_one_chunk() we can hit an existing chunk map.

There are several situations that this can happen:

- System chunk maps
  This is the most common case, where the system chunks are added from
  super block during bootstrap.

  But in that case, the system chunks in the super block should match
  the one in the chunk tree, if not there is definitely something wrong.

- Overlapping chunk maps
  This is rare, but potentially malicious.

  Crafted images or even some bitflips in the chunk tree can lead to
  this.
  In that case we should reject such cases.

To detect and reject those cases:

- Introduce a new helper, is_same_chunk_map()
  This checks most important members, so we can detect such problem
  without fully checking the stripes.

  If the helper returns false, then we output an error message and
  reject the mount.

- Use the full chunk map range for btrfs_find_chunk_map()
  The current search range is [@logical, @logical], which is only one
  bytenr in length.

  If we have the following case, btrfs_find_chunk_map() returns NULL but
  we still have an overlapping chunk map:

                   Logical
                   |<--- New chunk map --->|
                            |<--- Existing chunk map --->|

  Using the full range to do the search would return the existing chunk
  map and get the new one rejected.

Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: rename stripe_size inside volumes.c
Qu Wenruo [Fri, 16 Oct 2026 00:48:18 +0000 (11:18 +1030)]
btrfs: rename stripe_size inside volumes.c

Rename the "stripe_size" used inside volumes.c by:

- local variable in alloc_virtual_chunk()
- alloc_chunk_ctl::stripe_size
  All rename to "dev_extent_size".

- alloc_chunk_ctl::max_stripe_size
  Rename to "dev_extent_max" as there is already a "dev_extent_min".

- decide_stripe_size*() functions
  Rename to decide_dev_extent_size*().

This further reduces the confusion between "stripe_size" and
"stripe_len".

Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: rename btrfs_chunk_map::stripe_size
Qu Wenruo [Fri, 16 Oct 2026 00:48:17 +0000 (11:18 +1030)]
btrfs: rename btrfs_chunk_map::stripe_size

The member btrfs_chunk_map::stripe_size sounds very similar to
btrfs_chunk::stripe_len, but they have very different meanings.

btrfs_chunk_map::stripe_size is in fact the device extent size for the
chunk. E.g. a 2GiB RAID0 chunk with 2 stripes,
btrfs_chunk_map::stripe_size will be 1GiB (2GiB / 2).

But btrfs_chunk::stripe_len is the stripe length that striping profiles
should follow, and the value is now fixed to 64KiB.
E.g. for a 2GiB RAID0 chunk with 2 stripes, every write will be split
into 64KiB stripes, and then distributed across the 2 devices.

To avoid confusion, rename btrfs_chunk_map::stripe_size to
dev_extent_size.

And since we're here, also rename the helper btrfs_calc_stripe_length()
to btrfs_calc_dev_extent_size().

Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: scrub: fix lost error return value when scrubbing raid56 parity stripe
Filipe Manana [Thu, 15 Oct 2026 17:45:45 +0000 (18:45 +0100)]
btrfs: scrub: fix lost error return value when scrubbing raid56 parity stripe

If we find errors we are returning the value of 'ret', which has a value
of 0 from some previous function call that succeeded, instead of returning
an -EIO error. Fix this by returning -EIO instead of 'ret'.

Fixes: fab0c0f03cfd ("btrfs: introduce BTRFS_PATH_AUTO_RELEASE() helper")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: fix fiemap merging compressed extents
Filipe Manana [Thu, 15 Oct 2026 14:55:55 +0000 (15:55 +0100)]
btrfs: fix fiemap merging compressed extents

Compressed extents are never supposed to be merged by the fiemap code and
reported as a single extent, as each extent's content comes from a
different compression stream and has its own header and context.

We currently rely on checking the logical and physical address adjacency
to prevent merging compressed extents but that is broken. Consider the
following reproducer which explains why the merging happens:

  $ cat test.sh
  #!/bin/bash

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

  mkfs.btrfs -s 4K -f $DEV
  mount -o compress $DEV $MNT

  # Do a write that compresses to a single 4K extent and represents the
  # maximum compressed chunk size (128K).
  xfs_io -f -c "pwrite 0 128K" $MNT/foo

  # Sync to flush delalloc and allocate the 4K extent.
  sync -f $MNT

  # Now allocate a 124K extent in some other file, which will be adjacent
  # (to the right) of the 4K extent previously allocated.
  xfs_io -f -c "falloc 0 124K" $MNT/filler

  # Do another write to the main file at its current EOF that is
  # compressible and fits in a 4K extent.
  xfs_io -c "pwrite 128K 128K" $MNT/foo
  # Sync to flush delalloc and allocate the 4K extent.
  sync -f $MNT

  # Run fiemap which should report 2 encoded extents, each with a
  # logical size of 128K.
  xfs_io -c "fiemap -v" $MNT/foo

  umount $MNT

Running this, fiemap will report a single extent:

  $ ./test.sh
  (...)
  /mnt/sdi/foo:
   EXT: FILE-OFFSET      BLOCK-RANGE      TOTAL FLAGS
     0: [0..511]:        26624..27135       512   0x9

Fix this by never attempting to merge extents if the flags contain
FIEMAP_EXTENT_ENCODED.

Fixes: 4751832da990 ("btrfs: fiemap: Cache and merge fiemap extent before submit it to user")
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: fix the fsverity callback where unexpected range is verified
Qu Wenruo [Sat, 10 Oct 2026 06:29:49 +0000 (16:59 +1030)]
btrfs: fix the fsverity callback where unexpected range is verified

[BUG]
There is a bug report that on v7.2 kernel, compressed extents with
fsverity enabled can lead to warnings like the following:

 fs-verity (dm-3, inode 257): FILE CORRUPTED! pos=7471104, level=-1, want_hash=sha256:bedf0e7bc93b48694db719001a8d3e79229cc58ee638b41d4149193505090774, real_hash=sha256:ad7facb2586fc6e966c004d7d1d16b024f5805ff7cb47c7a85dabd8b48892ca7

The read itself eventually succeeds, and no read error is returned to
user space.

[CAUSE]
Since v7.2 btrfs has enabled large data folio support, now a folio can
contain multiple blocks even if the page size matches the fs block size.
And even before that, btrfs already has block size < page size support,
thus all involved code should assume a folio can contain multiple
blocks.

However the function btrfs_verify_folio() calls fsverity_verify_folio(),
which verifies the whole folio, even if the read range only covers part
of the folio.

This forces fsverity to verify garbage data that is not yet read from
disk, and causes verification failure.

This is a long-standing bug, but previously it only affected bs < ps
cases which is not that common.
Now with the large folio support, it's much easier to trigger with bs ==
ps cases.

[FIX]
Instead of calling fsverity_verify_folio(), call
fsverity_verify_blocks() to verify only the read range.

Reported-by: Roger Alasà <vonbloom@gmail.com>
Link: https://lore.kernel.org/linux-btrfs/CAELqY9==Ter2XQPRp=gjW5T75T+7kcZCXpn5roF2L6tY6mQNxw@mail.gmail.com/
Fixes: 146054090b08 ("btrfs: initial fsverity support")
Tested-by: Roger Alasà <vonbloom@gmail.com>
Reviewed-by: Eric Biggers <ebiggers@kernel.org>
Tested-by: Tito Duarte <duartito@gmail.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: verity: propagate orphan insertion errors when enabling verity
guolingxing [Thu, 15 Oct 2026 09:59:01 +0000 (09:59 +0000)]
btrfs: verity: propagate orphan insertion errors when enabling verity

btrfs_begin_enable_verity() ignores the return value of
btrfs_orphan_add() and unconditionally returns 0. If orphan insertion
fails, btrfs_orphan_add() aborts the transaction, but the generic
fs-verity code still proceeds with Merkle tree construction because
the begin_enable_verity callback reported success.

Return the error so that fs-verity stops immediately instead of
continuing after the initialization failure.

The transaction is already aborted by btrfs_orphan_add() and the
handle is released by btrfs_end_transaction(), so no additional
cleanup is needed.

Fixes: 705242538ff3 ("btrfs: verity metadata orphan items")
Signed-off-by: guolingxing <guolingxing@tju.edu.cn>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: sysfs: restore NOFS context on early return in btrfs_sysfs_add_block_group_type()
guolingxing [Thu, 15 Oct 2026 06:53:19 +0000 (06:53 +0000)]
btrfs: sysfs: restore NOFS context on early return in btrfs_sysfs_add_block_group_type()

btrfs_sysfs_add_block_group_type() sets up a NOFS context with
memalloc_nofs_save() because kobject_add() performs GFP_KERNEL
allocations deep in its call chain, and the function may be called
while holding a transaction handle or a lock required for a
transaction commit, where reclaim could deadlock.

Every other return path of this function calls memalloc_nofs_restore()
except the early return taken when another thread has already created
the kobject for the same raid index (this can happen when restriping).
Taking that path leaves PF_MEMALLOC_NOFS set on the calling task, so
all subsequent memory allocations performed by that task remain
restricted to the NOFS scope, which may lead to unexpected allocation
failures or deadlocks later on.

Restore the NOFS context before returning from that path.

Fixes: 49ea112da0e6 ("btrfs: do not create raid sysfs entries under any locks")
CC: stable@vger.kernel.org
Signed-off-by: guolingxing <guolingxing@tju.edu.cn>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: defrag: prevent inode truncated to zero from not being defragged again
Filipe Manana [Tue, 13 Oct 2026 16:04:00 +0000 (17:04 +0100)]
btrfs: defrag: prevent inode truncated to zero from not being defragged again

If we add an inode to autodefrag and the inode is truncated to an i_size
of zero before it's picked by autodefrag (run by the cleaner kthread),
we exit btrfs_run_defrag_inode() leaving the BTRFS_INODE_IN_DEFRAG flag
set in the inode, which prevents the inode from being auto defragged in
the future until it's evicted, loaded again and small writes happen to
it again.

Fix this by clearing BTRFS_INODE_IN_DEFRAG before we check if the current
offset is at or beyond the inode's i_size.

Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: cleanup dirty_cowonly_roots during btrfs_free_fs_roots()
Qu Wenruo [Tue, 13 Oct 2026 05:41:20 +0000 (16:11 +1030)]
btrfs: cleanup dirty_cowonly_roots during btrfs_free_fs_roots()

[EXISTING ERROR HANDLING QUIRK]
Sashiko mentioned an existing problem that, if btrfs_abort_transaction()
is triggered during the following call site, some roots will be attached
to dirty_cowonly_roots without being cleaned up:

 btrfs_commit_transaction()
 |- commit_cowonly_roots()
    |- list_move_tail();
    |  One root's dirty_list is moved from dirty_cowonly_roots to
    |  switch_commits.
    |  But there are still other dirty roots in dirty_cowonly_roots.
    |
    |- update_cowonly_root()
    |  |- btrfs_update_root()
    |     |- btrfs_abort_transaction()
    |
    |- return ret;

In that case, those dirty roots linked into dirty_cowonly_roots will
never be removed from that list.
As normally we require a transaction commit to move them, but since the
fs is already marked error, no new transaction can be started.

For roots that are already moved to switch_commits list, they are
cleaned up by btrfs_cleanup_one_transaction().

This is not going to cause memory leak on the btrfs_root structure
itself, as after a transaction is aborted, no one will read
dirty_cowonly_roots.

Furthermore dirty_cowonly_roots only tracks trees that are not
subvolume or log trees. They should not have root->dirty_log_pages.
And qgroup swapped blocks are going to be released during
btrfs_put_root().

Thus no memory leak from those two members either.

But we're still relying on a hidden behavior to keep us from leaking
memory.

[ENHANCEMENT]
Unlink all roots that are still linked to dirty_cowonly_roots during
btrfs_free_fs_roots(), and do one extra ASSERT() to make sure that their
dirty_log_pages are empty.

At that timing there is no other thread thus we're safe to unlink roots
without holding trans_lock.

Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: cleanup qgroup swapped blocks at root release
Qu Wenruo [Tue, 13 Oct 2026 05:41:19 +0000 (16:11 +1030)]
btrfs: cleanup qgroup swapped blocks at root release

Normally btrfs_qgroup_clean_swapped_blocks() is called when switching
the commit root of a subvolume tree.

However if a transaction is aborted before all dirty subvolumes are
linked to switch_commits, those left-over dirty subvolumes won't get
their qgroup swapped blocks cleaned up.

And since a transaction is already aborted, no new transaction is
allowed to be started, thus no way to cleanup the qgroup swapped blocks
for those subvolume trees.

Fix the problem by calling btrfs_qgroup_clean_swapped_blocks() inside
btrfs_put_root() when the last ref is dropped, so that at unmount time
those left-over qgroup swapped blocks are properly released.

This fix is inspired by the recent Sashiko reports about similar cases
on cowonly roots.

Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: always remove quota_root from dirty_cowonly_roots
Qu Wenruo [Tue, 13 Oct 2026 05:41:17 +0000 (16:11 +1030)]
btrfs: always remove quota_root from dirty_cowonly_roots

[ERROR HANDLING QUIRK]
When btrfs_quota_disable() failed at btrfs_clean_quota_tree() or
btrfs_del_root(), the quota_root->dirty_list is not removed from
fs_info->dirty_cowonly_roots, but the quota_root itself will be freed.

This leaves a dangling pointer in the dirty_cowonly_roots.

This is not a huge problem, as the transaction is aborted thus no one
will read the dirty_cowonly_roots for now.

Furthermore, quota_root should never be logged nor have qgroup swapped
tree blocks, thus it won't cause leaks from extent io tree nor qgroup
swapped blocks.

[ENHANCEMENT]
For the incoming cleanup of dirty_cowonly_roots during
btrfs_free_fs_roots(), any root that is still linked to
dirty_cowonly_roots will be read again, and this existing dangling
pointer is going to cause problem.

To prepare for that cleanup, move the list_del() call into the out
label, so that even if the transaction is aborted, we still unlink
quota_root from dirty_cowonly_roots before freeing it.

Assisted-by: LLM (exposing the bug during review)
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: unwind device add when sysfs registration fails
Adarsh Das [Wed, 7 Oct 2026 16:03:49 +0000 (21:33 +0530)]
btrfs: unwind device add when sysfs registration fails

btrfs_init_new_device() ignored the return value of
btrfs_sysfs_add_device(). When sysfs link creation failed (e.g. -EEXIST),
the add path continued, aborted the transaction with the same errno, and
tripped WARN_ON(btrfs_abort_should_print_stack()) while leaving the device
half-registered in memory.

Check the return value and unwind when registration fails, without
aborting the filesystem for errnos like -EEXIST. If add failed before
anything was published in sysfs, tear down the in-memory device state only
and do not call btrfs_sysfs_remove_device(). When the block-device link
was created but devid kobject registration fails, drop the link inside
btrfs_sysfs_add_device() before returning the error.

Reported-by: syzbot+3bf3e110b2d406b8166c@syzkaller.appspotmail.com
Link: https://lore.kernel.org/all/6a791c94.01d0871a.3a0d52.0099.GAE@google.com
Tested-by: syzbot+3bf3e110b2d406b8166c@syzkaller.appspotmail.com
Assisted-by: LLM
Reviewed-by: Johannes Thumshirn <johannes.thumshirn@wdc.com>
Signed-off-by: Adarsh Das <adarshdas950@gmail.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: add LOGICAL_INO_V2 flag for avoiding the tree modification log
Joanne Koong [Tue, 22 Sep 2026 20:12:57 +0000 (13:12 -0700)]
btrfs: add LOGICAL_INO_V2 flag for avoiding the tree modification log

At Meta, we use the LOGICAL_INO_V2 ioctl to estimate sharing-aware space
usage. We sample the logical address space and resolve each sample back
to the inodes which reference it. The measurement is statistical, so
with enough samples it gives good bounds on real usage.

Currently in the LOGICAL_INO_V2 ioctl path, iterate_extent_inodes()
(which can walk backrefs either against the current trees or against the
commit roots) acquires a tree modification log sequence number when
walking the current trees, since those trees are being modified while
the walk is in progress. The log is then enabled filesystem wide for as
long as any such walk is running, and is only disabled again once the
last walk has finished.

While it is enabled the cost impacts the whole filesystem, not only the
caller. Modifications of interior nodes of the extent tree and of
subvolume trees have to be recorded, serialized on a single filesystem
wide lock. Delayed refs with a sequence number at or above the oldest
active one can not be run (the run path bails out with -EAGAIN in
btrfs_run_delayed_refs_for_head()), and metadata refs above it can not
be merged, so they accumulate and that work is deferred to transaction
commit.

Currently, userspace has no way to ask for anything cheaper. Whenever a
transaction is running, the walk uses the tree modification log, even if
the caller would tolerate results that could be up to one commit interval
stale.

Give userspace this option by adding BTRFS_LOGICAL_INO_ARGS_COMMIT_ROOT,
which makes the backref walk use the commit roots and therefore never
enables the tree modification log. Behavior is unchanged unless the flag
gets explicitly passed by userspace. iterate_extent_inodes() already
takes a search_commit_root argument for this, which scrub, send and the
data relocation warning path all pass as true. The flag simply plumbs it
through to userspace.

Assisted-by: LLM
Reviewed-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: Joanne Koong <joannelkoong@gmail.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agobtrfs: fix chattr failing on nodatasum files that have the compress flag
Hengyu Liang [Sun, 11 Oct 2026 15:58:15 +0000 (11:58 -0400)]
btrfs: fix chattr failing on nodatasum files that have the compress flag

Commit cf1afec09e9f ("btrfs: validate properties before setting them")
made btrfs_set_prop() validate a property before setting it. For the
compression property, the validation fails with -EINVAL when the inode
has NODATASUM.

However, chattr writes back all the flags it read from the file, and
btrfs_fileattr_set() sets the compression property whenever the new
flags include FS_COMPR_FL, even when the compression flags do not
change. A file created on a filesystem mounted with nodatasum has
NODATASUM and still inherits the compress flag from its directory. As
of now, chattr fails on such a file when it changes any other flag.

The issue can be reproduced with:

    mkfs.btrfs -f /dev/sdb
    mount -o nodatasum /dev/sdb /mnt
    mkdir /mnt/dir
    chattr +c /mnt/dir
    touch /mnt/dir/file
    chattr +A /mnt/dir/file

Before commit cf1afec09e9f ("btrfs: validate properties before setting
them"), the last command succeeds.

After that commit, it fails with EINVAL.

This patch will make btrfs_fileattr_set() leave the compression flags
and the compression property alone when the call changes neither
FS_COMPR_FL nor FS_NOCOMP_FL.

Fixes: cf1afec09e9f ("btrfs: validate properties before setting them")
CC: stable@vger.kernel.org # 7.2+
Suggested-by: Qu Wenruo <wqu@suse.com>
Assisted-by: LLM
Signed-off-by: Hengyu Liang <hengyul@cs.unc.edu>
Reviewed-by: Qu Wenruo <wqu@suse.com>
Reviewed-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: Filipe Manana <fdmanana@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
2 weeks agoMerge tag 'spi-fix-v7.4-merge-window' of git://git.kernel.org/pub/scm/linux/kernel...
Linus Torvalds [Fri, 30 Oct 2026 18:27:10 +0000 (08:27 -1000)]
Merge tag 'spi-fix-v7.4-merge-window' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/spi

Pull spi fixes from Mark Brown:
 "Two patches here, one a straightforward device quirk and the other a
  fix for a potentially nasty data corruption bug in the zynq-qspi
  driver"

* tag 'spi-fix-v7.4-merge-window' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/spi:
  spi: cs42l43: Add speaker ID quirk for Dell XPS 13 DX13260 SKU 0E54
  spi: zynq-qspi: fix address buffer corruption and support 4-byte address

2 weeks agoMerge tag 'regulator-fix-v7.4-merge-window' of git://git.kernel.org/pub/scm/linux...
Linus Torvalds [Fri, 30 Oct 2026 18:24:02 +0000 (08:24 -1000)]
Merge tag 'regulator-fix-v7.4-merge-window' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/regulator

Pull regulator fix from Mark Brown:
 "One fix here, we had an issue with deferred hardware disables where
  if we were deferring while suspend was happening we would let the
  workqueue run which could result in us trying to access hardware after
  it or the buses used to access it were suspended.

  We fix this by completing any work as we suspend the individual
  regulators"

* tag 'regulator-fix-v7.4-merge-window' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/regulator:
  regulator: irq: freeze deferred hardware access during suspend

2 weeks agoMerge tag 'regmap-fix-v7.4-merge-window' of git://git.kernel.org/pub/scm/linux/kernel...
Linus Torvalds [Fri, 30 Oct 2026 18:20:58 +0000 (08:20 -1000)]
Merge tag 'regmap-fix-v7.4-merge-window' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/regmap

Pull regmap fix from Mark Brown:
 "One fix for a real issue that fortunately doesn't affect any in tree
  configurations"

* tag 'regmap-fix-v7.4-merge-window' of git://git.kernel.org/pub/scm/linux/kernel/git/broonie/regmap:
  regmap: irq: fix incorrect index calculation for read_sub_irq_data()

2 weeks agoMerge tag 'scsi-misc' of git://git.kernel.org/pub/scm/linux/kernel/git/jejb/scsi
Linus Torvalds [Fri, 30 Oct 2026 17:45:41 +0000 (07:45 -1000)]
Merge tag 'scsi-misc' of git://git.kernel.org/pub/scm/linux/kernel/git/jejb/scsi

Pull more SCSI updates from James Bottomley:
 "A couple of late arriving driver updates (lpfc, ufs) with the main
  addition being the lock context analysis update where clang static
  analysis coupled with annotations are used to verify driver guarantees
  about locks and warn on compile if they're inconsistent. This is
  mostly annotations with only a few code changes (except in scsi_debug
  which needed a fairly big rework to validate with locking context
  analysis)"

* tag 'scsi-misc' of git://git.kernel.org/pub/scm/linux/kernel/git/jejb/scsi: (103 commits)
  scsi: ufs: core: Do not release a reserved request in ufshcd_abort()
  scsi: ufs: core: Remove completed-without-interrupt path in ufshcd_abort()
  scsi: ufs: core: Fix double release in ufshcd_eh_timed_out()
  scsi: ufs: core: Fix double completion in ufshcd_clear_lu_cmds()
  scsi: ufs: core: Add a helper for clearing hba->outstanding_reqs
  scsi: ufs: core: Remove an always-false WARN_ONCE()
  scsi: fnic: Update module authors
  scsi: ufs: qcom: Power down UFS during system suspend on Milos
  scsi: MAINTAINERS: Update Marvell Ethernet storage maintainers
  scsi: handle out-of-range SG_SET_TIMEOUT values
  scsi: core: Update cdrom.h coments
  scsi: st: MAINTAINERS: Add Laurence Oberman and John Meneghini
  scsi: sd: Mark the disk dead if runtime resume fails in sd_remove()
  scsi: libiscsi_tcp: Prevent R2T range check overflow
  scsi: ufs: core: Fix stale comment in ufshcd_mcq_config_nr_queues()
  scsi: fnic: Annotate fnic_nvme functions with __must_hold()
  scsi: ufs: core: Fix a deadlock between clock scaling and device commands
  scsi: ufs: core: Clear stale UIC result byte before peer DME retries
  scsi: ufs: bsg: Reject UIC commands with a non-zero result byte
  scsi: ufs: bsg: Validate request_len before accessing request
  ...

2 weeks agoMerge tag 'block-7.4-20261029' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe...
Linus Torvalds [Fri, 30 Oct 2026 16:33:23 +0000 (06:33 -1000)]
Merge tag 'block-7.4-20261029' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux

Pull more block updates from Jens Axboe:
 "Bigger than usual for an end-of-merge-window pull request, main reason
  being that the MD side I had missed a pull on, and both NVMe and block
  got a good pile of LLM driven fixes where some of them may as well
  just go in now rather than wait a full cycle. This contains:

   - NVMe fixes via Keith:
      - nvme-tcp fallout from the parallel queue allocation: initialize
        pf_cache_lock and the header digest before requests are set up,
        and don't dereference a NULL queue->ctrl on reconnect
      - nvme-fabrics queue mapping fixes: reset io_queues on reconnect,
        limit each queue type to the online CPUs, and clear a poll map
        with no poll queues
      - nvme-tcp io_work priority inversion with send_mutex held
        (Seiji), error recovery on read_sock failure and skipping TLS
        control records while waiting for the ICResp (Martin B), TLS
        handshake timeout validation, and an address attribute race
      - nvme-rdma NULL metadata_sgl dereference with T10-PI
      - nvme-pci early boot hang with the quirks parameter
      - nvme-multipath ANA log bounds underflow, and an nvme-fc
        discovery reference leak
      - nvmet hardening: rdma inline SGL out-of-bounds write and short
        connect requests, fc use-after-free in LS create connection and
        teardown on admin queue failure, pci-epf transport error
        reporting and SGL length checks, zns NUMD wrap, fc stale read
        data, auth state and status fixes, ports list and qid_max
        locking, rdma double puts and irq-safe locking, and a double
        free on metadata SGL allocation failure
      - nvmet fixes from Josef: big discard length truncation, NULL
        derefs for PCI endpoint targets and debugfs host_traddr, stop
        listening when a tcp port is removed, and don't BUG() in
        nvme-loop when a scan runs beside a reset

   - MD fixes via Yu Kuai:
      - raid5 validation: reject too few disks, invalid reshape disks, a
        per-device size below one chunk, and an inconsistent reshape
        state from the superblock instead of BUG(), plus journal payload
        size checks
      - raid5 error path and lifetime fixes: extra_page leak and NULL
        derefs in free_conf/setup_conf, draining released_stripes before
        destroying the cache, RCU for the big_stripe_tree lookup, and
        per-array io_unit slab names
      - md core: reject v0.90 arrays with too many devices, validate
        bblog_size, take reconfig_mutex when enabling PPL, fix the
        mddev->private NULL deref when stopping an array under IO, and
        don't hand out the array before mddev->kobj is added
      - raid10 missing barrier wakeup, raid0 device count validation, a
        bogus mddev_unlock() in lbs_store(), and shared helpers

   - blk-mq fixes from Josef:
      - don't trust the bio cookie in blk_mq_poll()
      - keep tag sharing fair after a queue update
      - don't bring back flags of a completed request from the timeout
        handler
      - honor a restarted timer
      - initialize the dma state for P2P
      - quiesce a queue joining a quiesced tag set
      - set up and exit hctxs under tag_list_lock
      - free the tag bitmaps in the SRCU callback

   - blk-cgroup and friends from Josef:
      - keep the old blkg while reassociating a bio
      - free struct ioc after a grace period
      - don't truncate v1 iops limits
      - fix root io.stat on 32-bit
      - don't free a blkg with its punt work queued
      - flush iolatency enable_work after going offline
      - pass dead group I/O counts on and make reset_stats reset them
      - don't enter reclaim under rq_qos_mutex

   - Other core fixes from Josef:
      - a disk use-after-free in sync_bdevs()
      - don't losing the status of a failed flush request
      - 64-bit sector math for mac partitions
      - apply the segment size to the integrity buffer

   - blk-iocost: abort a weight transfer on invalid donation weights,
     and publish hweights as one atomic value

   - Fix a NULL deref and use-after-free in __blk_crypto_evict_key(),
     reachable via dm-inlinecrypt

   - Fix recursive i_rwsem locking in blkdev_write_iter(), from two
     fixes for the same race landing in the window

   - Advance the iterator after copy-in for SG_DXFER_TO_FROM_DEV, fixing
     an infinite loop in blk_rq_map_user_iov()

   - Check the open mode for LOOP_SET_STATUS in the compat ioctl

   - rnbd-srv use-after-free and kobject fixes

   - drbd timer and req_lock fixes

   - zloop cleanups and error path fixes

   - cdrom header and kernel-doc cleanups"

* tag 'block-7.4-20261029' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux: (109 commits)
  blk-crypto: fix NULL deref and UAF in __blk_crypto_evict_key()
  zloop: check that the zone backing file support ->{read,write}_iter
  zloop: fput file after failed zone init
  zloop: share more code for opening a zone backing file
  zloop: remove a duplicate call to zloop_get_block_size
  block: fix kernel-doc warnings in blk-map.c and blk-mq-dma.c
  blk-iocost: publish hweights as one atomic value
  blk-iocost: abort weight transfer on invalid donation weights
  rnbd-srv: publish the sess_dev at the end of OPEN
  rnbd-srv: fix use-after-free on two CLOSE messages
  block/rnbd-srv: drop the sess_dev kobject unlocked
  block/rnbd-srv: don't free the device on a sysfs error
  drbd: take req_lock to skip the initial sync as peer
  drbd: stop the start_resync timer of a dying device
  block: apply the segment size to the integrity buffer
  blk-mq: free the bitmaps of tags in the SRCU callback
  block: partitions/mac: compute the sectors in 64 bits
  blk-mq: set up a queue under tag_list_lock
  blk-mq: exit the hctxs of a queue under tag_list_lock
  blk-mq: quiesce a queue that joins a quiesced tag set
  ...

2 weeks agoMerge tag 'io_uring-7.4-20261029' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Fri, 30 Oct 2026 16:29:43 +0000 (06:29 -1000)]
Merge tag 'io_uring-7.4-20261029' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux

Pull io_uring fixes from Jens Axboe:

 - A batch of fixes from Chris:
    - Charge registered buffer arrays, rsrc nodes, tctx nodes and
      personalities to memcg, and free the XArray nodes a failed store
      leaves behind.
    - Clear bpf_ctx while submitting SQEs from a bpf-ops program, as the
      socket code otherwise skips both the capability check and
      lock_sock() for a setsockopt from the SQ.
    - Free the task context after an RCU grace period, closing a UAF
      when a foreign task frees the last request.
    - Stop io_ring_exit_work() from waiting on an SQPOLL thread held in
      get_signal(), and drop sqd->lock while the thread waits for
      in-flight requests, as either one could pin every iou_exit slot

 - io-wq fixes:
    - Don't create new workers once the exit has begun, which could
      leave an exiting worker in the thread group under exec
    - save the worker type before dropping its reference (KASAN UAF)
    - Defer io-wq enqueues from a foreign task to task_work, as an
      IOPOLL reap by another task could race io_wq_put_and_exit()

 - Keep the drain active when the deferred request being started is
   itself a drain request, and don't attach a new ring to an SQPOLL
   thread that is already canceling

 - Fix the multishot recv length limit accounting, and count cancelled
   timeouts in cq_timeouts so an armed off timeout doesn't fire early

 - Advance the buffer ring head when a pickup empties it, and keep the
   recvmsg buffer select length within MAX_RW_COUNT

 - Mask the socket type in the bpf filter population so SOCK_CLOEXEC or
   SOCK_NONBLOCK can't bypass a type filter, and enforce the per-task
   register restrictions for blind registration

 - Complete a non-blocking connect() that fails with -EAGAIN rather than
   retrying it through poll and io-wq, matching connect(2)

 - napi list traversal cleanup, and remove a useless min_not_zero()

* tag 'io_uring-7.4-20261029' of git://git.kernel.org/pub/scm/linux/kernel/git/axboe/linux: (21 commits)
  io_uring/sqpoll: don't attach to a thread that is canceling
  io_uring/net: fix multishot recv length limit accounting
  io_uring/timeout: count cancelled timeouts in cq_timeouts
  io_uring/napi: clean up list traversal with list_for_each_entry_safe()
  io_uring: defer foreign io-wq enqueues to task_work
  io_uring/io-wq: save worker type before dropping its reference
  io_uring/cancel: drop sqd->lock while SQPOLL waits
  io_uring/sqpoll: don't wait for the thread to exit
  io_uring: free the task context after a grace period
  io_uring/bpf-ops: clear bpf_ctx while submitting SQEs
  io_uring: free XArray nodes left by a failed store
  io_uring: charge tctx nodes and personalities
  io_uring/rsrc: charge buffer arrays and nodes to memcg
  io_uring/io-wq: no new workers once the exit has begun
  io_uring: keep the drain active when a deferred drain request is started
  io_uring/net: don't retry a non-blocking connect() that fails with -EAGAIN
  io_uring/register: enforce per-task restrictions in io_uring_register_blind()
  io_uring/net: mask socket type with SOCK_TYPE_MASK in io_socket_bpf_populate()
  io_uring/net: Remove useless min_not_zero() usage
  io_uring/net: keep recvmsg buffer select length within MAX_RW_COUNT
  ...

2 weeks agoMerge tag 'fbdev-for-7.4-rc1-2' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Fri, 30 Oct 2026 16:27:35 +0000 (06:27 -1000)]
Merge tag 'fbdev-for-7.4-rc1-2' of git://git.kernel.org/pub/scm/linux/kernel/git/deller/linux-fbdev

Pull more fbdev updates from Helge Deller:

 - atmel_lcdfb: avoid issues due to empty modelist in probe

 - simplify the console-blanking interface

* tag 'fbdev-for-7.4-rc1-2' of git://git.kernel.org/pub/scm/linux/kernel/git/deller/linux-fbdev:
  fbdev: atmel_lcdfb: fix list_first_entry() on possibly empty modelist in probe
  vt: Remove old-style con_blank
  vgacon: Implement struct consw.con_unblank
  sticon: Implement struct consw.con_unblank
  newport_con: Implement struct consw.con_unblank
  fbcon: Implement struct consw.con_unblank
  dummycon: Implement struct consw.con_unblank
  vt: Add con_unblank callback to struct consw

2 weeks agoMerge tag 'clk-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/clk/linux
Linus Torvalds [Fri, 30 Oct 2026 16:18:43 +0000 (06:18 -1000)]
Merge tag 'clk-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/clk/linux

Pull clk updates from Stephen Boyd:
 "Here's the clk changes for the merge window which is dominated in the
  diffstat by Qualcomm churning out new SoCs that need clk drivers.

  Looking beyond the sheer amount of lines of mostly data there we have
  a clk nexus DT binding change in the core clk framework and a driver
  core patch to add a subsys driver macro.

  The clock nexus support is useful for devices that map clks internally
  or for connectors on a board that route clock signals to another
  board. I suspect the use of this will expand in the future, so we have
  unit tests to make sure it doesn't break.

  The driver core change adds subsys_driver() and
  subsys_platform_driver() so we can register early drivers without
  open-coding that all (module_platform_driver() is at device initcall
  level so it isn't be used).

  Beyond the core framework bits we have lots of changes all over the
  tree to initialize 'struct clk_init_data'. The potential risk here is
  that someone forgets to initialize all the members of that structure
  and either the clk flags cause weird behavior later on or the parents
  are pointing at junk and the clk is orphaned forever. The patches just
  initialize the thing with zeroes to be safe. Longer term we should
  probably move this struct out of 'struct clk_hw' and pass it during
  clk registration time. That's a much bigger change and would require
  restructuring entire drivers that rely on the pointer being there.

  Finally, we have the usual fixes like calculation updates for
  dividers, handling error paths during clk registration, or fixing clk
  data now that drivers are using them. Those patches are dwarfed by the
  amount of new SoC support and only affect those SoCs and the consumers
  of those clks. Overall I'm more concerned the clk_init_data patches
  are going to expose some latent bugs that we didn't notice before
  because something was relying on clks being orphaned and now they're
  not.

  Core:
   - subsys_driver() / subsys_platform_driver() macros
   - Clock nexus DT binding support (with KUnit tests)
   - Spread-spectrum configuration validation
   - Fully initialize struct clk_init_data across many drivers

  New Drivers:
   - Anlogic DR1V90 CRU
   - ZTE zx297520v3 top, matrix, and LSP clocks
   - Samsung Exynos5515 and ACPM driver extended to Exynos850.
   - Qualcomm Eliza camera, camera-BIST, GPU, and video clks
   - Qualcomm Hawi / Maili camera and GPU controllers
   - Qualcomm Kuno global, RPMh
   - Qualcomm MSM8952 global, RPM
   - Qualcomm Nord camera/video clocks, EMAC interconnect, PHY resets
   - Qualcomm IPQ5210 / IPQ9650 network clocks
   - i.MX93 350 MHz fractional-N GP-PLL for display
   - i.MX pll14xx spread-spectrum clock generation
   - Amlogic A9 SCMI clock controller
   - Allwinner single-divider "update bit" support
   - EN7523 Serdes port selection"

* tag 'clk-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/clk/linux: (316 commits)
  clk: imx: pll14xx: support spread spectrum clock generation
  clk: cdce925: Size the PLL child name buffer for any int
  clk: stm32: fix clock array size for STM32MP21
  dt-bindings: clock: Convert HiSilicon clocks to DT schema
  clk: lmk04832: Handle reset GPIO lookup errors
  dt-bindings: clock: anlogic,dr1v90-cru: make external clocks optional
  clk: tegra: bpmp: remove kcalloc
  clk: mmp2-audio: add missing PM_CLK dependency
  clk: zte: Introduce a driver for zx297520v3 LSP clocks
  clk: zte: Introduce a driver for zx297520v3 matrix clocks
  clk: zte: Introduce a driver for zx297520v3 top clocks
  clk: zte: Add zx PLL support infrastructure
  clk: zte: Add regmap-based clocks
  clk: zte: Add Clock registration infrastructure
  dt-bindings: clk: zte: Add zx297520v3 LSP clock and reset controller
  dt-bindings: clk: zte: Add zx297520v3 matrix clock and reset controller
  dt-bindings: clk: zte: Add zx297520v3 top clock and reset controller
  clk: nuvoton: ma35d1: Add missing WDT/WWDT parent clocks
  dt-bindings: clock: ma35d1: Add missing WDT/WWDT parent clocks
  dt-bindings: clock: ma35d1: Drop CLK_MAX_IDX define
  ...

2 weeks agoio_uring/sqpoll: don't attach to a thread that is canceling
Jens Axboe [Fri, 30 Oct 2026 13:27:28 +0000 (07:27 -0600)]
io_uring/sqpoll: don't attach to a thread that is canceling

io_sq_offload_create() refuses to attach a ring to an SQPOLL thread
that has already gone, by checking sqd->thread under sqd->lock. Since
the thread drops the lock while io_uring_cancel_generic() waits for its
requests, that check can run while the thread is on its way out and
still see it. The new ring is then added to ctx_list, io_uring_setup()
succeeds, the thread finishes canceling and exits without ever having
looked at the ring, and io_uring_enter() fails with -EOWNERDEAD.

Only a thread that exits on a fatal signal can be caught like this, as
the stop bit is set once the last ring has let go of the sqd, when no fd
is left to attach through. A fatal signal is group wide and attaching
needs the same thread group, so the attacher is on its way out as well.
Still, make the check see it: set the stop bit before canceling,
whatever the reason for the exit, and test it when attaching.

Reported-by: Karl Mehltretter <kmehltretter@gmail.com>
Fixes: cb0306c52ffa ("io_uring/cancel: drop sqd->lock while SQPOLL waits")
Signed-off-by: Jens Axboe <axboe@kernel.dk>
3 weeks agoMerge tag 'fscrypt-for-linus' of git://git.kernel.org/pub/scm/fs/fscrypt/linux
Linus Torvalds [Fri, 30 Oct 2026 00:00:23 +0000 (14:00 -1000)]
Merge tag 'fscrypt-for-linus' of git://git.kernel.org/pub/scm/fs/fscrypt/linux

Pull fscrypt fixes from Eric Biggers:

 - Add more checks to prevent encryption on "large block size" ext4
   filesystems (s_blocksize > PAGE_SIZE), which isn't supported yet.
   There was already a mount-time check, but it wasn't enough.

 - Add missing memory barrier to fscrypt_find_mode_key()

 - Add missing zeroization in an error path

* tag 'fscrypt-for-linus' of git://git.kernel.org/pub/scm/fs/fscrypt/linux:
  ext4: reject encrypted inodes when block size > page size
  ext4: refuse encryption when block size > page size
  fscrypt: Fix missing barrier in fscrypt_find_mode_key()
  fscrypt: Explicitly zeroize sw_secret in error path

3 weeks agoMerge tag 'ntfs3_for_7.4' of https://github.com/Paragon-Software-Group/linux-ntfs3
Linus Torvalds [Thu, 29 Oct 2026 23:31:48 +0000 (13:31 -1000)]
Merge tag 'ntfs3_for_7.4' of https://github.com/Paragon-Software-Group/linux-ntfs3

Pull ntfs3 updates from Konstantin Komarov:
 "The bulk of this cycle is hardening against corrupted or maliciously
  crafted volumes. Most of these fixes come from fuzzing and KASAN
  reports. The main areas are:

   - $LogFile replay, where several unchecked on-disk sizes could make
     mount write past the MFT record buffer
   - MFT record and index parsing
   - extended attributes, where a bad $EA entry could leak up to 64K of
     kernel heap to userspace through getxattr()

  Reading a damaged compressed file could also return uninitialized page
  cache contents to userspace; that is fixed too.

  A few fixes affect healthy volumes as well: a heap overflow in
  fallocate(INSERT_RANGE) on small files, a use-after-free when a
  WOF-compressed file is opened for writing during a concurrent read, a
  lock-order deadlock in readdir, and stale disk data showing up in
  newly allocated clusters of compressed files.

  On the feature side there are new tracepoints covering mount, log
  replay, lookup, directory index, allocation, iomap and file I/O. There
  is also a new 'ugm' mount option (on by default): with ugm=0, newly
  created files don't get the WSL uid/gid/mode extended attributes,
  which Windows doesn't use.

  The rest is smaller correctness fixes and cleanups"

* tag 'ntfs3_for_7.4' of https://github.com/Paragon-Software-Group/linux-ntfs3: (52 commits)
  ntfs3: add file I/O tracepoints
  ntfs3: add iomap tracepoints
  ntfs3: add allocation tracepoints
  ntfs3: add directory index tracepoints
  ntfs3: add create inode tracepoint
  ntfs3: add namei tracepoints
  ntfs3: add mount and log replay tracepoints
  fs/ntfs3: validate the EA value length in ntfs_read_ea()
  fs/ntfs3: handle partial allocation in attr_data_get_block_locked()
  ntfs3: fix mapping pairs bounds check for alignment
  fs/ntfs3: bound DeleteAttribute asize against rec->used in do_action
  ntfs3: release ni_lock before dir_emit in ntfs_readdir to fix deadlocks
  fs/ntfs3: bound CreateAttribute asize against record_size in do_action
  fs/ntfs3: do not mark frame pages uptodate on read error
  fs/ntfs3: prevent positive E_NTFS_NONRESIDENT from reaching writeback error handling
  fs/ntfs3: fix ntfs_fnd leak when compare function is missing
  fs/ntfs3: fix stale attr_b in attr_allocate_frame()
  fs/ntfs3: reject unaligned hole punching on compressed files
  fs/ntfs3: take ni_lock() once in ntfs_readdir()
  fs/ntfs3: reserve a compression unit in maxbytes_sparse
  ...

3 weeks agoMerge tag 'kgdb-7.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/danielt...
Linus Torvalds [Thu, 29 Oct 2026 23:24:49 +0000 (13:24 -1000)]
Merge tag 'kgdb-7.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/danielt/linux

Pull kgdb updates from Daniel Thompson:
 "Varied updates this cycle.

  Naveen Kumar Chaudhary fixed a memory leak when the environment is
  already full, eliminated to weird historical cruft (CMD_BUFLEN having
  different values in different files) and removed some dead code.

  Fang Xieyan tackled a family of related buffer overflows in the gdb
  remote protocol parsing (great fixes from a defensive coding point of
  view but not security relavent; gdb can already do anything it wants
  to)"

* tag 'kgdb-7.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/danielt/linux:
  kgdb: Fix buffer overflow in the qRcmd packet handler
  kgdb: Fix buffer overflow in the 'M' and 'X' packet handlers
  kgdb: Fix buffer overflow in the 'm' packet handler
  kgdb: remove unreachable return in kgdb_reenter_check()
  kdb: unify CMD_BUFLEN definition into kdb_private.h
  kdb: fix memory leak in kdb_setenv() when environment is full

3 weeks agoMerge tag 'hyperv-next-signed-20261028' of git://git.kernel.org/pub/scm/linux/kernel...
Linus Torvalds [Thu, 29 Oct 2026 22:39:45 +0000 (12:39 -1000)]
Merge tag 'hyperv-next-signed-20261028' of git://git.kernel.org/pub/scm/linux/kernel/git/hyperv/linux

Pull hyperv updates from Wei Liu:

 - Update to documents and code comments (Michael Kelley)

 - Harden Vmbus (Kameron Carr)

 - Rework MSHV driver page deposit logic (Mukesh Rathor)

 - Vmbus kexec bug fix (Shradha Gupta)

 - Miscellaneous bug fixes (Daehyeon Ko, Jiale Yao, Sasha Levin)

* tag 'hyperv-next-signed-20261028' of git://git.kernel.org/pub/scm/linux/kernel/git/hyperv/linux:
  Drivers: hv: Remove leftover support for old Hyper-V versions
  mshv: Remove unused *_old memory deposit functions
  mshv: Redesign hypervisor memory deposit logic
  mshv: Rename memory deposit memory functions to _old
  mshv_vtl: reject poll files with multiple waitqueues
  mshv_vtl: detach poll waiter on POLLFREE
  mshv_vtl: initialize poll file mutex before device registration
  Documentation: hyperv: Update information on guest CPU offlining
  Documentation: hyperv: Remove support for guests on Hyper-V 2012/2012R2
  Drivers: hv: Run VMBus kexec cleanup from syscore shutdown
  kexec: Add helper to report an active kexec reboot
  tools: hv: remove unused rte_smp_mb()
  Documentation: hyperv: Update documentation for sending VMBus packets
  Drivers: hv: vmbus: Check ACPI companion before use
  Documentation: hyperv: Describe validation of the ring buffer indices
  Drivers: hv: vmbus: Keep the ring byte counts sane for a bad index
  Drivers: hv: vmbus: Compute ring byte counts from a caller-held snapshot
  Drivers: hv: vmbus: Use *_ONCE() to access shared ring buffer indices
  Drivers: hv: vmbus: Bounds check the shared ring buffer indices

3 weeks agoMerge tag 'riscv-for-linus-7.4-mw1' of git://git.kernel.org/pub/scm/linux/kernel...
Linus Torvalds [Thu, 29 Oct 2026 22:33:25 +0000 (12:33 -1000)]
Merge tag 'riscv-for-linus-7.4-mw1' of git://git.kernel.org/pub/scm/linux/kernel/git/riscv/linux

Pull RISC-V updates from Paul Walmsley:

 - Add support for crash hotplug

 - Improve user copy performance on cores with fast misaligned accesses

 - Optimize code paths involving pgtable_l{4,5}_enabled() by patching in
   the return values during early boot (since these don't change during
   runtime), or by specifying the return values directly in Kconfig
   files (for purpose-built kernels)

 - Change the PCIe bus reassignment behavior to depend on the
   PCI_REASSIGN_ALL_BUS PCI flag (as ARM64 does)

 - Avoid an unnecessary sstatus CSR read during context switch

 - Make the sbi_ecall() macro variadic, improving code clarity

 - Refactor __switch_to_vector() to prepare for upcoming vector context
   switch optimizations

 - Add a kselftest for vectorized user copy

 - Add bounds checking on the shadow stack restore token address to
   avoid it being used as an attack vector

 - Fix the shadow stack and indirect branch landing pad control
   functions to only update the CPU's envcfg CSR when operating on the
   current task

 - For MIPS RISC-V systems, add support for early boot-applied errata;
   and for P8700 RISC-V systems, avoid WFI usage in the kernel (since it
   is buggy)

 - Add the "B" RISC-V ISA extension to hwcap and hwprobe reporting

 - Add support for specifying and reporting the "Zic64b" RISC-V ISA
   extension, and add it to the SpacemiT K1, K3, and Sophgo SG2044 DT
   files

 - Require the block size of cache management operations to be specified
   in DT schema validation for the RISC-V ISA extensions Zicbom, Zicbop,
   and Zicboz

 - Some miscellaneous fixes: fix an incorrect bitfield width in the
   RVG_SYSTEM_CSR_MASK bitmask macro; make RISCV_ALTERNATIVE mandatory,
   now that XIP kernel support has been removed; and remove some
   unnecessary includes in kernel/smp.c

* tag 'riscv-for-linus-7.4-mw1' of git://git.kernel.org/pub/scm/linux/kernel/git/riscv/linux: (28 commits)
  riscv: mm: unexport _pgtable_l4_enabled and _pgtable_l5_enabled
  riscv: introduce RISCV_ISA_SV48 and RISCV_ISA_SV57
  riscv: support early isa ext and use it to optimize pgtable_l4|l5_enabled
  riscv: convert pgtable_l4|l5_enabled to inline function
  riscv: remove RISCV_ALTERNATIVE Kconfig option
  riscv: Add a getter for user PMLEN support
  riscv: dts: sophgo: sg2044: Add Zic64b ISA extension
  riscv: dts: spacemit: k1: Add Zic64b ISA extension
  riscv: dts: spacemit: k3: Add Zic64b ISA extension
  riscv: Add Zic64b to cpufeature and hwprobe
  dt-bindings: riscv: Add Zic64b extension description
  dt-bindings: riscv: Require block-size for Zicbom, Zicbop, and Zicboz
  riscv: Add B to hwcap and hwprobe
  riscv: remove unused profile.h includes
  riscv: cfi: Only write envcfg CSR when task is current
  riscv: cfi: Bounds check restore token before swap
  riscv: Add ERRATA_MIPS_P8700_WFI to replace WFI with mips.pause
  selftest: riscv: test vectorized user copy
  riscv: vector: refactor context switch for kernel-mode vector
  riscv: do not read csr in vector context switch
  ...

3 weeks agoMerge tag 'rust-fixes-7.4' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda...
Linus Torvalds [Thu, 29 Oct 2026 19:40:12 +0000 (09:40 -1000)]
Merge tag 'rust-fixes-7.4' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux

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

   - Fix 'objtool' warnings for the upcoming Rust 1.101.0 (expected
     2026-12-24) by adding one more 'noreturn' function

  'kernel' crate:

   - Fix KCFI failures on every call from C to Rust IRQ handlers and
     'hrtimer' callbacks by giving the C enum bindings the correct
     'cfi_encoding'. Also prevent the same issue for DMA callbacks
     taking 'dma_data_direction'

   - 'workqueue' module: fix a runtime warning when queueing work on the
     deprecated 'system_wq' by switching to 'system_{percpu,dfl}_wq'"

* tag 'rust-fixes-7.4' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux:
  rust: dma: declare cfi_encoding for dma_data_direction
  rust: hrtimer: declare cfi_encoding for hrtimer_restart
  rust: irq: declare cfi_encoding for irqreturn
  objtool/rust: add one more `noreturn` Rust function for Rust 1.101.0
  rust: workqueue: replace deprecated system_wq with system_{percpu,dfl}_wq

3 weeks agoMerge tag 'net-7.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net
Linus Torvalds [Thu, 29 Oct 2026 18:17:05 +0000 (08:17 -1000)]
Merge tag 'net-7.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net

Pull networking fixes from Jakub Kicinski:
 "Current release - new code bugs:

   - mctp: usblib: fix assertion breaking esoteric builds

  Previous releases - regressions:

   - Revert advertising the TCP MSS from the configured MTU

  - netlink: check sk_rcvbuf before charging the dump skb

   - eth:
      - ti: am65-cpts: fix support for PTP_EXTTS_REQUEST2 ioctl
      - mlx4: always create the eth and ib auxiliary devices
      - tg3: invert restart quirk logic to restrict SNP power-down bypass
      - bnxt: recycle agg buffers when Rx head buffer allocation fails

  Previous releases - always broken:

   - net: fix frag_list leak in skb_segment_list() error path

   - sctp: reject forged cookie peer_addr with unknown address family

   - vxlan: keep reserved_bits across changelink

   - net: limit priority VLAN untag depth

   - inet: frags: prevent acceptance of partially authenticated reassembly

   - gro: do not GRO GSO packets with inconsistent payload

   - tcp: avoid double destroy in tcp_abort() of an unaccepted child"

* tag 'net-7.4-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/netdev/net: (137 commits)
  tun: drop batched packets while the device is down
  selftests: net: netlink-dumps: start a dump with a notification queued
  netlink: check sk_rcvbuf before charging the dump skb
  net/sched: act_ife: do not consume the inner header on egress
  openvswitch: use eth_type_trans_careful() in internal_dev_recv()
  net: use eth_type_trans_careful() in __dev_forward_skb2()
  loopback: use eth_type_trans_careful()
  net: add eth_type_trans_careful()
  tcp: initialize mapped children before route lookup
  tcp: fix reordering addition overflow in MTU probing
  tcp: avoid double destroy in tcp_abort() of an unaccepted child
  net: bgmac: fix TX DMA unmapping and slot cleanup
  gro: do not GRO GSO packets with inconsistent payload
  net/packet: check TX_RING fragments before memory accounting
  eth: bnxt: hand XDP frags over to the copybreak skb
  eth: bnxt: free XDP frags when xdp_do_redirect() fails
  eth: bnxt: don't leak buffers when XDP agg buffer allocation fails
  eth: bnxt: resize Rx head buffers when rx-copybreak changes
  eth: bnxt: recycle agg buffers when Rx head buffer allocation fails
  netdev-genl: ignore NETDEV_UNREGISTER rebroadcasts
  ...

3 weeks agoMerge tag 'bpf-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf
Linus Torvalds [Thu, 29 Oct 2026 18:10:23 +0000 (08:10 -1000)]
Merge tag 'bpf-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf

Pull bpf fixes from Alexei Starovoitov:

 - Remove BPF_F_ARENA_SCALAR flag and .arena.data section in libbpf that
   were added for rust-bpf in this merge window. We found a cleaner
   approach that does it on compiler side instead of kernel/libbpf. No
   released kernel has them (Alexei Starovoitov)

 - Fix bpf_send_signal_task() returning -EPERM when it is called from a
   kernel thread (Aditya Sharma)

 - Various fixes (Alexei Starovoitov):
     - Use emit_rsb_call() to call bpf_unwind_target() in x86 JIT to fix
       objtool warning during the build
     - Fix scalar evolution: clear delta of a widened register, don't
       widen a pointer to a buffer, don't clamp a register whose type
       changed in the loop, and reset the range of a clamped packet
       pointer
     - Finish the insn in the state that maybe_fork_scalars() splits
       off, so that pruning doesn't drop it at the head of a counted
       loop
     - Preserve the registers that carry stack arguments across
       arch_bpf_timed_may_goto() on x86-64, arm64 and riscv64
     - Don't re-sort subprog_info[] for every new subprogram
     - Fix flaky map_kptr and rcu_reentry selftests

 - Use memmove() in bpf_skb_load_bytes(), bpf_skb_load_bytes_relative()
   and bpf_xdp_load_bytes(), since the destination can be a slice of the
   same packet (Ayushman Rout)

 - Fixes and follow-ups for scalar evolution: reject pointer operands in
   32-bit recurrences and latches, don't intersect with the current
   register range on clamp to avoid a false 'verifier bug', avoid false
   infinite loop reports, and recognize a 32-bit copy of the induction
   variable (Eduard Zingerman)

 - Fix out-of-bounds write to btf->types[] for split BTF and propagate
   btf_add_type() errors in btf_check_all_metas() (Feng Yang)

 - Fix use-after-free in bpf_timer callback that fires after its inner
   map was freed (Mani Tofigh)

 - Fix x86 JIT stopping before jumps converge: size backward jumps by
   the insns they jump over (Mykyta Yatsenko)

 - Fix use-after-free of struct_ops trampoline: dissociate struct_ops
   progs before the grace period of the map (Qiliang Yuan)

 - Validate stack argument reads against the caller state to fix
   out-of-bounds read in the verifier, and reject callbacks with stack
   arguments (Weiming Shi)

 - Tie borrowed iterator results and pointers loaded from trusted fields
   to the lifetime of their source, so that iterator next, destroy and
   reference release invalidate them (Xu Yunxiang)

* tag 'bpf-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf: (48 commits)
  bpf: Don't re-sort subprog_info[] for every new subprogram
  bpf: Fix out-of-bounds btf->types write for split BTF
  selftests/bpf: Test stack arguments across may_goto
  bpf: Keep stack arguments in arch_bpf_timed_may_goto()
  selftests/bpf: Test maybe_fork_scalars() at the head of a counted loop
  bpf: Finish the insn in the state that maybe_fork_scalars() splits off
  selftests/bpf: Test the clamp of pointers in scalar evolution
  bpf: Reset the range of a packet pointer that scalar evolution clamps
  bpf: Don't clamp a register whose type changed in the loop
  selftests/bpf: Test a loop that moves a pointer to a buffer
  bpf: Don't widen a pointer to a buffer in scalar evolution
  selftests/bpf: Avoid a page fault in rcu_reentry while the handler is armed
  selftests/bpf: Wait for the last maps of map_kptr to be freed
  selftests/bpf: Test that a widened register is not linked
  bpf: Clear delta of a register that scalar evolution widens
  bpf, x86: Remove r0_on_stack from fetching atomics in arena
  bpf: Remove BPF_F_ARENA_SCALAR
  selftests/bpf: Remove tests for arena access through numbers
  libbpf: Keep format strings of bpf_printk() in .rodata
  libbpf: Remove .arena.data
  ...

3 weeks agoMerge tag 'kthread-fix-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Thu, 29 Oct 2026 17:49:07 +0000 (07:49 -1000)]
Merge tag 'kthread-fix-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/frederic/linux-dynticks

Pull kthread fix from Frederic Weisbecker:
 "Fix a bug where dynamic CPU isolation through cpuset isolated
  partitions can move a kthread out of the housekeeping range.

  The fix makes sure the fallback affinity is always a set of online
  housekeeper"

* tag 'kthread-fix-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/frederic/linux-dynticks:
  kthread: Fall back when no preferred housekeeping CPU is online

3 weeks agoMerge tag 'docs-7.4-2' of git://git.kernel.org/pub/scm/linux/kernel/git/docs/linux
Linus Torvalds [Thu, 29 Oct 2026 17:46:22 +0000 (07:46 -1000)]
Merge tag 'docs-7.4-2' of git://git.kernel.org/pub/scm/linux/kernel/git/docs/linux

Pull more documentation updates from Jonathan Corbet:
 "A handful of late-arriving changes, most of which were ready ahead of
  the merge window:

   - More Portuguese translation updates

   - Some docs-build and self-test fixes

   - Bring documentation for the user-space access primitives
     in include/linux/uaccess.h into the docs build.

     This revealed a number of malformed kerneldoc comments,
     which are fixed in a subsequent tweak to uaccess.h"

* tag 'docs-7.4-2' of git://git.kernel.org/pub/scm/linux/kernel/git/docs/linux:
  uaccess: fix some erroneous kerneldoc comments
  docs/translations/pt_BR: admin-guide: add efi-stub.rst
  docs/translations/pt_BR: admin-guide: add kernel-parameters.rst
  docs/translations/pt_BR: admin-guide: add bootconfig.rst
  docs/translations/pt_BR: admin-guide: add perf-security.rst
  docs/translations/pt_BR: admin-guide: add LSM/index.rst
  docs/translations/pt_BR: admin-guide: add hw-vuln/index.rst
  docs/translations/pt_BR: admin-guide: add cputopology.rst
  docs/translations/pt_BR: admin-guide: add sysctl/index.rst
  docs/translations/pt_BR: admin-guide: add sysfs-rules.rst
  docs/translations/pt_BR: admin-guide: add features.rst
  docs: pt_BR: process: translate userspace debugging guide
  docs: kerneldoc.py: preserve headings in kernel-doc output
  docs: xforms_lists: Handle DECLARE_KHOSER_PTR() struct members
  docs: test_doc_build: don't select urllib3 yanked version
  docs: test_doc_build: address pylint warnings
  docs: test_doc_build: update it to support newer Sphinx versions
  docs: test_doc_build: better handle python version
  docs: admin-guide: Fix typo in kernel-parameters.txt
  docs: core-api: include documentation from linux/uaccess.h

3 weeks agoMerge tag 'sched_ext-for-7.4-fixes' of git://git.kernel.org/pub/scm/linux/kernel...
Linus Torvalds [Thu, 29 Oct 2026 17:38:53 +0000 (07:38 -1000)]
Merge tag 'sched_ext-for-7.4-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/tj/sched_ext

Pull sched_ext fixes from Tejun Heo:
 "This is a big pull for fixes, but much of it was in the works before
  the merge window.

  Most of these fixes are in sub-scheduler support, which nests BPF
  schedulers under a parent that hands them CPUs. It was heavily
  reworked over recent cycles and is now functionally complete. Porting
  real schedulers on it drove the latest additions and keeps finding
  corner cases.

  For example, once CPUs are shared and can be taken back, the kernel
  must keep every task moving when its scheduler can't run it or is
  failing, and those fallbacks interact subtly with each other and with
  other new core features.

   - The fallback paths meant to keep a task moving when its scheduler
     can't run it or is failing could themselves leave it stuck

   - The stall watchdog could blame a scheduler for time it wasn't
     responsible for, even taking down all of sched_ext

   - Sub-schedulers were told late, or not at all, which CPUs they could
     use

   - Deferred callbacks could stay queued or be dropped under core
     scheduling and proxy execution, with a sched/core fix to the
     duplicate check

   - Hardening: tracing programs can no longer call kfuncs that could
     deadlock the CPU"

* tag 'sched_ext-for-7.4-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/tj/sched_ext: (34 commits)
  sched_ext: Reject scx_bpf_sub_grant/revoke() in tracing programs
  sched_ext: Fix the rescue overload pick ejecting the wrong sub under bypass
  sched_ext: Fix use-after-free of a NONE rescuee leaving its sched while running
  sched_ext: Fix a lone IMMED task waiting behind a kept prev
  sched_ext: Fix queued bypassed tasks stalling when the host loses SCX_CAP_BASE
  sched_ext: Let the bypass load balancer move tasks homed on other cpus
  sched_ext: Factor out bypass_lb_move() and insert with the donor DSQ unlocked
  sched_ext: Fix the bypass load balancer stranding tasks on cpus where the host lacks SCX_CAP_BASE
  sched_ext: Fix bypassed tasks stalling when the host lacks SCX_CAP_BASE
  sched_ext: Expire prev's slice in dispatch_one() under bypass
  sched_ext: Fix a cpu idling after put_prev_task_scx() queues its task on the local DSQ
  sched_ext: Refuse extending a kernel slice
  sched_ext: Mark the rescue grant as a kernel slice with SCX_TASK_KERNEL_SLICE
  sched_ext: Fix a cpu idling with a runnable rescuee
  sched_ext: Restore a rescuee's slice after ops.stopping()
  sched_ext: Fix rescue served time disagreeing with the slice under proxy execution
  sched_ext: Move refill_task_slice_dfl() below apply_slice_vtime()
  sched_ext: Fix bypassed tasks looping on a host without SCX_CAP_ENQ
  sched_ext: Fix bypassed tasks stranded by the reenqueue limit
  sched_ext: Clear holding_cpu where the claim is confirmed
  ...

3 weeks agoMerge tag 'cgroup-for-7.4-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git...
Linus Torvalds [Thu, 29 Oct 2026 17:35:19 +0000 (07:35 -1000)]
Merge tag 'cgroup-for-7.4-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/tj/cgroup

Pull cgroup fixes from Tejun Heo:

 - cgroup.kill did not kill a process whose thread group leader had
   exited while other threads still ran, nor those threads once moved to
   another cgroup, letting a process survive its container being killed

 - A cgroup.procs write under favordynmods could migrate a newly forked
   process before fork linked it to its cgroup, corrupting cgroup task
   lists

 - cpuset partition fixes for nested hierarchies: invalidation, revival,
   shrinking and switches between root and isolated could leak isolated
   CPUs, skip or miscompute the housekeeping check, or leave wrong
   effective CPUs:

     - A root partition can no longer be created under an isolated
       parent or stay valid under one, as disabling it could leave no
       housekeeping CPUs

     - Enabling a partition failed when a grandchild held tasks,
       although the parent had none of its own

     - Separately, an allocation racing with a cpuset.mems update could
       drop its mempolicy nodemask and land on the wrong node, and a
       memoryless node in cpuset.mems triggered a spurious "movable
       nodes only" warning

     - Two no-functional-change cleanups of the effective CPU
       computation

* tag 'cgroup-for-7.4-fixes' of git://git.kernel.org/pub/scm/linux/kernel/git/tj/cgroup: (27 commits)
  cgroup/cpuset: Integrate compute_partition_effective_cpumask() into compute_effective_cpumask()
  cgroup/cpuset: Relocate compute_*effective_cpumask() and compute_effective_nodemask()
  cgroup/cpuset: Release invalid isolated CPUs with a shrunk root partition parent
  cgroup/cpuset: Release invalid isolated CPUs in compute_partition_effective_cpumask()
  cgroup/cpuset: Make sure compute_partition_effective_cpumask() is only called for valid partition
  cgroup/cpuset: Prevent recursive call of remote_cpus_update() via update_cpumasks_hier()
  selftests/cgroup: Check for a single range nohz_full CPUs before running test matrix
  cgroup/cpuset: Minor fixes to prstate_housekeeping_conflict()
  cgroup/cpuset: Fix incorrect effective_cpus bug in update_cpumasks_hier()
  cgroup/cpuset: Properly compute effective xcpus in update_parent_effective_cpumask()
  cgroup/cpuset: Find furthest isolated ancestor for invalidated isolated partition
  cgroup: don't kill migrated processes through their exiting threads
  cgroup/cpuset: check effective mems for a movable-only configuration
  cgroup/cpuset: Fix task checking when enabling a partition
  cgroup: serialize migrations of newly forked processes
  selftests/cgroup: test cgroup.kill with an exited thread group leader
  cgroup: fix cgroup.kill for exited thread group leader
  selftests/cgroup: Skip test_cpuset_prs.sh test if some required CPUs are offline
  selftests/cgroup: Add tests for nohz_full housekeeping check
  selftests/cgroup: Add tests for isolcpus housekeeping check
  ...

3 weeks agoblk-crypto: fix NULL deref and UAF in __blk_crypto_evict_key()
Baokun Li [Fri, 23 Oct 2026 08:19:08 +0000 (16:19 +0800)]
blk-crypto: fix NULL deref and UAF in __blk_crypto_evict_key()

Sashiko reported a possible NULL pointer dereference, triggered by the
following flow:

  dm-inlinecrypt ctor            # first use of the fallback
   â”œâ”€ blk_crypto_init_key()      # succeeds, ctx->key.size != 0
   â”œâ”€ blk_crypto_start_using_key()
   â”‚   â”œâ”€ hw-wrapped key: -EOPNOTSUPP
   â”‚   â”‚    # profile never allocated (NULL)
   â”‚   â””─ raw key: fallback_start_using_mode()
   â”‚      â””─ blk_crypto_fallback_init() fails
   â”‚         â””─ kfree(profile)   # not NULLed
   â”œâ”€ goto bad
   â””─ inlinecrypt_dtr()          # evicts whenever key.size is set
      â””─ blk_crypto_evict_key()
         â””─ blk_crypto_config_supported_natively() = false
            â””─ blk_crypto_fallback_evict_key()
               â””─ __blk_crypto_evict_key(blk_crypto_fallback_profile)
                  â””─ profile->num_slots # BOOM!!!

This issue can be reproduced using the following commands:

  dd if=/dev/zero of=/tmp/backing bs=1M count=64
  LOOP=$(losetup -f --show /tmp/backing)
  SZ=$(blockdev --getsz $LOOP)
  KEY=$(head -c 64 /dev/urandom | od -An -tx1 | tr -d ' \n')
  dmsetup create ic --table "0 $SZ inlinecrypt aes-xts-plain64 \
    $KEY 0 $LOOP 0 1 keytype:hw-wrapped"

And the following oops is triggered:

  ==================================================================
  blk-crypto: loop0: no support for wrapped keys
  Oops: general protection fault, probably for non-canonical address
        0xdffffc000000000b: 0000 [#1] SMP KASAN PTI
  KASAN: null-ptr-deref in range [0x0000000000000058-0x000000000000005f]
  CPU: 5 UID: 0 PID: 901 Comm: dmsetup 7.3.0-rc3 #1 PREEMPT(lazy)
  RIP: 0010:__blk_crypto_evict_key+0x2e/0x3b0
  Call Trace:
   blk_crypto_evict_key+0x24c/0x320
   inlinecrypt_dtr+0xf6/0x160
   inlinecrypt_ctr+0x2d3/0xbd0
   dm_table_add_target+0x661/0xf40
   table_load+0x1c4/0x490
   ctl_ioctl+0x32f/0x5f0
   dm_ctl_ioctl+0xe/0x20
  ==================================================================

dm-inlinecrypt is the only caller that can evict a key that was never
started, as fscrypt frees such a key without evicting it.

Fix this by returning early from blk_crypto_fallback_evict_key() when
tfms_inited[] is not set for the key's mode.  tfms_inited[] is only set
after blk_crypto_fallback_init() has successfully initialized the
profile, so the crash above is no longer reachable.

The bug has been latent since commit c984ff1423ae ("blk-crypto:
dynamically allocate fallback profile") was merged in v6.5, and only
became actually triggerable when commit e7f57d2c47e2 ("dm-inlinecrypt:
add target for inline block device encryption") was merged in v7.2.

Fixes: c984ff1423ae ("blk-crypto: dynamically allocate fallback profile")
Cc: stable@vger.kernel.org
Reported-by: Sashiko <sashiko-bot@kernel.org>
Closes: https://patch.msgid.link/sashiko-outbox-167341@kernel.org
Suggested-by: Eric Biggers <ebiggers@kernel.org>
Link: https://patch.msgid.link/20261014155131.GB322435@quark
Signed-off-by: Baokun Li <libaokun@linux.alibaba.com>
Reviewed-by: Eric Biggers <ebiggers@kernel.org>
Link: https://patch.msgid.link/20261023081908.3505413-1-libaokun@linux.alibaba.com
Signed-off-by: Jens Axboe <axboe@kernel.dk>
3 weeks agotun: drop batched packets while the device is down
Xiao Liang [Tue, 27 Oct 2026 10:18:27 +0000 (18:18 +0800)]
tun: drop batched packets while the device is down

tun_sendmsg() handles TUN_MSG_PTR batches from vhost-net by calling
tun_xdp_one() instead of tun_get_user(). But this path does not check
IFF_UP, allowing packets from a guest to be injected into the host
receive path while the device is administratively down.

Check IFF_UP in tun_xdp_one() before running XDP or building an skb.
Drop the packet when the device is down, matching tun_get_user().

Fixes: 043d222f93ab ("tuntap: accept an array of XDP buffs through sendmsg()")
Signed-off-by: Xiao Liang <shaw.leon@gmail.com>
Reviewed-by: Willem de Bruijn <willemb@google.com>
Link: https://patch.msgid.link/20261027101830.85327-1-shaw.leon@gmail.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agoMerge branch 'netlink-fix-a-dump-livelock-with-a-notification-queued'
Jakub Kicinski [Thu, 29 Oct 2026 16:15:50 +0000 (09:15 -0700)]
Merge branch 'netlink-fix-a-dump-livelock-with-a-notification-queued'

Jhonata Poma-Hansen says:

====================
netlink: fix a dump livelock with a notification queued

A netlink dump that starts while a notification is still charged to a
socket with a small receive buffer fails with ENOBUFS, and every retry
from recvmsg() fails the same way. A reader that peeks before reading,
as libnl does, never consumes the message at the head of the queue and
spins forever. I hit this with "iw dev wlan0 scan" on an arm64 board.

Patch 1 goes back to checking sk_rcvbuf before charging the dump skb,
as before commit ae8f160e7eb2. Patch 2 adds a selftest; it fails
without patch 1 and is skipped without the privileges to create a
netns.
====================

Link: https://patch.msgid.link/20261027-netlink-dump-livelock-v2-0-c4bb05352a33@gmail.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agoselftests: net: netlink-dumps: start a dump with a notification queued
Jhonata Poma-Hansen [Tue, 27 Oct 2026 14:04:02 +0000 (15:04 +0100)]
selftests: net: netlink-dumps: start a dump with a notification queued

Add a test which starts a link dump on a socket with SO_RCVBUF 2048
while a link notification is still queued, after a large read made the
kernel attempt large dump skbs. It reads like libnl does, peeking
before each read, and expects the dump to complete with a zero status
and at least one link. The notifications come from bringing lo up and
down, so the test runs in its own netns and is skipped without the
privileges to create one.

The test fails without the previous patch.

Signed-off-by: Jhonata Poma-Hansen <jhonata.poma@gmail.com>
Link: https://patch.msgid.link/20261027-netlink-dump-livelock-v2-2-c4bb05352a33@gmail.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agonetlink: check sk_rcvbuf before charging the dump skb
Jhonata Poma-Hansen [Tue, 27 Oct 2026 14:04:01 +0000 (15:04 +0100)]
netlink: check sk_rcvbuf before charging the dump skb

Since commit ae8f160e7eb2 ("netlink: Fix wraparounds of
sk->sk_rmem_alloc."), netlink_dump() charges the dump skb first and
queues it only if sk_rmem_alloc is still below sk_rcvbuf. Commit
a215b5723922 ("netlink: make sure we allow at least one dump skb")
added an exception for an empty socket.

A dump that starts while something else is still charged to a socket
with a small receive buffer fails with ENOBUFS and stays running.
Every recvmsg() retries it, fails again and sets sk_err, so a reader
that peeks before reading, as libnl does, gets ENOBUFS on the read
after each peek, never consumes the message at the head of the queue
and spins forever.

I hit this with "iw dev wlan0 scan" hanging at 100% CPU on an arm64
board with a 6.6 based kernel (iw 5.19 sets SO_RCVBUF to 8KiB). A
kprobe trace showed the scan dump starting while the NEW_SCAN_RESULTS
notification iw had just read was still charged to its socket,
because iw had preempted the sender before netlink_broadcast()
returned.

Check the limit before charging, as before ae8f160e7eb2, which also
covers the empty socket. netlink_recvmsg() continues a dump only at
or below half of sk_rcvbuf, so the skb is then always queued, and a
dump goes over the limit by at most one skb. Refuse a skb that would
take sk_rmem_alloc past INT_MAX, so the wraparound stays fixed.

Reproduced on net in a KVM guest with a userspace reproducer and the
selftest in the next patch; both pass with this fix.

Fixes: ae8f160e7eb2 ("netlink: Fix wraparounds of sk->sk_rmem_alloc.")
Signed-off-by: Jhonata Poma-Hansen <jhonata.poma@gmail.com>
Reviewed-by: Eric Dumazet <edumazet@kernel.org>
Link: https://patch.msgid.link/20261027-netlink-dump-livelock-v2-1-c4bb05352a33@gmail.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agoMerge branch 'net-fix-eth_type_trans-crashes-on-skbs-coming-from-the-stack'
Jakub Kicinski [Thu, 29 Oct 2026 16:11:22 +0000 (09:11 -0700)]
Merge branch 'net-fix-eth_type_trans-crashes-on-skbs-coming-from-the-stack'

Eric Dumazet says:

====================
net: fix eth_type_trans() crashes on skbs coming from the stack

eth_type_trans() assumes ETH_HLEN bytes are present in skb->head.
NIC drivers always provide this, and they should keep using the fast
version, without an extra pskb_may_pull().

Devices looping skbs from their transmit path back to their receive
path get skbs built by the stack instead. tc actions (act_vlan pop_eth,
act_ife decode), BPF helpers (bpf_skb_change_head() before a redirect)
or OVS actions (pop_eth followed by pop_mpls/pop_nsh) can leave fewer
than ETH_HLEN bytes in the linear part, and eth_type_trans() then hits
the BUG() in __skb_pull().

Instead of fixing every producer, or adding a check to all
eth_type_trans() users, fix the few consumers exposed to this:

- Patch 1 adds eth_type_trans_careful(), which pulls the Ethernet
  header first and returns a drop reason on failure.
- Patch 2 uses it in loopback_xmit().
- Patch 3 uses it in __dev_forward_skb2(), used by BPF redirects to
  ingress and by veth, macvlan, ipvlan, netdevsim and l2tp_eth.
- Patch 4 uses it in OVS internal_dev_recv(), covering both the MPLS
  (TEB) and NSH pop cases at once (only the MPLS case was tested).
- Patch 5 (from Jamal) fixes act_ife decode on egress, which was
  consuming the inner Ethernet header. This is no longer a crash after
  patch 2, but egress decode never delivered a correct frame.

Other eth_type_trans() users already pull the header or never see
such skbs:
- vrf_process_v{4,6}_outbound() already pull ETH_HLEN + IP header
  before vrf_local_xmit().
- tun already uses pskb_may_pull_reason(skb, ETH_HLEN).
- XDP: bpf_xdp_adjust_head() and bpf_xdp_adjust_tail() keep at least
  ETH_HLEN bytes in the linear part, and multi-buffer tail shrinking
  only trims frags.

Tested under virtme-ng with AF_PACKET reproducers. Without the series,
all four cases crash in eth_type_trans():
- lo egress "action vlan pop_eth", eth/eth/8192 bytes frame
- lo egress "action ife decode pipe", IFE frame with 8192 bytes payload
- lo egress "action vlan pop_eth continue", then a BPF program doing
  bpf_skb_change_head(skb, 1, 0) + bpf_redirect(veth1, BPF_F_INGRESS)
- OVS flow "pop_eth,pop_mpls(0x6558),0" to the internal port,
  eth/mpls/eth/4096 bytes frame
With the series, no crash. An ICMP echo inside an IFE frame decoded
on lo egress is now received and answered. Normal traffic on lo,
veth (including 8000 byte pings) and vrf is unchanged.

Link: https://lore.kernel.org/netdev/20261005052249.1914367-2-weir@nebusec.ai/
Link: https://lore.kernel.org/netdev/ACT-N6N4.v3.r0.20261023200137-4@mojatatu.com/
v1: https://lore.kernel.org/netdev/20261027082604.1485903-1-edumazet@kernel.org/
====================

Link: https://patch.msgid.link/20261028122703.2093730-1-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agonet/sched: act_ife: do not consume the inner header on egress
Jamal Hadi Salim [Wed, 28 Oct 2026 12:27:03 +0000 (13:27 +0100)]
net/sched: act_ife: do not consume the inner header on egress

The issue:
tcf_ife_decode() unconditionally calls eth_type_trans(), which pulls
ETH_HLEN.  On egress this consumes the inner Ethernet header, and the
device receives an skb whose data points to the L3 header:

- loopback_xmit() parses L3 data as Ethernet: the "ethertype" comes
  from the inner IPv4 source address, and the decapsulated packet is
  dropped or misparsed.
- a real NIC transmits the frame without its Ethernet header.

(The __skb_pull() BUG this used to trigger in loopback_xmit() when the
remaining linear area was short is handled by "loopback: use
eth_type_trans_careful()".)

The Fix:
Parse the inner Ethernet header with eth_type_trans() in both directions,
then restore the egress data position and MAC length.  On ingress the
existing behavior is unchanged.  On egress, push the inner Ethernet header
back after parsing so the xmit path sees the original frame and later
actions see a consistent network header.

Conditions to recreate the bug:
- egress tc filter on lo: action ife decode pipe;
- AF_PACKET SOCK_RAW frame: outer Ethernet with ETH_P_IFE, IFE metadata,
  inner Ethernet + a valid IPv4 ICMP echo request to a local address;
- before this patch, no echo is received; after it, the echo is
  delivered and answered.

Fixes: ef6980b6becb ("introduce IFE action")
Cc: stable@vger.kernel.org
Signed-off-by: Jamal Hadi Salim <jhs@mojatatu.com>
[edumazet: reworded changelog, the crash is now handled in loopback]
Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Link: https://patch.msgid.link/20261028122703.2093730-6-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agoopenvswitch: use eth_type_trans_careful() in internal_dev_recv()
Eric Dumazet [Wed, 28 Oct 2026 12:27:02 +0000 (13:27 +0100)]
openvswitch: use eth_type_trans_careful() in internal_dev_recv()

OVS actions like pop_eth followed by pop_mpls(ETH_P_TEB) or pop_nsh
can expose an inner Ethernet header which is not in the linear part
of the skb. Output to an internal port then crashes in eth_type_trans():

  flow: in_port(0),eth(),eth_type(0x8847),mpls(lse=0x00010140)
  actions: pop_eth,pop_mpls(0x6558),0
  # AF_PACKET SOCK_RAW on dp0: eth / mpls / eth / 4096 bytes of payload

  kernel BUG at include/linux/skbuff.h:2839!
  RIP: 0010:eth_type_trans (include/linux/etherdevice.h:635 net/ethernet/eth.c:163)
  Call Trace:
   internal_dev_recv (net/openvswitch/vport-internal_dev.c:202) openvswitch
   do_execute_actions (net/openvswitch/actions.c:1296) openvswitch
   ovs_execute_actions (net/openvswitch/actions.c:1606) openvswitch
   ovs_dp_process_packet (net/openvswitch/datapath.c:310) openvswitch
   ovs_vport_receive (net/openvswitch/vport.c:448) openvswitch
   internal_dev_xmit (net/openvswitch/vport-internal_dev.c:42) openvswitch
   dev_hard_start_xmit (include/linux/netdevice.h:5455 include/linux/netdevice.h:5464 net/core/dev.c:4057 net/core/dev.c:4073)
   __dev_queue_xmit (net/core/dev.c:5066)
   packet_sendmsg (net/packet/af_packet.c:3157 net/packet/af_packet.c:3189)

Use eth_type_trans_careful(), and drop the packet if the Ethernet
header can not be pulled. This covers all OVS actions at the consumer,
instead of fixing each producer.

Fixes: b2d0f5d5dc53 ("openvswitch: enable NSH support")
Fixes: f66b53fdbb22 ("openvswitch: New MPLS actions for layer 2 tunnelling")
Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Reviewed-by: Aaron Conole <aconole@redhat.com>
Reviewed-by: Jamal Hadi Salim <jhs@mojatatu.com>
Tested-by: Jamal Hadi Salim <jhs@mojatatu.com>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Reviewed-by: Willem de Bruijn <willemb@google.com>
Link: https://patch.msgid.link/20261028122703.2093730-5-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agonet: use eth_type_trans_careful() in __dev_forward_skb2()
Eric Dumazet [Wed, 28 Oct 2026 12:27:01 +0000 (13:27 +0100)]
net: use eth_type_trans_careful() in __dev_forward_skb2()

A tc egress BPF program can push a tiny link-layer header with
bpf_skb_change_head() on an skb whose head is almost empty, then
redirect it to an Ethernet device ingress. __bpf_redirect_common()
only checks mac_header < network_header, and __dev_forward_skb2()
crashes in eth_type_trans():

  tc filter add dev lo egress pref 1 matchall action vlan pop_eth continue
  tc filter add dev lo egress pref 2 bpf da obj prog.o
  # prog: bpf_skb_change_head(skb, 1, 0);
  #       return bpf_redirect(veth1_ifindex, BPF_F_INGRESS);
  # AF_PACKET SOCK_RAW on lo: eth / eth / 8192 bytes of payload

  kernel BUG at include/linux/skbuff.h:2839!
  RIP: 0010:eth_type_trans (include/linux/etherdevice.h:635 net/ethernet/eth.c:163)
  Call Trace:
   __dev_forward_skb2 (net/core/dev.c:2507)
   dev_forward_skb_nomtu (net/core/dev.c:2546)
   __dev_queue_xmit (net/core/dev.c:4738 net/core/dev.c:4998)
   packet_sendmsg (net/packet/af_packet.c:3157 net/packet/af_packet.c:3189)

Use eth_type_trans_careful(), and drop the packet if the Ethernet
header can not be pulled. This also covers other dev_forward_skb()
users (veth, macvlan, ipvlan, netdevsim, l2tp_eth).

Update the empty_skb BPF selftest: at lwt_xmit, BPF_PROG_TEST_RUN
strips the Ethernet header, so the "veth ETH_HLEN+1" packet is a 1-byte
skb. Redirecting it to veth ingress used to read the Ethernet header
past skb->tail and deliver a 1-byte frame; it is now dropped with
NET_RX_DROP, as veth_xmit() already does at egress.

Fixes: 3a0af8fd61f9 ("bpf: BPF for lightweight tunnel infrastructure")
Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Reviewed-by: Jamal Hadi Salim <jhs@mojatatu.com>
Tested-by: Jamal Hadi Salim <jhs@mojatatu.com>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Reviewed-by: Willem de Bruijn <willemb@google.com>
Link: https://patch.msgid.link/20261028122703.2093730-4-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agoloopback: use eth_type_trans_careful()
Eric Dumazet [Wed, 28 Oct 2026 12:27:00 +0000 (13:27 +0100)]
loopback: use eth_type_trans_careful()

tc egress actions can leave an skb with fewer than ETH_HLEN bytes in
its linear part. loopback_xmit() then crashes in eth_type_trans():

  tc qdisc add dev lo clsact
  tc filter add dev lo egress matchall action vlan pop_eth
  # AF_PACKET SOCK_RAW: eth / eth / 8192 bytes of payload

  kernel BUG at include/linux/skbuff.h:2839!
  RIP: 0010:eth_type_trans (include/linux/etherdevice.h:635 net/ethernet/eth.c:163)
  Call Trace:
   loopback_xmit (drivers/net/loopback.c:87)
   dev_hard_start_xmit (include/linux/netdevice.h:5455 include/linux/netdevice.h:5464 net/core/dev.c:4057 net/core/dev.c:4073)
   __dev_queue_xmit (net/core/dev.c:5066)
   packet_sendmsg (net/packet/af_packet.c:3157 net/packet/af_packet.c:3189)

The same happens with "action ife decode" on lo egress.

Use eth_type_trans_careful(), and drop the packet if the Ethernet
header can not be pulled.

Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Reported-by: Vega <vega@nebusec.ai>
Link: https://lore.kernel.org/netdev/20261005052249.1914367-2-weir@nebusec.ai/
Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Reviewed-by: Jamal Hadi Salim <jhs@mojatatu.com>
Tested-by: Jamal Hadi Salim <jhs@mojatatu.com>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Reviewed-by: Willem de Bruijn <willemb@google.com>
Link: https://patch.msgid.link/20261028122703.2093730-3-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agonet: add eth_type_trans_careful()
Eric Dumazet [Wed, 28 Oct 2026 12:26:59 +0000 (13:26 +0100)]
net: add eth_type_trans_careful()

eth_type_trans() assumes ETH_HLEN bytes are present in skb->head.
NIC drivers always provide this, and they should keep using the fast
version.

Devices looping skbs from their transmit path back to their receive
path get skbs built by the stack instead. Their link-layer header
might have been popped by tc actions (act_vlan pop_eth, act_ife decode)
or OVS actions (pop_eth + pop_mpls / pop_nsh), leaving fewer than
ETH_HLEN bytes in the linear part. eth_type_trans() then hits
the BUG() in __skb_pull().

Add eth_type_trans_careful(), which first pulls the Ethernet header,
and returns a drop reason on failure, so that the few devices exposed
to this can drop such packets.

Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Reviewed-by: Aaron Conole <aconole@redhat.com>
Reviewed-by: Willem de Bruijn <willemb@google.com>
Reviewed-by: Jamal Hadi Salim <jhs@mojatatu.com>
Tested-by: Jamal Hadi Salim <jhs@mojatatu.com>
Acked-by: Alexei Starovoitov <ast@kernel.org>
Link: https://patch.msgid.link/20261028122703.2093730-2-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agotcp: initialize mapped children before route lookup
Kyle Zeng [Wed, 28 Oct 2026 15:41:01 +0000 (16:41 +0100)]
tcp: initialize mapped children before route lookup

IPv4 passive opens on a dual-stack listener go through
tcp_v4_syn_recv_sock() with tcp_v6_mapped_child_init() as the optional
initializer. The callback currently runs after the output route lookup.
If that lookup fails, tcp_done() destroys a clone whose pinet6 and
ipv6_fl_list still refer to the listener's state.

With the flowlabel list head in inet_sock, fl6_free_socklist() walks
the clone's list and RCU-frees its nodes without unlinking them from the
live listener. Subsequent flowlabel operations can use or free the nodes
again. Commit 858d2a4f67ff ("tcp: fix potential race in
tcp_v6_syn_recv_sock()") moved the initializer before ehash insertion,
but did not cover this error path.

Invoke the existing initializer after the IPv4 fields it consumes have
been set, but before route lookup can fail. It needs neither the
destination nor sk_setup_caps(), and all later disposal paths remain
covered.

Fixes: 1c17f4373d4d ("ipv6: Move ipv6_fl_list from ipv6_pinfo to inet_sock.")
Signed-off-by: Kyle Zeng <kylebot@openai.com>
Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Reviewed-by: Kuniyuki Iwashima <kuniyu@google.com>
Link: https://patch.msgid.link/20261028154101.2153360-1-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agotcp: fix reordering addition overflow in MTU probing
Kyle Zeng [Wed, 28 Oct 2026 16:02:26 +0000 (17:02 +0100)]
tcp: fix reordering addition overflow in MTU probing

Commit efb8763d7bbb ("net: ipv4: bound TCP reordering sysctl writes and
MTU probe sizes") widened size_needed and the MSS multiplication, but
tp->reordering + 1 is still evaluated as u32. RTAX_REORDERING accepts
an unrestricted u32, and tcp_init_metrics() can install U32_MAX.

In that case the extra-data requirement becomes zero. A write queue
with probe_size - 1 data bytes and a FIN satisfies the sequence-space
check. The coalescing walk can pass the queue head to
tcp_skb_can_collapse(), and tcp_clone_payload() can produce an skb
whose advertised payload exceeds the data in its fragments. Local
delivery followed by TCP_ZEROCOPY_RECEIVE can then walk beyond the
fragment array. KASAN reports a slab-out-of-bounds read in
can_map_frag().

Cast reordering before incrementing it so the arithmetic handles the
entire u32 metric range. For U32_MAX, the required size exceeds the
32-bit queue and window limits, so the existing checks skip the probe.
The calculation is unchanged for all other reordering values.

Fixes: efb8763d7bbb ("net: ipv4: bound TCP reordering sysctl writes and MTU probe sizes")
Cc: stable@vger.kernel.org
Cc: Wyatt Feng <bronzed_45_vested@icloud.com>
Cc: Ren Wei <n05ec@lzu.edu.cn>
Signed-off-by: Kyle Zeng <kylebot@openai.com>
Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Reviewed-by: Neal Cardwell <ncardwell@google.com>
Reviewed-by: Kuniyuki Iwashima <kuniyu@google.com>
Reviewed-by: Jiayuan Chen <jiayuan.chen@linux.dev>
Link: https://patch.msgid.link/20261028160226.2170244-1-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agotcp: avoid double destroy in tcp_abort() of an unaccepted child
Kyle Zeng [Wed, 28 Oct 2026 16:08:47 +0000 (17:08 +0100)]
tcp: avoid double destroy in tcp_abort() of an unaccepted child

tcp_abort() checks for TCP_CLOSE while only owning the socket lock,
then grabs the BH lock before calling tcp_done_with_error().

For a child still sitting in a listener accept queue (which can be
reached via SOCK_DESTROY or bpf_sock_destroy()), inet_csk_listen_stop()
can run in this window: it only holds the child BH lock, and calls
inet_child_forget(), which disconnects, orphans and destroys the child.

tcp_abort() then calls tcp_done_with_error() -> tcp_done(), which sees
SOCK_DEAD and calls inet_csk_destroy_sock() a second time, leading to
a double sock_put() and a use-after-free.

Recheck TCP_CLOSE after acquiring the BH lock, unless we just closed
a listener ourselves, in which case tcp_done_with_error() must still
run to report the error.

Note that the WARN_ON(sock_owned_by_user(child)) in
inet_csk_listen_stop() can still trigger in this window.

Fixes: bac76cf89816 ("tcp: fix forever orphan socket caused by tcp_abort")
Signed-off-by: Kyle Zeng <kylebot@openai.com>
[edumazet: recheck TCP_CLOSE under the BH lock instead of moving the test, smaller diff]
Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Reviewed-by: Kuniyuki Iwashima <kuniyu@google.com>
Link: https://patch.msgid.link/20261028160847.2170959-1-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agonet: bgmac: fix TX DMA unmapping and slot cleanup
Rosen Penev [Wed, 28 Oct 2026 16:48:39 +0000 (09:48 -0700)]
net: bgmac: fix TX DMA unmapping and slot cleanup

When mapping a fragment fails, bgmac_dma_tx_add() unwinds with the
wrong slots. It passes the failed fragment's slot->dma_addr, which
holds the mapping error, to dma_unmap_single() for the head. The
fragment loop indexes from ring->end instead of ring->end + 1, so it
unmaps the head a second time as a page and leaves the last mapped
fragment mapped. None of the affected slots get their dma_addr cleared
either, which includes the head slot when mapping the head fails.

bgmac_dma_tx_ring_free() unmaps every slot with a non-zero dma_addr,
so tearing down the ring unmaps these addresses again. It also frees
the skbs of pending TX slots but leaves slot->skb and slot->dma_addr
set. The slots survive a down/up cycle, and bgmac_dma_tx_add() only
sets slot->skb on the last slot of a packet. If a slot with a stale
pointer is later used for the head or a fragment of a scatter/gather
packet, bgmac_dma_tx_free() frees the old skb a second time when that
slot completes.

bgmac_dma_tx_ring_free() also picks dma_unmap_single() or
dma_unmap_page() by looking at slot->skb, which is set on the last slot
of a packet, while the head was mapped with dma_map_single() and the
fragments with skb_frag_dma_map().

In the error path, unmap the head and each mapped fragment from their
own slots, and clear dma_addr on every slot the failed packet touched.
In bgmac_dma_tx_ring_free(), choose the unmap function by the SOF flag
of the descriptor like bgmac_dma_tx_free() does, unmap every slot
before freeing any skb, since a packet can wrap around the end of the
ring with its skb on the last slot, and clear both fields.

This was found through code inspection by an LLM while hitting other
bugs on an Asus RT-N16. It did not hit these ones specifically.

Fixes: 9cde94506eac ("bgmac: implement scatter/gather support")
Signed-off-by: Rosen Penev <rosenp@gmail.com>
Reviewed-by: Florian Fainelli <florian.fainelli@broadcom.com>
Link: https://patch.msgid.link/20261028164839.28605-1-rosenp@gmail.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agogro: do not GRO GSO packets with inconsistent payload
Kyle Zeng [Wed, 28 Oct 2026 17:13:50 +0000 (18:13 +0100)]
gro: do not GRO GSO packets with inconsistent payload

tcp_gro_receive() excludes empty non-GSO packets with the unsigned
len - 1 check, but its GSO branch only checks that gso_size matches
the held packet's MSS. A trusted TCP GSO skb can reach GRO again with
no payload after TC pedit increases its TCP data offset.

If the skb is fully linear, skb_gro_receive() then enters its fragment
transfer path with nr_frags == 0. The do-while loop copies skb_frag_t
entries backwards beyond both fragment arrays. An unprivileged process
using its own user and network namespaces can trigger a KASAN
slab-out-of-bounds write and panic through veth, pedit and GRE.

More generally, the payload of such a packet can be shrunk to any
value, making it inconsistent with its gso_segs, and a GSO packet
with gso_segs == 0 contributes no segment to the GRO packet.

Do not aggregate GSO packets with gso_segs == 0, and require the
payload of GSO packets to be consistent with gso_segs and gso_size,
the last segment being allowed to be short. This rejects the empty
skb before either TCP merge helper, and covers both IPv4 and IPv6.

Fixes: 5eddb24901ee ("gro: add support of (hw)gro packets to gro stack")
Signed-off-by: Kyle Zeng <kylebot@openai.com>
[edumazet: check payload against gso_segs, refuse gso_segs == 0]
Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Reviewed-by: Willem de Bruijn <willemb@google.com>
Link: https://patch.msgid.link/20261028171350.2205175-1-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agonet/packet: check TX_RING fragments before memory accounting
Kyle Zeng [Wed, 28 Oct 2026 18:14:50 +0000 (19:14 +0100)]
net/packet: check TX_RING fragments before memory accounting

tpacket_fill_skb() adds the full non-linear payload length to
skb->truesize and sk_wmem_alloc before checking MAX_SKB_FRAGS. With
PACKET_VNET_HDR, userspace can submit a ring-sized frame even when it
greatly exceeds the device MTU.

A near-INT_MAX frame can saturate sk_wmem_alloc before the fragment
loop rejects it. A subsequent refcount_add(0x40000001) can temporarily
turn REFCOUNT_SATURATED into 1. A concurrent TX completion can then
drop that apparent last reference and free the still-live packet
socket before refcount_warn_saturate() restores the counter.

Check that the remaining payload fits in MAX_SKB_FRAGS pages before
accounting it. Include the initial page offset in the calculation,
and move the existing -EFAULT handling out of the fragment loop.
This preserves the accepted packet sizes and error code while
preventing an invalid frame from injecting an oversized byte charge.

Fixes: 69e3c75f4d54 ("net: TX_RING and packet mmap")
Cc: stable@vger.kernel.org
Cc: Willem de Bruijn <willemdebruijn.kernel@gmail.com>
Signed-off-by: Kyle Zeng <kylebot@openai.com>
[edumazet: use net_warn_ratelimited() instead of pr_err(), add a Fixes: tag]
Signed-off-by: Eric Dumazet <edumazet@kernel.org>
Reviewed-by: Willem de Bruijn <willemb@google.com>
Link: https://patch.msgid.link/20261028181450.2221013-1-edumazet@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>
3 weeks agoMerge branch 'eth-bnxt-fix-rx-buffer-leaks-under-oom'
Jakub Kicinski [Thu, 29 Oct 2026 15:50:27 +0000 (08:50 -0700)]
Merge branch 'eth-bnxt-fix-rx-buffer-leaks-under-oom'

Jakub Kicinski says:

====================
eth: bnxt: fix Rx buffer leaks under OOM

Commit bd3beb5c8691 ("eth: bnxt: disable rx-copybreak by default")
changed the defaults putting users on buggy(ier) driver paths.

Fix various ways bnxt may leak buffers under OOM. The first patch
fixes the real bug that was hit in production. Second patch fixes
an issue I hit while testing the first one. The next 3 patches
fix other Rx buffer leaks pointed out by an LLM during review.
====================

Link: https://patch.msgid.link/20261027234940.1267225-1-kuba@kernel.org
Signed-off-by: Jakub Kicinski <kuba@kernel.org>